id int32 0 165k | 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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
23,500 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/wallet/DefaultRiskAnalysis.java | DefaultRiskAnalysis.isInputStandard | public static RuleViolation isInputStandard(TransactionInput input) {
for (ScriptChunk chunk : input.getScriptSig().getChunks()) {
if (chunk.data != null && !chunk.isShortestPossiblePushData())
return RuleViolation.SHORTEST_POSSIBLE_PUSHDATA;
if (chunk.isPushData()) {
ECDSASignature signature;
try {
signature = ECKey.ECDSASignature.decodeFromDER(chunk.data);
} catch (SignatureDecodeException x) {
// Doesn't look like a signature.
signature = null;
}
if (signature != null) {
if (!TransactionSignature.isEncodingCanonical(chunk.data))
return RuleViolation.SIGNATURE_CANONICAL_ENCODING;
if (!signature.isCanonical())
return RuleViolation.SIGNATURE_CANONICAL_ENCODING;
}
}
}
return RuleViolation.NONE;
} | java | public static RuleViolation isInputStandard(TransactionInput input) {
for (ScriptChunk chunk : input.getScriptSig().getChunks()) {
if (chunk.data != null && !chunk.isShortestPossiblePushData())
return RuleViolation.SHORTEST_POSSIBLE_PUSHDATA;
if (chunk.isPushData()) {
ECDSASignature signature;
try {
signature = ECKey.ECDSASignature.decodeFromDER(chunk.data);
} catch (SignatureDecodeException x) {
// Doesn't look like a signature.
signature = null;
}
if (signature != null) {
if (!TransactionSignature.isEncodingCanonical(chunk.data))
return RuleViolation.SIGNATURE_CANONICAL_ENCODING;
if (!signature.isCanonical())
return RuleViolation.SIGNATURE_CANONICAL_ENCODING;
}
}
}
return RuleViolation.NONE;
} | [
"public",
"static",
"RuleViolation",
"isInputStandard",
"(",
"TransactionInput",
"input",
")",
"{",
"for",
"(",
"ScriptChunk",
"chunk",
":",
"input",
".",
"getScriptSig",
"(",
")",
".",
"getChunks",
"(",
")",
")",
"{",
"if",
"(",
"chunk",
".",
"data",
"!=",
"null",
"&&",
"!",
"chunk",
".",
"isShortestPossiblePushData",
"(",
")",
")",
"return",
"RuleViolation",
".",
"SHORTEST_POSSIBLE_PUSHDATA",
";",
"if",
"(",
"chunk",
".",
"isPushData",
"(",
")",
")",
"{",
"ECDSASignature",
"signature",
";",
"try",
"{",
"signature",
"=",
"ECKey",
".",
"ECDSASignature",
".",
"decodeFromDER",
"(",
"chunk",
".",
"data",
")",
";",
"}",
"catch",
"(",
"SignatureDecodeException",
"x",
")",
"{",
"// Doesn't look like a signature.",
"signature",
"=",
"null",
";",
"}",
"if",
"(",
"signature",
"!=",
"null",
")",
"{",
"if",
"(",
"!",
"TransactionSignature",
".",
"isEncodingCanonical",
"(",
"chunk",
".",
"data",
")",
")",
"return",
"RuleViolation",
".",
"SIGNATURE_CANONICAL_ENCODING",
";",
"if",
"(",
"!",
"signature",
".",
"isCanonical",
"(",
")",
")",
"return",
"RuleViolation",
".",
"SIGNATURE_CANONICAL_ENCODING",
";",
"}",
"}",
"}",
"return",
"RuleViolation",
".",
"NONE",
";",
"}"
] | Checks if the given input passes some of the AreInputsStandard checks. Not complete. | [
"Checks",
"if",
"the",
"given",
"input",
"passes",
"some",
"of",
"the",
"AreInputsStandard",
"checks",
".",
"Not",
"complete",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/wallet/DefaultRiskAnalysis.java#L186-L207 |
23,501 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/wallet/SendRequest.java | SendRequest.forTx | public static SendRequest forTx(Transaction tx) {
SendRequest req = new SendRequest();
req.tx = tx;
return req;
} | java | public static SendRequest forTx(Transaction tx) {
SendRequest req = new SendRequest();
req.tx = tx;
return req;
} | [
"public",
"static",
"SendRequest",
"forTx",
"(",
"Transaction",
"tx",
")",
"{",
"SendRequest",
"req",
"=",
"new",
"SendRequest",
"(",
")",
";",
"req",
".",
"tx",
"=",
"tx",
";",
"return",
"req",
";",
"}"
] | Simply wraps a pre-built incomplete transaction provided by you. | [
"Simply",
"wraps",
"a",
"pre",
"-",
"built",
"incomplete",
"transaction",
"provided",
"by",
"you",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/wallet/SendRequest.java#L196-L200 |
23,502 | bitcoinj/bitcoinj | wallettemplate/src/main/java/wallettemplate/utils/QRCodeImages.java | QRCodeImages.imageFromString | public static Image imageFromString(String uri, int width, int height) {
return imageFromMatrix(matrixFromString(uri, width, height));
} | java | public static Image imageFromString(String uri, int width, int height) {
return imageFromMatrix(matrixFromString(uri, width, height));
} | [
"public",
"static",
"Image",
"imageFromString",
"(",
"String",
"uri",
",",
"int",
"width",
",",
"int",
"height",
")",
"{",
"return",
"imageFromMatrix",
"(",
"matrixFromString",
"(",
"uri",
",",
"width",
",",
"height",
")",
")",
";",
"}"
] | Create an Image from a Bitcoin URI
@param uri Bitcoin URI
@param width width of image
@param height height of image
@return a javafx Image | [
"Create",
"an",
"Image",
"from",
"a",
"Bitcoin",
"URI"
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/wallettemplate/src/main/java/wallettemplate/utils/QRCodeImages.java#L39-L41 |
23,503 | bitcoinj/bitcoinj | wallettemplate/src/main/java/wallettemplate/utils/QRCodeImages.java | QRCodeImages.matrixFromString | private static BitMatrix matrixFromString(String uri, int width, int height) {
Writer qrWriter = new QRCodeWriter();
BitMatrix matrix;
try {
matrix = qrWriter.encode(uri, BarcodeFormat.QR_CODE, width, height);
} catch (WriterException e) {
throw new RuntimeException(e);
}
return matrix;
} | java | private static BitMatrix matrixFromString(String uri, int width, int height) {
Writer qrWriter = new QRCodeWriter();
BitMatrix matrix;
try {
matrix = qrWriter.encode(uri, BarcodeFormat.QR_CODE, width, height);
} catch (WriterException e) {
throw new RuntimeException(e);
}
return matrix;
} | [
"private",
"static",
"BitMatrix",
"matrixFromString",
"(",
"String",
"uri",
",",
"int",
"width",
",",
"int",
"height",
")",
"{",
"Writer",
"qrWriter",
"=",
"new",
"QRCodeWriter",
"(",
")",
";",
"BitMatrix",
"matrix",
";",
"try",
"{",
"matrix",
"=",
"qrWriter",
".",
"encode",
"(",
"uri",
",",
"BarcodeFormat",
".",
"QR_CODE",
",",
"width",
",",
"height",
")",
";",
"}",
"catch",
"(",
"WriterException",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"e",
")",
";",
"}",
"return",
"matrix",
";",
"}"
] | Create a BitMatrix from a Bitcoin URI
@param uri Bitcoin URI
@return A BitMatrix for the QRCode for the URI | [
"Create",
"a",
"BitMatrix",
"from",
"a",
"Bitcoin",
"URI"
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/wallettemplate/src/main/java/wallettemplate/utils/QRCodeImages.java#L48-L57 |
23,504 | bitcoinj/bitcoinj | wallettemplate/src/main/java/wallettemplate/utils/QRCodeImages.java | QRCodeImages.imageFromMatrix | private static Image imageFromMatrix(BitMatrix matrix) {
int height = matrix.getHeight();
int width = matrix.getWidth();
WritableImage image = new WritableImage(width, height);
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
Color color = matrix.get(x,y) ? Color.BLACK : Color.WHITE;
image.getPixelWriter().setColor(x, y, color);
}
}
return image;
} | java | private static Image imageFromMatrix(BitMatrix matrix) {
int height = matrix.getHeight();
int width = matrix.getWidth();
WritableImage image = new WritableImage(width, height);
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
Color color = matrix.get(x,y) ? Color.BLACK : Color.WHITE;
image.getPixelWriter().setColor(x, y, color);
}
}
return image;
} | [
"private",
"static",
"Image",
"imageFromMatrix",
"(",
"BitMatrix",
"matrix",
")",
"{",
"int",
"height",
"=",
"matrix",
".",
"getHeight",
"(",
")",
";",
"int",
"width",
"=",
"matrix",
".",
"getWidth",
"(",
")",
";",
"WritableImage",
"image",
"=",
"new",
"WritableImage",
"(",
"width",
",",
"height",
")",
";",
"for",
"(",
"int",
"y",
"=",
"0",
";",
"y",
"<",
"height",
";",
"y",
"++",
")",
"{",
"for",
"(",
"int",
"x",
"=",
"0",
";",
"x",
"<",
"width",
";",
"x",
"++",
")",
"{",
"Color",
"color",
"=",
"matrix",
".",
"get",
"(",
"x",
",",
"y",
")",
"?",
"Color",
".",
"BLACK",
":",
"Color",
".",
"WHITE",
";",
"image",
".",
"getPixelWriter",
"(",
")",
".",
"setColor",
"(",
"x",
",",
"y",
",",
"color",
")",
";",
"}",
"}",
"return",
"image",
";",
"}"
] | Create a JavaFX Image from a BitMatrix
@param matrix the matrix
@return the QRCode Image | [
"Create",
"a",
"JavaFX",
"Image",
"from",
"a",
"BitMatrix"
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/wallettemplate/src/main/java/wallettemplate/utils/QRCodeImages.java#L64-L75 |
23,505 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/TransactionOutput.java | TransactionOutput.getIndex | public int getIndex() {
List<TransactionOutput> outputs = getParentTransaction().getOutputs();
for (int i = 0; i < outputs.size(); i++) {
if (outputs.get(i) == this)
return i;
}
throw new IllegalStateException("Output linked to wrong parent transaction?");
} | java | public int getIndex() {
List<TransactionOutput> outputs = getParentTransaction().getOutputs();
for (int i = 0; i < outputs.size(); i++) {
if (outputs.get(i) == this)
return i;
}
throw new IllegalStateException("Output linked to wrong parent transaction?");
} | [
"public",
"int",
"getIndex",
"(",
")",
"{",
"List",
"<",
"TransactionOutput",
">",
"outputs",
"=",
"getParentTransaction",
"(",
")",
".",
"getOutputs",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"outputs",
".",
"size",
"(",
")",
";",
"i",
"++",
")",
"{",
"if",
"(",
"outputs",
".",
"get",
"(",
"i",
")",
"==",
"this",
")",
"return",
"i",
";",
"}",
"throw",
"new",
"IllegalStateException",
"(",
"\"Output linked to wrong parent transaction?\"",
")",
";",
"}"
] | Gets the index of this output in the parent transaction, or throws if this output is free standing. Iterates
over the parents list to discover this. | [
"Gets",
"the",
"index",
"of",
"this",
"output",
"in",
"the",
"parent",
"transaction",
"or",
"throws",
"if",
"this",
"output",
"is",
"free",
"standing",
".",
"Iterates",
"over",
"the",
"parents",
"list",
"to",
"discover",
"this",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/TransactionOutput.java#L175-L182 |
23,506 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/TransactionOutput.java | TransactionOutput.markAsSpent | public void markAsSpent(TransactionInput input) {
checkState(availableForSpending);
availableForSpending = false;
spentBy = input;
if (parent != null)
if (log.isDebugEnabled()) log.debug("Marked {}:{} as spent by {}", getParentTransactionHash(), getIndex(), input);
else
if (log.isDebugEnabled()) log.debug("Marked floating output as spent by {}", input);
} | java | public void markAsSpent(TransactionInput input) {
checkState(availableForSpending);
availableForSpending = false;
spentBy = input;
if (parent != null)
if (log.isDebugEnabled()) log.debug("Marked {}:{} as spent by {}", getParentTransactionHash(), getIndex(), input);
else
if (log.isDebugEnabled()) log.debug("Marked floating output as spent by {}", input);
} | [
"public",
"void",
"markAsSpent",
"(",
"TransactionInput",
"input",
")",
"{",
"checkState",
"(",
"availableForSpending",
")",
";",
"availableForSpending",
"=",
"false",
";",
"spentBy",
"=",
"input",
";",
"if",
"(",
"parent",
"!=",
"null",
")",
"if",
"(",
"log",
".",
"isDebugEnabled",
"(",
")",
")",
"log",
".",
"debug",
"(",
"\"Marked {}:{} as spent by {}\"",
",",
"getParentTransactionHash",
"(",
")",
",",
"getIndex",
"(",
")",
",",
"input",
")",
";",
"else",
"if",
"(",
"log",
".",
"isDebugEnabled",
"(",
")",
")",
"log",
".",
"debug",
"(",
"\"Marked floating output as spent by {}\"",
",",
"input",
")",
";",
"}"
] | Sets this objects availableForSpending flag to false and the spentBy pointer to the given input.
If the input is null, it means this output was signed over to somebody else rather than one of our own keys.
@throws IllegalStateException if the transaction was already marked as spent. | [
"Sets",
"this",
"objects",
"availableForSpending",
"flag",
"to",
"false",
"and",
"the",
"spentBy",
"pointer",
"to",
"the",
"given",
"input",
".",
"If",
"the",
"input",
"is",
"null",
"it",
"means",
"this",
"output",
"was",
"signed",
"over",
"to",
"somebody",
"else",
"rather",
"than",
"one",
"of",
"our",
"own",
"keys",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/TransactionOutput.java#L242-L250 |
23,507 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/TransactionOutput.java | TransactionOutput.getParentTransactionDepthInBlocks | public int getParentTransactionDepthInBlocks() {
if (getParentTransaction() != null) {
TransactionConfidence confidence = getParentTransaction().getConfidence();
if (confidence.getConfidenceType() == TransactionConfidence.ConfidenceType.BUILDING) {
return confidence.getDepthInBlocks();
}
}
return -1;
} | java | public int getParentTransactionDepthInBlocks() {
if (getParentTransaction() != null) {
TransactionConfidence confidence = getParentTransaction().getConfidence();
if (confidence.getConfidenceType() == TransactionConfidence.ConfidenceType.BUILDING) {
return confidence.getDepthInBlocks();
}
}
return -1;
} | [
"public",
"int",
"getParentTransactionDepthInBlocks",
"(",
")",
"{",
"if",
"(",
"getParentTransaction",
"(",
")",
"!=",
"null",
")",
"{",
"TransactionConfidence",
"confidence",
"=",
"getParentTransaction",
"(",
")",
".",
"getConfidence",
"(",
")",
";",
"if",
"(",
"confidence",
".",
"getConfidenceType",
"(",
")",
"==",
"TransactionConfidence",
".",
"ConfidenceType",
".",
"BUILDING",
")",
"{",
"return",
"confidence",
".",
"getDepthInBlocks",
"(",
")",
";",
"}",
"}",
"return",
"-",
"1",
";",
"}"
] | Returns the depth in blocks of the parent tx.
<p>If the transaction appears in the top block, the depth is one. If it's anything else (pending, dead, unknown)
then -1.</p>
@return The tx depth or -1. | [
"Returns",
"the",
"depth",
"in",
"blocks",
"of",
"the",
"parent",
"tx",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/TransactionOutput.java#L386-L394 |
23,508 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/TransactionOutput.java | TransactionOutput.duplicateDetached | public TransactionOutput duplicateDetached() {
return new TransactionOutput(params, null, Coin.valueOf(value), Arrays.copyOf(scriptBytes, scriptBytes.length));
} | java | public TransactionOutput duplicateDetached() {
return new TransactionOutput(params, null, Coin.valueOf(value), Arrays.copyOf(scriptBytes, scriptBytes.length));
} | [
"public",
"TransactionOutput",
"duplicateDetached",
"(",
")",
"{",
"return",
"new",
"TransactionOutput",
"(",
"params",
",",
"null",
",",
"Coin",
".",
"valueOf",
"(",
"value",
")",
",",
"Arrays",
".",
"copyOf",
"(",
"scriptBytes",
",",
"scriptBytes",
".",
"length",
")",
")",
";",
"}"
] | Returns a copy of the output detached from its containing transaction, if need be. | [
"Returns",
"a",
"copy",
"of",
"the",
"output",
"detached",
"from",
"its",
"containing",
"transaction",
"if",
"need",
"be",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/TransactionOutput.java#L405-L407 |
23,509 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/AlertMessage.java | AlertMessage.isSignatureValid | public boolean isSignatureValid() {
try {
return ECKey.verify(Sha256Hash.hashTwice(content), signature, params.getAlertSigningKey());
} catch (SignatureDecodeException e) {
return false;
}
} | java | public boolean isSignatureValid() {
try {
return ECKey.verify(Sha256Hash.hashTwice(content), signature, params.getAlertSigningKey());
} catch (SignatureDecodeException e) {
return false;
}
} | [
"public",
"boolean",
"isSignatureValid",
"(",
")",
"{",
"try",
"{",
"return",
"ECKey",
".",
"verify",
"(",
"Sha256Hash",
".",
"hashTwice",
"(",
"content",
")",
",",
"signature",
",",
"params",
".",
"getAlertSigningKey",
"(",
")",
")",
";",
"}",
"catch",
"(",
"SignatureDecodeException",
"e",
")",
"{",
"return",
"false",
";",
"}",
"}"
] | Returns true if the digital signature attached to the message verifies. Don't do anything with the alert if it
doesn't verify, because that would allow arbitrary attackers to spam your users. | [
"Returns",
"true",
"if",
"the",
"digital",
"signature",
"attached",
"to",
"the",
"message",
"verifies",
".",
"Don",
"t",
"do",
"anything",
"with",
"the",
"alert",
"if",
"it",
"doesn",
"t",
"verify",
"because",
"that",
"would",
"allow",
"arbitrary",
"attackers",
"to",
"spam",
"your",
"users",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/AlertMessage.java#L117-L123 |
23,510 | bitcoinj/bitcoinj | wallettemplate/src/main/java/wallettemplate/utils/easing/EasingInterpolator.java | EasingInterpolator.curve | @Override
protected final double curve(final double v) {
switch (easingMode.get()) {
case EASE_IN:
return baseCurve(v);
case EASE_OUT:
return 1 - baseCurve(1 - v);
case EASE_BOTH:
if (v <= 0.5) {
return baseCurve(2 * v) / 2;
} else {
return (2 - baseCurve(2 * (1 - v))) / 2;
}
}
return baseCurve(v);
} | java | @Override
protected final double curve(final double v) {
switch (easingMode.get()) {
case EASE_IN:
return baseCurve(v);
case EASE_OUT:
return 1 - baseCurve(1 - v);
case EASE_BOTH:
if (v <= 0.5) {
return baseCurve(2 * v) / 2;
} else {
return (2 - baseCurve(2 * (1 - v))) / 2;
}
}
return baseCurve(v);
} | [
"@",
"Override",
"protected",
"final",
"double",
"curve",
"(",
"final",
"double",
"v",
")",
"{",
"switch",
"(",
"easingMode",
".",
"get",
"(",
")",
")",
"{",
"case",
"EASE_IN",
":",
"return",
"baseCurve",
"(",
"v",
")",
";",
"case",
"EASE_OUT",
":",
"return",
"1",
"-",
"baseCurve",
"(",
"1",
"-",
"v",
")",
";",
"case",
"EASE_BOTH",
":",
"if",
"(",
"v",
"<=",
"0.5",
")",
"{",
"return",
"baseCurve",
"(",
"2",
"*",
"v",
")",
"/",
"2",
";",
"}",
"else",
"{",
"return",
"(",
"2",
"-",
"baseCurve",
"(",
"2",
"*",
"(",
"1",
"-",
"v",
")",
")",
")",
"/",
"2",
";",
"}",
"}",
"return",
"baseCurve",
"(",
"v",
")",
";",
"}"
] | Curves the function depending on the easing mode.
@param v The normalized value (between 0 and 1).
@return The resulting value of the function. | [
"Curves",
"the",
"function",
"depending",
"on",
"the",
"easing",
"mode",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/wallettemplate/src/main/java/wallettemplate/utils/easing/EasingInterpolator.java#L99-L115 |
23,511 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/Message.java | Message.bitcoinSerialize | public final void bitcoinSerialize(OutputStream stream) throws IOException {
// 1st check for cached bytes.
if (payload != null && length != UNKNOWN_LENGTH) {
stream.write(payload, offset, length);
return;
}
bitcoinSerializeToStream(stream);
} | java | public final void bitcoinSerialize(OutputStream stream) throws IOException {
// 1st check for cached bytes.
if (payload != null && length != UNKNOWN_LENGTH) {
stream.write(payload, offset, length);
return;
}
bitcoinSerializeToStream(stream);
} | [
"public",
"final",
"void",
"bitcoinSerialize",
"(",
"OutputStream",
"stream",
")",
"throws",
"IOException",
"{",
"// 1st check for cached bytes.",
"if",
"(",
"payload",
"!=",
"null",
"&&",
"length",
"!=",
"UNKNOWN_LENGTH",
")",
"{",
"stream",
".",
"write",
"(",
"payload",
",",
"offset",
",",
"length",
")",
";",
"return",
";",
"}",
"bitcoinSerializeToStream",
"(",
"stream",
")",
";",
"}"
] | Serialize this message to the provided OutputStream using the bitcoin wire format.
@param stream
@throws IOException | [
"Serialize",
"this",
"message",
"to",
"the",
"provided",
"OutputStream",
"using",
"the",
"bitcoin",
"wire",
"format",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/Message.java#L259-L267 |
23,512 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/Message.java | Message.readObject | private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException {
in.defaultReadObject();
if (null != params) {
this.serializer = params.getDefaultSerializer();
}
} | java | private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException {
in.defaultReadObject();
if (null != params) {
this.serializer = params.getDefaultSerializer();
}
} | [
"private",
"void",
"readObject",
"(",
"ObjectInputStream",
"in",
")",
"throws",
"IOException",
",",
"ClassNotFoundException",
"{",
"in",
".",
"defaultReadObject",
"(",
")",
";",
"if",
"(",
"null",
"!=",
"params",
")",
"{",
"this",
".",
"serializer",
"=",
"params",
".",
"getDefaultSerializer",
"(",
")",
";",
"}",
"}"
] | Set the serializer for this message when deserialized by Java. | [
"Set",
"the",
"serializer",
"for",
"this",
"message",
"when",
"deserialized",
"by",
"Java",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/Message.java#L374-L380 |
23,513 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/BitcoinSerializer.java | BitcoinSerializer.deserialize | @Override
public Message deserialize(ByteBuffer in) throws ProtocolException, IOException {
// A Bitcoin protocol message has the following format.
//
// - 4 byte magic number: 0xfabfb5da for the testnet or
// 0xf9beb4d9 for production
// - 12 byte command in ASCII
// - 4 byte payload size
// - 4 byte checksum
// - Payload data
//
// The checksum is the first 4 bytes of a SHA256 hash of the message payload. It isn't
// present for all messages, notably, the first one on a connection.
//
// Bitcoin Core ignores garbage before the magic header bytes. We have to do the same because
// sometimes it sends us stuff that isn't part of any message.
seekPastMagicBytes(in);
BitcoinPacketHeader header = new BitcoinPacketHeader(in);
// Now try to read the whole message.
return deserializePayload(header, in);
} | java | @Override
public Message deserialize(ByteBuffer in) throws ProtocolException, IOException {
// A Bitcoin protocol message has the following format.
//
// - 4 byte magic number: 0xfabfb5da for the testnet or
// 0xf9beb4d9 for production
// - 12 byte command in ASCII
// - 4 byte payload size
// - 4 byte checksum
// - Payload data
//
// The checksum is the first 4 bytes of a SHA256 hash of the message payload. It isn't
// present for all messages, notably, the first one on a connection.
//
// Bitcoin Core ignores garbage before the magic header bytes. We have to do the same because
// sometimes it sends us stuff that isn't part of any message.
seekPastMagicBytes(in);
BitcoinPacketHeader header = new BitcoinPacketHeader(in);
// Now try to read the whole message.
return deserializePayload(header, in);
} | [
"@",
"Override",
"public",
"Message",
"deserialize",
"(",
"ByteBuffer",
"in",
")",
"throws",
"ProtocolException",
",",
"IOException",
"{",
"// A Bitcoin protocol message has the following format.",
"//",
"// - 4 byte magic number: 0xfabfb5da for the testnet or",
"// 0xf9beb4d9 for production",
"// - 12 byte command in ASCII",
"// - 4 byte payload size",
"// - 4 byte checksum",
"// - Payload data",
"//",
"// The checksum is the first 4 bytes of a SHA256 hash of the message payload. It isn't",
"// present for all messages, notably, the first one on a connection.",
"//",
"// Bitcoin Core ignores garbage before the magic header bytes. We have to do the same because",
"// sometimes it sends us stuff that isn't part of any message.",
"seekPastMagicBytes",
"(",
"in",
")",
";",
"BitcoinPacketHeader",
"header",
"=",
"new",
"BitcoinPacketHeader",
"(",
"in",
")",
";",
"// Now try to read the whole message.",
"return",
"deserializePayload",
"(",
"header",
",",
"in",
")",
";",
"}"
] | Reads a message from the given ByteBuffer and returns it. | [
"Reads",
"a",
"message",
"from",
"the",
"given",
"ByteBuffer",
"and",
"returns",
"it",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/BitcoinSerializer.java#L129-L149 |
23,514 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/BitcoinSerializer.java | BitcoinSerializer.makeAddressMessage | @Override
public AddressMessage makeAddressMessage(byte[] payloadBytes, int length) throws ProtocolException {
return new AddressMessage(params, payloadBytes, this, length);
} | java | @Override
public AddressMessage makeAddressMessage(byte[] payloadBytes, int length) throws ProtocolException {
return new AddressMessage(params, payloadBytes, this, length);
} | [
"@",
"Override",
"public",
"AddressMessage",
"makeAddressMessage",
"(",
"byte",
"[",
"]",
"payloadBytes",
",",
"int",
"length",
")",
"throws",
"ProtocolException",
"{",
"return",
"new",
"AddressMessage",
"(",
"params",
",",
"payloadBytes",
",",
"this",
",",
"length",
")",
";",
"}"
] | Make an address message from the payload. Extension point for alternative
serialization format support. | [
"Make",
"an",
"address",
"message",
"from",
"the",
"payload",
".",
"Extension",
"point",
"for",
"alternative",
"serialization",
"format",
"support",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/BitcoinSerializer.java#L254-L257 |
23,515 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/BitcoinSerializer.java | BitcoinSerializer.makeBlock | @Override
public Block makeBlock(final byte[] payloadBytes, final int offset, final int length) throws ProtocolException {
return new Block(params, payloadBytes, offset, this, length);
} | java | @Override
public Block makeBlock(final byte[] payloadBytes, final int offset, final int length) throws ProtocolException {
return new Block(params, payloadBytes, offset, this, length);
} | [
"@",
"Override",
"public",
"Block",
"makeBlock",
"(",
"final",
"byte",
"[",
"]",
"payloadBytes",
",",
"final",
"int",
"offset",
",",
"final",
"int",
"length",
")",
"throws",
"ProtocolException",
"{",
"return",
"new",
"Block",
"(",
"params",
",",
"payloadBytes",
",",
"offset",
",",
"this",
",",
"length",
")",
";",
"}"
] | Make a block from the payload. Extension point for alternative
serialization format support. | [
"Make",
"a",
"block",
"from",
"the",
"payload",
".",
"Extension",
"point",
"for",
"alternative",
"serialization",
"format",
"support",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/BitcoinSerializer.java#L272-L275 |
23,516 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/BitcoinSerializer.java | BitcoinSerializer.makeInventoryMessage | @Override
public InventoryMessage makeInventoryMessage(byte[] payloadBytes, int length) throws ProtocolException {
return new InventoryMessage(params, payloadBytes, this, length);
} | java | @Override
public InventoryMessage makeInventoryMessage(byte[] payloadBytes, int length) throws ProtocolException {
return new InventoryMessage(params, payloadBytes, this, length);
} | [
"@",
"Override",
"public",
"InventoryMessage",
"makeInventoryMessage",
"(",
"byte",
"[",
"]",
"payloadBytes",
",",
"int",
"length",
")",
"throws",
"ProtocolException",
"{",
"return",
"new",
"InventoryMessage",
"(",
"params",
",",
"payloadBytes",
",",
"this",
",",
"length",
")",
";",
"}"
] | Make an inventory message from the payload. Extension point for alternative
serialization format support. | [
"Make",
"an",
"inventory",
"message",
"from",
"the",
"payload",
".",
"Extension",
"point",
"for",
"alternative",
"serialization",
"format",
"support",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/BitcoinSerializer.java#L299-L302 |
23,517 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/listeners/DownloadProgressTracker.java | DownloadProgressTracker.progress | protected void progress(double pct, int blocksSoFar, Date date) {
log.info(String.format(Locale.US, "Chain download %d%% done with %d blocks to go, block date %s", (int) pct, blocksSoFar,
Utils.dateTimeFormat(date)));
} | java | protected void progress(double pct, int blocksSoFar, Date date) {
log.info(String.format(Locale.US, "Chain download %d%% done with %d blocks to go, block date %s", (int) pct, blocksSoFar,
Utils.dateTimeFormat(date)));
} | [
"protected",
"void",
"progress",
"(",
"double",
"pct",
",",
"int",
"blocksSoFar",
",",
"Date",
"date",
")",
"{",
"log",
".",
"info",
"(",
"String",
".",
"format",
"(",
"Locale",
".",
"US",
",",
"\"Chain download %d%% done with %d blocks to go, block date %s\"",
",",
"(",
"int",
")",
"pct",
",",
"blocksSoFar",
",",
"Utils",
".",
"dateTimeFormat",
"(",
"date",
")",
")",
")",
";",
"}"
] | Called when download progress is made.
@param pct the percentage of chain downloaded, estimated
@param date the date of the last block downloaded | [
"Called",
"when",
"download",
"progress",
"is",
"made",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/listeners/DownloadProgressTracker.java#L94-L97 |
23,518 | bitcoinj/bitcoinj | wallettemplate/src/main/java/wallettemplate/SendMoneyController.java | SendMoneyController.initialize | public void initialize() {
Coin balance = Main.bitcoin.wallet().getBalance();
checkState(!balance.isZero());
new BitcoinAddressValidator(Main.params, address, sendBtn);
new TextFieldValidator(amountEdit, text ->
!WTUtils.didThrow(() -> checkState(Coin.parseCoin(text).compareTo(balance) <= 0)));
amountEdit.setText(balance.toPlainString());
address.setPromptText(Address.fromKey(Main.params, new ECKey(), Main.PREFERRED_OUTPUT_SCRIPT_TYPE).toString());
} | java | public void initialize() {
Coin balance = Main.bitcoin.wallet().getBalance();
checkState(!balance.isZero());
new BitcoinAddressValidator(Main.params, address, sendBtn);
new TextFieldValidator(amountEdit, text ->
!WTUtils.didThrow(() -> checkState(Coin.parseCoin(text).compareTo(balance) <= 0)));
amountEdit.setText(balance.toPlainString());
address.setPromptText(Address.fromKey(Main.params, new ECKey(), Main.PREFERRED_OUTPUT_SCRIPT_TYPE).toString());
} | [
"public",
"void",
"initialize",
"(",
")",
"{",
"Coin",
"balance",
"=",
"Main",
".",
"bitcoin",
".",
"wallet",
"(",
")",
".",
"getBalance",
"(",
")",
";",
"checkState",
"(",
"!",
"balance",
".",
"isZero",
"(",
")",
")",
";",
"new",
"BitcoinAddressValidator",
"(",
"Main",
".",
"params",
",",
"address",
",",
"sendBtn",
")",
";",
"new",
"TextFieldValidator",
"(",
"amountEdit",
",",
"text",
"->",
"!",
"WTUtils",
".",
"didThrow",
"(",
"(",
")",
"->",
"checkState",
"(",
"Coin",
".",
"parseCoin",
"(",
"text",
")",
".",
"compareTo",
"(",
"balance",
")",
"<=",
"0",
")",
")",
")",
";",
"amountEdit",
".",
"setText",
"(",
"balance",
".",
"toPlainString",
"(",
")",
")",
";",
"address",
".",
"setPromptText",
"(",
"Address",
".",
"fromKey",
"(",
"Main",
".",
"params",
",",
"new",
"ECKey",
"(",
")",
",",
"Main",
".",
"PREFERRED_OUTPUT_SCRIPT_TYPE",
")",
".",
"toString",
"(",
")",
")",
";",
"}"
] | Called by FXMLLoader | [
"Called",
"by",
"FXMLLoader"
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/wallettemplate/src/main/java/wallettemplate/SendMoneyController.java#L56-L64 |
23,519 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/VarInt.java | VarInt.encode | public byte[] encode() {
byte[] bytes;
switch (sizeOf(value)) {
case 1:
return new byte[]{(byte) value};
case 3:
bytes = new byte[3];
bytes[0] = (byte) 253;
Utils.uint16ToByteArrayLE((int) value, bytes, 1);
return bytes;
case 5:
bytes = new byte[5];
bytes[0] = (byte) 254;
Utils.uint32ToByteArrayLE(value, bytes, 1);
return bytes;
default:
bytes = new byte[9];
bytes[0] = (byte) 255;
Utils.int64ToByteArrayLE(value, bytes, 1);
return bytes;
}
} | java | public byte[] encode() {
byte[] bytes;
switch (sizeOf(value)) {
case 1:
return new byte[]{(byte) value};
case 3:
bytes = new byte[3];
bytes[0] = (byte) 253;
Utils.uint16ToByteArrayLE((int) value, bytes, 1);
return bytes;
case 5:
bytes = new byte[5];
bytes[0] = (byte) 254;
Utils.uint32ToByteArrayLE(value, bytes, 1);
return bytes;
default:
bytes = new byte[9];
bytes[0] = (byte) 255;
Utils.int64ToByteArrayLE(value, bytes, 1);
return bytes;
}
} | [
"public",
"byte",
"[",
"]",
"encode",
"(",
")",
"{",
"byte",
"[",
"]",
"bytes",
";",
"switch",
"(",
"sizeOf",
"(",
"value",
")",
")",
"{",
"case",
"1",
":",
"return",
"new",
"byte",
"[",
"]",
"{",
"(",
"byte",
")",
"value",
"}",
";",
"case",
"3",
":",
"bytes",
"=",
"new",
"byte",
"[",
"3",
"]",
";",
"bytes",
"[",
"0",
"]",
"=",
"(",
"byte",
")",
"253",
";",
"Utils",
".",
"uint16ToByteArrayLE",
"(",
"(",
"int",
")",
"value",
",",
"bytes",
",",
"1",
")",
";",
"return",
"bytes",
";",
"case",
"5",
":",
"bytes",
"=",
"new",
"byte",
"[",
"5",
"]",
";",
"bytes",
"[",
"0",
"]",
"=",
"(",
"byte",
")",
"254",
";",
"Utils",
".",
"uint32ToByteArrayLE",
"(",
"value",
",",
"bytes",
",",
"1",
")",
";",
"return",
"bytes",
";",
"default",
":",
"bytes",
"=",
"new",
"byte",
"[",
"9",
"]",
";",
"bytes",
"[",
"0",
"]",
"=",
"(",
"byte",
")",
"255",
";",
"Utils",
".",
"int64ToByteArrayLE",
"(",
"value",
",",
"bytes",
",",
"1",
")",
";",
"return",
"bytes",
";",
"}",
"}"
] | Encodes the value into its minimal representation.
@return the minimal encoded bytes of the value | [
"Encodes",
"the",
"value",
"into",
"its",
"minimal",
"representation",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/VarInt.java#L93-L114 |
23,520 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/Context.java | Context.getOrCreate | public static Context getOrCreate(NetworkParameters params) {
Context context;
try {
context = get();
} catch (IllegalStateException e) {
log.warn("Implicitly creating context. This is a migration step and this message will eventually go away.");
context = new Context(params);
return context;
}
if (context.getParams() != params)
throw new IllegalStateException("Context does not match implicit network params: " + context.getParams() + " vs " + params);
return context;
} | java | public static Context getOrCreate(NetworkParameters params) {
Context context;
try {
context = get();
} catch (IllegalStateException e) {
log.warn("Implicitly creating context. This is a migration step and this message will eventually go away.");
context = new Context(params);
return context;
}
if (context.getParams() != params)
throw new IllegalStateException("Context does not match implicit network params: " + context.getParams() + " vs " + params);
return context;
} | [
"public",
"static",
"Context",
"getOrCreate",
"(",
"NetworkParameters",
"params",
")",
"{",
"Context",
"context",
";",
"try",
"{",
"context",
"=",
"get",
"(",
")",
";",
"}",
"catch",
"(",
"IllegalStateException",
"e",
")",
"{",
"log",
".",
"warn",
"(",
"\"Implicitly creating context. This is a migration step and this message will eventually go away.\"",
")",
";",
"context",
"=",
"new",
"Context",
"(",
"params",
")",
";",
"return",
"context",
";",
"}",
"if",
"(",
"context",
".",
"getParams",
"(",
")",
"!=",
"params",
")",
"throw",
"new",
"IllegalStateException",
"(",
"\"Context does not match implicit network params: \"",
"+",
"context",
".",
"getParams",
"(",
")",
"+",
"\" vs \"",
"+",
"params",
")",
";",
"return",
"context",
";",
"}"
] | A temporary internal shim designed to help us migrate internally in a way that doesn't wreck source compatibility. | [
"A",
"temporary",
"internal",
"shim",
"designed",
"to",
"help",
"us",
"migrate",
"internally",
"in",
"a",
"way",
"that",
"doesn",
"t",
"wreck",
"source",
"compatibility",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/Context.java#L131-L143 |
23,521 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/Block.java | Block.parseTransactions | protected void parseTransactions(final int transactionsOffset) throws ProtocolException {
cursor = transactionsOffset;
optimalEncodingMessageSize = HEADER_SIZE;
if (payload.length == cursor) {
// This message is just a header, it has no transactions.
transactionBytesValid = false;
return;
}
int numTransactions = (int) readVarInt();
optimalEncodingMessageSize += VarInt.sizeOf(numTransactions);
transactions = new ArrayList<>(Math.min(numTransactions, Utils.MAX_INITIAL_ARRAY_LENGTH));
for (int i = 0; i < numTransactions; i++) {
Transaction tx = new Transaction(params, payload, cursor, this, serializer, UNKNOWN_LENGTH, null);
// Label the transaction as coming from the P2P network, so code that cares where we first saw it knows.
tx.getConfidence().setSource(TransactionConfidence.Source.NETWORK);
transactions.add(tx);
cursor += tx.getMessageSize();
optimalEncodingMessageSize += tx.getOptimalEncodingMessageSize();
}
transactionBytesValid = serializer.isParseRetainMode();
} | java | protected void parseTransactions(final int transactionsOffset) throws ProtocolException {
cursor = transactionsOffset;
optimalEncodingMessageSize = HEADER_SIZE;
if (payload.length == cursor) {
// This message is just a header, it has no transactions.
transactionBytesValid = false;
return;
}
int numTransactions = (int) readVarInt();
optimalEncodingMessageSize += VarInt.sizeOf(numTransactions);
transactions = new ArrayList<>(Math.min(numTransactions, Utils.MAX_INITIAL_ARRAY_LENGTH));
for (int i = 0; i < numTransactions; i++) {
Transaction tx = new Transaction(params, payload, cursor, this, serializer, UNKNOWN_LENGTH, null);
// Label the transaction as coming from the P2P network, so code that cares where we first saw it knows.
tx.getConfidence().setSource(TransactionConfidence.Source.NETWORK);
transactions.add(tx);
cursor += tx.getMessageSize();
optimalEncodingMessageSize += tx.getOptimalEncodingMessageSize();
}
transactionBytesValid = serializer.isParseRetainMode();
} | [
"protected",
"void",
"parseTransactions",
"(",
"final",
"int",
"transactionsOffset",
")",
"throws",
"ProtocolException",
"{",
"cursor",
"=",
"transactionsOffset",
";",
"optimalEncodingMessageSize",
"=",
"HEADER_SIZE",
";",
"if",
"(",
"payload",
".",
"length",
"==",
"cursor",
")",
"{",
"// This message is just a header, it has no transactions.",
"transactionBytesValid",
"=",
"false",
";",
"return",
";",
"}",
"int",
"numTransactions",
"=",
"(",
"int",
")",
"readVarInt",
"(",
")",
";",
"optimalEncodingMessageSize",
"+=",
"VarInt",
".",
"sizeOf",
"(",
"numTransactions",
")",
";",
"transactions",
"=",
"new",
"ArrayList",
"<>",
"(",
"Math",
".",
"min",
"(",
"numTransactions",
",",
"Utils",
".",
"MAX_INITIAL_ARRAY_LENGTH",
")",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"numTransactions",
";",
"i",
"++",
")",
"{",
"Transaction",
"tx",
"=",
"new",
"Transaction",
"(",
"params",
",",
"payload",
",",
"cursor",
",",
"this",
",",
"serializer",
",",
"UNKNOWN_LENGTH",
",",
"null",
")",
";",
"// Label the transaction as coming from the P2P network, so code that cares where we first saw it knows.",
"tx",
".",
"getConfidence",
"(",
")",
".",
"setSource",
"(",
"TransactionConfidence",
".",
"Source",
".",
"NETWORK",
")",
";",
"transactions",
".",
"add",
"(",
"tx",
")",
";",
"cursor",
"+=",
"tx",
".",
"getMessageSize",
"(",
")",
";",
"optimalEncodingMessageSize",
"+=",
"tx",
".",
"getOptimalEncodingMessageSize",
"(",
")",
";",
"}",
"transactionBytesValid",
"=",
"serializer",
".",
"isParseRetainMode",
"(",
")",
";",
"}"
] | Parse transactions from the block.
@param transactionsOffset Offset of the transactions within the block.
Useful for non-Bitcoin chains where the block header may not be a fixed
size. | [
"Parse",
"transactions",
"from",
"the",
"block",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/Block.java#L230-L251 |
23,522 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/Block.java | Block.writeHeader | void writeHeader(OutputStream stream) throws IOException {
// try for cached write first
if (headerBytesValid && payload != null && payload.length >= offset + HEADER_SIZE) {
stream.write(payload, offset, HEADER_SIZE);
return;
}
// fall back to manual write
Utils.uint32ToByteStreamLE(version, stream);
stream.write(prevBlockHash.getReversedBytes());
stream.write(getMerkleRoot().getReversedBytes());
Utils.uint32ToByteStreamLE(time, stream);
Utils.uint32ToByteStreamLE(difficultyTarget, stream);
Utils.uint32ToByteStreamLE(nonce, stream);
} | java | void writeHeader(OutputStream stream) throws IOException {
// try for cached write first
if (headerBytesValid && payload != null && payload.length >= offset + HEADER_SIZE) {
stream.write(payload, offset, HEADER_SIZE);
return;
}
// fall back to manual write
Utils.uint32ToByteStreamLE(version, stream);
stream.write(prevBlockHash.getReversedBytes());
stream.write(getMerkleRoot().getReversedBytes());
Utils.uint32ToByteStreamLE(time, stream);
Utils.uint32ToByteStreamLE(difficultyTarget, stream);
Utils.uint32ToByteStreamLE(nonce, stream);
} | [
"void",
"writeHeader",
"(",
"OutputStream",
"stream",
")",
"throws",
"IOException",
"{",
"// try for cached write first",
"if",
"(",
"headerBytesValid",
"&&",
"payload",
"!=",
"null",
"&&",
"payload",
".",
"length",
">=",
"offset",
"+",
"HEADER_SIZE",
")",
"{",
"stream",
".",
"write",
"(",
"payload",
",",
"offset",
",",
"HEADER_SIZE",
")",
";",
"return",
";",
"}",
"// fall back to manual write",
"Utils",
".",
"uint32ToByteStreamLE",
"(",
"version",
",",
"stream",
")",
";",
"stream",
".",
"write",
"(",
"prevBlockHash",
".",
"getReversedBytes",
"(",
")",
")",
";",
"stream",
".",
"write",
"(",
"getMerkleRoot",
"(",
")",
".",
"getReversedBytes",
"(",
")",
")",
";",
"Utils",
".",
"uint32ToByteStreamLE",
"(",
"time",
",",
"stream",
")",
";",
"Utils",
".",
"uint32ToByteStreamLE",
"(",
"difficultyTarget",
",",
"stream",
")",
";",
"Utils",
".",
"uint32ToByteStreamLE",
"(",
"nonce",
",",
"stream",
")",
";",
"}"
] | default for testing | [
"default",
"for",
"testing"
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/Block.java#L279-L292 |
23,523 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/Block.java | Block.bitcoinSerialize | @Override
public byte[] bitcoinSerialize() {
// we have completely cached byte array.
if (headerBytesValid && transactionBytesValid) {
Preconditions.checkNotNull(payload, "Bytes should never be null if headerBytesValid && transactionBytesValid");
if (length == payload.length) {
return payload;
} else {
// byte array is offset so copy out the correct range.
byte[] buf = new byte[length];
System.arraycopy(payload, offset, buf, 0, length);
return buf;
}
}
// At least one of the two cacheable components is invalid
// so fall back to stream write since we can't be sure of the length.
ByteArrayOutputStream stream = new UnsafeByteArrayOutputStream(length == UNKNOWN_LENGTH ? HEADER_SIZE + guessTransactionsLength() : length);
try {
writeHeader(stream);
writeTransactions(stream);
} catch (IOException e) {
// Cannot happen, we are serializing to a memory stream.
}
return stream.toByteArray();
} | java | @Override
public byte[] bitcoinSerialize() {
// we have completely cached byte array.
if (headerBytesValid && transactionBytesValid) {
Preconditions.checkNotNull(payload, "Bytes should never be null if headerBytesValid && transactionBytesValid");
if (length == payload.length) {
return payload;
} else {
// byte array is offset so copy out the correct range.
byte[] buf = new byte[length];
System.arraycopy(payload, offset, buf, 0, length);
return buf;
}
}
// At least one of the two cacheable components is invalid
// so fall back to stream write since we can't be sure of the length.
ByteArrayOutputStream stream = new UnsafeByteArrayOutputStream(length == UNKNOWN_LENGTH ? HEADER_SIZE + guessTransactionsLength() : length);
try {
writeHeader(stream);
writeTransactions(stream);
} catch (IOException e) {
// Cannot happen, we are serializing to a memory stream.
}
return stream.toByteArray();
} | [
"@",
"Override",
"public",
"byte",
"[",
"]",
"bitcoinSerialize",
"(",
")",
"{",
"// we have completely cached byte array.",
"if",
"(",
"headerBytesValid",
"&&",
"transactionBytesValid",
")",
"{",
"Preconditions",
".",
"checkNotNull",
"(",
"payload",
",",
"\"Bytes should never be null if headerBytesValid && transactionBytesValid\"",
")",
";",
"if",
"(",
"length",
"==",
"payload",
".",
"length",
")",
"{",
"return",
"payload",
";",
"}",
"else",
"{",
"// byte array is offset so copy out the correct range.",
"byte",
"[",
"]",
"buf",
"=",
"new",
"byte",
"[",
"length",
"]",
";",
"System",
".",
"arraycopy",
"(",
"payload",
",",
"offset",
",",
"buf",
",",
"0",
",",
"length",
")",
";",
"return",
"buf",
";",
"}",
"}",
"// At least one of the two cacheable components is invalid",
"// so fall back to stream write since we can't be sure of the length.",
"ByteArrayOutputStream",
"stream",
"=",
"new",
"UnsafeByteArrayOutputStream",
"(",
"length",
"==",
"UNKNOWN_LENGTH",
"?",
"HEADER_SIZE",
"+",
"guessTransactionsLength",
"(",
")",
":",
"length",
")",
";",
"try",
"{",
"writeHeader",
"(",
"stream",
")",
";",
"writeTransactions",
"(",
"stream",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"// Cannot happen, we are serializing to a memory stream.",
"}",
"return",
"stream",
".",
"toByteArray",
"(",
")",
";",
"}"
] | Special handling to check if we have a valid byte array for both header
and transactions | [
"Special",
"handling",
"to",
"check",
"if",
"we",
"have",
"a",
"valid",
"byte",
"array",
"for",
"both",
"header",
"and",
"transactions"
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/Block.java#L317-L342 |
23,524 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/Block.java | Block.guessTransactionsLength | private int guessTransactionsLength() {
if (transactionBytesValid)
return payload.length - HEADER_SIZE;
if (transactions == null)
return 0;
int len = VarInt.sizeOf(transactions.size());
for (Transaction tx : transactions) {
// 255 is just a guess at an average tx length
len += tx.length == UNKNOWN_LENGTH ? 255 : tx.length;
}
return len;
} | java | private int guessTransactionsLength() {
if (transactionBytesValid)
return payload.length - HEADER_SIZE;
if (transactions == null)
return 0;
int len = VarInt.sizeOf(transactions.size());
for (Transaction tx : transactions) {
// 255 is just a guess at an average tx length
len += tx.length == UNKNOWN_LENGTH ? 255 : tx.length;
}
return len;
} | [
"private",
"int",
"guessTransactionsLength",
"(",
")",
"{",
"if",
"(",
"transactionBytesValid",
")",
"return",
"payload",
".",
"length",
"-",
"HEADER_SIZE",
";",
"if",
"(",
"transactions",
"==",
"null",
")",
"return",
"0",
";",
"int",
"len",
"=",
"VarInt",
".",
"sizeOf",
"(",
"transactions",
".",
"size",
"(",
")",
")",
";",
"for",
"(",
"Transaction",
"tx",
":",
"transactions",
")",
"{",
"// 255 is just a guess at an average tx length",
"len",
"+=",
"tx",
".",
"length",
"==",
"UNKNOWN_LENGTH",
"?",
"255",
":",
"tx",
".",
"length",
";",
"}",
"return",
"len",
";",
"}"
] | Provides a reasonable guess at the byte length of the transactions part of the block.
The returned value will be accurate in 99% of cases and in those cases where not will probably slightly
oversize.
This is used to preallocate the underlying byte array for a ByteArrayOutputStream. If the size is under the
real value the only penalty is resizing of the underlying byte array. | [
"Provides",
"a",
"reasonable",
"guess",
"at",
"the",
"byte",
"length",
"of",
"the",
"transactions",
"part",
"of",
"the",
"block",
".",
"The",
"returned",
"value",
"will",
"be",
"accurate",
"in",
"99%",
"of",
"cases",
"and",
"in",
"those",
"cases",
"where",
"not",
"will",
"probably",
"slightly",
"oversize",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/Block.java#L359-L370 |
23,525 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/Block.java | Block.calculateHash | private Sha256Hash calculateHash() {
try {
ByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(HEADER_SIZE);
writeHeader(bos);
return Sha256Hash.wrapReversed(Sha256Hash.hashTwice(bos.toByteArray()));
} catch (IOException e) {
throw new RuntimeException(e); // Cannot happen.
}
} | java | private Sha256Hash calculateHash() {
try {
ByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(HEADER_SIZE);
writeHeader(bos);
return Sha256Hash.wrapReversed(Sha256Hash.hashTwice(bos.toByteArray()));
} catch (IOException e) {
throw new RuntimeException(e); // Cannot happen.
}
} | [
"private",
"Sha256Hash",
"calculateHash",
"(",
")",
"{",
"try",
"{",
"ByteArrayOutputStream",
"bos",
"=",
"new",
"UnsafeByteArrayOutputStream",
"(",
"HEADER_SIZE",
")",
";",
"writeHeader",
"(",
"bos",
")",
";",
"return",
"Sha256Hash",
".",
"wrapReversed",
"(",
"Sha256Hash",
".",
"hashTwice",
"(",
"bos",
".",
"toByteArray",
"(",
")",
")",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"e",
")",
";",
"// Cannot happen.",
"}",
"}"
] | Calculates the block hash by serializing the block and hashing the
resulting bytes. | [
"Calculates",
"the",
"block",
"hash",
"by",
"serializing",
"the",
"block",
"and",
"hashing",
"the",
"resulting",
"bytes",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/Block.java#L402-L410 |
23,526 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/Block.java | Block.cloneAsHeader | public Block cloneAsHeader() {
Block block = new Block(params, BLOCK_VERSION_GENESIS);
copyBitcoinHeaderTo(block);
return block;
} | java | public Block cloneAsHeader() {
Block block = new Block(params, BLOCK_VERSION_GENESIS);
copyBitcoinHeaderTo(block);
return block;
} | [
"public",
"Block",
"cloneAsHeader",
"(",
")",
"{",
"Block",
"block",
"=",
"new",
"Block",
"(",
"params",
",",
"BLOCK_VERSION_GENESIS",
")",
";",
"copyBitcoinHeaderTo",
"(",
"block",
")",
";",
"return",
"block",
";",
"}"
] | Returns a copy of the block, but without any transactions. | [
"Returns",
"a",
"copy",
"of",
"the",
"block",
"but",
"without",
"any",
"transactions",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/Block.java#L452-L456 |
23,527 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/Block.java | Block.copyBitcoinHeaderTo | protected final void copyBitcoinHeaderTo(final Block block) {
block.nonce = nonce;
block.prevBlockHash = prevBlockHash;
block.merkleRoot = getMerkleRoot();
block.version = version;
block.time = time;
block.difficultyTarget = difficultyTarget;
block.transactions = null;
block.hash = getHash();
} | java | protected final void copyBitcoinHeaderTo(final Block block) {
block.nonce = nonce;
block.prevBlockHash = prevBlockHash;
block.merkleRoot = getMerkleRoot();
block.version = version;
block.time = time;
block.difficultyTarget = difficultyTarget;
block.transactions = null;
block.hash = getHash();
} | [
"protected",
"final",
"void",
"copyBitcoinHeaderTo",
"(",
"final",
"Block",
"block",
")",
"{",
"block",
".",
"nonce",
"=",
"nonce",
";",
"block",
".",
"prevBlockHash",
"=",
"prevBlockHash",
";",
"block",
".",
"merkleRoot",
"=",
"getMerkleRoot",
"(",
")",
";",
"block",
".",
"version",
"=",
"version",
";",
"block",
".",
"time",
"=",
"time",
";",
"block",
".",
"difficultyTarget",
"=",
"difficultyTarget",
";",
"block",
".",
"transactions",
"=",
"null",
";",
"block",
".",
"hash",
"=",
"getHash",
"(",
")",
";",
"}"
] | Copy the block without transactions into the provided empty block. | [
"Copy",
"the",
"block",
"without",
"transactions",
"into",
"the",
"provided",
"empty",
"block",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/Block.java#L459-L468 |
23,528 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/Block.java | Block.getDifficultyTargetAsInteger | public BigInteger getDifficultyTargetAsInteger() throws VerificationException {
BigInteger target = Utils.decodeCompactBits(difficultyTarget);
if (target.signum() <= 0 || target.compareTo(params.maxTarget) > 0)
throw new VerificationException("Difficulty target is bad: " + target.toString());
return target;
} | java | public BigInteger getDifficultyTargetAsInteger() throws VerificationException {
BigInteger target = Utils.decodeCompactBits(difficultyTarget);
if (target.signum() <= 0 || target.compareTo(params.maxTarget) > 0)
throw new VerificationException("Difficulty target is bad: " + target.toString());
return target;
} | [
"public",
"BigInteger",
"getDifficultyTargetAsInteger",
"(",
")",
"throws",
"VerificationException",
"{",
"BigInteger",
"target",
"=",
"Utils",
".",
"decodeCompactBits",
"(",
"difficultyTarget",
")",
";",
"if",
"(",
"target",
".",
"signum",
"(",
")",
"<=",
"0",
"||",
"target",
".",
"compareTo",
"(",
"params",
".",
"maxTarget",
")",
">",
"0",
")",
"throw",
"new",
"VerificationException",
"(",
"\"Difficulty target is bad: \"",
"+",
"target",
".",
"toString",
"(",
")",
")",
";",
"return",
"target",
";",
"}"
] | Returns the difficulty target as a 256 bit value that can be compared to a SHA-256 hash. Inside a block the
target is represented using a compact form. If this form decodes to a value that is out of bounds, an exception
is thrown. | [
"Returns",
"the",
"difficulty",
"target",
"as",
"a",
"256",
"bit",
"value",
"that",
"can",
"be",
"compared",
"to",
"a",
"SHA",
"-",
"256",
"hash",
".",
"Inside",
"a",
"block",
"the",
"target",
"is",
"represented",
"using",
"a",
"compact",
"form",
".",
"If",
"this",
"form",
"decodes",
"to",
"a",
"value",
"that",
"is",
"out",
"of",
"bounds",
"an",
"exception",
"is",
"thrown",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/Block.java#L526-L531 |
23,529 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/Block.java | Block.checkTransactions | private void checkTransactions(final int height, final EnumSet<VerifyFlag> flags)
throws VerificationException {
// The first transaction in a block must always be a coinbase transaction.
if (!transactions.get(0).isCoinBase())
throw new VerificationException("First tx is not coinbase");
if (flags.contains(Block.VerifyFlag.HEIGHT_IN_COINBASE) && height >= BLOCK_HEIGHT_GENESIS) {
transactions.get(0).checkCoinBaseHeight(height);
}
// The rest must not be.
for (int i = 1; i < transactions.size(); i++) {
if (transactions.get(i).isCoinBase())
throw new VerificationException("TX " + i + " is coinbase when it should not be.");
}
} | java | private void checkTransactions(final int height, final EnumSet<VerifyFlag> flags)
throws VerificationException {
// The first transaction in a block must always be a coinbase transaction.
if (!transactions.get(0).isCoinBase())
throw new VerificationException("First tx is not coinbase");
if (flags.contains(Block.VerifyFlag.HEIGHT_IN_COINBASE) && height >= BLOCK_HEIGHT_GENESIS) {
transactions.get(0).checkCoinBaseHeight(height);
}
// The rest must not be.
for (int i = 1; i < transactions.size(); i++) {
if (transactions.get(i).isCoinBase())
throw new VerificationException("TX " + i + " is coinbase when it should not be.");
}
} | [
"private",
"void",
"checkTransactions",
"(",
"final",
"int",
"height",
",",
"final",
"EnumSet",
"<",
"VerifyFlag",
">",
"flags",
")",
"throws",
"VerificationException",
"{",
"// The first transaction in a block must always be a coinbase transaction.",
"if",
"(",
"!",
"transactions",
".",
"get",
"(",
"0",
")",
".",
"isCoinBase",
"(",
")",
")",
"throw",
"new",
"VerificationException",
"(",
"\"First tx is not coinbase\"",
")",
";",
"if",
"(",
"flags",
".",
"contains",
"(",
"Block",
".",
"VerifyFlag",
".",
"HEIGHT_IN_COINBASE",
")",
"&&",
"height",
">=",
"BLOCK_HEIGHT_GENESIS",
")",
"{",
"transactions",
".",
"get",
"(",
"0",
")",
".",
"checkCoinBaseHeight",
"(",
"height",
")",
";",
"}",
"// The rest must not be.",
"for",
"(",
"int",
"i",
"=",
"1",
";",
"i",
"<",
"transactions",
".",
"size",
"(",
")",
";",
"i",
"++",
")",
"{",
"if",
"(",
"transactions",
".",
"get",
"(",
"i",
")",
".",
"isCoinBase",
"(",
")",
")",
"throw",
"new",
"VerificationException",
"(",
"\"TX \"",
"+",
"i",
"+",
"\" is coinbase when it should not be.\"",
")",
";",
"}",
"}"
] | Verify the transactions on a block.
@param height block height, if known, or -1 otherwise. If provided, used
to validate the coinbase input script of v2 and above blocks.
@throws VerificationException if there was an error verifying the block. | [
"Verify",
"the",
"transactions",
"on",
"a",
"block",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/Block.java#L686-L699 |
23,530 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/Block.java | Block.verifyTransactions | public void verifyTransactions(final int height, final EnumSet<VerifyFlag> flags) throws VerificationException {
// Now we need to check that the body of the block actually matches the headers. The network won't generate
// an invalid block, but if we didn't validate this then an untrusted man-in-the-middle could obtain the next
// valid block from the network and simply replace the transactions in it with their own fictional
// transactions that reference spent or non-existent inputs.
if (transactions.isEmpty())
throw new VerificationException("Block had no transactions");
if (this.getOptimalEncodingMessageSize() > MAX_BLOCK_SIZE)
throw new VerificationException("Block larger than MAX_BLOCK_SIZE");
checkTransactions(height, flags);
checkMerkleRoot();
checkSigOps();
for (Transaction transaction : transactions)
transaction.verify();
} | java | public void verifyTransactions(final int height, final EnumSet<VerifyFlag> flags) throws VerificationException {
// Now we need to check that the body of the block actually matches the headers. The network won't generate
// an invalid block, but if we didn't validate this then an untrusted man-in-the-middle could obtain the next
// valid block from the network and simply replace the transactions in it with their own fictional
// transactions that reference spent or non-existent inputs.
if (transactions.isEmpty())
throw new VerificationException("Block had no transactions");
if (this.getOptimalEncodingMessageSize() > MAX_BLOCK_SIZE)
throw new VerificationException("Block larger than MAX_BLOCK_SIZE");
checkTransactions(height, flags);
checkMerkleRoot();
checkSigOps();
for (Transaction transaction : transactions)
transaction.verify();
} | [
"public",
"void",
"verifyTransactions",
"(",
"final",
"int",
"height",
",",
"final",
"EnumSet",
"<",
"VerifyFlag",
">",
"flags",
")",
"throws",
"VerificationException",
"{",
"// Now we need to check that the body of the block actually matches the headers. The network won't generate",
"// an invalid block, but if we didn't validate this then an untrusted man-in-the-middle could obtain the next",
"// valid block from the network and simply replace the transactions in it with their own fictional",
"// transactions that reference spent or non-existent inputs.",
"if",
"(",
"transactions",
".",
"isEmpty",
"(",
")",
")",
"throw",
"new",
"VerificationException",
"(",
"\"Block had no transactions\"",
")",
";",
"if",
"(",
"this",
".",
"getOptimalEncodingMessageSize",
"(",
")",
">",
"MAX_BLOCK_SIZE",
")",
"throw",
"new",
"VerificationException",
"(",
"\"Block larger than MAX_BLOCK_SIZE\"",
")",
";",
"checkTransactions",
"(",
"height",
",",
"flags",
")",
";",
"checkMerkleRoot",
"(",
")",
";",
"checkSigOps",
"(",
")",
";",
"for",
"(",
"Transaction",
"transaction",
":",
"transactions",
")",
"transaction",
".",
"verify",
"(",
")",
";",
"}"
] | Checks the block contents
@param height block height, if known, or -1 otherwise. If valid, used
to validate the coinbase input script of v2 and above blocks.
@param flags flags to indicate which tests should be applied (i.e.
whether to test for height in the coinbase transaction).
@throws VerificationException if there was an error verifying the block. | [
"Checks",
"the",
"block",
"contents"
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/Block.java#L728-L742 |
23,531 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/Block.java | Block.verify | public void verify(final int height, final EnumSet<VerifyFlag> flags) throws VerificationException {
verifyHeader();
verifyTransactions(height, flags);
} | java | public void verify(final int height, final EnumSet<VerifyFlag> flags) throws VerificationException {
verifyHeader();
verifyTransactions(height, flags);
} | [
"public",
"void",
"verify",
"(",
"final",
"int",
"height",
",",
"final",
"EnumSet",
"<",
"VerifyFlag",
">",
"flags",
")",
"throws",
"VerificationException",
"{",
"verifyHeader",
"(",
")",
";",
"verifyTransactions",
"(",
"height",
",",
"flags",
")",
";",
"}"
] | Verifies both the header and that the transactions hash to the merkle root.
@param height block height, if known, or -1 otherwise.
@param flags flags to indicate which tests should be applied (i.e.
whether to test for height in the coinbase transaction).
@throws VerificationException if there was an error verifying the block. | [
"Verifies",
"both",
"the",
"header",
"and",
"that",
"the",
"transactions",
"hash",
"to",
"the",
"merkle",
"root",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/Block.java#L752-L755 |
23,532 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/Block.java | Block.addTransaction | void addTransaction(Transaction t, boolean runSanityChecks) {
unCacheTransactions();
if (transactions == null) {
transactions = new ArrayList<>();
}
t.setParent(this);
if (runSanityChecks && transactions.size() == 0 && !t.isCoinBase())
throw new RuntimeException("Attempted to add a non-coinbase transaction as the first transaction: " + t);
else if (runSanityChecks && transactions.size() > 0 && t.isCoinBase())
throw new RuntimeException("Attempted to add a coinbase transaction when there already is one: " + t);
transactions.add(t);
adjustLength(transactions.size(), t.length);
// Force a recalculation next time the values are needed.
merkleRoot = null;
hash = null;
} | java | void addTransaction(Transaction t, boolean runSanityChecks) {
unCacheTransactions();
if (transactions == null) {
transactions = new ArrayList<>();
}
t.setParent(this);
if (runSanityChecks && transactions.size() == 0 && !t.isCoinBase())
throw new RuntimeException("Attempted to add a non-coinbase transaction as the first transaction: " + t);
else if (runSanityChecks && transactions.size() > 0 && t.isCoinBase())
throw new RuntimeException("Attempted to add a coinbase transaction when there already is one: " + t);
transactions.add(t);
adjustLength(transactions.size(), t.length);
// Force a recalculation next time the values are needed.
merkleRoot = null;
hash = null;
} | [
"void",
"addTransaction",
"(",
"Transaction",
"t",
",",
"boolean",
"runSanityChecks",
")",
"{",
"unCacheTransactions",
"(",
")",
";",
"if",
"(",
"transactions",
"==",
"null",
")",
"{",
"transactions",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"}",
"t",
".",
"setParent",
"(",
"this",
")",
";",
"if",
"(",
"runSanityChecks",
"&&",
"transactions",
".",
"size",
"(",
")",
"==",
"0",
"&&",
"!",
"t",
".",
"isCoinBase",
"(",
")",
")",
"throw",
"new",
"RuntimeException",
"(",
"\"Attempted to add a non-coinbase transaction as the first transaction: \"",
"+",
"t",
")",
";",
"else",
"if",
"(",
"runSanityChecks",
"&&",
"transactions",
".",
"size",
"(",
")",
">",
"0",
"&&",
"t",
".",
"isCoinBase",
"(",
")",
")",
"throw",
"new",
"RuntimeException",
"(",
"\"Attempted to add a coinbase transaction when there already is one: \"",
"+",
"t",
")",
";",
"transactions",
".",
"add",
"(",
"t",
")",
";",
"adjustLength",
"(",
"transactions",
".",
"size",
"(",
")",
",",
"t",
".",
"length",
")",
";",
"// Force a recalculation next time the values are needed.",
"merkleRoot",
"=",
"null",
";",
"hash",
"=",
"null",
";",
"}"
] | Adds a transaction to this block, with or without checking the sanity of doing so | [
"Adds",
"a",
"transaction",
"to",
"this",
"block",
"with",
"or",
"without",
"checking",
"the",
"sanity",
"of",
"doing",
"so"
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/Block.java#L803-L818 |
23,533 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/Block.java | Block.getTransactions | @Nullable
public List<Transaction> getTransactions() {
return transactions == null ? null : ImmutableList.copyOf(transactions);
} | java | @Nullable
public List<Transaction> getTransactions() {
return transactions == null ? null : ImmutableList.copyOf(transactions);
} | [
"@",
"Nullable",
"public",
"List",
"<",
"Transaction",
">",
"getTransactions",
"(",
")",
"{",
"return",
"transactions",
"==",
"null",
"?",
"null",
":",
"ImmutableList",
".",
"copyOf",
"(",
"transactions",
")",
";",
"}"
] | Returns an immutable list of transactions held in this block, or null if this object represents just a header. | [
"Returns",
"an",
"immutable",
"list",
"of",
"transactions",
"held",
"in",
"this",
"block",
"or",
"null",
"if",
"this",
"object",
"represents",
"just",
"a",
"header",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/Block.java#L895-L898 |
23,534 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/Block.java | Block.createNextBlock | @VisibleForTesting
public Block createNextBlock(Address to, long version, long time, int blockHeight) {
return createNextBlock(to, version, null, time, pubkeyForTesting, FIFTY_COINS, blockHeight);
} | java | @VisibleForTesting
public Block createNextBlock(Address to, long version, long time, int blockHeight) {
return createNextBlock(to, version, null, time, pubkeyForTesting, FIFTY_COINS, blockHeight);
} | [
"@",
"VisibleForTesting",
"public",
"Block",
"createNextBlock",
"(",
"Address",
"to",
",",
"long",
"version",
",",
"long",
"time",
",",
"int",
"blockHeight",
")",
"{",
"return",
"createNextBlock",
"(",
"to",
",",
"version",
",",
"null",
",",
"time",
",",
"pubkeyForTesting",
",",
"FIFTY_COINS",
",",
"blockHeight",
")",
";",
"}"
] | Returns a solved block that builds on top of this one. This exists for unit tests. | [
"Returns",
"a",
"solved",
"block",
"that",
"builds",
"on",
"top",
"of",
"this",
"one",
".",
"This",
"exists",
"for",
"unit",
"tests",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/Block.java#L945-L948 |
23,535 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/PeerSocketHandler.java | PeerSocketHandler.close | public void close() {
lock.lock();
try {
if (writeTarget == null) {
closePending = true;
return;
}
} finally {
lock.unlock();
}
writeTarget.closeConnection();
} | java | public void close() {
lock.lock();
try {
if (writeTarget == null) {
closePending = true;
return;
}
} finally {
lock.unlock();
}
writeTarget.closeConnection();
} | [
"public",
"void",
"close",
"(",
")",
"{",
"lock",
".",
"lock",
"(",
")",
";",
"try",
"{",
"if",
"(",
"writeTarget",
"==",
"null",
")",
"{",
"closePending",
"=",
"true",
";",
"return",
";",
"}",
"}",
"finally",
"{",
"lock",
".",
"unlock",
"(",
")",
";",
"}",
"writeTarget",
".",
"closeConnection",
"(",
")",
";",
"}"
] | Closes the connection to the peer if one exists, or immediately closes the connection as soon as it opens | [
"Closes",
"the",
"connection",
"to",
"the",
"peer",
"if",
"one",
"exists",
"or",
"immediately",
"closes",
"the",
"connection",
"as",
"soon",
"as",
"it",
"opens"
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/PeerSocketHandler.java#L101-L112 |
23,536 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/PeerSocketHandler.java | PeerSocketHandler.exceptionCaught | private void exceptionCaught(Exception e) {
PeerAddress addr = getAddress();
String s = addr == null ? "?" : addr.toString();
if (e instanceof ConnectException || e instanceof IOException) {
// Short message for network errors
log.info(s + " - " + e.getMessage());
} else {
log.warn(s + " - ", e);
Thread.UncaughtExceptionHandler handler = Threading.uncaughtExceptionHandler;
if (handler != null)
handler.uncaughtException(Thread.currentThread(), e);
}
close();
} | java | private void exceptionCaught(Exception e) {
PeerAddress addr = getAddress();
String s = addr == null ? "?" : addr.toString();
if (e instanceof ConnectException || e instanceof IOException) {
// Short message for network errors
log.info(s + " - " + e.getMessage());
} else {
log.warn(s + " - ", e);
Thread.UncaughtExceptionHandler handler = Threading.uncaughtExceptionHandler;
if (handler != null)
handler.uncaughtException(Thread.currentThread(), e);
}
close();
} | [
"private",
"void",
"exceptionCaught",
"(",
"Exception",
"e",
")",
"{",
"PeerAddress",
"addr",
"=",
"getAddress",
"(",
")",
";",
"String",
"s",
"=",
"addr",
"==",
"null",
"?",
"\"?\"",
":",
"addr",
".",
"toString",
"(",
")",
";",
"if",
"(",
"e",
"instanceof",
"ConnectException",
"||",
"e",
"instanceof",
"IOException",
")",
"{",
"// Short message for network errors",
"log",
".",
"info",
"(",
"s",
"+",
"\" - \"",
"+",
"e",
".",
"getMessage",
"(",
")",
")",
";",
"}",
"else",
"{",
"log",
".",
"warn",
"(",
"s",
"+",
"\" - \"",
",",
"e",
")",
";",
"Thread",
".",
"UncaughtExceptionHandler",
"handler",
"=",
"Threading",
".",
"uncaughtExceptionHandler",
";",
"if",
"(",
"handler",
"!=",
"null",
")",
"handler",
".",
"uncaughtException",
"(",
"Thread",
".",
"currentThread",
"(",
")",
",",
"e",
")",
";",
"}",
"close",
"(",
")",
";",
"}"
] | Catch any exceptions, logging them and then closing the channel. | [
"Catch",
"any",
"exceptions",
"logging",
"them",
"and",
"then",
"closing",
"the",
"channel",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/PeerSocketHandler.java#L227-L241 |
23,537 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/kits/WalletAppKit.java | WalletAppKit.setPeerNodes | public WalletAppKit setPeerNodes(PeerAddress... addresses) {
checkState(state() == State.NEW, "Cannot call after startup");
this.peerAddresses = addresses;
return this;
} | java | public WalletAppKit setPeerNodes(PeerAddress... addresses) {
checkState(state() == State.NEW, "Cannot call after startup");
this.peerAddresses = addresses;
return this;
} | [
"public",
"WalletAppKit",
"setPeerNodes",
"(",
"PeerAddress",
"...",
"addresses",
")",
"{",
"checkState",
"(",
"state",
"(",
")",
"==",
"State",
".",
"NEW",
",",
"\"Cannot call after startup\"",
")",
";",
"this",
".",
"peerAddresses",
"=",
"addresses",
";",
"return",
"this",
";",
"}"
] | Will only connect to the given addresses. Cannot be called after startup. | [
"Will",
"only",
"connect",
"to",
"the",
"given",
"addresses",
".",
"Cannot",
"be",
"called",
"after",
"startup",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/kits/WalletAppKit.java#L122-L126 |
23,538 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/kits/WalletAppKit.java | WalletAppKit.connectToLocalHost | public WalletAppKit connectToLocalHost() {
try {
final InetAddress localHost = InetAddress.getLocalHost();
return setPeerNodes(new PeerAddress(params, localHost, params.getPort()));
} catch (UnknownHostException e) {
// Borked machine with no loopback adapter configured properly.
throw new RuntimeException(e);
}
} | java | public WalletAppKit connectToLocalHost() {
try {
final InetAddress localHost = InetAddress.getLocalHost();
return setPeerNodes(new PeerAddress(params, localHost, params.getPort()));
} catch (UnknownHostException e) {
// Borked machine with no loopback adapter configured properly.
throw new RuntimeException(e);
}
} | [
"public",
"WalletAppKit",
"connectToLocalHost",
"(",
")",
"{",
"try",
"{",
"final",
"InetAddress",
"localHost",
"=",
"InetAddress",
".",
"getLocalHost",
"(",
")",
";",
"return",
"setPeerNodes",
"(",
"new",
"PeerAddress",
"(",
"params",
",",
"localHost",
",",
"params",
".",
"getPort",
"(",
")",
")",
")",
";",
"}",
"catch",
"(",
"UnknownHostException",
"e",
")",
"{",
"// Borked machine with no loopback adapter configured properly.",
"throw",
"new",
"RuntimeException",
"(",
"e",
")",
";",
"}",
"}"
] | Will only connect to localhost. Cannot be called after startup. | [
"Will",
"only",
"connect",
"to",
"localhost",
".",
"Cannot",
"be",
"called",
"after",
"startup",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/kits/WalletAppKit.java#L129-L137 |
23,539 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/kits/WalletAppKit.java | WalletAppKit.setUserAgent | public WalletAppKit setUserAgent(String userAgent, String version) {
this.userAgent = checkNotNull(userAgent);
this.version = checkNotNull(version);
return this;
} | java | public WalletAppKit setUserAgent(String userAgent, String version) {
this.userAgent = checkNotNull(userAgent);
this.version = checkNotNull(version);
return this;
} | [
"public",
"WalletAppKit",
"setUserAgent",
"(",
"String",
"userAgent",
",",
"String",
"version",
")",
"{",
"this",
".",
"userAgent",
"=",
"checkNotNull",
"(",
"userAgent",
")",
";",
"this",
".",
"version",
"=",
"checkNotNull",
"(",
"version",
")",
";",
"return",
"this",
";",
"}"
] | Sets the string that will appear in the subver field of the version message.
@param userAgent A short string that should be the name of your app, e.g. "My Wallet"
@param version A short string that contains the version number, e.g. "1.0-BETA" | [
"Sets",
"the",
"string",
"that",
"will",
"appear",
"in",
"the",
"subver",
"field",
"of",
"the",
"version",
"message",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/kits/WalletAppKit.java#L190-L194 |
23,540 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/kits/WalletAppKit.java | WalletAppKit.isChainFileLocked | public boolean isChainFileLocked() throws IOException {
RandomAccessFile file2 = null;
try {
File file = new File(directory, filePrefix + ".spvchain");
if (!file.exists())
return false;
if (file.isDirectory())
return false;
file2 = new RandomAccessFile(file, "rw");
FileLock lock = file2.getChannel().tryLock();
if (lock == null)
return true;
lock.release();
return false;
} finally {
if (file2 != null)
file2.close();
}
} | java | public boolean isChainFileLocked() throws IOException {
RandomAccessFile file2 = null;
try {
File file = new File(directory, filePrefix + ".spvchain");
if (!file.exists())
return false;
if (file.isDirectory())
return false;
file2 = new RandomAccessFile(file, "rw");
FileLock lock = file2.getChannel().tryLock();
if (lock == null)
return true;
lock.release();
return false;
} finally {
if (file2 != null)
file2.close();
}
} | [
"public",
"boolean",
"isChainFileLocked",
"(",
")",
"throws",
"IOException",
"{",
"RandomAccessFile",
"file2",
"=",
"null",
";",
"try",
"{",
"File",
"file",
"=",
"new",
"File",
"(",
"directory",
",",
"filePrefix",
"+",
"\".spvchain\"",
")",
";",
"if",
"(",
"!",
"file",
".",
"exists",
"(",
")",
")",
"return",
"false",
";",
"if",
"(",
"file",
".",
"isDirectory",
"(",
")",
")",
"return",
"false",
";",
"file2",
"=",
"new",
"RandomAccessFile",
"(",
"file",
",",
"\"rw\"",
")",
";",
"FileLock",
"lock",
"=",
"file2",
".",
"getChannel",
"(",
")",
".",
"tryLock",
"(",
")",
";",
"if",
"(",
"lock",
"==",
"null",
")",
"return",
"true",
";",
"lock",
".",
"release",
"(",
")",
";",
"return",
"false",
";",
"}",
"finally",
"{",
"if",
"(",
"file2",
"!=",
"null",
")",
"file2",
".",
"close",
"(",
")",
";",
"}",
"}"
] | Tests to see if the spvchain file has an operating system file lock on it. Useful for checking if your app
is already running. If another copy of your app is running and you start the appkit anyway, an exception will
be thrown during the startup process. Returns false if the chain file does not exist or is a directory. | [
"Tests",
"to",
"see",
"if",
"the",
"spvchain",
"file",
"has",
"an",
"operating",
"system",
"file",
"lock",
"on",
"it",
".",
"Useful",
"for",
"checking",
"if",
"your",
"app",
"is",
"already",
"running",
".",
"If",
"another",
"copy",
"of",
"your",
"app",
"is",
"running",
"and",
"you",
"start",
"the",
"appkit",
"anyway",
"an",
"exception",
"will",
"be",
"thrown",
"during",
"the",
"startup",
"process",
".",
"Returns",
"false",
"if",
"the",
"chain",
"file",
"does",
"not",
"exist",
"or",
"is",
"a",
"directory",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/kits/WalletAppKit.java#L259-L277 |
23,541 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/net/AbstractTimeoutHandler.java | AbstractTimeoutHandler.resetTimeout | protected synchronized void resetTimeout() {
if (timeoutTask != null)
timeoutTask.cancel();
if (timeoutMillis == 0 || !timeoutEnabled)
return;
timeoutTask = new TimerTask() {
@Override
public void run() {
timeoutOccurred();
}
};
timeoutTimer.schedule(timeoutTask, timeoutMillis);
} | java | protected synchronized void resetTimeout() {
if (timeoutTask != null)
timeoutTask.cancel();
if (timeoutMillis == 0 || !timeoutEnabled)
return;
timeoutTask = new TimerTask() {
@Override
public void run() {
timeoutOccurred();
}
};
timeoutTimer.schedule(timeoutTask, timeoutMillis);
} | [
"protected",
"synchronized",
"void",
"resetTimeout",
"(",
")",
"{",
"if",
"(",
"timeoutTask",
"!=",
"null",
")",
"timeoutTask",
".",
"cancel",
"(",
")",
";",
"if",
"(",
"timeoutMillis",
"==",
"0",
"||",
"!",
"timeoutEnabled",
")",
"return",
";",
"timeoutTask",
"=",
"new",
"TimerTask",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"run",
"(",
")",
"{",
"timeoutOccurred",
"(",
")",
";",
"}",
"}",
";",
"timeoutTimer",
".",
"schedule",
"(",
"timeoutTask",
",",
"timeoutMillis",
")",
";",
"}"
] | Resets the current progress towards timeout to 0. | [
"Resets",
"the",
"current",
"progress",
"towards",
"timeout",
"to",
"0",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/net/AbstractTimeoutHandler.java#L67-L79 |
23,542 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/utils/VersionTally.java | VersionTally.add | public void add(final long version) {
versionWindow[versionWriteHead++] = version;
if (versionWriteHead == versionWindow.length) {
versionWriteHead = 0;
}
versionsStored++;
} | java | public void add(final long version) {
versionWindow[versionWriteHead++] = version;
if (versionWriteHead == versionWindow.length) {
versionWriteHead = 0;
}
versionsStored++;
} | [
"public",
"void",
"add",
"(",
"final",
"long",
"version",
")",
"{",
"versionWindow",
"[",
"versionWriteHead",
"++",
"]",
"=",
"version",
";",
"if",
"(",
"versionWriteHead",
"==",
"versionWindow",
".",
"length",
")",
"{",
"versionWriteHead",
"=",
"0",
";",
"}",
"versionsStored",
"++",
";",
"}"
] | Add a new block version to the tally, and return the count for that version
within the window.
@param version the block version to add. | [
"Add",
"a",
"new",
"block",
"version",
"to",
"the",
"tally",
"and",
"return",
"the",
"count",
"for",
"that",
"version",
"within",
"the",
"window",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/utils/VersionTally.java#L62-L68 |
23,543 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/utils/VersionTally.java | VersionTally.getCountAtOrAbove | public Integer getCountAtOrAbove(final long version) {
if (versionsStored < versionWindow.length) {
return null;
}
int count = 0;
for (int versionIdx = 0; versionIdx < versionWindow.length; versionIdx++) {
if (versionWindow[versionIdx] >= version) {
count++;
}
}
return count;
} | java | public Integer getCountAtOrAbove(final long version) {
if (versionsStored < versionWindow.length) {
return null;
}
int count = 0;
for (int versionIdx = 0; versionIdx < versionWindow.length; versionIdx++) {
if (versionWindow[versionIdx] >= version) {
count++;
}
}
return count;
} | [
"public",
"Integer",
"getCountAtOrAbove",
"(",
"final",
"long",
"version",
")",
"{",
"if",
"(",
"versionsStored",
"<",
"versionWindow",
".",
"length",
")",
"{",
"return",
"null",
";",
"}",
"int",
"count",
"=",
"0",
";",
"for",
"(",
"int",
"versionIdx",
"=",
"0",
";",
"versionIdx",
"<",
"versionWindow",
".",
"length",
";",
"versionIdx",
"++",
")",
"{",
"if",
"(",
"versionWindow",
"[",
"versionIdx",
"]",
">=",
"version",
")",
"{",
"count",
"++",
";",
"}",
"}",
"return",
"count",
";",
"}"
] | Get the count of blocks at or above the given version, within the window.
@param version the block version to query.
@return the count for the block version, or null if the window is not yet
full. | [
"Get",
"the",
"count",
"of",
"blocks",
"at",
"or",
"above",
"the",
"given",
"version",
"within",
"the",
"window",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/utils/VersionTally.java#L77-L89 |
23,544 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/utils/VersionTally.java | VersionTally.initialize | public void initialize(final BlockStore blockStore, final StoredBlock chainHead)
throws BlockStoreException {
StoredBlock versionBlock = chainHead;
final Stack<Long> versions = new Stack<>();
// We don't know how many blocks back we can go, so load what we can first
versions.push(versionBlock.getHeader().getVersion());
for (int headOffset = 0; headOffset < versionWindow.length; headOffset++) {
versionBlock = versionBlock.getPrev(blockStore);
if (null == versionBlock) {
break;
}
versions.push(versionBlock.getHeader().getVersion());
}
// Replay the versions into the tally
while (!versions.isEmpty()) {
add(versions.pop());
}
} | java | public void initialize(final BlockStore blockStore, final StoredBlock chainHead)
throws BlockStoreException {
StoredBlock versionBlock = chainHead;
final Stack<Long> versions = new Stack<>();
// We don't know how many blocks back we can go, so load what we can first
versions.push(versionBlock.getHeader().getVersion());
for (int headOffset = 0; headOffset < versionWindow.length; headOffset++) {
versionBlock = versionBlock.getPrev(blockStore);
if (null == versionBlock) {
break;
}
versions.push(versionBlock.getHeader().getVersion());
}
// Replay the versions into the tally
while (!versions.isEmpty()) {
add(versions.pop());
}
} | [
"public",
"void",
"initialize",
"(",
"final",
"BlockStore",
"blockStore",
",",
"final",
"StoredBlock",
"chainHead",
")",
"throws",
"BlockStoreException",
"{",
"StoredBlock",
"versionBlock",
"=",
"chainHead",
";",
"final",
"Stack",
"<",
"Long",
">",
"versions",
"=",
"new",
"Stack",
"<>",
"(",
")",
";",
"// We don't know how many blocks back we can go, so load what we can first",
"versions",
".",
"push",
"(",
"versionBlock",
".",
"getHeader",
"(",
")",
".",
"getVersion",
"(",
")",
")",
";",
"for",
"(",
"int",
"headOffset",
"=",
"0",
";",
"headOffset",
"<",
"versionWindow",
".",
"length",
";",
"headOffset",
"++",
")",
"{",
"versionBlock",
"=",
"versionBlock",
".",
"getPrev",
"(",
"blockStore",
")",
";",
"if",
"(",
"null",
"==",
"versionBlock",
")",
"{",
"break",
";",
"}",
"versions",
".",
"push",
"(",
"versionBlock",
".",
"getHeader",
"(",
")",
".",
"getVersion",
"(",
")",
")",
";",
"}",
"// Replay the versions into the tally",
"while",
"(",
"!",
"versions",
".",
"isEmpty",
"(",
")",
")",
"{",
"add",
"(",
"versions",
".",
"pop",
"(",
")",
")",
";",
"}",
"}"
] | Initialize the version tally from the block store. Note this does not
search backwards past the start of the block store, so if starting from
a checkpoint this may not fill the window.
@param blockStore block store to load blocks from.
@param chainHead current chain tip. | [
"Initialize",
"the",
"version",
"tally",
"from",
"the",
"block",
"store",
".",
"Note",
"this",
"does",
"not",
"search",
"backwards",
"past",
"the",
"start",
"of",
"the",
"block",
"store",
"so",
"if",
"starting",
"from",
"a",
"checkpoint",
"this",
"may",
"not",
"fill",
"the",
"window",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/utils/VersionTally.java#L99-L118 |
23,545 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/uri/BitcoinURI.java | BitcoinURI.putWithValidation | private void putWithValidation(String key, Object value) throws BitcoinURIParseException {
if (parameterMap.containsKey(key)) {
throw new BitcoinURIParseException(String.format(Locale.US, "'%s' is duplicated, URI is invalid", key));
} else {
parameterMap.put(key, value);
}
} | java | private void putWithValidation(String key, Object value) throws BitcoinURIParseException {
if (parameterMap.containsKey(key)) {
throw new BitcoinURIParseException(String.format(Locale.US, "'%s' is duplicated, URI is invalid", key));
} else {
parameterMap.put(key, value);
}
} | [
"private",
"void",
"putWithValidation",
"(",
"String",
"key",
",",
"Object",
"value",
")",
"throws",
"BitcoinURIParseException",
"{",
"if",
"(",
"parameterMap",
".",
"containsKey",
"(",
"key",
")",
")",
"{",
"throw",
"new",
"BitcoinURIParseException",
"(",
"String",
".",
"format",
"(",
"Locale",
".",
"US",
",",
"\"'%s' is duplicated, URI is invalid\"",
",",
"key",
")",
")",
";",
"}",
"else",
"{",
"parameterMap",
".",
"put",
"(",
"key",
",",
"value",
")",
";",
"}",
"}"
] | Put the value against the key in the map checking for duplication. This avoids address field overwrite etc.
@param key The key for the map
@param value The value to store | [
"Put",
"the",
"value",
"against",
"the",
"key",
"in",
"the",
"map",
"checking",
"for",
"duplication",
".",
"This",
"avoids",
"address",
"field",
"overwrite",
"etc",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/uri/BitcoinURI.java#L250-L256 |
23,546 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/uri/BitcoinURI.java | BitcoinURI.encodeURLString | static String encodeURLString(String stringToEncode) {
try {
return java.net.URLEncoder.encode(stringToEncode, "UTF-8").replace("+", ENCODED_SPACE_CHARACTER);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e); // can't happen
}
} | java | static String encodeURLString(String stringToEncode) {
try {
return java.net.URLEncoder.encode(stringToEncode, "UTF-8").replace("+", ENCODED_SPACE_CHARACTER);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e); // can't happen
}
} | [
"static",
"String",
"encodeURLString",
"(",
"String",
"stringToEncode",
")",
"{",
"try",
"{",
"return",
"java",
".",
"net",
".",
"URLEncoder",
".",
"encode",
"(",
"stringToEncode",
",",
"\"UTF-8\"",
")",
".",
"replace",
"(",
"\"+\"",
",",
"ENCODED_SPACE_CHARACTER",
")",
";",
"}",
"catch",
"(",
"UnsupportedEncodingException",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"e",
")",
";",
"// can't happen",
"}",
"}"
] | Encode a string using URL encoding
@param stringToEncode The string to URL encode | [
"Encode",
"a",
"string",
"using",
"URL",
"encoding"
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/uri/BitcoinURI.java#L413-L419 |
23,547 | bitcoinj/bitcoinj | wallettemplate/src/main/java/wallettemplate/utils/AlertWindowController.java | AlertWindowController.crashAlert | public void crashAlert(Stage stage, String crashMessage) {
messageLabel.setText("Unfortunately, we screwed up and the app crashed. Sorry about that!");
detailsLabel.setText(crashMessage);
cancelButton.setVisible(false);
actionButton.setVisible(false);
okButton.setOnAction(actionEvent -> stage.close());
} | java | public void crashAlert(Stage stage, String crashMessage) {
messageLabel.setText("Unfortunately, we screwed up and the app crashed. Sorry about that!");
detailsLabel.setText(crashMessage);
cancelButton.setVisible(false);
actionButton.setVisible(false);
okButton.setOnAction(actionEvent -> stage.close());
} | [
"public",
"void",
"crashAlert",
"(",
"Stage",
"stage",
",",
"String",
"crashMessage",
")",
"{",
"messageLabel",
".",
"setText",
"(",
"\"Unfortunately, we screwed up and the app crashed. Sorry about that!\"",
")",
";",
"detailsLabel",
".",
"setText",
"(",
"crashMessage",
")",
";",
"cancelButton",
".",
"setVisible",
"(",
"false",
")",
";",
"actionButton",
".",
"setVisible",
"(",
"false",
")",
";",
"okButton",
".",
"setOnAction",
"(",
"actionEvent",
"->",
"stage",
".",
"close",
"(",
")",
")",
";",
"}"
] | Initialize this alert dialog for information about a crash. | [
"Initialize",
"this",
"alert",
"dialog",
"for",
"information",
"about",
"a",
"crash",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/wallettemplate/src/main/java/wallettemplate/utils/AlertWindowController.java#L31-L38 |
23,548 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/protocols/channels/StoredPaymentChannelServerStates.java | StoredPaymentChannelServerStates.getBroadcaster | private TransactionBroadcaster getBroadcaster() {
try {
return broadcasterFuture.get(MAX_SECONDS_TO_WAIT_FOR_BROADCASTER_TO_BE_SET, TimeUnit.SECONDS);
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (ExecutionException e) {
throw new RuntimeException(e);
} catch (TimeoutException e) {
String err = "Transaction broadcaster not set";
log.error(err);
throw new RuntimeException(err,e);
}
} | java | private TransactionBroadcaster getBroadcaster() {
try {
return broadcasterFuture.get(MAX_SECONDS_TO_WAIT_FOR_BROADCASTER_TO_BE_SET, TimeUnit.SECONDS);
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (ExecutionException e) {
throw new RuntimeException(e);
} catch (TimeoutException e) {
String err = "Transaction broadcaster not set";
log.error(err);
throw new RuntimeException(err,e);
}
} | [
"private",
"TransactionBroadcaster",
"getBroadcaster",
"(",
")",
"{",
"try",
"{",
"return",
"broadcasterFuture",
".",
"get",
"(",
"MAX_SECONDS_TO_WAIT_FOR_BROADCASTER_TO_BE_SET",
",",
"TimeUnit",
".",
"SECONDS",
")",
";",
"}",
"catch",
"(",
"InterruptedException",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"e",
")",
";",
"}",
"catch",
"(",
"ExecutionException",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"e",
")",
";",
"}",
"catch",
"(",
"TimeoutException",
"e",
")",
"{",
"String",
"err",
"=",
"\"Transaction broadcaster not set\"",
";",
"log",
".",
"error",
"(",
"err",
")",
";",
"throw",
"new",
"RuntimeException",
"(",
"err",
",",
"e",
")",
";",
"}",
"}"
] | If the broadcaster has not been set for MAX_SECONDS_TO_WAIT_FOR_BROADCASTER_TO_BE_SET seconds, then
the programmer probably forgot to set it and we should throw exception. | [
"If",
"the",
"broadcaster",
"has",
"not",
"been",
"set",
"for",
"MAX_SECONDS_TO_WAIT_FOR_BROADCASTER_TO_BE_SET",
"seconds",
"then",
"the",
"programmer",
"probably",
"forgot",
"to",
"set",
"it",
"and",
"we",
"should",
"throw",
"exception",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/protocols/channels/StoredPaymentChannelServerStates.java#L136-L148 |
23,549 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/crypto/TransactionSignature.java | TransactionSignature.calcSigHashValue | public static int calcSigHashValue(Transaction.SigHash mode, boolean anyoneCanPay) {
Preconditions.checkArgument(SigHash.ALL == mode || SigHash.NONE == mode || SigHash.SINGLE == mode); // enforce compatibility since this code was made before the SigHash enum was updated
int sighashFlags = mode.value;
if (anyoneCanPay)
sighashFlags |= Transaction.SigHash.ANYONECANPAY.value;
return sighashFlags;
} | java | public static int calcSigHashValue(Transaction.SigHash mode, boolean anyoneCanPay) {
Preconditions.checkArgument(SigHash.ALL == mode || SigHash.NONE == mode || SigHash.SINGLE == mode); // enforce compatibility since this code was made before the SigHash enum was updated
int sighashFlags = mode.value;
if (anyoneCanPay)
sighashFlags |= Transaction.SigHash.ANYONECANPAY.value;
return sighashFlags;
} | [
"public",
"static",
"int",
"calcSigHashValue",
"(",
"Transaction",
".",
"SigHash",
"mode",
",",
"boolean",
"anyoneCanPay",
")",
"{",
"Preconditions",
".",
"checkArgument",
"(",
"SigHash",
".",
"ALL",
"==",
"mode",
"||",
"SigHash",
".",
"NONE",
"==",
"mode",
"||",
"SigHash",
".",
"SINGLE",
"==",
"mode",
")",
";",
"// enforce compatibility since this code was made before the SigHash enum was updated",
"int",
"sighashFlags",
"=",
"mode",
".",
"value",
";",
"if",
"(",
"anyoneCanPay",
")",
"sighashFlags",
"|=",
"Transaction",
".",
"SigHash",
".",
"ANYONECANPAY",
".",
"value",
";",
"return",
"sighashFlags",
";",
"}"
] | Calculates the byte used in the protocol to represent the combination of mode and anyoneCanPay. | [
"Calculates",
"the",
"byte",
"used",
"in",
"the",
"protocol",
"to",
"represent",
"the",
"combination",
"of",
"mode",
"and",
"anyoneCanPay",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/crypto/TransactionSignature.java#L71-L77 |
23,550 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/crypto/TransactionSignature.java | TransactionSignature.isEncodingCanonical | public static boolean isEncodingCanonical(byte[] signature) {
// See Bitcoin Core's IsCanonicalSignature, https://bitcointalk.org/index.php?topic=8392.msg127623#msg127623
// A canonical signature exists of: <30> <total len> <02> <len R> <R> <02> <len S> <S> <hashtype>
// Where R and S are not negative (their first byte has its highest bit not set), and not
// excessively padded (do not start with a 0 byte, unless an otherwise negative number follows,
// in which case a single 0 byte is necessary and even required).
// Empty signatures, while not strictly DER encoded, are allowed.
if (signature.length == 0)
return true;
if (signature.length < 9 || signature.length > 73)
return false;
int hashType = (signature[signature.length-1] & 0xff) & ~Transaction.SigHash.ANYONECANPAY.value; // mask the byte to prevent sign-extension hurting us
if (hashType < Transaction.SigHash.ALL.value || hashType > Transaction.SigHash.SINGLE.value)
return false;
// "wrong type" "wrong length marker"
if ((signature[0] & 0xff) != 0x30 || (signature[1] & 0xff) != signature.length-3)
return false;
int lenR = signature[3] & 0xff;
if (5 + lenR >= signature.length || lenR == 0)
return false;
int lenS = signature[5+lenR] & 0xff;
if (lenR + lenS + 7 != signature.length || lenS == 0)
return false;
// R value type mismatch R value negative
if (signature[4-2] != 0x02 || (signature[4] & 0x80) == 0x80)
return false;
if (lenR > 1 && signature[4] == 0x00 && (signature[4+1] & 0x80) != 0x80)
return false; // R value excessively padded
// S value type mismatch S value negative
if (signature[6 + lenR - 2] != 0x02 || (signature[6 + lenR] & 0x80) == 0x80)
return false;
if (lenS > 1 && signature[6 + lenR] == 0x00 && (signature[6 + lenR + 1] & 0x80) != 0x80)
return false; // S value excessively padded
return true;
} | java | public static boolean isEncodingCanonical(byte[] signature) {
// See Bitcoin Core's IsCanonicalSignature, https://bitcointalk.org/index.php?topic=8392.msg127623#msg127623
// A canonical signature exists of: <30> <total len> <02> <len R> <R> <02> <len S> <S> <hashtype>
// Where R and S are not negative (their first byte has its highest bit not set), and not
// excessively padded (do not start with a 0 byte, unless an otherwise negative number follows,
// in which case a single 0 byte is necessary and even required).
// Empty signatures, while not strictly DER encoded, are allowed.
if (signature.length == 0)
return true;
if (signature.length < 9 || signature.length > 73)
return false;
int hashType = (signature[signature.length-1] & 0xff) & ~Transaction.SigHash.ANYONECANPAY.value; // mask the byte to prevent sign-extension hurting us
if (hashType < Transaction.SigHash.ALL.value || hashType > Transaction.SigHash.SINGLE.value)
return false;
// "wrong type" "wrong length marker"
if ((signature[0] & 0xff) != 0x30 || (signature[1] & 0xff) != signature.length-3)
return false;
int lenR = signature[3] & 0xff;
if (5 + lenR >= signature.length || lenR == 0)
return false;
int lenS = signature[5+lenR] & 0xff;
if (lenR + lenS + 7 != signature.length || lenS == 0)
return false;
// R value type mismatch R value negative
if (signature[4-2] != 0x02 || (signature[4] & 0x80) == 0x80)
return false;
if (lenR > 1 && signature[4] == 0x00 && (signature[4+1] & 0x80) != 0x80)
return false; // R value excessively padded
// S value type mismatch S value negative
if (signature[6 + lenR - 2] != 0x02 || (signature[6 + lenR] & 0x80) == 0x80)
return false;
if (lenS > 1 && signature[6 + lenR] == 0x00 && (signature[6 + lenR + 1] & 0x80) != 0x80)
return false; // S value excessively padded
return true;
} | [
"public",
"static",
"boolean",
"isEncodingCanonical",
"(",
"byte",
"[",
"]",
"signature",
")",
"{",
"// See Bitcoin Core's IsCanonicalSignature, https://bitcointalk.org/index.php?topic=8392.msg127623#msg127623",
"// A canonical signature exists of: <30> <total len> <02> <len R> <R> <02> <len S> <S> <hashtype>",
"// Where R and S are not negative (their first byte has its highest bit not set), and not",
"// excessively padded (do not start with a 0 byte, unless an otherwise negative number follows,",
"// in which case a single 0 byte is necessary and even required).",
"// Empty signatures, while not strictly DER encoded, are allowed.",
"if",
"(",
"signature",
".",
"length",
"==",
"0",
")",
"return",
"true",
";",
"if",
"(",
"signature",
".",
"length",
"<",
"9",
"||",
"signature",
".",
"length",
">",
"73",
")",
"return",
"false",
";",
"int",
"hashType",
"=",
"(",
"signature",
"[",
"signature",
".",
"length",
"-",
"1",
"]",
"&",
"0xff",
")",
"&",
"~",
"Transaction",
".",
"SigHash",
".",
"ANYONECANPAY",
".",
"value",
";",
"// mask the byte to prevent sign-extension hurting us",
"if",
"(",
"hashType",
"<",
"Transaction",
".",
"SigHash",
".",
"ALL",
".",
"value",
"||",
"hashType",
">",
"Transaction",
".",
"SigHash",
".",
"SINGLE",
".",
"value",
")",
"return",
"false",
";",
"// \"wrong type\" \"wrong length marker\"",
"if",
"(",
"(",
"signature",
"[",
"0",
"]",
"&",
"0xff",
")",
"!=",
"0x30",
"||",
"(",
"signature",
"[",
"1",
"]",
"&",
"0xff",
")",
"!=",
"signature",
".",
"length",
"-",
"3",
")",
"return",
"false",
";",
"int",
"lenR",
"=",
"signature",
"[",
"3",
"]",
"&",
"0xff",
";",
"if",
"(",
"5",
"+",
"lenR",
">=",
"signature",
".",
"length",
"||",
"lenR",
"==",
"0",
")",
"return",
"false",
";",
"int",
"lenS",
"=",
"signature",
"[",
"5",
"+",
"lenR",
"]",
"&",
"0xff",
";",
"if",
"(",
"lenR",
"+",
"lenS",
"+",
"7",
"!=",
"signature",
".",
"length",
"||",
"lenS",
"==",
"0",
")",
"return",
"false",
";",
"// R value type mismatch R value negative",
"if",
"(",
"signature",
"[",
"4",
"-",
"2",
"]",
"!=",
"0x02",
"||",
"(",
"signature",
"[",
"4",
"]",
"&",
"0x80",
")",
"==",
"0x80",
")",
"return",
"false",
";",
"if",
"(",
"lenR",
">",
"1",
"&&",
"signature",
"[",
"4",
"]",
"==",
"0x00",
"&&",
"(",
"signature",
"[",
"4",
"+",
"1",
"]",
"&",
"0x80",
")",
"!=",
"0x80",
")",
"return",
"false",
";",
"// R value excessively padded",
"// S value type mismatch S value negative",
"if",
"(",
"signature",
"[",
"6",
"+",
"lenR",
"-",
"2",
"]",
"!=",
"0x02",
"||",
"(",
"signature",
"[",
"6",
"+",
"lenR",
"]",
"&",
"0x80",
")",
"==",
"0x80",
")",
"return",
"false",
";",
"if",
"(",
"lenS",
">",
"1",
"&&",
"signature",
"[",
"6",
"+",
"lenR",
"]",
"==",
"0x00",
"&&",
"(",
"signature",
"[",
"6",
"+",
"lenR",
"+",
"1",
"]",
"&",
"0x80",
")",
"!=",
"0x80",
")",
"return",
"false",
";",
"// S value excessively padded",
"return",
"true",
";",
"}"
] | Returns true if the given signature is has canonical encoding, and will thus be accepted as standard by
Bitcoin Core. DER and the SIGHASH encoding allow for quite some flexibility in how the same structures
are encoded, and this can open up novel attacks in which a man in the middle takes a transaction and then
changes its signature such that the transaction hash is different but it's still valid. This can confuse wallets
and generally violates people's mental model of how Bitcoin should work, thus, non-canonical signatures are now
not relayed by default. | [
"Returns",
"true",
"if",
"the",
"given",
"signature",
"is",
"has",
"canonical",
"encoding",
"and",
"will",
"thus",
"be",
"accepted",
"as",
"standard",
"by",
"Bitcoin",
"Core",
".",
"DER",
"and",
"the",
"SIGHASH",
"encoding",
"allow",
"for",
"quite",
"some",
"flexibility",
"in",
"how",
"the",
"same",
"structures",
"are",
"encoded",
"and",
"this",
"can",
"open",
"up",
"novel",
"attacks",
"in",
"which",
"a",
"man",
"in",
"the",
"middle",
"takes",
"a",
"transaction",
"and",
"then",
"changes",
"its",
"signature",
"such",
"that",
"the",
"transaction",
"hash",
"is",
"different",
"but",
"it",
"s",
"still",
"valid",
".",
"This",
"can",
"confuse",
"wallets",
"and",
"generally",
"violates",
"people",
"s",
"mental",
"model",
"of",
"how",
"Bitcoin",
"should",
"work",
"thus",
"non",
"-",
"canonical",
"signatures",
"are",
"now",
"not",
"relayed",
"by",
"default",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/crypto/TransactionSignature.java#L87-L129 |
23,551 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/crypto/TransactionSignature.java | TransactionSignature.encodeToBitcoin | public byte[] encodeToBitcoin() {
try {
ByteArrayOutputStream bos = derByteStream();
bos.write(sighashFlags);
return bos.toByteArray();
} catch (IOException e) {
throw new RuntimeException(e); // Cannot happen.
}
} | java | public byte[] encodeToBitcoin() {
try {
ByteArrayOutputStream bos = derByteStream();
bos.write(sighashFlags);
return bos.toByteArray();
} catch (IOException e) {
throw new RuntimeException(e); // Cannot happen.
}
} | [
"public",
"byte",
"[",
"]",
"encodeToBitcoin",
"(",
")",
"{",
"try",
"{",
"ByteArrayOutputStream",
"bos",
"=",
"derByteStream",
"(",
")",
";",
"bos",
".",
"write",
"(",
"sighashFlags",
")",
";",
"return",
"bos",
".",
"toByteArray",
"(",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"e",
")",
";",
"// Cannot happen.",
"}",
"}"
] | What we get back from the signer are the two components of a signature, r and s. To get a flat byte stream
of the type used by Bitcoin we have to encode them using DER encoding, which is just a way to pack the two
components into a structure, and then we append a byte to the end for the sighash flags. | [
"What",
"we",
"get",
"back",
"from",
"the",
"signer",
"are",
"the",
"two",
"components",
"of",
"a",
"signature",
"r",
"and",
"s",
".",
"To",
"get",
"a",
"flat",
"byte",
"stream",
"of",
"the",
"type",
"used",
"by",
"Bitcoin",
"we",
"have",
"to",
"encode",
"them",
"using",
"DER",
"encoding",
"which",
"is",
"just",
"a",
"way",
"to",
"pack",
"the",
"two",
"components",
"into",
"a",
"structure",
"and",
"then",
"we",
"append",
"a",
"byte",
"to",
"the",
"end",
"for",
"the",
"sighash",
"flags",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/crypto/TransactionSignature.java#L150-L158 |
23,552 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/crypto/TransactionSignature.java | TransactionSignature.decodeFromBitcoin | public static TransactionSignature decodeFromBitcoin(byte[] bytes, boolean requireCanonicalEncoding,
boolean requireCanonicalSValue) throws SignatureDecodeException, VerificationException {
// Bitcoin encoding is DER signature + sighash byte.
if (requireCanonicalEncoding && !isEncodingCanonical(bytes))
throw new VerificationException.NoncanonicalSignature();
ECKey.ECDSASignature sig = ECKey.ECDSASignature.decodeFromDER(bytes);
if (requireCanonicalSValue && !sig.isCanonical())
throw new VerificationException("S-value is not canonical.");
// In Bitcoin, any value of the final byte is valid, but not necessarily canonical. See javadocs for
// isEncodingCanonical to learn more about this. So we must store the exact byte found.
return new TransactionSignature(sig.r, sig.s, bytes[bytes.length - 1]);
} | java | public static TransactionSignature decodeFromBitcoin(byte[] bytes, boolean requireCanonicalEncoding,
boolean requireCanonicalSValue) throws SignatureDecodeException, VerificationException {
// Bitcoin encoding is DER signature + sighash byte.
if (requireCanonicalEncoding && !isEncodingCanonical(bytes))
throw new VerificationException.NoncanonicalSignature();
ECKey.ECDSASignature sig = ECKey.ECDSASignature.decodeFromDER(bytes);
if (requireCanonicalSValue && !sig.isCanonical())
throw new VerificationException("S-value is not canonical.");
// In Bitcoin, any value of the final byte is valid, but not necessarily canonical. See javadocs for
// isEncodingCanonical to learn more about this. So we must store the exact byte found.
return new TransactionSignature(sig.r, sig.s, bytes[bytes.length - 1]);
} | [
"public",
"static",
"TransactionSignature",
"decodeFromBitcoin",
"(",
"byte",
"[",
"]",
"bytes",
",",
"boolean",
"requireCanonicalEncoding",
",",
"boolean",
"requireCanonicalSValue",
")",
"throws",
"SignatureDecodeException",
",",
"VerificationException",
"{",
"// Bitcoin encoding is DER signature + sighash byte.",
"if",
"(",
"requireCanonicalEncoding",
"&&",
"!",
"isEncodingCanonical",
"(",
"bytes",
")",
")",
"throw",
"new",
"VerificationException",
".",
"NoncanonicalSignature",
"(",
")",
";",
"ECKey",
".",
"ECDSASignature",
"sig",
"=",
"ECKey",
".",
"ECDSASignature",
".",
"decodeFromDER",
"(",
"bytes",
")",
";",
"if",
"(",
"requireCanonicalSValue",
"&&",
"!",
"sig",
".",
"isCanonical",
"(",
")",
")",
"throw",
"new",
"VerificationException",
"(",
"\"S-value is not canonical.\"",
")",
";",
"// In Bitcoin, any value of the final byte is valid, but not necessarily canonical. See javadocs for",
"// isEncodingCanonical to learn more about this. So we must store the exact byte found.",
"return",
"new",
"TransactionSignature",
"(",
"sig",
".",
"r",
",",
"sig",
".",
"s",
",",
"bytes",
"[",
"bytes",
".",
"length",
"-",
"1",
"]",
")",
";",
"}"
] | Returns a decoded signature.
@param requireCanonicalEncoding if the encoding of the signature must
be canonical.
@param requireCanonicalSValue if the S-value must be canonical (below half
the order of the curve).
@throws SignatureDecodeException if the signature is unparseable in some way.
@throws VerificationException if the signature is invalid. | [
"Returns",
"a",
"decoded",
"signature",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/crypto/TransactionSignature.java#L175-L187 |
23,553 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/wallet/DeterministicKeyChain.java | Builder.watch | public T watch(DeterministicKey accountKey) {
checkState(accountPath == null, "either watch or accountPath");
this.watchingKey = accountKey;
this.isFollowing = false;
return self();
} | java | public T watch(DeterministicKey accountKey) {
checkState(accountPath == null, "either watch or accountPath");
this.watchingKey = accountKey;
this.isFollowing = false;
return self();
} | [
"public",
"T",
"watch",
"(",
"DeterministicKey",
"accountKey",
")",
"{",
"checkState",
"(",
"accountPath",
"==",
"null",
",",
"\"either watch or accountPath\"",
")",
";",
"this",
".",
"watchingKey",
"=",
"accountKey",
";",
"this",
".",
"isFollowing",
"=",
"false",
";",
"return",
"self",
"(",
")",
";",
"}"
] | Creates a key chain that watches the given account key. | [
"Creates",
"a",
"key",
"chain",
"that",
"watches",
"the",
"given",
"account",
"key",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/wallet/DeterministicKeyChain.java#L236-L241 |
23,554 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/wallet/DeterministicKeyChain.java | Builder.watchAndFollow | public T watchAndFollow(DeterministicKey accountKey) {
checkState(accountPath == null, "either watchAndFollow or accountPath");
this.watchingKey = accountKey;
this.isFollowing = true;
return self();
} | java | public T watchAndFollow(DeterministicKey accountKey) {
checkState(accountPath == null, "either watchAndFollow or accountPath");
this.watchingKey = accountKey;
this.isFollowing = true;
return self();
} | [
"public",
"T",
"watchAndFollow",
"(",
"DeterministicKey",
"accountKey",
")",
"{",
"checkState",
"(",
"accountPath",
"==",
"null",
",",
"\"either watchAndFollow or accountPath\"",
")",
";",
"this",
".",
"watchingKey",
"=",
"accountKey",
";",
"this",
".",
"isFollowing",
"=",
"true",
";",
"return",
"self",
"(",
")",
";",
"}"
] | Creates a deterministic key chain with the given watch key and that follows some other keychain. In a married
wallet following keychain represents "spouse". Watch key has to be an account key. | [
"Creates",
"a",
"deterministic",
"key",
"chain",
"with",
"the",
"given",
"watch",
"key",
"and",
"that",
"follows",
"some",
"other",
"keychain",
".",
"In",
"a",
"married",
"wallet",
"following",
"keychain",
"represents",
"spouse",
".",
"Watch",
"key",
"has",
"to",
"be",
"an",
"account",
"key",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/wallet/DeterministicKeyChain.java#L247-L252 |
23,555 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/wallet/DeterministicKeyChain.java | Builder.spend | public T spend(DeterministicKey accountKey) {
checkState(accountPath == null, "either spend or accountPath");
this.spendingKey = accountKey;
this.isFollowing = false;
return self();
} | java | public T spend(DeterministicKey accountKey) {
checkState(accountPath == null, "either spend or accountPath");
this.spendingKey = accountKey;
this.isFollowing = false;
return self();
} | [
"public",
"T",
"spend",
"(",
"DeterministicKey",
"accountKey",
")",
"{",
"checkState",
"(",
"accountPath",
"==",
"null",
",",
"\"either spend or accountPath\"",
")",
";",
"this",
".",
"spendingKey",
"=",
"accountKey",
";",
"this",
".",
"isFollowing",
"=",
"false",
";",
"return",
"self",
"(",
")",
";",
"}"
] | Creates a key chain that can spend from the given account key. | [
"Creates",
"a",
"key",
"chain",
"that",
"can",
"spend",
"from",
"the",
"given",
"account",
"key",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/wallet/DeterministicKeyChain.java#L257-L262 |
23,556 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/script/ScriptPattern.java | ScriptPattern.isSentToCltvPaymentChannel | public static boolean isSentToCltvPaymentChannel(Script script) {
List<ScriptChunk> chunks = script.chunks;
if (chunks.size() != 10) return false;
// Check that opcodes match the pre-determined format.
if (!chunks.get(0).equalsOpCode(OP_IF)) return false;
// chunk[1] = recipient pubkey
if (!chunks.get(2).equalsOpCode(OP_CHECKSIGVERIFY)) return false;
if (!chunks.get(3).equalsOpCode(OP_ELSE)) return false;
// chunk[4] = locktime
if (!chunks.get(5).equalsOpCode(OP_CHECKLOCKTIMEVERIFY)) return false;
if (!chunks.get(6).equalsOpCode(OP_DROP)) return false;
if (!chunks.get(7).equalsOpCode(OP_ENDIF)) return false;
// chunk[8] = sender pubkey
if (!chunks.get(9).equalsOpCode(OP_CHECKSIG)) return false;
return true;
} | java | public static boolean isSentToCltvPaymentChannel(Script script) {
List<ScriptChunk> chunks = script.chunks;
if (chunks.size() != 10) return false;
// Check that opcodes match the pre-determined format.
if (!chunks.get(0).equalsOpCode(OP_IF)) return false;
// chunk[1] = recipient pubkey
if (!chunks.get(2).equalsOpCode(OP_CHECKSIGVERIFY)) return false;
if (!chunks.get(3).equalsOpCode(OP_ELSE)) return false;
// chunk[4] = locktime
if (!chunks.get(5).equalsOpCode(OP_CHECKLOCKTIMEVERIFY)) return false;
if (!chunks.get(6).equalsOpCode(OP_DROP)) return false;
if (!chunks.get(7).equalsOpCode(OP_ENDIF)) return false;
// chunk[8] = sender pubkey
if (!chunks.get(9).equalsOpCode(OP_CHECKSIG)) return false;
return true;
} | [
"public",
"static",
"boolean",
"isSentToCltvPaymentChannel",
"(",
"Script",
"script",
")",
"{",
"List",
"<",
"ScriptChunk",
">",
"chunks",
"=",
"script",
".",
"chunks",
";",
"if",
"(",
"chunks",
".",
"size",
"(",
")",
"!=",
"10",
")",
"return",
"false",
";",
"// Check that opcodes match the pre-determined format.",
"if",
"(",
"!",
"chunks",
".",
"get",
"(",
"0",
")",
".",
"equalsOpCode",
"(",
"OP_IF",
")",
")",
"return",
"false",
";",
"// chunk[1] = recipient pubkey",
"if",
"(",
"!",
"chunks",
".",
"get",
"(",
"2",
")",
".",
"equalsOpCode",
"(",
"OP_CHECKSIGVERIFY",
")",
")",
"return",
"false",
";",
"if",
"(",
"!",
"chunks",
".",
"get",
"(",
"3",
")",
".",
"equalsOpCode",
"(",
"OP_ELSE",
")",
")",
"return",
"false",
";",
"// chunk[4] = locktime",
"if",
"(",
"!",
"chunks",
".",
"get",
"(",
"5",
")",
".",
"equalsOpCode",
"(",
"OP_CHECKLOCKTIMEVERIFY",
")",
")",
"return",
"false",
";",
"if",
"(",
"!",
"chunks",
".",
"get",
"(",
"6",
")",
".",
"equalsOpCode",
"(",
"OP_DROP",
")",
")",
"return",
"false",
";",
"if",
"(",
"!",
"chunks",
".",
"get",
"(",
"7",
")",
".",
"equalsOpCode",
"(",
"OP_ENDIF",
")",
")",
"return",
"false",
";",
"// chunk[8] = sender pubkey",
"if",
"(",
"!",
"chunks",
".",
"get",
"(",
"9",
")",
".",
"equalsOpCode",
"(",
"OP_CHECKSIG",
")",
")",
"return",
"false",
";",
"return",
"true",
";",
"}"
] | Returns whether this script matches the format used for LOCKTIMEVERIFY transactions. | [
"Returns",
"whether",
"this",
"script",
"matches",
"the",
"format",
"used",
"for",
"LOCKTIMEVERIFY",
"transactions",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/script/ScriptPattern.java#L230-L245 |
23,557 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/script/ScriptPattern.java | ScriptPattern.isOpReturn | public static boolean isOpReturn(Script script) {
List<ScriptChunk> chunks = script.chunks;
return chunks.size() > 0 && chunks.get(0).equalsOpCode(ScriptOpCodes.OP_RETURN);
} | java | public static boolean isOpReturn(Script script) {
List<ScriptChunk> chunks = script.chunks;
return chunks.size() > 0 && chunks.get(0).equalsOpCode(ScriptOpCodes.OP_RETURN);
} | [
"public",
"static",
"boolean",
"isOpReturn",
"(",
"Script",
"script",
")",
"{",
"List",
"<",
"ScriptChunk",
">",
"chunks",
"=",
"script",
".",
"chunks",
";",
"return",
"chunks",
".",
"size",
"(",
")",
">",
"0",
"&&",
"chunks",
".",
"get",
"(",
"0",
")",
".",
"equalsOpCode",
"(",
"ScriptOpCodes",
".",
"OP_RETURN",
")",
";",
"}"
] | Returns whether this script is using OP_RETURN to store arbitrary data. | [
"Returns",
"whether",
"this",
"script",
"is",
"using",
"OP_RETURN",
"to",
"store",
"arbitrary",
"data",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/script/ScriptPattern.java#L276-L279 |
23,558 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/ECKey.java | ECKey.toASN1 | public byte[] toASN1() {
try {
byte[] privKeyBytes = getPrivKeyBytes();
ByteArrayOutputStream baos = new ByteArrayOutputStream(400);
// ASN1_SEQUENCE(EC_PRIVATEKEY) = {
// ASN1_SIMPLE(EC_PRIVATEKEY, version, LONG),
// ASN1_SIMPLE(EC_PRIVATEKEY, privateKey, ASN1_OCTET_STRING),
// ASN1_EXP_OPT(EC_PRIVATEKEY, parameters, ECPKPARAMETERS, 0),
// ASN1_EXP_OPT(EC_PRIVATEKEY, publicKey, ASN1_BIT_STRING, 1)
// } ASN1_SEQUENCE_END(EC_PRIVATEKEY)
DERSequenceGenerator seq = new DERSequenceGenerator(baos);
seq.addObject(new ASN1Integer(1)); // version
seq.addObject(new DEROctetString(privKeyBytes));
seq.addObject(new DERTaggedObject(0, CURVE_PARAMS.toASN1Primitive()));
seq.addObject(new DERTaggedObject(1, new DERBitString(getPubKey())));
seq.close();
return baos.toByteArray();
} catch (IOException e) {
throw new RuntimeException(e); // Cannot happen, writing to memory stream.
}
} | java | public byte[] toASN1() {
try {
byte[] privKeyBytes = getPrivKeyBytes();
ByteArrayOutputStream baos = new ByteArrayOutputStream(400);
// ASN1_SEQUENCE(EC_PRIVATEKEY) = {
// ASN1_SIMPLE(EC_PRIVATEKEY, version, LONG),
// ASN1_SIMPLE(EC_PRIVATEKEY, privateKey, ASN1_OCTET_STRING),
// ASN1_EXP_OPT(EC_PRIVATEKEY, parameters, ECPKPARAMETERS, 0),
// ASN1_EXP_OPT(EC_PRIVATEKEY, publicKey, ASN1_BIT_STRING, 1)
// } ASN1_SEQUENCE_END(EC_PRIVATEKEY)
DERSequenceGenerator seq = new DERSequenceGenerator(baos);
seq.addObject(new ASN1Integer(1)); // version
seq.addObject(new DEROctetString(privKeyBytes));
seq.addObject(new DERTaggedObject(0, CURVE_PARAMS.toASN1Primitive()));
seq.addObject(new DERTaggedObject(1, new DERBitString(getPubKey())));
seq.close();
return baos.toByteArray();
} catch (IOException e) {
throw new RuntimeException(e); // Cannot happen, writing to memory stream.
}
} | [
"public",
"byte",
"[",
"]",
"toASN1",
"(",
")",
"{",
"try",
"{",
"byte",
"[",
"]",
"privKeyBytes",
"=",
"getPrivKeyBytes",
"(",
")",
";",
"ByteArrayOutputStream",
"baos",
"=",
"new",
"ByteArrayOutputStream",
"(",
"400",
")",
";",
"// ASN1_SEQUENCE(EC_PRIVATEKEY) = {",
"// ASN1_SIMPLE(EC_PRIVATEKEY, version, LONG),",
"// ASN1_SIMPLE(EC_PRIVATEKEY, privateKey, ASN1_OCTET_STRING),",
"// ASN1_EXP_OPT(EC_PRIVATEKEY, parameters, ECPKPARAMETERS, 0),",
"// ASN1_EXP_OPT(EC_PRIVATEKEY, publicKey, ASN1_BIT_STRING, 1)",
"// } ASN1_SEQUENCE_END(EC_PRIVATEKEY)",
"DERSequenceGenerator",
"seq",
"=",
"new",
"DERSequenceGenerator",
"(",
"baos",
")",
";",
"seq",
".",
"addObject",
"(",
"new",
"ASN1Integer",
"(",
"1",
")",
")",
";",
"// version",
"seq",
".",
"addObject",
"(",
"new",
"DEROctetString",
"(",
"privKeyBytes",
")",
")",
";",
"seq",
".",
"addObject",
"(",
"new",
"DERTaggedObject",
"(",
"0",
",",
"CURVE_PARAMS",
".",
"toASN1Primitive",
"(",
")",
")",
")",
";",
"seq",
".",
"addObject",
"(",
"new",
"DERTaggedObject",
"(",
"1",
",",
"new",
"DERBitString",
"(",
"getPubKey",
"(",
")",
")",
")",
")",
";",
"seq",
".",
"close",
"(",
")",
";",
"return",
"baos",
".",
"toByteArray",
"(",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"e",
")",
";",
"// Cannot happen, writing to memory stream.",
"}",
"}"
] | Output this ECKey as an ASN.1 encoded private key, as understood by OpenSSL or used by Bitcoin Core
in its wallet storage format.
@throws org.bitcoinj.core.ECKey.MissingPrivateKeyException if the private key is missing or encrypted. | [
"Output",
"this",
"ECKey",
"as",
"an",
"ASN",
".",
"1",
"encoded",
"private",
"key",
"as",
"understood",
"by",
"OpenSSL",
"or",
"used",
"by",
"Bitcoin",
"Core",
"in",
"its",
"wallet",
"storage",
"format",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/ECKey.java#L425-L446 |
23,559 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/ECKey.java | ECKey.findRecoveryId | public byte findRecoveryId(Sha256Hash hash, ECDSASignature sig) {
byte recId = -1;
for (byte i = 0; i < 4; i++) {
ECKey k = ECKey.recoverFromSignature(i, sig, hash, isCompressed());
if (k != null && k.pub.equals(pub)) {
recId = i;
break;
}
}
if (recId == -1)
throw new RuntimeException("Could not construct a recoverable key. This should never happen.");
return recId;
} | java | public byte findRecoveryId(Sha256Hash hash, ECDSASignature sig) {
byte recId = -1;
for (byte i = 0; i < 4; i++) {
ECKey k = ECKey.recoverFromSignature(i, sig, hash, isCompressed());
if (k != null && k.pub.equals(pub)) {
recId = i;
break;
}
}
if (recId == -1)
throw new RuntimeException("Could not construct a recoverable key. This should never happen.");
return recId;
} | [
"public",
"byte",
"findRecoveryId",
"(",
"Sha256Hash",
"hash",
",",
"ECDSASignature",
"sig",
")",
"{",
"byte",
"recId",
"=",
"-",
"1",
";",
"for",
"(",
"byte",
"i",
"=",
"0",
";",
"i",
"<",
"4",
";",
"i",
"++",
")",
"{",
"ECKey",
"k",
"=",
"ECKey",
".",
"recoverFromSignature",
"(",
"i",
",",
"sig",
",",
"hash",
",",
"isCompressed",
"(",
")",
")",
";",
"if",
"(",
"k",
"!=",
"null",
"&&",
"k",
".",
"pub",
".",
"equals",
"(",
"pub",
")",
")",
"{",
"recId",
"=",
"i",
";",
"break",
";",
"}",
"}",
"if",
"(",
"recId",
"==",
"-",
"1",
")",
"throw",
"new",
"RuntimeException",
"(",
"\"Could not construct a recoverable key. This should never happen.\"",
")",
";",
"return",
"recId",
";",
"}"
] | Returns the recovery ID, a byte with value between 0 and 3, inclusive, that specifies which of 4 possible
curve points was used to sign a message. This value is also referred to as "v".
@throws RuntimeException if no recovery ID can be found. | [
"Returns",
"the",
"recovery",
"ID",
"a",
"byte",
"with",
"value",
"between",
"0",
"and",
"3",
"inclusive",
"that",
"specifies",
"which",
"of",
"4",
"possible",
"curve",
"points",
"was",
"used",
"to",
"sign",
"a",
"message",
".",
"This",
"value",
"is",
"also",
"referred",
"to",
"as",
"v",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/ECKey.java#L947-L959 |
23,560 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/ECKey.java | ECKey.encrypt | public ECKey encrypt(KeyCrypter keyCrypter, KeyParameter aesKey) throws KeyCrypterException {
checkNotNull(keyCrypter);
final byte[] privKeyBytes = getPrivKeyBytes();
EncryptedData encryptedPrivateKey = keyCrypter.encrypt(privKeyBytes, aesKey);
ECKey result = ECKey.fromEncrypted(encryptedPrivateKey, keyCrypter, getPubKey());
result.setCreationTimeSeconds(creationTimeSeconds);
return result;
} | java | public ECKey encrypt(KeyCrypter keyCrypter, KeyParameter aesKey) throws KeyCrypterException {
checkNotNull(keyCrypter);
final byte[] privKeyBytes = getPrivKeyBytes();
EncryptedData encryptedPrivateKey = keyCrypter.encrypt(privKeyBytes, aesKey);
ECKey result = ECKey.fromEncrypted(encryptedPrivateKey, keyCrypter, getPubKey());
result.setCreationTimeSeconds(creationTimeSeconds);
return result;
} | [
"public",
"ECKey",
"encrypt",
"(",
"KeyCrypter",
"keyCrypter",
",",
"KeyParameter",
"aesKey",
")",
"throws",
"KeyCrypterException",
"{",
"checkNotNull",
"(",
"keyCrypter",
")",
";",
"final",
"byte",
"[",
"]",
"privKeyBytes",
"=",
"getPrivKeyBytes",
"(",
")",
";",
"EncryptedData",
"encryptedPrivateKey",
"=",
"keyCrypter",
".",
"encrypt",
"(",
"privKeyBytes",
",",
"aesKey",
")",
";",
"ECKey",
"result",
"=",
"ECKey",
".",
"fromEncrypted",
"(",
"encryptedPrivateKey",
",",
"keyCrypter",
",",
"getPubKey",
"(",
")",
")",
";",
"result",
".",
"setCreationTimeSeconds",
"(",
"creationTimeSeconds",
")",
";",
"return",
"result",
";",
"}"
] | Create an encrypted private key with the keyCrypter and the AES key supplied.
This method returns a new encrypted key and leaves the original unchanged.
@param keyCrypter The keyCrypter that specifies exactly how the encrypted bytes are created.
@param aesKey The KeyParameter with the AES encryption key (usually constructed with keyCrypter#deriveKey and cached as it is slow to create).
@return encryptedKey | [
"Create",
"an",
"encrypted",
"private",
"key",
"with",
"the",
"keyCrypter",
"and",
"the",
"AES",
"key",
"supplied",
".",
"This",
"method",
"returns",
"a",
"new",
"encrypted",
"key",
"and",
"leaves",
"the",
"original",
"unchanged",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/ECKey.java#L1086-L1093 |
23,561 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/ECKey.java | ECKey.decrypt | public ECKey decrypt(KeyCrypter keyCrypter, KeyParameter aesKey) throws KeyCrypterException {
checkNotNull(keyCrypter);
// Check that the keyCrypter matches the one used to encrypt the keys, if set.
if (this.keyCrypter != null && !this.keyCrypter.equals(keyCrypter))
throw new KeyCrypterException("The keyCrypter being used to decrypt the key is different to the one that was used to encrypt it");
checkState(encryptedPrivateKey != null, "This key is not encrypted");
byte[] unencryptedPrivateKey = keyCrypter.decrypt(encryptedPrivateKey, aesKey);
if (unencryptedPrivateKey.length != 32)
throw new KeyCrypterException.InvalidCipherText(
"Decrypted key must be 32 bytes long, but is " + unencryptedPrivateKey.length);
ECKey key = ECKey.fromPrivate(unencryptedPrivateKey);
if (!isCompressed())
key = key.decompress();
if (!Arrays.equals(key.getPubKey(), getPubKey()))
throw new KeyCrypterException("Provided AES key is wrong");
key.setCreationTimeSeconds(creationTimeSeconds);
return key;
} | java | public ECKey decrypt(KeyCrypter keyCrypter, KeyParameter aesKey) throws KeyCrypterException {
checkNotNull(keyCrypter);
// Check that the keyCrypter matches the one used to encrypt the keys, if set.
if (this.keyCrypter != null && !this.keyCrypter.equals(keyCrypter))
throw new KeyCrypterException("The keyCrypter being used to decrypt the key is different to the one that was used to encrypt it");
checkState(encryptedPrivateKey != null, "This key is not encrypted");
byte[] unencryptedPrivateKey = keyCrypter.decrypt(encryptedPrivateKey, aesKey);
if (unencryptedPrivateKey.length != 32)
throw new KeyCrypterException.InvalidCipherText(
"Decrypted key must be 32 bytes long, but is " + unencryptedPrivateKey.length);
ECKey key = ECKey.fromPrivate(unencryptedPrivateKey);
if (!isCompressed())
key = key.decompress();
if (!Arrays.equals(key.getPubKey(), getPubKey()))
throw new KeyCrypterException("Provided AES key is wrong");
key.setCreationTimeSeconds(creationTimeSeconds);
return key;
} | [
"public",
"ECKey",
"decrypt",
"(",
"KeyCrypter",
"keyCrypter",
",",
"KeyParameter",
"aesKey",
")",
"throws",
"KeyCrypterException",
"{",
"checkNotNull",
"(",
"keyCrypter",
")",
";",
"// Check that the keyCrypter matches the one used to encrypt the keys, if set.",
"if",
"(",
"this",
".",
"keyCrypter",
"!=",
"null",
"&&",
"!",
"this",
".",
"keyCrypter",
".",
"equals",
"(",
"keyCrypter",
")",
")",
"throw",
"new",
"KeyCrypterException",
"(",
"\"The keyCrypter being used to decrypt the key is different to the one that was used to encrypt it\"",
")",
";",
"checkState",
"(",
"encryptedPrivateKey",
"!=",
"null",
",",
"\"This key is not encrypted\"",
")",
";",
"byte",
"[",
"]",
"unencryptedPrivateKey",
"=",
"keyCrypter",
".",
"decrypt",
"(",
"encryptedPrivateKey",
",",
"aesKey",
")",
";",
"if",
"(",
"unencryptedPrivateKey",
".",
"length",
"!=",
"32",
")",
"throw",
"new",
"KeyCrypterException",
".",
"InvalidCipherText",
"(",
"\"Decrypted key must be 32 bytes long, but is \"",
"+",
"unencryptedPrivateKey",
".",
"length",
")",
";",
"ECKey",
"key",
"=",
"ECKey",
".",
"fromPrivate",
"(",
"unencryptedPrivateKey",
")",
";",
"if",
"(",
"!",
"isCompressed",
"(",
")",
")",
"key",
"=",
"key",
".",
"decompress",
"(",
")",
";",
"if",
"(",
"!",
"Arrays",
".",
"equals",
"(",
"key",
".",
"getPubKey",
"(",
")",
",",
"getPubKey",
"(",
")",
")",
")",
"throw",
"new",
"KeyCrypterException",
"(",
"\"Provided AES key is wrong\"",
")",
";",
"key",
".",
"setCreationTimeSeconds",
"(",
"creationTimeSeconds",
")",
";",
"return",
"key",
";",
"}"
] | Create a decrypted private key with the keyCrypter and AES key supplied. Note that if the aesKey is wrong, this
has some chance of throwing KeyCrypterException due to the corrupted padding that will result, but it can also
just yield a garbage key.
@param keyCrypter The keyCrypter that specifies exactly how the decrypted bytes are created.
@param aesKey The KeyParameter with the AES encryption key (usually constructed with keyCrypter#deriveKey and cached). | [
"Create",
"a",
"decrypted",
"private",
"key",
"with",
"the",
"keyCrypter",
"and",
"AES",
"key",
"supplied",
".",
"Note",
"that",
"if",
"the",
"aesKey",
"is",
"wrong",
"this",
"has",
"some",
"chance",
"of",
"throwing",
"KeyCrypterException",
"due",
"to",
"the",
"corrupted",
"padding",
"that",
"will",
"result",
"but",
"it",
"can",
"also",
"just",
"yield",
"a",
"garbage",
"key",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/ECKey.java#L1103-L1120 |
23,562 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/ECKey.java | ECKey.decrypt | public ECKey decrypt(KeyParameter aesKey) throws KeyCrypterException {
final KeyCrypter crypter = getKeyCrypter();
if (crypter == null)
throw new KeyCrypterException("No key crypter available");
return decrypt(crypter, aesKey);
} | java | public ECKey decrypt(KeyParameter aesKey) throws KeyCrypterException {
final KeyCrypter crypter = getKeyCrypter();
if (crypter == null)
throw new KeyCrypterException("No key crypter available");
return decrypt(crypter, aesKey);
} | [
"public",
"ECKey",
"decrypt",
"(",
"KeyParameter",
"aesKey",
")",
"throws",
"KeyCrypterException",
"{",
"final",
"KeyCrypter",
"crypter",
"=",
"getKeyCrypter",
"(",
")",
";",
"if",
"(",
"crypter",
"==",
"null",
")",
"throw",
"new",
"KeyCrypterException",
"(",
"\"No key crypter available\"",
")",
";",
"return",
"decrypt",
"(",
"crypter",
",",
"aesKey",
")",
";",
"}"
] | Create a decrypted private key with AES key. Note that if the AES key is wrong, this
has some chance of throwing KeyCrypterException due to the corrupted padding that will result, but it can also
just yield a garbage key.
@param aesKey The KeyParameter with the AES encryption key (usually constructed with keyCrypter#deriveKey and cached). | [
"Create",
"a",
"decrypted",
"private",
"key",
"with",
"AES",
"key",
".",
"Note",
"that",
"if",
"the",
"AES",
"key",
"is",
"wrong",
"this",
"has",
"some",
"chance",
"of",
"throwing",
"KeyCrypterException",
"due",
"to",
"the",
"corrupted",
"padding",
"that",
"will",
"result",
"but",
"it",
"can",
"also",
"just",
"yield",
"a",
"garbage",
"key",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/ECKey.java#L1129-L1134 |
23,563 | prometheus/jmx_exporter | collector/src/main/java/io/prometheus/jmx/JmxScraper.java | JmxScraper.logScrape | private static void logScrape(ObjectName mbeanName, Set<String> names, String msg) {
logScrape(mbeanName + "_" + names, msg);
} | java | private static void logScrape(ObjectName mbeanName, Set<String> names, String msg) {
logScrape(mbeanName + "_" + names, msg);
} | [
"private",
"static",
"void",
"logScrape",
"(",
"ObjectName",
"mbeanName",
",",
"Set",
"<",
"String",
">",
"names",
",",
"String",
"msg",
")",
"{",
"logScrape",
"(",
"mbeanName",
"+",
"\"_\"",
"+",
"names",
",",
"msg",
")",
";",
"}"
] | For debugging. | [
"For",
"debugging",
"."
] | 6a8d92c580b93d62a1a9183cbb7cb1a3b19a8473 | https://github.com/prometheus/jmx_exporter/blob/6a8d92c580b93d62a1a9183cbb7cb1a3b19a8473/collector/src/main/java/io/prometheus/jmx/JmxScraper.java#L282-L284 |
23,564 | prometheus/jmx_exporter | collector/src/main/java/io/prometheus/jmx/JmxCollector.java | JmxCollector.safeName | static String safeName(String name) {
if (name == null) {
return null;
}
boolean prevCharIsUnderscore = false;
StringBuilder safeNameBuilder = new StringBuilder(name.length());
if (!name.isEmpty() && Character.isDigit(name.charAt(0))) {
// prevent a numeric prefix.
safeNameBuilder.append("_");
}
for (char nameChar : name.toCharArray()) {
boolean isUnsafeChar = !JmxCollector.isLegalCharacter(nameChar);
if ((isUnsafeChar || nameChar == '_')) {
if (prevCharIsUnderscore) {
continue;
} else {
safeNameBuilder.append("_");
prevCharIsUnderscore = true;
}
} else {
safeNameBuilder.append(nameChar);
prevCharIsUnderscore = false;
}
}
return safeNameBuilder.toString();
} | java | static String safeName(String name) {
if (name == null) {
return null;
}
boolean prevCharIsUnderscore = false;
StringBuilder safeNameBuilder = new StringBuilder(name.length());
if (!name.isEmpty() && Character.isDigit(name.charAt(0))) {
// prevent a numeric prefix.
safeNameBuilder.append("_");
}
for (char nameChar : name.toCharArray()) {
boolean isUnsafeChar = !JmxCollector.isLegalCharacter(nameChar);
if ((isUnsafeChar || nameChar == '_')) {
if (prevCharIsUnderscore) {
continue;
} else {
safeNameBuilder.append("_");
prevCharIsUnderscore = true;
}
} else {
safeNameBuilder.append(nameChar);
prevCharIsUnderscore = false;
}
}
return safeNameBuilder.toString();
} | [
"static",
"String",
"safeName",
"(",
"String",
"name",
")",
"{",
"if",
"(",
"name",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"boolean",
"prevCharIsUnderscore",
"=",
"false",
";",
"StringBuilder",
"safeNameBuilder",
"=",
"new",
"StringBuilder",
"(",
"name",
".",
"length",
"(",
")",
")",
";",
"if",
"(",
"!",
"name",
".",
"isEmpty",
"(",
")",
"&&",
"Character",
".",
"isDigit",
"(",
"name",
".",
"charAt",
"(",
"0",
")",
")",
")",
"{",
"// prevent a numeric prefix.",
"safeNameBuilder",
".",
"append",
"(",
"\"_\"",
")",
";",
"}",
"for",
"(",
"char",
"nameChar",
":",
"name",
".",
"toCharArray",
"(",
")",
")",
"{",
"boolean",
"isUnsafeChar",
"=",
"!",
"JmxCollector",
".",
"isLegalCharacter",
"(",
"nameChar",
")",
";",
"if",
"(",
"(",
"isUnsafeChar",
"||",
"nameChar",
"==",
"'",
"'",
")",
")",
"{",
"if",
"(",
"prevCharIsUnderscore",
")",
"{",
"continue",
";",
"}",
"else",
"{",
"safeNameBuilder",
".",
"append",
"(",
"\"_\"",
")",
";",
"prevCharIsUnderscore",
"=",
"true",
";",
"}",
"}",
"else",
"{",
"safeNameBuilder",
".",
"append",
"(",
"nameChar",
")",
";",
"prevCharIsUnderscore",
"=",
"false",
";",
"}",
"}",
"return",
"safeNameBuilder",
".",
"toString",
"(",
")",
";",
"}"
] | Change invalid chars to underscore, and merge underscores.
@param name Input string
@return | [
"Change",
"invalid",
"chars",
"to",
"underscore",
"and",
"merge",
"underscores",
"."
] | 6a8d92c580b93d62a1a9183cbb7cb1a3b19a8473 | https://github.com/prometheus/jmx_exporter/blob/6a8d92c580b93d62a1a9183cbb7cb1a3b19a8473/collector/src/main/java/io/prometheus/jmx/JmxCollector.java#L245-L271 |
23,565 | banq/jdonframework | src/main/java/com/jdon/async/disruptor/ValueEventProcessor.java | ValueEventProcessor.waitForBlocking | public EventResultDisruptor waitForBlocking() {
SequenceBarrier barrier = ringBuffer.newBarrier();
try {
long a = barrier.waitFor(waitAtSequence);
if (ringBuffer != null)
return ringBuffer.get(a);
} catch (Exception e) {
e.printStackTrace();
} finally {
barrier.alert();
}
return null;
} | java | public EventResultDisruptor waitForBlocking() {
SequenceBarrier barrier = ringBuffer.newBarrier();
try {
long a = barrier.waitFor(waitAtSequence);
if (ringBuffer != null)
return ringBuffer.get(a);
} catch (Exception e) {
e.printStackTrace();
} finally {
barrier.alert();
}
return null;
} | [
"public",
"EventResultDisruptor",
"waitForBlocking",
"(",
")",
"{",
"SequenceBarrier",
"barrier",
"=",
"ringBuffer",
".",
"newBarrier",
"(",
")",
";",
"try",
"{",
"long",
"a",
"=",
"barrier",
".",
"waitFor",
"(",
"waitAtSequence",
")",
";",
"if",
"(",
"ringBuffer",
"!=",
"null",
")",
"return",
"ringBuffer",
".",
"get",
"(",
"a",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"e",
".",
"printStackTrace",
"(",
")",
";",
"}",
"finally",
"{",
"barrier",
".",
"alert",
"(",
")",
";",
"}",
"return",
"null",
";",
"}"
] | not really block, the waiting time is longer than not block. | [
"not",
"really",
"block",
"the",
"waiting",
"time",
"is",
"longer",
"than",
"not",
"block",
"."
] | 72b451caac04f775e57f52aaed3d8775044ead53 | https://github.com/banq/jdonframework/blob/72b451caac04f775e57f52aaed3d8775044ead53/src/main/java/com/jdon/async/disruptor/ValueEventProcessor.java#L56-L68 |
23,566 | banq/jdonframework | JdonAccessory/jdon-struts1x/src/main/java/com/jdon/strutsutil/taglib/MPageTag.java | MPageTag.doStartTag | public int doStartTag() throws JspException {
// Generate the URL to be encoded
String pageUrl = calculateURL();
StringBuilder url = new StringBuilder(pageUrl);
if (pageUrl.indexOf("?") < 0)
url.append("?");
else
url.append("&");
ModelListForm form = null;
try {
form = (ModelListForm) FormBeanUtil.lookupActionForm((HttpServletRequest) pageContext.getRequest(), actionFormName);
if (form == null)
throw new Exception();
} catch (Exception e) {
Debug.logError("[JdonFramework]not found actionFormName value: " + actionFormName, module);
throw new JspException(" not found " + actionFormName);
}
int start = form.getStart();
int allCount = form.getAllCount();
int count = form.getCount();
url.append("count=").append(count);
String nextPage = "";
if ((allCount > (start + count)))
nextPage = NEXTPAGE;
pageContext.setAttribute(URLNAME, url.toString());
pageContext.setAttribute(START, Integer.toString(start));
pageContext.setAttribute(COUNT, Integer.toString(count));
pageContext.setAttribute(ALLCOUNT, Integer.toString(allCount));
pageContext.setAttribute(NEXTPAGE, nextPage);
int currentPage = 1;
if (count > 0) {
currentPage = (start / count) + 1;
}
// 当前只有一页,没有下一页
if ((currentPage == 1) && (nextPage.length() == 0)) {
pageContext.setAttribute(DISP, "off"); // 不显示其它标识
} else
pageContext.setAttribute(DISP, "on");
// Evaluate the body of this tag
return (EVAL_BODY_INCLUDE);
} | java | public int doStartTag() throws JspException {
// Generate the URL to be encoded
String pageUrl = calculateURL();
StringBuilder url = new StringBuilder(pageUrl);
if (pageUrl.indexOf("?") < 0)
url.append("?");
else
url.append("&");
ModelListForm form = null;
try {
form = (ModelListForm) FormBeanUtil.lookupActionForm((HttpServletRequest) pageContext.getRequest(), actionFormName);
if (form == null)
throw new Exception();
} catch (Exception e) {
Debug.logError("[JdonFramework]not found actionFormName value: " + actionFormName, module);
throw new JspException(" not found " + actionFormName);
}
int start = form.getStart();
int allCount = form.getAllCount();
int count = form.getCount();
url.append("count=").append(count);
String nextPage = "";
if ((allCount > (start + count)))
nextPage = NEXTPAGE;
pageContext.setAttribute(URLNAME, url.toString());
pageContext.setAttribute(START, Integer.toString(start));
pageContext.setAttribute(COUNT, Integer.toString(count));
pageContext.setAttribute(ALLCOUNT, Integer.toString(allCount));
pageContext.setAttribute(NEXTPAGE, nextPage);
int currentPage = 1;
if (count > 0) {
currentPage = (start / count) + 1;
}
// 当前只有一页,没有下一页
if ((currentPage == 1) && (nextPage.length() == 0)) {
pageContext.setAttribute(DISP, "off"); // 不显示其它标识
} else
pageContext.setAttribute(DISP, "on");
// Evaluate the body of this tag
return (EVAL_BODY_INCLUDE);
} | [
"public",
"int",
"doStartTag",
"(",
")",
"throws",
"JspException",
"{",
"// Generate the URL to be encoded\r",
"String",
"pageUrl",
"=",
"calculateURL",
"(",
")",
";",
"StringBuilder",
"url",
"=",
"new",
"StringBuilder",
"(",
"pageUrl",
")",
";",
"if",
"(",
"pageUrl",
".",
"indexOf",
"(",
"\"?\"",
")",
"<",
"0",
")",
"url",
".",
"append",
"(",
"\"?\"",
")",
";",
"else",
"url",
".",
"append",
"(",
"\"&\"",
")",
";",
"ModelListForm",
"form",
"=",
"null",
";",
"try",
"{",
"form",
"=",
"(",
"ModelListForm",
")",
"FormBeanUtil",
".",
"lookupActionForm",
"(",
"(",
"HttpServletRequest",
")",
"pageContext",
".",
"getRequest",
"(",
")",
",",
"actionFormName",
")",
";",
"if",
"(",
"form",
"==",
"null",
")",
"throw",
"new",
"Exception",
"(",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"Debug",
".",
"logError",
"(",
"\"[JdonFramework]not found actionFormName value: \"",
"+",
"actionFormName",
",",
"module",
")",
";",
"throw",
"new",
"JspException",
"(",
"\" not found \"",
"+",
"actionFormName",
")",
";",
"}",
"int",
"start",
"=",
"form",
".",
"getStart",
"(",
")",
";",
"int",
"allCount",
"=",
"form",
".",
"getAllCount",
"(",
")",
";",
"int",
"count",
"=",
"form",
".",
"getCount",
"(",
")",
";",
"url",
".",
"append",
"(",
"\"count=\"",
")",
".",
"append",
"(",
"count",
")",
";",
"String",
"nextPage",
"=",
"\"\"",
";",
"if",
"(",
"(",
"allCount",
">",
"(",
"start",
"+",
"count",
")",
")",
")",
"nextPage",
"=",
"NEXTPAGE",
";",
"pageContext",
".",
"setAttribute",
"(",
"URLNAME",
",",
"url",
".",
"toString",
"(",
")",
")",
";",
"pageContext",
".",
"setAttribute",
"(",
"START",
",",
"Integer",
".",
"toString",
"(",
"start",
")",
")",
";",
"pageContext",
".",
"setAttribute",
"(",
"COUNT",
",",
"Integer",
".",
"toString",
"(",
"count",
")",
")",
";",
"pageContext",
".",
"setAttribute",
"(",
"ALLCOUNT",
",",
"Integer",
".",
"toString",
"(",
"allCount",
")",
")",
";",
"pageContext",
".",
"setAttribute",
"(",
"NEXTPAGE",
",",
"nextPage",
")",
";",
"int",
"currentPage",
"=",
"1",
";",
"if",
"(",
"count",
">",
"0",
")",
"{",
"currentPage",
"=",
"(",
"start",
"/",
"count",
")",
"+",
"1",
";",
"}",
"// 当前只有一页,没有下一页\r",
"if",
"(",
"(",
"currentPage",
"==",
"1",
")",
"&&",
"(",
"nextPage",
".",
"length",
"(",
")",
"==",
"0",
")",
")",
"{",
"pageContext",
".",
"setAttribute",
"(",
"DISP",
",",
"\"off\"",
")",
";",
"// 不显示其它标识\r",
"}",
"else",
"pageContext",
".",
"setAttribute",
"(",
"DISP",
",",
"\"on\"",
")",
";",
"// Evaluate the body of this tag\r",
"return",
"(",
"EVAL_BODY_INCLUDE",
")",
";",
"}"
] | Render the beginning of the hyperlink.
@exception JspException
if a JSP exception has occurred | [
"Render",
"the",
"beginning",
"of",
"the",
"hyperlink",
"."
] | 72b451caac04f775e57f52aaed3d8775044ead53 | https://github.com/banq/jdonframework/blob/72b451caac04f775e57f52aaed3d8775044ead53/JdonAccessory/jdon-struts1x/src/main/java/com/jdon/strutsutil/taglib/MPageTag.java#L65-L114 |
23,567 | banq/jdonframework | JdonAccessory/jdon-struts1x/src/main/java/com/jdon/servicelocator/ejb/ServiceLocator.java | ServiceLocator.getLocalHome | public EJBLocalHome getLocalHome(String jndiHomeName) throws ServiceLocatorException {
EJBLocalHome home = null;
try {
home = (EJBLocalHome) ic.lookup(jndiHomeName);
} catch (NamingException ne) {
throw new ServiceLocatorException(ne);
} catch (Exception e) {
throw new ServiceLocatorException(e);
}
return home;
} | java | public EJBLocalHome getLocalHome(String jndiHomeName) throws ServiceLocatorException {
EJBLocalHome home = null;
try {
home = (EJBLocalHome) ic.lookup(jndiHomeName);
} catch (NamingException ne) {
throw new ServiceLocatorException(ne);
} catch (Exception e) {
throw new ServiceLocatorException(e);
}
return home;
} | [
"public",
"EJBLocalHome",
"getLocalHome",
"(",
"String",
"jndiHomeName",
")",
"throws",
"ServiceLocatorException",
"{",
"EJBLocalHome",
"home",
"=",
"null",
";",
"try",
"{",
"home",
"=",
"(",
"EJBLocalHome",
")",
"ic",
".",
"lookup",
"(",
"jndiHomeName",
")",
";",
"}",
"catch",
"(",
"NamingException",
"ne",
")",
"{",
"throw",
"new",
"ServiceLocatorException",
"(",
"ne",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"throw",
"new",
"ServiceLocatorException",
"(",
"e",
")",
";",
"}",
"return",
"home",
";",
"}"
] | will get the ejb Local home factory. clients need to cast to the type of
EJBHome they desire
@return the Local EJB Home corresponding to the homeName | [
"will",
"get",
"the",
"ejb",
"Local",
"home",
"factory",
".",
"clients",
"need",
"to",
"cast",
"to",
"the",
"type",
"of",
"EJBHome",
"they",
"desire"
] | 72b451caac04f775e57f52aaed3d8775044ead53 | https://github.com/banq/jdonframework/blob/72b451caac04f775e57f52aaed3d8775044ead53/JdonAccessory/jdon-struts1x/src/main/java/com/jdon/servicelocator/ejb/ServiceLocator.java#L45-L55 |
23,568 | banq/jdonframework | JdonAccessory/jdon-struts1x/src/main/java/com/jdon/servicelocator/ejb/ServiceLocator.java | ServiceLocator.getRemoteHome | public EJBHome getRemoteHome(String jndiHomeName, Class className) throws ServiceLocatorException {
EJBHome home = null;
try {
Object objref = ic.lookup(jndiHomeName);
Object obj = PortableRemoteObject.narrow(objref, className);
home = (EJBHome) obj;
} catch (NamingException ne) {
throw new ServiceLocatorException(ne);
} catch (Exception e) {
throw new ServiceLocatorException(e);
}
return home;
} | java | public EJBHome getRemoteHome(String jndiHomeName, Class className) throws ServiceLocatorException {
EJBHome home = null;
try {
Object objref = ic.lookup(jndiHomeName);
Object obj = PortableRemoteObject.narrow(objref, className);
home = (EJBHome) obj;
} catch (NamingException ne) {
throw new ServiceLocatorException(ne);
} catch (Exception e) {
throw new ServiceLocatorException(e);
}
return home;
} | [
"public",
"EJBHome",
"getRemoteHome",
"(",
"String",
"jndiHomeName",
",",
"Class",
"className",
")",
"throws",
"ServiceLocatorException",
"{",
"EJBHome",
"home",
"=",
"null",
";",
"try",
"{",
"Object",
"objref",
"=",
"ic",
".",
"lookup",
"(",
"jndiHomeName",
")",
";",
"Object",
"obj",
"=",
"PortableRemoteObject",
".",
"narrow",
"(",
"objref",
",",
"className",
")",
";",
"home",
"=",
"(",
"EJBHome",
")",
"obj",
";",
"}",
"catch",
"(",
"NamingException",
"ne",
")",
"{",
"throw",
"new",
"ServiceLocatorException",
"(",
"ne",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"throw",
"new",
"ServiceLocatorException",
"(",
"e",
")",
";",
"}",
"return",
"home",
";",
"}"
] | will get the ejb Remote home factory. clients need to cast to the type of
EJBHome they desire
@return the EJB Home corresponding to the homeName | [
"will",
"get",
"the",
"ejb",
"Remote",
"home",
"factory",
".",
"clients",
"need",
"to",
"cast",
"to",
"the",
"type",
"of",
"EJBHome",
"they",
"desire"
] | 72b451caac04f775e57f52aaed3d8775044ead53 | https://github.com/banq/jdonframework/blob/72b451caac04f775e57f52aaed3d8775044ead53/JdonAccessory/jdon-struts1x/src/main/java/com/jdon/servicelocator/ejb/ServiceLocator.java#L63-L75 |
23,569 | banq/jdonframework | src/main/java/com/jdon/async/disruptor/DisruptorFactory.java | DisruptorFactory.createDisruptor | public Disruptor createDisruptor(String topic) {
TreeSet handlers = getHandles(topic);
if (handlers == null)
return null;
Disruptor dw = createDw(topic);
Disruptor disruptor = addEventMessageHandler(dw, topic, handlers);
if (disruptor == null)
return null;
disruptor.start();
return disruptor;
} | java | public Disruptor createDisruptor(String topic) {
TreeSet handlers = getHandles(topic);
if (handlers == null)
return null;
Disruptor dw = createDw(topic);
Disruptor disruptor = addEventMessageHandler(dw, topic, handlers);
if (disruptor == null)
return null;
disruptor.start();
return disruptor;
} | [
"public",
"Disruptor",
"createDisruptor",
"(",
"String",
"topic",
")",
"{",
"TreeSet",
"handlers",
"=",
"getHandles",
"(",
"topic",
")",
";",
"if",
"(",
"handlers",
"==",
"null",
")",
"return",
"null",
";",
"Disruptor",
"dw",
"=",
"createDw",
"(",
"topic",
")",
";",
"Disruptor",
"disruptor",
"=",
"addEventMessageHandler",
"(",
"dw",
",",
"topic",
",",
"handlers",
")",
";",
"if",
"(",
"disruptor",
"==",
"null",
")",
"return",
"null",
";",
"disruptor",
".",
"start",
"(",
")",
";",
"return",
"disruptor",
";",
"}"
] | one topic one EventDisruptor
@param topic
@return | [
"one",
"topic",
"one",
"EventDisruptor"
] | 72b451caac04f775e57f52aaed3d8775044ead53 | https://github.com/banq/jdonframework/blob/72b451caac04f775e57f52aaed3d8775044ead53/src/main/java/com/jdon/async/disruptor/DisruptorFactory.java#L126-L137 |
23,570 | banq/jdonframework | JdonAccessory/jdon-struts1x/src/main/java/com/jdon/strutsutil/FormBeanUtil.java | FormBeanUtil.lookupActionForm | public static ActionForm lookupActionForm(HttpServletRequest request, String formName) {
ActionForm actionForm = null;
actionForm = (ActionForm) request.getAttribute(formName);
if (actionForm == null && request.getSession(false) != null) {
HttpSession session = request.getSession(false);
actionForm = (ActionForm) session.getAttribute(formName);
}
return actionForm;
} | java | public static ActionForm lookupActionForm(HttpServletRequest request, String formName) {
ActionForm actionForm = null;
actionForm = (ActionForm) request.getAttribute(formName);
if (actionForm == null && request.getSession(false) != null) {
HttpSession session = request.getSession(false);
actionForm = (ActionForm) session.getAttribute(formName);
}
return actionForm;
} | [
"public",
"static",
"ActionForm",
"lookupActionForm",
"(",
"HttpServletRequest",
"request",
",",
"String",
"formName",
")",
"{",
"ActionForm",
"actionForm",
"=",
"null",
";",
"actionForm",
"=",
"(",
"ActionForm",
")",
"request",
".",
"getAttribute",
"(",
"formName",
")",
";",
"if",
"(",
"actionForm",
"==",
"null",
"&&",
"request",
".",
"getSession",
"(",
"false",
")",
"!=",
"null",
")",
"{",
"HttpSession",
"session",
"=",
"request",
".",
"getSession",
"(",
"false",
")",
";",
"actionForm",
"=",
"(",
"ActionForm",
")",
"session",
".",
"getAttribute",
"(",
"formName",
")",
";",
"}",
"return",
"actionForm",
";",
"}"
] | lookup ActionForm in
@param request
@return | [
"lookup",
"ActionForm",
"in"
] | 72b451caac04f775e57f52aaed3d8775044ead53 | https://github.com/banq/jdonframework/blob/72b451caac04f775e57f52aaed3d8775044ead53/JdonAccessory/jdon-struts1x/src/main/java/com/jdon/strutsutil/FormBeanUtil.java#L97-L105 |
23,571 | banq/jdonframework | src/main/java/com/jdon/container/builder/ContainerDirector.java | ContainerDirector.prepareAppRoot | public synchronized void prepareAppRoot(String configureFileName) throws Exception {
if (!cb.isKernelStartup()) {
cb.registerAppRoot(configureFileName);
logger.info(configureFileName + " is ready.");
}
} | java | public synchronized void prepareAppRoot(String configureFileName) throws Exception {
if (!cb.isKernelStartup()) {
cb.registerAppRoot(configureFileName);
logger.info(configureFileName + " is ready.");
}
} | [
"public",
"synchronized",
"void",
"prepareAppRoot",
"(",
"String",
"configureFileName",
")",
"throws",
"Exception",
"{",
"if",
"(",
"!",
"cb",
".",
"isKernelStartup",
"(",
")",
")",
"{",
"cb",
".",
"registerAppRoot",
"(",
"configureFileName",
")",
";",
"logger",
".",
"info",
"(",
"configureFileName",
"+",
"\" is ready.\"",
")",
";",
"}",
"}"
] | prepare the applicaition configure files
@param configureFileName | [
"prepare",
"the",
"applicaition",
"configure",
"files"
] | 72b451caac04f775e57f52aaed3d8775044ead53 | https://github.com/banq/jdonframework/blob/72b451caac04f775e57f52aaed3d8775044ead53/src/main/java/com/jdon/container/builder/ContainerDirector.java#L46-L51 |
23,572 | banq/jdonframework | src/main/java/com/jdon/container/pico/JdonPicoContainer.java | JdonPicoContainer.getInstance | public Object getInstance(ComponentAdapter componentAdapter) {
Object componentKey = componentAdapter.getComponentKey();
Object instance = compKeyInstances.get(componentKey);
if (instance == null) {
instance = loadSaveInstance(componentAdapter, componentKey);
}
return instance;
} | java | public Object getInstance(ComponentAdapter componentAdapter) {
Object componentKey = componentAdapter.getComponentKey();
Object instance = compKeyInstances.get(componentKey);
if (instance == null) {
instance = loadSaveInstance(componentAdapter, componentKey);
}
return instance;
} | [
"public",
"Object",
"getInstance",
"(",
"ComponentAdapter",
"componentAdapter",
")",
"{",
"Object",
"componentKey",
"=",
"componentAdapter",
".",
"getComponentKey",
"(",
")",
";",
"Object",
"instance",
"=",
"compKeyInstances",
".",
"get",
"(",
"componentKey",
")",
";",
"if",
"(",
"instance",
"==",
"null",
")",
"{",
"instance",
"=",
"loadSaveInstance",
"(",
"componentAdapter",
",",
"componentKey",
")",
";",
"}",
"return",
"instance",
";",
"}"
] | modify this method of old DefaultPicocontainer
@param componentAdapter
@return | [
"modify",
"this",
"method",
"of",
"old",
"DefaultPicocontainer"
] | 72b451caac04f775e57f52aaed3d8775044ead53 | https://github.com/banq/jdonframework/blob/72b451caac04f775e57f52aaed3d8775044ead53/src/main/java/com/jdon/container/pico/JdonPicoContainer.java#L331-L338 |
23,573 | banq/jdonframework | JdonAccessory/jdon-hibernate3x/src/main/java/com/jdon/model/query/JdbcTemp.java | JdbcTemp.querySingleObject | public Object querySingleObject(Collection queryParams, String sqlquery) throws Exception {
Debug.logVerbose("[JdonFramework]--> enter getSingleObject ", module);
Connection c = null;
PreparedStatement ps = null;
ResultSet rs = null;
Object o = null;
try {
c = dataSource.getConnection();
ps = c.prepareStatement(sqlquery, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
Debug.logVerbose(sqlquery, module);
jdbcUtil.setQueryParams(queryParams, ps);
rs = ps.executeQuery();
if (rs.first()) {
o = rs.getObject(1);
Debug.logVerbose("[JdonFramework]-->in db found it:" + o.getClass().getName(), module);
}
} catch (SQLException se) {
throw new SQLException("SQLException: " + se.getMessage());
} catch (Exception ex) {
Debug.logError(ex, module);
throw new Exception(ex);
} finally {
if (rs != null)
try {
rs.close();
} catch (SQLException quiet) {
}
if (ps != null)
try {
ps.close();
} catch (SQLException quiet) {
}
if (c != null)
try {
c.close();
} catch (SQLException quiet) {
}
}
return o;
} | java | public Object querySingleObject(Collection queryParams, String sqlquery) throws Exception {
Debug.logVerbose("[JdonFramework]--> enter getSingleObject ", module);
Connection c = null;
PreparedStatement ps = null;
ResultSet rs = null;
Object o = null;
try {
c = dataSource.getConnection();
ps = c.prepareStatement(sqlquery, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
Debug.logVerbose(sqlquery, module);
jdbcUtil.setQueryParams(queryParams, ps);
rs = ps.executeQuery();
if (rs.first()) {
o = rs.getObject(1);
Debug.logVerbose("[JdonFramework]-->in db found it:" + o.getClass().getName(), module);
}
} catch (SQLException se) {
throw new SQLException("SQLException: " + se.getMessage());
} catch (Exception ex) {
Debug.logError(ex, module);
throw new Exception(ex);
} finally {
if (rs != null)
try {
rs.close();
} catch (SQLException quiet) {
}
if (ps != null)
try {
ps.close();
} catch (SQLException quiet) {
}
if (c != null)
try {
c.close();
} catch (SQLException quiet) {
}
}
return o;
} | [
"public",
"Object",
"querySingleObject",
"(",
"Collection",
"queryParams",
",",
"String",
"sqlquery",
")",
"throws",
"Exception",
"{",
"Debug",
".",
"logVerbose",
"(",
"\"[JdonFramework]--> enter getSingleObject \"",
",",
"module",
")",
";",
"Connection",
"c",
"=",
"null",
";",
"PreparedStatement",
"ps",
"=",
"null",
";",
"ResultSet",
"rs",
"=",
"null",
";",
"Object",
"o",
"=",
"null",
";",
"try",
"{",
"c",
"=",
"dataSource",
".",
"getConnection",
"(",
")",
";",
"ps",
"=",
"c",
".",
"prepareStatement",
"(",
"sqlquery",
",",
"ResultSet",
".",
"TYPE_SCROLL_INSENSITIVE",
",",
"ResultSet",
".",
"CONCUR_READ_ONLY",
")",
";",
"Debug",
".",
"logVerbose",
"(",
"sqlquery",
",",
"module",
")",
";",
"jdbcUtil",
".",
"setQueryParams",
"(",
"queryParams",
",",
"ps",
")",
";",
"rs",
"=",
"ps",
".",
"executeQuery",
"(",
")",
";",
"if",
"(",
"rs",
".",
"first",
"(",
")",
")",
"{",
"o",
"=",
"rs",
".",
"getObject",
"(",
"1",
")",
";",
"Debug",
".",
"logVerbose",
"(",
"\"[JdonFramework]-->in db found it:\"",
"+",
"o",
".",
"getClass",
"(",
")",
".",
"getName",
"(",
")",
",",
"module",
")",
";",
"}",
"}",
"catch",
"(",
"SQLException",
"se",
")",
"{",
"throw",
"new",
"SQLException",
"(",
"\"SQLException: \"",
"+",
"se",
".",
"getMessage",
"(",
")",
")",
";",
"}",
"catch",
"(",
"Exception",
"ex",
")",
"{",
"Debug",
".",
"logError",
"(",
"ex",
",",
"module",
")",
";",
"throw",
"new",
"Exception",
"(",
"ex",
")",
";",
"}",
"finally",
"{",
"if",
"(",
"rs",
"!=",
"null",
")",
"try",
"{",
"rs",
".",
"close",
"(",
")",
";",
"}",
"catch",
"(",
"SQLException",
"quiet",
")",
"{",
"}",
"if",
"(",
"ps",
"!=",
"null",
")",
"try",
"{",
"ps",
".",
"close",
"(",
")",
";",
"}",
"catch",
"(",
"SQLException",
"quiet",
")",
"{",
"}",
"if",
"(",
"c",
"!=",
"null",
")",
"try",
"{",
"c",
".",
"close",
"(",
")",
";",
"}",
"catch",
"(",
"SQLException",
"quiet",
")",
"{",
"}",
"}",
"return",
"o",
";",
"}"
] | get a single object from database
fit for this sql: select name from user where id=?
the "name" is single result
@param queryParams
@param sqlquery
@return
@throws Exception | [
"get",
"a",
"single",
"object",
"from",
"database"
] | 72b451caac04f775e57f52aaed3d8775044ead53 | https://github.com/banq/jdonframework/blob/72b451caac04f775e57f52aaed3d8775044ead53/JdonAccessory/jdon-hibernate3x/src/main/java/com/jdon/model/query/JdbcTemp.java#L61-L102 |
23,574 | banq/jdonframework | src/main/java/com/jdon/util/SetCharacterEncodingFilter.java | SetCharacterEncodingFilter.init | public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
this.encoding = filterConfig.getInitParameter("encoding");
String value = filterConfig.getInitParameter("ignore");
if (value == null)
this.ignore = true;
else if (value.equalsIgnoreCase("true"))
this.ignore = true;
else if (value.equalsIgnoreCase("yes"))
this.ignore = true;
else
this.ignore = false;
} | java | public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
this.encoding = filterConfig.getInitParameter("encoding");
String value = filterConfig.getInitParameter("ignore");
if (value == null)
this.ignore = true;
else if (value.equalsIgnoreCase("true"))
this.ignore = true;
else if (value.equalsIgnoreCase("yes"))
this.ignore = true;
else
this.ignore = false;
} | [
"public",
"void",
"init",
"(",
"FilterConfig",
"filterConfig",
")",
"throws",
"ServletException",
"{",
"this",
".",
"filterConfig",
"=",
"filterConfig",
";",
"this",
".",
"encoding",
"=",
"filterConfig",
".",
"getInitParameter",
"(",
"\"encoding\"",
")",
";",
"String",
"value",
"=",
"filterConfig",
".",
"getInitParameter",
"(",
"\"ignore\"",
")",
";",
"if",
"(",
"value",
"==",
"null",
")",
"this",
".",
"ignore",
"=",
"true",
";",
"else",
"if",
"(",
"value",
".",
"equalsIgnoreCase",
"(",
"\"true\"",
")",
")",
"this",
".",
"ignore",
"=",
"true",
";",
"else",
"if",
"(",
"value",
".",
"equalsIgnoreCase",
"(",
"\"yes\"",
")",
")",
"this",
".",
"ignore",
"=",
"true",
";",
"else",
"this",
".",
"ignore",
"=",
"false",
";",
"}"
] | Place this filter into service.
@param filterConfig The filter configuration object | [
"Place",
"this",
"filter",
"into",
"service",
"."
] | 72b451caac04f775e57f52aaed3d8775044ead53 | https://github.com/banq/jdonframework/blob/72b451caac04f775e57f52aaed3d8775044ead53/src/main/java/com/jdon/util/SetCharacterEncodingFilter.java#L101-L115 |
23,575 | banq/jdonframework | src/main/java/com/jdon/util/RequestUtil.java | RequestUtil.getRequestParameters | public static String getRequestParameters(HttpServletRequest aRequest) {
// set the ALGORIGTHM as defined for the application
// ALGORITHM = (String) aRequest.getAttribute(Constants.ENC_ALGORITHM);
Map m = aRequest.getParameterMap();
return createQueryStringFromMap(m, "&").toString();
} | java | public static String getRequestParameters(HttpServletRequest aRequest) {
// set the ALGORIGTHM as defined for the application
// ALGORITHM = (String) aRequest.getAttribute(Constants.ENC_ALGORITHM);
Map m = aRequest.getParameterMap();
return createQueryStringFromMap(m, "&").toString();
} | [
"public",
"static",
"String",
"getRequestParameters",
"(",
"HttpServletRequest",
"aRequest",
")",
"{",
"// set the ALGORIGTHM as defined for the application\r",
"// ALGORITHM = (String) aRequest.getAttribute(Constants.ENC_ALGORITHM);\r",
"Map",
"m",
"=",
"aRequest",
".",
"getParameterMap",
"(",
")",
";",
"return",
"createQueryStringFromMap",
"(",
"m",
",",
"\"&\"",
")",
".",
"toString",
"(",
")",
";",
"}"
] | Creates query String from request body parameters | [
"Creates",
"query",
"String",
"from",
"request",
"body",
"parameters"
] | 72b451caac04f775e57f52aaed3d8775044ead53 | https://github.com/banq/jdonframework/blob/72b451caac04f775e57f52aaed3d8775044ead53/src/main/java/com/jdon/util/RequestUtil.java#L37-L43 |
23,576 | banq/jdonframework | src/main/java/com/jdon/util/RequestUtil.java | RequestUtil.createQueryStringFromMap | public static StringBuilder createQueryStringFromMap(Map m, String ampersand) {
StringBuilder aReturn = new StringBuilder("");
Set aEntryS = m.entrySet();
Iterator aEntryI = aEntryS.iterator();
while (aEntryI.hasNext()) {
Map.Entry aEntry = (Map.Entry) aEntryI.next();
Object o = aEntry.getValue();
if (o == null) {
append(aEntry.getKey(), "", aReturn, ampersand);
} else if (o instanceof String) {
append(aEntry.getKey(), o, aReturn, ampersand);
} else if (o instanceof String[]) {
String[] aValues = (String[]) o;
for (int i = 0; i < aValues.length; i++) {
append(aEntry.getKey(), aValues[i], aReturn, ampersand);
}
} else {
append(aEntry.getKey(), o, aReturn, ampersand);
}
}
return aReturn;
} | java | public static StringBuilder createQueryStringFromMap(Map m, String ampersand) {
StringBuilder aReturn = new StringBuilder("");
Set aEntryS = m.entrySet();
Iterator aEntryI = aEntryS.iterator();
while (aEntryI.hasNext()) {
Map.Entry aEntry = (Map.Entry) aEntryI.next();
Object o = aEntry.getValue();
if (o == null) {
append(aEntry.getKey(), "", aReturn, ampersand);
} else if (o instanceof String) {
append(aEntry.getKey(), o, aReturn, ampersand);
} else if (o instanceof String[]) {
String[] aValues = (String[]) o;
for (int i = 0; i < aValues.length; i++) {
append(aEntry.getKey(), aValues[i], aReturn, ampersand);
}
} else {
append(aEntry.getKey(), o, aReturn, ampersand);
}
}
return aReturn;
} | [
"public",
"static",
"StringBuilder",
"createQueryStringFromMap",
"(",
"Map",
"m",
",",
"String",
"ampersand",
")",
"{",
"StringBuilder",
"aReturn",
"=",
"new",
"StringBuilder",
"(",
"\"\"",
")",
";",
"Set",
"aEntryS",
"=",
"m",
".",
"entrySet",
"(",
")",
";",
"Iterator",
"aEntryI",
"=",
"aEntryS",
".",
"iterator",
"(",
")",
";",
"while",
"(",
"aEntryI",
".",
"hasNext",
"(",
")",
")",
"{",
"Map",
".",
"Entry",
"aEntry",
"=",
"(",
"Map",
".",
"Entry",
")",
"aEntryI",
".",
"next",
"(",
")",
";",
"Object",
"o",
"=",
"aEntry",
".",
"getValue",
"(",
")",
";",
"if",
"(",
"o",
"==",
"null",
")",
"{",
"append",
"(",
"aEntry",
".",
"getKey",
"(",
")",
",",
"\"\"",
",",
"aReturn",
",",
"ampersand",
")",
";",
"}",
"else",
"if",
"(",
"o",
"instanceof",
"String",
")",
"{",
"append",
"(",
"aEntry",
".",
"getKey",
"(",
")",
",",
"o",
",",
"aReturn",
",",
"ampersand",
")",
";",
"}",
"else",
"if",
"(",
"o",
"instanceof",
"String",
"[",
"]",
")",
"{",
"String",
"[",
"]",
"aValues",
"=",
"(",
"String",
"[",
"]",
")",
"o",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"aValues",
".",
"length",
";",
"i",
"++",
")",
"{",
"append",
"(",
"aEntry",
".",
"getKey",
"(",
")",
",",
"aValues",
"[",
"i",
"]",
",",
"aReturn",
",",
"ampersand",
")",
";",
"}",
"}",
"else",
"{",
"append",
"(",
"aEntry",
".",
"getKey",
"(",
")",
",",
"o",
",",
"aReturn",
",",
"ampersand",
")",
";",
"}",
"}",
"return",
"aReturn",
";",
"}"
] | Builds a query string from a given map of parameters
@param m
A map of parameters
@param ampersand
String to use for ampersands (e.g. "&" or "&" )
@return query string (with no leading "?") | [
"Builds",
"a",
"query",
"string",
"from",
"a",
"given",
"map",
"of",
"parameters"
] | 72b451caac04f775e57f52aaed3d8775044ead53 | https://github.com/banq/jdonframework/blob/72b451caac04f775e57f52aaed3d8775044ead53/src/main/java/com/jdon/util/RequestUtil.java#L55-L80 |
23,577 | banq/jdonframework | src/main/java/com/jdon/util/RequestUtil.java | RequestUtil.append | private static StringBuilder append(Object key, Object value, StringBuilder queryString, String ampersand) {
if (queryString.length() > 0) {
queryString.append(ampersand);
}
// Use encodeURL from Struts' RequestUtils class - it's JDK 1.3 and 1.4
// compliant
queryString.append(encodeURL(key.toString()));
queryString.append("=");
queryString.append(encodeURL(value.toString()));
return queryString;
} | java | private static StringBuilder append(Object key, Object value, StringBuilder queryString, String ampersand) {
if (queryString.length() > 0) {
queryString.append(ampersand);
}
// Use encodeURL from Struts' RequestUtils class - it's JDK 1.3 and 1.4
// compliant
queryString.append(encodeURL(key.toString()));
queryString.append("=");
queryString.append(encodeURL(value.toString()));
return queryString;
} | [
"private",
"static",
"StringBuilder",
"append",
"(",
"Object",
"key",
",",
"Object",
"value",
",",
"StringBuilder",
"queryString",
",",
"String",
"ampersand",
")",
"{",
"if",
"(",
"queryString",
".",
"length",
"(",
")",
">",
"0",
")",
"{",
"queryString",
".",
"append",
"(",
"ampersand",
")",
";",
"}",
"// Use encodeURL from Struts' RequestUtils class - it's JDK 1.3 and 1.4\r",
"// compliant\r",
"queryString",
".",
"append",
"(",
"encodeURL",
"(",
"key",
".",
"toString",
"(",
")",
")",
")",
";",
"queryString",
".",
"append",
"(",
"\"=\"",
")",
";",
"queryString",
".",
"append",
"(",
"encodeURL",
"(",
"value",
".",
"toString",
"(",
")",
")",
")",
";",
"return",
"queryString",
";",
"}"
] | Appends new key and value pair to query string
@param key
parameter name
@param value
value of parameter
@param queryString
existing query string
@param ampersand
string to use for ampersand (e.g. "&" or "&")
@return query string (with no leading "?") | [
"Appends",
"new",
"key",
"and",
"value",
"pair",
"to",
"query",
"string"
] | 72b451caac04f775e57f52aaed3d8775044ead53 | https://github.com/banq/jdonframework/blob/72b451caac04f775e57f52aaed3d8775044ead53/src/main/java/com/jdon/util/RequestUtil.java#L96-L108 |
23,578 | banq/jdonframework | src/main/java/com/jdon/util/RequestUtil.java | RequestUtil.stowRequestAttributes | public static void stowRequestAttributes(HttpServletRequest aRequest) {
if (aRequest.getSession().getAttribute(STOWED_REQUEST_ATTRIBS) != null) {
return;
}
Enumeration e = aRequest.getAttributeNames();
Map map = new HashMap();
while (e.hasMoreElements()) {
String name = (String) e.nextElement();
map.put(name, aRequest.getAttribute(name));
}
aRequest.getSession().setAttribute(STOWED_REQUEST_ATTRIBS, map);
} | java | public static void stowRequestAttributes(HttpServletRequest aRequest) {
if (aRequest.getSession().getAttribute(STOWED_REQUEST_ATTRIBS) != null) {
return;
}
Enumeration e = aRequest.getAttributeNames();
Map map = new HashMap();
while (e.hasMoreElements()) {
String name = (String) e.nextElement();
map.put(name, aRequest.getAttribute(name));
}
aRequest.getSession().setAttribute(STOWED_REQUEST_ATTRIBS, map);
} | [
"public",
"static",
"void",
"stowRequestAttributes",
"(",
"HttpServletRequest",
"aRequest",
")",
"{",
"if",
"(",
"aRequest",
".",
"getSession",
"(",
")",
".",
"getAttribute",
"(",
"STOWED_REQUEST_ATTRIBS",
")",
"!=",
"null",
")",
"{",
"return",
";",
"}",
"Enumeration",
"e",
"=",
"aRequest",
".",
"getAttributeNames",
"(",
")",
";",
"Map",
"map",
"=",
"new",
"HashMap",
"(",
")",
";",
"while",
"(",
"e",
".",
"hasMoreElements",
"(",
")",
")",
"{",
"String",
"name",
"=",
"(",
"String",
")",
"e",
".",
"nextElement",
"(",
")",
";",
"map",
".",
"put",
"(",
"name",
",",
"aRequest",
".",
"getAttribute",
"(",
"name",
")",
")",
";",
"}",
"aRequest",
".",
"getSession",
"(",
")",
".",
"setAttribute",
"(",
"STOWED_REQUEST_ATTRIBS",
",",
"map",
")",
";",
"}"
] | Stores request attributes in session
@param aRequest
the current request | [
"Stores",
"request",
"attributes",
"in",
"session"
] | 72b451caac04f775e57f52aaed3d8775044ead53 | https://github.com/banq/jdonframework/blob/72b451caac04f775e57f52aaed3d8775044ead53/src/main/java/com/jdon/util/RequestUtil.java#L116-L130 |
23,579 | banq/jdonframework | src/main/java/com/jdon/util/RequestUtil.java | RequestUtil.reclaimRequestAttributes | public static void reclaimRequestAttributes(HttpServletRequest aRequest) {
Map map = (Map) aRequest.getSession().getAttribute(STOWED_REQUEST_ATTRIBS);
if (map == null) {
return;
}
Iterator itr = map.keySet().iterator();
while (itr.hasNext()) {
String name = (String) itr.next();
aRequest.setAttribute(name, map.get(name));
}
aRequest.getSession().removeAttribute(STOWED_REQUEST_ATTRIBS);
} | java | public static void reclaimRequestAttributes(HttpServletRequest aRequest) {
Map map = (Map) aRequest.getSession().getAttribute(STOWED_REQUEST_ATTRIBS);
if (map == null) {
return;
}
Iterator itr = map.keySet().iterator();
while (itr.hasNext()) {
String name = (String) itr.next();
aRequest.setAttribute(name, map.get(name));
}
aRequest.getSession().removeAttribute(STOWED_REQUEST_ATTRIBS);
} | [
"public",
"static",
"void",
"reclaimRequestAttributes",
"(",
"HttpServletRequest",
"aRequest",
")",
"{",
"Map",
"map",
"=",
"(",
"Map",
")",
"aRequest",
".",
"getSession",
"(",
")",
".",
"getAttribute",
"(",
"STOWED_REQUEST_ATTRIBS",
")",
";",
"if",
"(",
"map",
"==",
"null",
")",
"{",
"return",
";",
"}",
"Iterator",
"itr",
"=",
"map",
".",
"keySet",
"(",
")",
".",
"iterator",
"(",
")",
";",
"while",
"(",
"itr",
".",
"hasNext",
"(",
")",
")",
"{",
"String",
"name",
"=",
"(",
"String",
")",
"itr",
".",
"next",
"(",
")",
";",
"aRequest",
".",
"setAttribute",
"(",
"name",
",",
"map",
".",
"get",
"(",
"name",
")",
")",
";",
"}",
"aRequest",
".",
"getSession",
"(",
")",
".",
"removeAttribute",
"(",
"STOWED_REQUEST_ATTRIBS",
")",
";",
"}"
] | Returns request attributes from session to request
@param aRequest
DOCUMENT ME! | [
"Returns",
"request",
"attributes",
"from",
"session",
"to",
"request"
] | 72b451caac04f775e57f52aaed3d8775044ead53 | https://github.com/banq/jdonframework/blob/72b451caac04f775e57f52aaed3d8775044ead53/src/main/java/com/jdon/util/RequestUtil.java#L138-L153 |
23,580 | banq/jdonframework | src/main/java/com/jdon/util/RequestUtil.java | RequestUtil.setCookie | public static void setCookie(HttpServletResponse response, String name, String value, String path) {
Cookie cookie = new Cookie(name, value);
cookie.setSecure(false);
cookie.setPath(path);
cookie.setMaxAge(3600 * 24 * 30); // 30 days
response.addCookie(cookie);
} | java | public static void setCookie(HttpServletResponse response, String name, String value, String path) {
Cookie cookie = new Cookie(name, value);
cookie.setSecure(false);
cookie.setPath(path);
cookie.setMaxAge(3600 * 24 * 30); // 30 days
response.addCookie(cookie);
} | [
"public",
"static",
"void",
"setCookie",
"(",
"HttpServletResponse",
"response",
",",
"String",
"name",
",",
"String",
"value",
",",
"String",
"path",
")",
"{",
"Cookie",
"cookie",
"=",
"new",
"Cookie",
"(",
"name",
",",
"value",
")",
";",
"cookie",
".",
"setSecure",
"(",
"false",
")",
";",
"cookie",
".",
"setPath",
"(",
"path",
")",
";",
"cookie",
".",
"setMaxAge",
"(",
"3600",
"*",
"24",
"*",
"30",
")",
";",
"// 30 days\r",
"response",
".",
"addCookie",
"(",
"cookie",
")",
";",
"}"
] | Convenience method to set a cookie
@param response
@param name
@param value
@param path
@return HttpServletResponse | [
"Convenience",
"method",
"to",
"set",
"a",
"cookie"
] | 72b451caac04f775e57f52aaed3d8775044ead53 | https://github.com/banq/jdonframework/blob/72b451caac04f775e57f52aaed3d8775044ead53/src/main/java/com/jdon/util/RequestUtil.java#L182-L190 |
23,581 | banq/jdonframework | src/main/java/com/jdon/util/RequestUtil.java | RequestUtil.getAppURL | public static String getAppURL(HttpServletRequest request) {
StringBuffer url = new StringBuffer();
int port = request.getServerPort();
if (port < 0) {
port = 80; // Work around java.net.URL bug
}
String scheme = request.getScheme();
url.append(scheme);
url.append("://");
url.append(request.getServerName());
if ((scheme.equals("http") && (port != 80)) || (scheme.equals("https") && (port != 443))) {
url.append(':');
url.append(port);
}
return url.toString();
} | java | public static String getAppURL(HttpServletRequest request) {
StringBuffer url = new StringBuffer();
int port = request.getServerPort();
if (port < 0) {
port = 80; // Work around java.net.URL bug
}
String scheme = request.getScheme();
url.append(scheme);
url.append("://");
url.append(request.getServerName());
if ((scheme.equals("http") && (port != 80)) || (scheme.equals("https") && (port != 443))) {
url.append(':');
url.append(port);
}
return url.toString();
} | [
"public",
"static",
"String",
"getAppURL",
"(",
"HttpServletRequest",
"request",
")",
"{",
"StringBuffer",
"url",
"=",
"new",
"StringBuffer",
"(",
")",
";",
"int",
"port",
"=",
"request",
".",
"getServerPort",
"(",
")",
";",
"if",
"(",
"port",
"<",
"0",
")",
"{",
"port",
"=",
"80",
";",
"// Work around java.net.URL bug\r",
"}",
"String",
"scheme",
"=",
"request",
".",
"getScheme",
"(",
")",
";",
"url",
".",
"append",
"(",
"scheme",
")",
";",
"url",
".",
"append",
"(",
"\"://\"",
")",
";",
"url",
".",
"append",
"(",
"request",
".",
"getServerName",
"(",
")",
")",
";",
"if",
"(",
"(",
"scheme",
".",
"equals",
"(",
"\"http\"",
")",
"&&",
"(",
"port",
"!=",
"80",
")",
")",
"||",
"(",
"scheme",
".",
"equals",
"(",
"\"https\"",
")",
"&&",
"(",
"port",
"!=",
"443",
")",
")",
")",
"{",
"url",
".",
"append",
"(",
"'",
"'",
")",
";",
"url",
".",
"append",
"(",
"port",
")",
";",
"}",
"return",
"url",
".",
"toString",
"(",
")",
";",
"}"
] | Convenience method to get the application's URL based on request
variables. | [
"Convenience",
"method",
"to",
"get",
"the",
"application",
"s",
"URL",
"based",
"on",
"request",
"variables",
"."
] | 72b451caac04f775e57f52aaed3d8775044ead53 | https://github.com/banq/jdonframework/blob/72b451caac04f775e57f52aaed3d8775044ead53/src/main/java/com/jdon/util/RequestUtil.java#L249-L264 |
23,582 | banq/jdonframework | src/main/java/com/jdon/util/RequestUtil.java | RequestUtil.decodePasswordCookie | private static String[] decodePasswordCookie(String cookieVal) {
// check that the cookie value isn't null or zero-length
if (cookieVal == null || cookieVal.length() <= 0) {
return null;
}
// unrafel the cookie value
char[] chars = cookieVal.toCharArray();
byte[] bytes = new byte[chars.length / 2];
int b;
for (int n = 0, m = 0; n < bytes.length; n++) {
b = chars[m++] - ENCODE_CHAR_OFFSET1;
b |= (chars[m++] - ENCODE_CHAR_OFFSET2) << 4;
bytes[n] = (byte) (b ^ (ENCODE_XORMASK + n));
}
cookieVal = new String(bytes);
int pos = cookieVal.indexOf(ENCODE_DELIMETER);
String username = (pos < 0) ? "" : cookieVal.substring(0, pos);
String password = (pos < 0) ? "" : cookieVal.substring(pos + 1);
return new String[] { username, password };
} | java | private static String[] decodePasswordCookie(String cookieVal) {
// check that the cookie value isn't null or zero-length
if (cookieVal == null || cookieVal.length() <= 0) {
return null;
}
// unrafel the cookie value
char[] chars = cookieVal.toCharArray();
byte[] bytes = new byte[chars.length / 2];
int b;
for (int n = 0, m = 0; n < bytes.length; n++) {
b = chars[m++] - ENCODE_CHAR_OFFSET1;
b |= (chars[m++] - ENCODE_CHAR_OFFSET2) << 4;
bytes[n] = (byte) (b ^ (ENCODE_XORMASK + n));
}
cookieVal = new String(bytes);
int pos = cookieVal.indexOf(ENCODE_DELIMETER);
String username = (pos < 0) ? "" : cookieVal.substring(0, pos);
String password = (pos < 0) ? "" : cookieVal.substring(pos + 1);
return new String[] { username, password };
} | [
"private",
"static",
"String",
"[",
"]",
"decodePasswordCookie",
"(",
"String",
"cookieVal",
")",
"{",
"// check that the cookie value isn't null or zero-length\r",
"if",
"(",
"cookieVal",
"==",
"null",
"||",
"cookieVal",
".",
"length",
"(",
")",
"<=",
"0",
")",
"{",
"return",
"null",
";",
"}",
"// unrafel the cookie value\r",
"char",
"[",
"]",
"chars",
"=",
"cookieVal",
".",
"toCharArray",
"(",
")",
";",
"byte",
"[",
"]",
"bytes",
"=",
"new",
"byte",
"[",
"chars",
".",
"length",
"/",
"2",
"]",
";",
"int",
"b",
";",
"for",
"(",
"int",
"n",
"=",
"0",
",",
"m",
"=",
"0",
";",
"n",
"<",
"bytes",
".",
"length",
";",
"n",
"++",
")",
"{",
"b",
"=",
"chars",
"[",
"m",
"++",
"]",
"-",
"ENCODE_CHAR_OFFSET1",
";",
"b",
"|=",
"(",
"chars",
"[",
"m",
"++",
"]",
"-",
"ENCODE_CHAR_OFFSET2",
")",
"<<",
"4",
";",
"bytes",
"[",
"n",
"]",
"=",
"(",
"byte",
")",
"(",
"b",
"^",
"(",
"ENCODE_XORMASK",
"+",
"n",
")",
")",
";",
"}",
"cookieVal",
"=",
"new",
"String",
"(",
"bytes",
")",
";",
"int",
"pos",
"=",
"cookieVal",
".",
"indexOf",
"(",
"ENCODE_DELIMETER",
")",
";",
"String",
"username",
"=",
"(",
"pos",
"<",
"0",
")",
"?",
"\"\"",
":",
"cookieVal",
".",
"substring",
"(",
"0",
",",
"pos",
")",
";",
"String",
"password",
"=",
"(",
"pos",
"<",
"0",
")",
"?",
"\"\"",
":",
"cookieVal",
".",
"substring",
"(",
"pos",
"+",
"1",
")",
";",
"return",
"new",
"String",
"[",
"]",
"{",
"username",
",",
"password",
"}",
";",
"}"
] | Unrafels a cookie string containing a username and password.
@param value
The cookie value.
@return String[] containing the username at index 0 and the password at
index 1, or <code>{ null, null }</code> if cookieVal equals
<code>null</code> or the empty string. | [
"Unrafels",
"a",
"cookie",
"string",
"containing",
"a",
"username",
"and",
"password",
"."
] | 72b451caac04f775e57f52aaed3d8775044ead53 | https://github.com/banq/jdonframework/blob/72b451caac04f775e57f52aaed3d8775044ead53/src/main/java/com/jdon/util/RequestUtil.java#L334-L356 |
23,583 | banq/jdonframework | src/main/java/com/jdon/controller/WebAppUtil.java | WebAppUtil.getComponentInstance | public static Object getComponentInstance(String name, HttpServletRequest request) {
ServletContext sc = request.getSession().getServletContext();
ContainerWrapper containerWrapper = scf.findContainer(new ServletContextWrapper(sc));
if (!containerWrapper.isStart()) {
Debug.logError("JdonFramework not yet started, please try later ", module);
return null;
}
return containerWrapper.lookup(name);
} | java | public static Object getComponentInstance(String name, HttpServletRequest request) {
ServletContext sc = request.getSession().getServletContext();
ContainerWrapper containerWrapper = scf.findContainer(new ServletContextWrapper(sc));
if (!containerWrapper.isStart()) {
Debug.logError("JdonFramework not yet started, please try later ", module);
return null;
}
return containerWrapper.lookup(name);
} | [
"public",
"static",
"Object",
"getComponentInstance",
"(",
"String",
"name",
",",
"HttpServletRequest",
"request",
")",
"{",
"ServletContext",
"sc",
"=",
"request",
".",
"getSession",
"(",
")",
".",
"getServletContext",
"(",
")",
";",
"ContainerWrapper",
"containerWrapper",
"=",
"scf",
".",
"findContainer",
"(",
"new",
"ServletContextWrapper",
"(",
"sc",
")",
")",
";",
"if",
"(",
"!",
"containerWrapper",
".",
"isStart",
"(",
")",
")",
"{",
"Debug",
".",
"logError",
"(",
"\"JdonFramework not yet started, please try later \"",
",",
"module",
")",
";",
"return",
"null",
";",
"}",
"return",
"containerWrapper",
".",
"lookup",
"(",
"name",
")",
";",
"}"
] | get a component that registered in container. the component is not
different from the service. the component instance is single instance Any
intercepter will be disable | [
"get",
"a",
"component",
"that",
"registered",
"in",
"container",
".",
"the",
"component",
"is",
"not",
"different",
"from",
"the",
"service",
".",
"the",
"component",
"instance",
"is",
"single",
"instance",
"Any",
"intercepter",
"will",
"be",
"disable"
] | 72b451caac04f775e57f52aaed3d8775044ead53 | https://github.com/banq/jdonframework/blob/72b451caac04f775e57f52aaed3d8775044ead53/src/main/java/com/jdon/controller/WebAppUtil.java#L136-L144 |
23,584 | banq/jdonframework | src/main/java/com/jdon/controller/WebAppUtil.java | WebAppUtil.getContainer | public static ContainerWrapper getContainer(HttpServletRequest request) throws Exception {
ContainerFinderImp scf = new ContainerFinderImp();
ServletContext sc = request.getSession().getServletContext();
return scf.findContainer(new ServletContextWrapper(sc));
} | java | public static ContainerWrapper getContainer(HttpServletRequest request) throws Exception {
ContainerFinderImp scf = new ContainerFinderImp();
ServletContext sc = request.getSession().getServletContext();
return scf.findContainer(new ServletContextWrapper(sc));
} | [
"public",
"static",
"ContainerWrapper",
"getContainer",
"(",
"HttpServletRequest",
"request",
")",
"throws",
"Exception",
"{",
"ContainerFinderImp",
"scf",
"=",
"new",
"ContainerFinderImp",
"(",
")",
";",
"ServletContext",
"sc",
"=",
"request",
".",
"getSession",
"(",
")",
".",
"getServletContext",
"(",
")",
";",
"return",
"scf",
".",
"findContainer",
"(",
"new",
"ServletContextWrapper",
"(",
"sc",
")",
")",
";",
"}"
] | get this Web application's container
@param request
HttpServletRequest
@return ContainerWrapper
@throws Exception | [
"get",
"this",
"Web",
"application",
"s",
"container"
] | 72b451caac04f775e57f52aaed3d8775044ead53 | https://github.com/banq/jdonframework/blob/72b451caac04f775e57f52aaed3d8775044ead53/src/main/java/com/jdon/controller/WebAppUtil.java#L231-L235 |
23,585 | banq/jdonframework | src/main/java/com/jdon/domain/dci/RoleAssigner.java | RoleAssigner.assignAggregateRoot | public Object assignAggregateRoot(Object datamodel) {
modelProxyInjection.injectProperties(datamodel);
return modelAdvisor.createProxy(datamodel);
} | java | public Object assignAggregateRoot(Object datamodel) {
modelProxyInjection.injectProperties(datamodel);
return modelAdvisor.createProxy(datamodel);
} | [
"public",
"Object",
"assignAggregateRoot",
"(",
"Object",
"datamodel",
")",
"{",
"modelProxyInjection",
".",
"injectProperties",
"(",
"datamodel",
")",
";",
"return",
"modelAdvisor",
".",
"createProxy",
"(",
"datamodel",
")",
";",
"}"
] | assign a object as a AggregateRoot role, AggregateRoot can receive a
command and reactive a event in CQRS.
when we get a domain mode from repository with @introduce("modelcache")
and @Around, the mode has been assign as a AggregateRoot;no need call
this method.
@param datamodel | [
"assign",
"a",
"object",
"as",
"a",
"AggregateRoot",
"role",
"AggregateRoot",
"can",
"receive",
"a",
"command",
"and",
"reactive",
"a",
"event",
"in",
"CQRS",
"."
] | 72b451caac04f775e57f52aaed3d8775044ead53 | https://github.com/banq/jdonframework/blob/72b451caac04f775e57f52aaed3d8775044ead53/src/main/java/com/jdon/domain/dci/RoleAssigner.java#L61-L64 |
23,586 | banq/jdonframework | src/main/java/com/jdon/util/task/TaskEngine.java | TaskEngine.scheduleTask | public static TimerTask scheduleTask(Runnable task, long delay, long period) {
TimerTask timerTask = new ScheduledTask(task);
taskTimer.scheduleAtFixedRate(timerTask, delay, period);
return timerTask;
} | java | public static TimerTask scheduleTask(Runnable task, long delay, long period) {
TimerTask timerTask = new ScheduledTask(task);
taskTimer.scheduleAtFixedRate(timerTask, delay, period);
return timerTask;
} | [
"public",
"static",
"TimerTask",
"scheduleTask",
"(",
"Runnable",
"task",
",",
"long",
"delay",
",",
"long",
"period",
")",
"{",
"TimerTask",
"timerTask",
"=",
"new",
"ScheduledTask",
"(",
"task",
")",
";",
"taskTimer",
".",
"scheduleAtFixedRate",
"(",
"timerTask",
",",
"delay",
",",
"period",
")",
";",
"return",
"timerTask",
";",
"}"
] | Schedules a task to periodically run. This is useful for tasks such as
updating search indexes, deleting old data at periodic intervals, etc.
@param task
task to be scheduled.
@param delay
delay in milliseconds before task is to be executed.
@param period
time in milliseconds between successive task executions.
@return a TimerTask object which can be used to track executions of the
task and to cancel subsequent executions. | [
"Schedules",
"a",
"task",
"to",
"periodically",
"run",
".",
"This",
"is",
"useful",
"for",
"tasks",
"such",
"as",
"updating",
"search",
"indexes",
"deleting",
"old",
"data",
"at",
"periodic",
"intervals",
"etc",
"."
] | 72b451caac04f775e57f52aaed3d8775044ead53 | https://github.com/banq/jdonframework/blob/72b451caac04f775e57f52aaed3d8775044ead53/src/main/java/com/jdon/util/task/TaskEngine.java#L114-L118 |
23,587 | banq/jdonframework | src/main/java/com/jdon/util/task/TaskEngine.java | TaskEngine.nextTask | private static Runnable nextTask() {
synchronized (lock) {
// Block until we have another object in the queue to execute.
while (taskList.isEmpty()) {
try {
lock.wait();
} catch (InterruptedException ie) {
}
}
return (Runnable) taskList.removeLast();
}
} | java | private static Runnable nextTask() {
synchronized (lock) {
// Block until we have another object in the queue to execute.
while (taskList.isEmpty()) {
try {
lock.wait();
} catch (InterruptedException ie) {
}
}
return (Runnable) taskList.removeLast();
}
} | [
"private",
"static",
"Runnable",
"nextTask",
"(",
")",
"{",
"synchronized",
"(",
"lock",
")",
"{",
"// Block until we have another object in the queue to execute.\r",
"while",
"(",
"taskList",
".",
"isEmpty",
"(",
")",
")",
"{",
"try",
"{",
"lock",
".",
"wait",
"(",
")",
";",
"}",
"catch",
"(",
"InterruptedException",
"ie",
")",
"{",
"}",
"}",
"return",
"(",
"Runnable",
")",
"taskList",
".",
"removeLast",
"(",
")",
";",
"}",
"}"
] | Return the next task in the queue. If no task is available, this method
will block until a task is added to the queue.
@return a <code>Task</code> object | [
"Return",
"the",
"next",
"task",
"in",
"the",
"queue",
".",
"If",
"no",
"task",
"is",
"available",
"this",
"method",
"will",
"block",
"until",
"a",
"task",
"is",
"added",
"to",
"the",
"queue",
"."
] | 72b451caac04f775e57f52aaed3d8775044ead53 | https://github.com/banq/jdonframework/blob/72b451caac04f775e57f52aaed3d8775044ead53/src/main/java/com/jdon/util/task/TaskEngine.java#L147-L158 |
23,588 | banq/jdonframework | src/main/java/com/jdon/container/finder/ContainerFinderImp.java | ContainerFinderImp.findContainer | public ContainerWrapper findContainer(AppContextWrapper sc) {
ContainerRegistryBuilder cb = (ContainerRegistryBuilder) sc.getAttribute(ContainerRegistryBuilder.APPLICATION_CONTEXT_ATTRIBUTE_NAME);
if (cb == null)
cb = prepare(sc);
launch(sc, cb);
return cb.getContainerWrapper();
} | java | public ContainerWrapper findContainer(AppContextWrapper sc) {
ContainerRegistryBuilder cb = (ContainerRegistryBuilder) sc.getAttribute(ContainerRegistryBuilder.APPLICATION_CONTEXT_ATTRIBUTE_NAME);
if (cb == null)
cb = prepare(sc);
launch(sc, cb);
return cb.getContainerWrapper();
} | [
"public",
"ContainerWrapper",
"findContainer",
"(",
"AppContextWrapper",
"sc",
")",
"{",
"ContainerRegistryBuilder",
"cb",
"=",
"(",
"ContainerRegistryBuilder",
")",
"sc",
".",
"getAttribute",
"(",
"ContainerRegistryBuilder",
".",
"APPLICATION_CONTEXT_ATTRIBUTE_NAME",
")",
";",
"if",
"(",
"cb",
"==",
"null",
")",
"cb",
"=",
"prepare",
"(",
"sc",
")",
";",
"launch",
"(",
"sc",
",",
"cb",
")",
";",
"return",
"cb",
".",
"getContainerWrapper",
"(",
")",
";",
"}"
] | lazy startup container when first time the method is called, it will
startup the container
@param sc
ServletContext
@return ContainerWrapper
@throws Exception | [
"lazy",
"startup",
"container",
"when",
"first",
"time",
"the",
"method",
"is",
"called",
"it",
"will",
"startup",
"the",
"container"
] | 72b451caac04f775e57f52aaed3d8775044ead53 | https://github.com/banq/jdonframework/blob/72b451caac04f775e57f52aaed3d8775044ead53/src/main/java/com/jdon/container/finder/ContainerFinderImp.java#L39-L45 |
23,589 | banq/jdonframework | src/main/java/com/jdon/controller/service/WebServiceFactory.java | WebServiceFactory.getService | public Object getService(TargetMetaDef targetMetaDef, RequestWrapper request) {
userTargetMetaDefFactory.createTargetMetaRequest(targetMetaDef, request.getContextHolder());
return webServiceAccessor.getService(request);
} | java | public Object getService(TargetMetaDef targetMetaDef, RequestWrapper request) {
userTargetMetaDefFactory.createTargetMetaRequest(targetMetaDef, request.getContextHolder());
return webServiceAccessor.getService(request);
} | [
"public",
"Object",
"getService",
"(",
"TargetMetaDef",
"targetMetaDef",
",",
"RequestWrapper",
"request",
")",
"{",
"userTargetMetaDefFactory",
".",
"createTargetMetaRequest",
"(",
"targetMetaDef",
",",
"request",
".",
"getContextHolder",
"(",
")",
")",
";",
"return",
"webServiceAccessor",
".",
"getService",
"(",
"request",
")",
";",
"}"
] | get a service instance the service must have a interface and implements
it. | [
"get",
"a",
"service",
"instance",
"the",
"service",
"must",
"have",
"a",
"interface",
"and",
"implements",
"it",
"."
] | 72b451caac04f775e57f52aaed3d8775044ead53 | https://github.com/banq/jdonframework/blob/72b451caac04f775e57f52aaed3d8775044ead53/src/main/java/com/jdon/controller/service/WebServiceFactory.java#L68-L71 |
23,590 | banq/jdonframework | src/main/java/com/jdon/container/pico/JdonInstantiatingComponentAdapter.java | JdonInstantiatingComponentAdapter.createDefaultParameters | protected Parameter[] createDefaultParameters(Class[] parameters) {
Parameter[] componentParameters = new Parameter[parameters.length];
for (int i = 0; i < parameters.length; i++) {
componentParameters[i] = ComponentParameter.DEFAULT;
}
return componentParameters;
} | java | protected Parameter[] createDefaultParameters(Class[] parameters) {
Parameter[] componentParameters = new Parameter[parameters.length];
for (int i = 0; i < parameters.length; i++) {
componentParameters[i] = ComponentParameter.DEFAULT;
}
return componentParameters;
} | [
"protected",
"Parameter",
"[",
"]",
"createDefaultParameters",
"(",
"Class",
"[",
"]",
"parameters",
")",
"{",
"Parameter",
"[",
"]",
"componentParameters",
"=",
"new",
"Parameter",
"[",
"parameters",
".",
"length",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"parameters",
".",
"length",
";",
"i",
"++",
")",
"{",
"componentParameters",
"[",
"i",
"]",
"=",
"ComponentParameter",
".",
"DEFAULT",
";",
"}",
"return",
"componentParameters",
";",
"}"
] | Create default parameters for the given types.
@param parameters
the parameter types
@return the array with the default parameters. | [
"Create",
"default",
"parameters",
"for",
"the",
"given",
"types",
"."
] | 72b451caac04f775e57f52aaed3d8775044ead53 | https://github.com/banq/jdonframework/blob/72b451caac04f775e57f52aaed3d8775044ead53/src/main/java/com/jdon/container/pico/JdonInstantiatingComponentAdapter.java#L148-L154 |
23,591 | banq/jdonframework | src/main/java/com/jdon/container/pico/JdonInstantiatingComponentAdapter.java | JdonInstantiatingComponentAdapter.newInstance | protected Object newInstance(Constructor constructor, Object[] parameters) throws InstantiationException, IllegalAccessException,
InvocationTargetException {
if (allowNonPublicClasses) {
constructor.setAccessible(true);
}
return constructor.newInstance(parameters);
} | java | protected Object newInstance(Constructor constructor, Object[] parameters) throws InstantiationException, IllegalAccessException,
InvocationTargetException {
if (allowNonPublicClasses) {
constructor.setAccessible(true);
}
return constructor.newInstance(parameters);
} | [
"protected",
"Object",
"newInstance",
"(",
"Constructor",
"constructor",
",",
"Object",
"[",
"]",
"parameters",
")",
"throws",
"InstantiationException",
",",
"IllegalAccessException",
",",
"InvocationTargetException",
"{",
"if",
"(",
"allowNonPublicClasses",
")",
"{",
"constructor",
".",
"setAccessible",
"(",
"true",
")",
";",
"}",
"return",
"constructor",
".",
"newInstance",
"(",
"parameters",
")",
";",
"}"
] | Instantiate an object with given parameters and respect the accessible
flag.
@param constructor
the constructor to use
@param parameters
the parameters for the constructor
@return the new object.
@throws InstantiationException
@throws IllegalAccessException
@throws InvocationTargetException | [
"Instantiate",
"an",
"object",
"with",
"given",
"parameters",
"and",
"respect",
"the",
"accessible",
"flag",
"."
] | 72b451caac04f775e57f52aaed3d8775044ead53 | https://github.com/banq/jdonframework/blob/72b451caac04f775e57f52aaed3d8775044ead53/src/main/java/com/jdon/container/pico/JdonInstantiatingComponentAdapter.java#L212-L218 |
23,592 | banq/jdonframework | src/main/java/com/jdon/util/jdom/DataFormatFilter.java | DataFormatFilter.startElement | public void startElement (String uri, String localName,
String qName, Attributes atts)
throws SAXException
{
if (!stateStack.empty()) {
doNewline();
doIndent();
}
stateStack.push(SEEN_ELEMENT);
state = SEEN_NOTHING;
super.startElement(uri, localName, qName, atts);
} | java | public void startElement (String uri, String localName,
String qName, Attributes atts)
throws SAXException
{
if (!stateStack.empty()) {
doNewline();
doIndent();
}
stateStack.push(SEEN_ELEMENT);
state = SEEN_NOTHING;
super.startElement(uri, localName, qName, atts);
} | [
"public",
"void",
"startElement",
"(",
"String",
"uri",
",",
"String",
"localName",
",",
"String",
"qName",
",",
"Attributes",
"atts",
")",
"throws",
"SAXException",
"{",
"if",
"(",
"!",
"stateStack",
".",
"empty",
"(",
")",
")",
"{",
"doNewline",
"(",
")",
";",
"doIndent",
"(",
")",
";",
"}",
"stateStack",
".",
"push",
"(",
"SEEN_ELEMENT",
")",
";",
"state",
"=",
"SEEN_NOTHING",
";",
"super",
".",
"startElement",
"(",
"uri",
",",
"localName",
",",
"qName",
",",
"atts",
")",
";",
"}"
] | Add newline and indentation prior to start tag.
<p>Each tag will begin on a new line, and will be
indented by the current indent step times the number
of ancestors that the element has.</p>
<p>The newline and indentation will be passed on down
the filter chain through regular characters events.</p>
@param uri The element's Namespace URI.
@param localName The element's local name.
@param qName The element's qualified (prefixed) name.
@param atts The element's attribute list.
@exception org.xml.sax.SAXException If a filter
further down the chain raises an exception.
@see org.xml.sax.ContentHandler#startElement | [
"Add",
"newline",
"and",
"indentation",
"prior",
"to",
"start",
"tag",
"."
] | 72b451caac04f775e57f52aaed3d8775044ead53 | https://github.com/banq/jdonframework/blob/72b451caac04f775e57f52aaed3d8775044ead53/src/main/java/com/jdon/util/jdom/DataFormatFilter.java#L245-L256 |
23,593 | banq/jdonframework | src/main/java/com/jdon/util/jdom/DataFormatFilter.java | DataFormatFilter.endElement | public void endElement (String uri, String localName, String qName)
throws SAXException
{
boolean seenElement = (state == SEEN_ELEMENT);
state = stateStack.pop();
if (seenElement) {
doNewline();
doIndent();
}
super.endElement(uri, localName, qName);
} | java | public void endElement (String uri, String localName, String qName)
throws SAXException
{
boolean seenElement = (state == SEEN_ELEMENT);
state = stateStack.pop();
if (seenElement) {
doNewline();
doIndent();
}
super.endElement(uri, localName, qName);
} | [
"public",
"void",
"endElement",
"(",
"String",
"uri",
",",
"String",
"localName",
",",
"String",
"qName",
")",
"throws",
"SAXException",
"{",
"boolean",
"seenElement",
"=",
"(",
"state",
"==",
"SEEN_ELEMENT",
")",
";",
"state",
"=",
"stateStack",
".",
"pop",
"(",
")",
";",
"if",
"(",
"seenElement",
")",
"{",
"doNewline",
"(",
")",
";",
"doIndent",
"(",
")",
";",
"}",
"super",
".",
"endElement",
"(",
"uri",
",",
"localName",
",",
"qName",
")",
";",
"}"
] | Add newline and indentation prior to end tag.
<p>If the element has contained other elements, the tag
will appear indented on a new line; otherwise, it will
appear immediately following whatever came before.</p>
<p>The newline and indentation will be passed on down
the filter chain through regular characters events.</p>
@param uri The element's Namespace URI.
@param localName The element's local name.
@param qName The element's qualified (prefixed) name.
@exception org.xml.sax.SAXException If a filter
further down the chain raises an exception.
@see org.xml.sax.ContentHandler#endElement | [
"Add",
"newline",
"and",
"indentation",
"prior",
"to",
"end",
"tag",
"."
] | 72b451caac04f775e57f52aaed3d8775044ead53 | https://github.com/banq/jdonframework/blob/72b451caac04f775e57f52aaed3d8775044ead53/src/main/java/com/jdon/util/jdom/DataFormatFilter.java#L276-L286 |
23,594 | banq/jdonframework | src/main/java/com/jdon/util/jdom/DataFormatFilter.java | DataFormatFilter.doIndent | private void doIndent ()
throws SAXException
{
int n = indentStep * stateStack.size();
if (n > 0) {
char ch[] = new char[n];
for (int i = 0; i < n; i++) {
ch[i] = INDENT_CHAR;
}
super.characters(ch, 0, n);
}
} | java | private void doIndent ()
throws SAXException
{
int n = indentStep * stateStack.size();
if (n > 0) {
char ch[] = new char[n];
for (int i = 0; i < n; i++) {
ch[i] = INDENT_CHAR;
}
super.characters(ch, 0, n);
}
} | [
"private",
"void",
"doIndent",
"(",
")",
"throws",
"SAXException",
"{",
"int",
"n",
"=",
"indentStep",
"*",
"stateStack",
".",
"size",
"(",
")",
";",
"if",
"(",
"n",
">",
"0",
")",
"{",
"char",
"ch",
"[",
"]",
"=",
"new",
"char",
"[",
"n",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"n",
";",
"i",
"++",
")",
"{",
"ch",
"[",
"i",
"]",
"=",
"INDENT_CHAR",
";",
"}",
"super",
".",
"characters",
"(",
"ch",
",",
"0",
",",
"n",
")",
";",
"}",
"}"
] | Add indentation for the current level.
@exception org.xml.sax.SAXException If a filter
further down the chain raises an exception. | [
"Add",
"indentation",
"for",
"the",
"current",
"level",
"."
] | 72b451caac04f775e57f52aaed3d8775044ead53 | https://github.com/banq/jdonframework/blob/72b451caac04f775e57f52aaed3d8775044ead53/src/main/java/com/jdon/util/jdom/DataFormatFilter.java#L332-L343 |
23,595 | banq/jdonframework | src/main/java/com/jdon/container/pico/JdonConstructorInjectionComponentAdapter.java | JdonConstructorInjectionComponentAdapter.getComponentInstance | public Object getComponentInstance(PicoContainer container) throws PicoInitializationException, PicoIntrospectionException,
AssignabilityRegistrationException, NotConcreteRegistrationException {
if (instantiationGuard == null) {
instantiationGuard = new Guard() {
public Object run() {
final Constructor constructor;
try {
constructor = getGreediestSatisfiableConstructor(guardedContainer);
} catch (AmbiguousComponentResolutionException e) {
e.setComponent(getComponentImplementation());
throw e;
}
ComponentMonitor componentMonitor = currentMonitor();
try {
Object[] parameters = getConstructorArguments(guardedContainer, constructor);
componentMonitor.instantiating(constructor);
long startTime = System.currentTimeMillis();
Object inst = newInstance(constructor, parameters);
componentMonitor.instantiated(constructor, System.currentTimeMillis() - startTime);
return inst;
} catch (InvocationTargetException e) {
componentMonitor.instantiationFailed(constructor, e);
if (e.getTargetException() instanceof RuntimeException) {
throw (RuntimeException) e.getTargetException();
} else if (e.getTargetException() instanceof Error) {
throw (Error) e.getTargetException();
}
throw new PicoInvocationTargetInitializationException(e.getTargetException());
} catch (InstantiationException e) {
// can't get here because checkConcrete() will catch it
// earlier, but see PICO-191
// /CLOVER:OFF
componentMonitor.instantiationFailed(constructor, e);
throw new PicoInitializationException("Should never get here");
// /CLOVER:ON
} catch (IllegalAccessException e) {
// can't get here because either filtered or access mode
// set
// /CLOVER:OFF
componentMonitor.instantiationFailed(constructor, e);
throw new PicoInitializationException(e);
// /CLOVER:ON
}
}
};
}
instantiationGuard.setArguments(container);
Object result = instantiationGuard.observe(getComponentImplementation());
instantiationGuard.clear();
return result;
} | java | public Object getComponentInstance(PicoContainer container) throws PicoInitializationException, PicoIntrospectionException,
AssignabilityRegistrationException, NotConcreteRegistrationException {
if (instantiationGuard == null) {
instantiationGuard = new Guard() {
public Object run() {
final Constructor constructor;
try {
constructor = getGreediestSatisfiableConstructor(guardedContainer);
} catch (AmbiguousComponentResolutionException e) {
e.setComponent(getComponentImplementation());
throw e;
}
ComponentMonitor componentMonitor = currentMonitor();
try {
Object[] parameters = getConstructorArguments(guardedContainer, constructor);
componentMonitor.instantiating(constructor);
long startTime = System.currentTimeMillis();
Object inst = newInstance(constructor, parameters);
componentMonitor.instantiated(constructor, System.currentTimeMillis() - startTime);
return inst;
} catch (InvocationTargetException e) {
componentMonitor.instantiationFailed(constructor, e);
if (e.getTargetException() instanceof RuntimeException) {
throw (RuntimeException) e.getTargetException();
} else if (e.getTargetException() instanceof Error) {
throw (Error) e.getTargetException();
}
throw new PicoInvocationTargetInitializationException(e.getTargetException());
} catch (InstantiationException e) {
// can't get here because checkConcrete() will catch it
// earlier, but see PICO-191
// /CLOVER:OFF
componentMonitor.instantiationFailed(constructor, e);
throw new PicoInitializationException("Should never get here");
// /CLOVER:ON
} catch (IllegalAccessException e) {
// can't get here because either filtered or access mode
// set
// /CLOVER:OFF
componentMonitor.instantiationFailed(constructor, e);
throw new PicoInitializationException(e);
// /CLOVER:ON
}
}
};
}
instantiationGuard.setArguments(container);
Object result = instantiationGuard.observe(getComponentImplementation());
instantiationGuard.clear();
return result;
} | [
"public",
"Object",
"getComponentInstance",
"(",
"PicoContainer",
"container",
")",
"throws",
"PicoInitializationException",
",",
"PicoIntrospectionException",
",",
"AssignabilityRegistrationException",
",",
"NotConcreteRegistrationException",
"{",
"if",
"(",
"instantiationGuard",
"==",
"null",
")",
"{",
"instantiationGuard",
"=",
"new",
"Guard",
"(",
")",
"{",
"public",
"Object",
"run",
"(",
")",
"{",
"final",
"Constructor",
"constructor",
";",
"try",
"{",
"constructor",
"=",
"getGreediestSatisfiableConstructor",
"(",
"guardedContainer",
")",
";",
"}",
"catch",
"(",
"AmbiguousComponentResolutionException",
"e",
")",
"{",
"e",
".",
"setComponent",
"(",
"getComponentImplementation",
"(",
")",
")",
";",
"throw",
"e",
";",
"}",
"ComponentMonitor",
"componentMonitor",
"=",
"currentMonitor",
"(",
")",
";",
"try",
"{",
"Object",
"[",
"]",
"parameters",
"=",
"getConstructorArguments",
"(",
"guardedContainer",
",",
"constructor",
")",
";",
"componentMonitor",
".",
"instantiating",
"(",
"constructor",
")",
";",
"long",
"startTime",
"=",
"System",
".",
"currentTimeMillis",
"(",
")",
";",
"Object",
"inst",
"=",
"newInstance",
"(",
"constructor",
",",
"parameters",
")",
";",
"componentMonitor",
".",
"instantiated",
"(",
"constructor",
",",
"System",
".",
"currentTimeMillis",
"(",
")",
"-",
"startTime",
")",
";",
"return",
"inst",
";",
"}",
"catch",
"(",
"InvocationTargetException",
"e",
")",
"{",
"componentMonitor",
".",
"instantiationFailed",
"(",
"constructor",
",",
"e",
")",
";",
"if",
"(",
"e",
".",
"getTargetException",
"(",
")",
"instanceof",
"RuntimeException",
")",
"{",
"throw",
"(",
"RuntimeException",
")",
"e",
".",
"getTargetException",
"(",
")",
";",
"}",
"else",
"if",
"(",
"e",
".",
"getTargetException",
"(",
")",
"instanceof",
"Error",
")",
"{",
"throw",
"(",
"Error",
")",
"e",
".",
"getTargetException",
"(",
")",
";",
"}",
"throw",
"new",
"PicoInvocationTargetInitializationException",
"(",
"e",
".",
"getTargetException",
"(",
")",
")",
";",
"}",
"catch",
"(",
"InstantiationException",
"e",
")",
"{",
"// can't get here because checkConcrete() will catch it\r",
"// earlier, but see PICO-191\r",
"// /CLOVER:OFF\r",
"componentMonitor",
".",
"instantiationFailed",
"(",
"constructor",
",",
"e",
")",
";",
"throw",
"new",
"PicoInitializationException",
"(",
"\"Should never get here\"",
")",
";",
"// /CLOVER:ON\r",
"}",
"catch",
"(",
"IllegalAccessException",
"e",
")",
"{",
"// can't get here because either filtered or access mode\r",
"// set\r",
"// /CLOVER:OFF\r",
"componentMonitor",
".",
"instantiationFailed",
"(",
"constructor",
",",
"e",
")",
";",
"throw",
"new",
"PicoInitializationException",
"(",
"e",
")",
";",
"// /CLOVER:ON\r",
"}",
"}",
"}",
";",
"}",
"instantiationGuard",
".",
"setArguments",
"(",
"container",
")",
";",
"Object",
"result",
"=",
"instantiationGuard",
".",
"observe",
"(",
"getComponentImplementation",
"(",
")",
")",
";",
"instantiationGuard",
".",
"clear",
"(",
")",
";",
"return",
"result",
";",
"}"
] | difference with picocontainer | [
"difference",
"with",
"picocontainer"
] | 72b451caac04f775e57f52aaed3d8775044ead53 | https://github.com/banq/jdonframework/blob/72b451caac04f775e57f52aaed3d8775044ead53/src/main/java/com/jdon/container/pico/JdonConstructorInjectionComponentAdapter.java#L95-L146 |
23,596 | banq/jdonframework | src/main/java/com/jdon/container/pico/JdonConstructorInjectionComponentAdapter.java | JdonConstructorInjectionComponentAdapter.newInstance | protected Object newInstance(Constructor constructor, Object[] parameters) throws InstantiationException, IllegalAccessException,
InvocationTargetException {
if (allowNonPublicClasses) {
constructor.setAccessible(true);
}
Object o = constructor.newInstance(parameters);
ComponentAdvsior componentAdvsior = (ComponentAdvsior) configInfo.getContainerWrapper().lookup(ComponentAdvsior.NAME);
Object proxy = null;
if (componentAdvsior != null)
proxy = componentAdvsior.createProxy(o);
if (!proxy.getClass().isInstance(o)) {
Map orignals = getContainerOrignals(configInfo.getContainerWrapper());
orignals.put((String) this.getComponentKey(), o);
}
return proxy;
} | java | protected Object newInstance(Constructor constructor, Object[] parameters) throws InstantiationException, IllegalAccessException,
InvocationTargetException {
if (allowNonPublicClasses) {
constructor.setAccessible(true);
}
Object o = constructor.newInstance(parameters);
ComponentAdvsior componentAdvsior = (ComponentAdvsior) configInfo.getContainerWrapper().lookup(ComponentAdvsior.NAME);
Object proxy = null;
if (componentAdvsior != null)
proxy = componentAdvsior.createProxy(o);
if (!proxy.getClass().isInstance(o)) {
Map orignals = getContainerOrignals(configInfo.getContainerWrapper());
orignals.put((String) this.getComponentKey(), o);
}
return proxy;
} | [
"protected",
"Object",
"newInstance",
"(",
"Constructor",
"constructor",
",",
"Object",
"[",
"]",
"parameters",
")",
"throws",
"InstantiationException",
",",
"IllegalAccessException",
",",
"InvocationTargetException",
"{",
"if",
"(",
"allowNonPublicClasses",
")",
"{",
"constructor",
".",
"setAccessible",
"(",
"true",
")",
";",
"}",
"Object",
"o",
"=",
"constructor",
".",
"newInstance",
"(",
"parameters",
")",
";",
"ComponentAdvsior",
"componentAdvsior",
"=",
"(",
"ComponentAdvsior",
")",
"configInfo",
".",
"getContainerWrapper",
"(",
")",
".",
"lookup",
"(",
"ComponentAdvsior",
".",
"NAME",
")",
";",
"Object",
"proxy",
"=",
"null",
";",
"if",
"(",
"componentAdvsior",
"!=",
"null",
")",
"proxy",
"=",
"componentAdvsior",
".",
"createProxy",
"(",
"o",
")",
";",
"if",
"(",
"!",
"proxy",
".",
"getClass",
"(",
")",
".",
"isInstance",
"(",
"o",
")",
")",
"{",
"Map",
"orignals",
"=",
"getContainerOrignals",
"(",
"configInfo",
".",
"getContainerWrapper",
"(",
")",
")",
";",
"orignals",
".",
"put",
"(",
"(",
"String",
")",
"this",
".",
"getComponentKey",
"(",
")",
",",
"o",
")",
";",
"}",
"return",
"proxy",
";",
"}"
] | overide InstantiatingComponentAdapter 's newInstance | [
"overide",
"InstantiatingComponentAdapter",
"s",
"newInstance"
] | 72b451caac04f775e57f52aaed3d8775044ead53 | https://github.com/banq/jdonframework/blob/72b451caac04f775e57f52aaed3d8775044ead53/src/main/java/com/jdon/container/pico/JdonConstructorInjectionComponentAdapter.java#L149-L167 |
23,597 | banq/jdonframework | src/main/java/com/jdon/container/visitor/http/HttpSessionVisitorFactoryImp.java | HttpSessionVisitorFactoryImp.createtVisitor | public ComponentVisitor createtVisitor(SessionWrapper session, TargetMetaDef targetMetaDef) {
if (session != null)
return createtSessionVisitor(session, targetMetaDef);
else
return new NoSessionProxyComponentVisitor(componentVisitor, targetMetaRequestsHolder);
} | java | public ComponentVisitor createtVisitor(SessionWrapper session, TargetMetaDef targetMetaDef) {
if (session != null)
return createtSessionVisitor(session, targetMetaDef);
else
return new NoSessionProxyComponentVisitor(componentVisitor, targetMetaRequestsHolder);
} | [
"public",
"ComponentVisitor",
"createtVisitor",
"(",
"SessionWrapper",
"session",
",",
"TargetMetaDef",
"targetMetaDef",
")",
"{",
"if",
"(",
"session",
"!=",
"null",
")",
"return",
"createtSessionVisitor",
"(",
"session",
",",
"targetMetaDef",
")",
";",
"else",
"return",
"new",
"NoSessionProxyComponentVisitor",
"(",
"componentVisitor",
",",
"targetMetaRequestsHolder",
")",
";",
"}"
] | return a ComponentVisitor with cache. the httpSession is used for
optimizing the component performance
@param request
@param targetMetaDef
@return | [
"return",
"a",
"ComponentVisitor",
"with",
"cache",
".",
"the",
"httpSession",
"is",
"used",
"for",
"optimizing",
"the",
"component",
"performance"
] | 72b451caac04f775e57f52aaed3d8775044ead53 | https://github.com/banq/jdonframework/blob/72b451caac04f775e57f52aaed3d8775044ead53/src/main/java/com/jdon/container/visitor/http/HttpSessionVisitorFactoryImp.java#L53-L59 |
23,598 | banq/jdonframework | JdonAccessory/jdon-jdbc/src/main/java/com/jdon/model/query/PageIteratorSolver.java | PageIteratorSolver.querySingleObject | public Object querySingleObject(Collection queryParams, String sqlquery) throws Exception {
JdbcTemp jdbcTemp = new JdbcTemp(dataSource);
return jdbcTemp.querySingleObject(queryParams, sqlquery);
} | java | public Object querySingleObject(Collection queryParams, String sqlquery) throws Exception {
JdbcTemp jdbcTemp = new JdbcTemp(dataSource);
return jdbcTemp.querySingleObject(queryParams, sqlquery);
} | [
"public",
"Object",
"querySingleObject",
"(",
"Collection",
"queryParams",
",",
"String",
"sqlquery",
")",
"throws",
"Exception",
"{",
"JdbcTemp",
"jdbcTemp",
"=",
"new",
"JdbcTemp",
"(",
"dataSource",
")",
";",
"return",
"jdbcTemp",
".",
"querySingleObject",
"(",
"queryParams",
",",
"sqlquery",
")",
";",
"}"
] | query one object from database delgate to JdbCQueryTemp's
querySingleObject method
@param queryParams
query sql parameter (?)
@param sqlquery
query sql
@return Object
@throws Exception | [
"query",
"one",
"object",
"from",
"database",
"delgate",
"to",
"JdbCQueryTemp",
"s",
"querySingleObject",
"method"
] | 72b451caac04f775e57f52aaed3d8775044ead53 | https://github.com/banq/jdonframework/blob/72b451caac04f775e57f52aaed3d8775044ead53/JdonAccessory/jdon-jdbc/src/main/java/com/jdon/model/query/PageIteratorSolver.java#L134-L137 |
23,599 | banq/jdonframework | JdonAccessory/jdon-jdbc/src/main/java/com/jdon/model/query/PageIteratorSolver.java | PageIteratorSolver.queryMultiObject | public List queryMultiObject(Collection queryParams, String sqlquery) throws Exception {
JdbcTemp jdbcTemp = new JdbcTemp(dataSource);
return jdbcTemp.queryMultiObject(queryParams, sqlquery);
} | java | public List queryMultiObject(Collection queryParams, String sqlquery) throws Exception {
JdbcTemp jdbcTemp = new JdbcTemp(dataSource);
return jdbcTemp.queryMultiObject(queryParams, sqlquery);
} | [
"public",
"List",
"queryMultiObject",
"(",
"Collection",
"queryParams",
",",
"String",
"sqlquery",
")",
"throws",
"Exception",
"{",
"JdbcTemp",
"jdbcTemp",
"=",
"new",
"JdbcTemp",
"(",
"dataSource",
")",
";",
"return",
"jdbcTemp",
".",
"queryMultiObject",
"(",
"queryParams",
",",
"sqlquery",
")",
";",
"}"
] | query multi object from database delgate to JdbCQueryTemp's
queryMultiObject method
@param queryParams
@param sqlquery
@return
@throws Exception | [
"query",
"multi",
"object",
"from",
"database",
"delgate",
"to",
"JdbCQueryTemp",
"s",
"queryMultiObject",
"method"
] | 72b451caac04f775e57f52aaed3d8775044ead53 | https://github.com/banq/jdonframework/blob/72b451caac04f775e57f52aaed3d8775044ead53/JdonAccessory/jdon-jdbc/src/main/java/com/jdon/model/query/PageIteratorSolver.java#L148-L151 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.