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
|
|---|---|---|---|---|---|---|---|---|---|---|---|
16,800
|
undertow-io/undertow
|
core/src/main/java/io/undertow/server/HttpServerExchange.java
|
HttpServerExchange.terminateRequest
|
void terminateRequest() {
int oldVal = state;
if (allAreSet(oldVal, FLAG_REQUEST_TERMINATED)) {
// idempotent
return;
}
if (requestChannel != null) {
requestChannel.requestDone();
}
this.state = oldVal | FLAG_REQUEST_TERMINATED;
if (anyAreSet(oldVal, FLAG_RESPONSE_TERMINATED)) {
invokeExchangeCompleteListeners();
}
}
|
java
|
void terminateRequest() {
int oldVal = state;
if (allAreSet(oldVal, FLAG_REQUEST_TERMINATED)) {
// idempotent
return;
}
if (requestChannel != null) {
requestChannel.requestDone();
}
this.state = oldVal | FLAG_REQUEST_TERMINATED;
if (anyAreSet(oldVal, FLAG_RESPONSE_TERMINATED)) {
invokeExchangeCompleteListeners();
}
}
|
[
"void",
"terminateRequest",
"(",
")",
"{",
"int",
"oldVal",
"=",
"state",
";",
"if",
"(",
"allAreSet",
"(",
"oldVal",
",",
"FLAG_REQUEST_TERMINATED",
")",
")",
"{",
"// idempotent",
"return",
";",
"}",
"if",
"(",
"requestChannel",
"!=",
"null",
")",
"{",
"requestChannel",
".",
"requestDone",
"(",
")",
";",
"}",
"this",
".",
"state",
"=",
"oldVal",
"|",
"FLAG_REQUEST_TERMINATED",
";",
"if",
"(",
"anyAreSet",
"(",
"oldVal",
",",
"FLAG_RESPONSE_TERMINATED",
")",
")",
"{",
"invokeExchangeCompleteListeners",
"(",
")",
";",
"}",
"}"
] |
Force the codec to treat the request as fully read. Should only be invoked by handlers which downgrade
the socket or implement a transfer coding.
|
[
"Force",
"the",
"codec",
"to",
"treat",
"the",
"request",
"as",
"fully",
"read",
".",
"Should",
"only",
"be",
"invoked",
"by",
"handlers",
"which",
"downgrade",
"the",
"socket",
"or",
"implement",
"a",
"transfer",
"coding",
"."
] |
87de0b856a7a4ba8faf5b659537b9af07b763263
|
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/HttpServerExchange.java#L1256-L1269
|
16,801
|
undertow-io/undertow
|
core/src/main/java/io/undertow/server/HttpServerExchange.java
|
HttpServerExchange.terminateResponse
|
HttpServerExchange terminateResponse() {
int oldVal = state;
if (allAreSet(oldVal, FLAG_RESPONSE_TERMINATED)) {
// idempotent
return this;
}
if(responseChannel != null) {
responseChannel.responseDone();
}
this.state = oldVal | FLAG_RESPONSE_TERMINATED;
if (anyAreSet(oldVal, FLAG_REQUEST_TERMINATED)) {
invokeExchangeCompleteListeners();
}
return this;
}
|
java
|
HttpServerExchange terminateResponse() {
int oldVal = state;
if (allAreSet(oldVal, FLAG_RESPONSE_TERMINATED)) {
// idempotent
return this;
}
if(responseChannel != null) {
responseChannel.responseDone();
}
this.state = oldVal | FLAG_RESPONSE_TERMINATED;
if (anyAreSet(oldVal, FLAG_REQUEST_TERMINATED)) {
invokeExchangeCompleteListeners();
}
return this;
}
|
[
"HttpServerExchange",
"terminateResponse",
"(",
")",
"{",
"int",
"oldVal",
"=",
"state",
";",
"if",
"(",
"allAreSet",
"(",
"oldVal",
",",
"FLAG_RESPONSE_TERMINATED",
")",
")",
"{",
"// idempotent",
"return",
"this",
";",
"}",
"if",
"(",
"responseChannel",
"!=",
"null",
")",
"{",
"responseChannel",
".",
"responseDone",
"(",
")",
";",
"}",
"this",
".",
"state",
"=",
"oldVal",
"|",
"FLAG_RESPONSE_TERMINATED",
";",
"if",
"(",
"anyAreSet",
"(",
"oldVal",
",",
"FLAG_REQUEST_TERMINATED",
")",
")",
"{",
"invokeExchangeCompleteListeners",
"(",
")",
";",
"}",
"return",
"this",
";",
"}"
] |
Force the codec to treat the response as fully written. Should only be invoked by handlers which downgrade
the socket or implement a transfer coding.
|
[
"Force",
"the",
"codec",
"to",
"treat",
"the",
"response",
"as",
"fully",
"written",
".",
"Should",
"only",
"be",
"invoked",
"by",
"handlers",
"which",
"downgrade",
"the",
"socket",
"or",
"implement",
"a",
"transfer",
"coding",
"."
] |
87de0b856a7a4ba8faf5b659537b9af07b763263
|
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/HttpServerExchange.java#L1552-L1566
|
16,802
|
undertow-io/undertow
|
core/src/main/java/io/undertow/server/HttpServerExchange.java
|
HttpServerExchange.setMaxEntitySize
|
public HttpServerExchange setMaxEntitySize(final long maxEntitySize) {
if (!isRequestChannelAvailable()) {
throw UndertowMessages.MESSAGES.requestChannelAlreadyProvided();
}
this.maxEntitySize = maxEntitySize;
connection.maxEntitySizeUpdated(this);
return this;
}
|
java
|
public HttpServerExchange setMaxEntitySize(final long maxEntitySize) {
if (!isRequestChannelAvailable()) {
throw UndertowMessages.MESSAGES.requestChannelAlreadyProvided();
}
this.maxEntitySize = maxEntitySize;
connection.maxEntitySizeUpdated(this);
return this;
}
|
[
"public",
"HttpServerExchange",
"setMaxEntitySize",
"(",
"final",
"long",
"maxEntitySize",
")",
"{",
"if",
"(",
"!",
"isRequestChannelAvailable",
"(",
")",
")",
"{",
"throw",
"UndertowMessages",
".",
"MESSAGES",
".",
"requestChannelAlreadyProvided",
"(",
")",
";",
"}",
"this",
".",
"maxEntitySize",
"=",
"maxEntitySize",
";",
"connection",
".",
"maxEntitySizeUpdated",
"(",
"this",
")",
";",
"return",
"this",
";",
"}"
] |
Sets the max entity size for this exchange. This cannot be modified after the request channel has been obtained.
@param maxEntitySize The max entity size
|
[
"Sets",
"the",
"max",
"entity",
"size",
"for",
"this",
"exchange",
".",
"This",
"cannot",
"be",
"modified",
"after",
"the",
"request",
"channel",
"has",
"been",
"obtained",
"."
] |
87de0b856a7a4ba8faf5b659537b9af07b763263
|
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/HttpServerExchange.java#L1810-L1817
|
16,803
|
undertow-io/undertow
|
core/src/main/java/io/undertow/server/HttpServerExchange.java
|
HttpServerExchange.addResponseCommitListener
|
public void addResponseCommitListener(final ResponseCommitListener listener) {
//technically it is possible to modify the exchange after the response conduit has been created
//as the response channel should not be retrieved until it is about to be written to
//if we get complaints about this we can add support for it, however it makes the exchange bigger and the connectors more complex
addResponseWrapper(new ConduitWrapper<StreamSinkConduit>() {
@Override
public StreamSinkConduit wrap(ConduitFactory<StreamSinkConduit> factory, HttpServerExchange exchange) {
listener.beforeCommit(exchange);
return factory.create();
}
});
}
|
java
|
public void addResponseCommitListener(final ResponseCommitListener listener) {
//technically it is possible to modify the exchange after the response conduit has been created
//as the response channel should not be retrieved until it is about to be written to
//if we get complaints about this we can add support for it, however it makes the exchange bigger and the connectors more complex
addResponseWrapper(new ConduitWrapper<StreamSinkConduit>() {
@Override
public StreamSinkConduit wrap(ConduitFactory<StreamSinkConduit> factory, HttpServerExchange exchange) {
listener.beforeCommit(exchange);
return factory.create();
}
});
}
|
[
"public",
"void",
"addResponseCommitListener",
"(",
"final",
"ResponseCommitListener",
"listener",
")",
"{",
"//technically it is possible to modify the exchange after the response conduit has been created",
"//as the response channel should not be retrieved until it is about to be written to",
"//if we get complaints about this we can add support for it, however it makes the exchange bigger and the connectors more complex",
"addResponseWrapper",
"(",
"new",
"ConduitWrapper",
"<",
"StreamSinkConduit",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"StreamSinkConduit",
"wrap",
"(",
"ConduitFactory",
"<",
"StreamSinkConduit",
">",
"factory",
",",
"HttpServerExchange",
"exchange",
")",
"{",
"listener",
".",
"beforeCommit",
"(",
"exchange",
")",
";",
"return",
"factory",
".",
"create",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Adds a listener that will be invoked on response commit
@param listener The response listener
|
[
"Adds",
"a",
"listener",
"that",
"will",
"be",
"invoked",
"on",
"response",
"commit"
] |
87de0b856a7a4ba8faf5b659537b9af07b763263
|
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/HttpServerExchange.java#L1836-L1848
|
16,804
|
undertow-io/undertow
|
core/src/main/java/io/undertow/server/HttpServerExchange.java
|
HttpServerExchange.runResumeReadWrite
|
boolean runResumeReadWrite() {
boolean ret = false;
if(anyAreSet(state, FLAG_SHOULD_RESUME_WRITES)) {
responseChannel.runResume();
ret = true;
}
if(anyAreSet(state, FLAG_SHOULD_RESUME_READS)) {
requestChannel.runResume();
ret = true;
}
return ret;
}
|
java
|
boolean runResumeReadWrite() {
boolean ret = false;
if(anyAreSet(state, FLAG_SHOULD_RESUME_WRITES)) {
responseChannel.runResume();
ret = true;
}
if(anyAreSet(state, FLAG_SHOULD_RESUME_READS)) {
requestChannel.runResume();
ret = true;
}
return ret;
}
|
[
"boolean",
"runResumeReadWrite",
"(",
")",
"{",
"boolean",
"ret",
"=",
"false",
";",
"if",
"(",
"anyAreSet",
"(",
"state",
",",
"FLAG_SHOULD_RESUME_WRITES",
")",
")",
"{",
"responseChannel",
".",
"runResume",
"(",
")",
";",
"ret",
"=",
"true",
";",
"}",
"if",
"(",
"anyAreSet",
"(",
"state",
",",
"FLAG_SHOULD_RESUME_READS",
")",
")",
"{",
"requestChannel",
".",
"runResume",
"(",
")",
";",
"ret",
"=",
"true",
";",
"}",
"return",
"ret",
";",
"}"
] |
Actually resumes reads or writes, if the relevant method has been called.
@return <code>true</code> if reads or writes were resumed
|
[
"Actually",
"resumes",
"reads",
"or",
"writes",
"if",
"the",
"relevant",
"method",
"has",
"been",
"called",
"."
] |
87de0b856a7a4ba8faf5b659537b9af07b763263
|
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/server/HttpServerExchange.java#L1855-L1866
|
16,805
|
undertow-io/undertow
|
servlet/src/main/java/io/undertow/servlet/compat/rewrite/RewriteCond.java
|
RewriteCond.evaluate
|
public boolean evaluate(Matcher rule, Matcher cond, Resolver resolver) {
String value = test.evaluate(rule, cond, resolver);
if (nocase) {
value = value.toLowerCase(Locale.ENGLISH);
}
Condition condition = this.condition.get();
if (condition == null) {
if (condPattern.startsWith("<")) {
LexicalCondition ncondition = new LexicalCondition();
ncondition.type = -1;
ncondition.condition = condPattern.substring(1);
condition = ncondition;
} else if (condPattern.startsWith(">")) {
LexicalCondition ncondition = new LexicalCondition();
ncondition.type = 1;
ncondition.condition = condPattern.substring(1);
condition = ncondition;
} else if (condPattern.startsWith("=")) {
LexicalCondition ncondition = new LexicalCondition();
ncondition.type = 0;
ncondition.condition = condPattern.substring(1);
condition = ncondition;
} else if (condPattern.equals("-d")) {
ResourceCondition ncondition = new ResourceCondition();
ncondition.type = 0;
condition = ncondition;
} else if (condPattern.equals("-f")) {
ResourceCondition ncondition = new ResourceCondition();
ncondition.type = 1;
condition = ncondition;
} else if (condPattern.equals("-s")) {
ResourceCondition ncondition = new ResourceCondition();
ncondition.type = 2;
condition = ncondition;
} else {
PatternCondition ncondition = new PatternCondition();
int flags = 0;
if (isNocase()) {
flags |= Pattern.CASE_INSENSITIVE;
}
ncondition.pattern = Pattern.compile(condPattern, flags);
condition = ncondition;
}
this.condition.set(condition);
}
if (positive) {
return condition.evaluate(value, resolver);
} else {
return !condition.evaluate(value, resolver);
}
}
|
java
|
public boolean evaluate(Matcher rule, Matcher cond, Resolver resolver) {
String value = test.evaluate(rule, cond, resolver);
if (nocase) {
value = value.toLowerCase(Locale.ENGLISH);
}
Condition condition = this.condition.get();
if (condition == null) {
if (condPattern.startsWith("<")) {
LexicalCondition ncondition = new LexicalCondition();
ncondition.type = -1;
ncondition.condition = condPattern.substring(1);
condition = ncondition;
} else if (condPattern.startsWith(">")) {
LexicalCondition ncondition = new LexicalCondition();
ncondition.type = 1;
ncondition.condition = condPattern.substring(1);
condition = ncondition;
} else if (condPattern.startsWith("=")) {
LexicalCondition ncondition = new LexicalCondition();
ncondition.type = 0;
ncondition.condition = condPattern.substring(1);
condition = ncondition;
} else if (condPattern.equals("-d")) {
ResourceCondition ncondition = new ResourceCondition();
ncondition.type = 0;
condition = ncondition;
} else if (condPattern.equals("-f")) {
ResourceCondition ncondition = new ResourceCondition();
ncondition.type = 1;
condition = ncondition;
} else if (condPattern.equals("-s")) {
ResourceCondition ncondition = new ResourceCondition();
ncondition.type = 2;
condition = ncondition;
} else {
PatternCondition ncondition = new PatternCondition();
int flags = 0;
if (isNocase()) {
flags |= Pattern.CASE_INSENSITIVE;
}
ncondition.pattern = Pattern.compile(condPattern, flags);
condition = ncondition;
}
this.condition.set(condition);
}
if (positive) {
return condition.evaluate(value, resolver);
} else {
return !condition.evaluate(value, resolver);
}
}
|
[
"public",
"boolean",
"evaluate",
"(",
"Matcher",
"rule",
",",
"Matcher",
"cond",
",",
"Resolver",
"resolver",
")",
"{",
"String",
"value",
"=",
"test",
".",
"evaluate",
"(",
"rule",
",",
"cond",
",",
"resolver",
")",
";",
"if",
"(",
"nocase",
")",
"{",
"value",
"=",
"value",
".",
"toLowerCase",
"(",
"Locale",
".",
"ENGLISH",
")",
";",
"}",
"Condition",
"condition",
"=",
"this",
".",
"condition",
".",
"get",
"(",
")",
";",
"if",
"(",
"condition",
"==",
"null",
")",
"{",
"if",
"(",
"condPattern",
".",
"startsWith",
"(",
"\"<\"",
")",
")",
"{",
"LexicalCondition",
"ncondition",
"=",
"new",
"LexicalCondition",
"(",
")",
";",
"ncondition",
".",
"type",
"=",
"-",
"1",
";",
"ncondition",
".",
"condition",
"=",
"condPattern",
".",
"substring",
"(",
"1",
")",
";",
"condition",
"=",
"ncondition",
";",
"}",
"else",
"if",
"(",
"condPattern",
".",
"startsWith",
"(",
"\">\"",
")",
")",
"{",
"LexicalCondition",
"ncondition",
"=",
"new",
"LexicalCondition",
"(",
")",
";",
"ncondition",
".",
"type",
"=",
"1",
";",
"ncondition",
".",
"condition",
"=",
"condPattern",
".",
"substring",
"(",
"1",
")",
";",
"condition",
"=",
"ncondition",
";",
"}",
"else",
"if",
"(",
"condPattern",
".",
"startsWith",
"(",
"\"=\"",
")",
")",
"{",
"LexicalCondition",
"ncondition",
"=",
"new",
"LexicalCondition",
"(",
")",
";",
"ncondition",
".",
"type",
"=",
"0",
";",
"ncondition",
".",
"condition",
"=",
"condPattern",
".",
"substring",
"(",
"1",
")",
";",
"condition",
"=",
"ncondition",
";",
"}",
"else",
"if",
"(",
"condPattern",
".",
"equals",
"(",
"\"-d\"",
")",
")",
"{",
"ResourceCondition",
"ncondition",
"=",
"new",
"ResourceCondition",
"(",
")",
";",
"ncondition",
".",
"type",
"=",
"0",
";",
"condition",
"=",
"ncondition",
";",
"}",
"else",
"if",
"(",
"condPattern",
".",
"equals",
"(",
"\"-f\"",
")",
")",
"{",
"ResourceCondition",
"ncondition",
"=",
"new",
"ResourceCondition",
"(",
")",
";",
"ncondition",
".",
"type",
"=",
"1",
";",
"condition",
"=",
"ncondition",
";",
"}",
"else",
"if",
"(",
"condPattern",
".",
"equals",
"(",
"\"-s\"",
")",
")",
"{",
"ResourceCondition",
"ncondition",
"=",
"new",
"ResourceCondition",
"(",
")",
";",
"ncondition",
".",
"type",
"=",
"2",
";",
"condition",
"=",
"ncondition",
";",
"}",
"else",
"{",
"PatternCondition",
"ncondition",
"=",
"new",
"PatternCondition",
"(",
")",
";",
"int",
"flags",
"=",
"0",
";",
"if",
"(",
"isNocase",
"(",
")",
")",
"{",
"flags",
"|=",
"Pattern",
".",
"CASE_INSENSITIVE",
";",
"}",
"ncondition",
".",
"pattern",
"=",
"Pattern",
".",
"compile",
"(",
"condPattern",
",",
"flags",
")",
";",
"condition",
"=",
"ncondition",
";",
"}",
"this",
".",
"condition",
".",
"set",
"(",
"condition",
")",
";",
"}",
"if",
"(",
"positive",
")",
"{",
"return",
"condition",
".",
"evaluate",
"(",
"value",
",",
"resolver",
")",
";",
"}",
"else",
"{",
"return",
"!",
"condition",
".",
"evaluate",
"(",
"value",
",",
"resolver",
")",
";",
"}",
"}"
] |
Evaluate the condition based on the context
@param rule corresponding matched rule
@param cond last matched condition
@return
|
[
"Evaluate",
"the",
"condition",
"based",
"on",
"the",
"context"
] |
87de0b856a7a4ba8faf5b659537b9af07b763263
|
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/servlet/src/main/java/io/undertow/servlet/compat/rewrite/RewriteCond.java#L201-L251
|
16,806
|
yanzhenjie/AndPermission
|
support/src/main/java/com/yanzhenjie/permission/runtime/LRequest.java
|
LRequest.callbackSucceed
|
private void callbackSucceed() {
if (mGranted != null) {
List<String> permissionList = asList(mPermissions);
try {
mGranted.onAction(permissionList);
} catch (Exception e) {
Log.e("AndPermission", "Please check the onGranted() method body for bugs.", e);
if (mDenied != null) {
mDenied.onAction(permissionList);
}
}
}
}
|
java
|
private void callbackSucceed() {
if (mGranted != null) {
List<String> permissionList = asList(mPermissions);
try {
mGranted.onAction(permissionList);
} catch (Exception e) {
Log.e("AndPermission", "Please check the onGranted() method body for bugs.", e);
if (mDenied != null) {
mDenied.onAction(permissionList);
}
}
}
}
|
[
"private",
"void",
"callbackSucceed",
"(",
")",
"{",
"if",
"(",
"mGranted",
"!=",
"null",
")",
"{",
"List",
"<",
"String",
">",
"permissionList",
"=",
"asList",
"(",
"mPermissions",
")",
";",
"try",
"{",
"mGranted",
".",
"onAction",
"(",
"permissionList",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"Log",
".",
"e",
"(",
"\"AndPermission\"",
",",
"\"Please check the onGranted() method body for bugs.\"",
",",
"e",
")",
";",
"if",
"(",
"mDenied",
"!=",
"null",
")",
"{",
"mDenied",
".",
"onAction",
"(",
"permissionList",
")",
";",
"}",
"}",
"}",
"}"
] |
Callback acceptance status.
|
[
"Callback",
"acceptance",
"status",
"."
] |
bbfaaecdb8ecf0f2aa270d80c0b88d022dddda7c
|
https://github.com/yanzhenjie/AndPermission/blob/bbfaaecdb8ecf0f2aa270d80c0b88d022dddda7c/support/src/main/java/com/yanzhenjie/permission/runtime/LRequest.java#L94-L106
|
16,807
|
yanzhenjie/AndPermission
|
support/src/main/java/com/yanzhenjie/permission/runtime/LRequest.java
|
LRequest.getDeniedPermissions
|
private static List<String> getDeniedPermissions(PermissionChecker checker, Source source, String... permissions) {
List<String> deniedList = new ArrayList<>(1);
for (String permission : permissions) {
if (!checker.hasPermission(source.getContext(), permission)) {
deniedList.add(permission);
}
}
return deniedList;
}
|
java
|
private static List<String> getDeniedPermissions(PermissionChecker checker, Source source, String... permissions) {
List<String> deniedList = new ArrayList<>(1);
for (String permission : permissions) {
if (!checker.hasPermission(source.getContext(), permission)) {
deniedList.add(permission);
}
}
return deniedList;
}
|
[
"private",
"static",
"List",
"<",
"String",
">",
"getDeniedPermissions",
"(",
"PermissionChecker",
"checker",
",",
"Source",
"source",
",",
"String",
"...",
"permissions",
")",
"{",
"List",
"<",
"String",
">",
"deniedList",
"=",
"new",
"ArrayList",
"<>",
"(",
"1",
")",
";",
"for",
"(",
"String",
"permission",
":",
"permissions",
")",
"{",
"if",
"(",
"!",
"checker",
".",
"hasPermission",
"(",
"source",
".",
"getContext",
"(",
")",
",",
"permission",
")",
")",
"{",
"deniedList",
".",
"add",
"(",
"permission",
")",
";",
"}",
"}",
"return",
"deniedList",
";",
"}"
] |
Get denied permissions.
|
[
"Get",
"denied",
"permissions",
"."
] |
bbfaaecdb8ecf0f2aa270d80c0b88d022dddda7c
|
https://github.com/yanzhenjie/AndPermission/blob/bbfaaecdb8ecf0f2aa270d80c0b88d022dddda7c/support/src/main/java/com/yanzhenjie/permission/runtime/LRequest.java#L120-L128
|
16,808
|
yanzhenjie/AndPermission
|
support/src/main/java/com/yanzhenjie/permission/bridge/BridgeActivity.java
|
BridgeActivity.requestInstall
|
static void requestInstall(Source source) {
Intent intent = new Intent(source.getContext(), BridgeActivity.class);
intent.putExtra(KEY_TYPE, BridgeRequest.TYPE_INSTALL);
source.startActivity(intent);
}
|
java
|
static void requestInstall(Source source) {
Intent intent = new Intent(source.getContext(), BridgeActivity.class);
intent.putExtra(KEY_TYPE, BridgeRequest.TYPE_INSTALL);
source.startActivity(intent);
}
|
[
"static",
"void",
"requestInstall",
"(",
"Source",
"source",
")",
"{",
"Intent",
"intent",
"=",
"new",
"Intent",
"(",
"source",
".",
"getContext",
"(",
")",
",",
"BridgeActivity",
".",
"class",
")",
";",
"intent",
".",
"putExtra",
"(",
"KEY_TYPE",
",",
"BridgeRequest",
".",
"TYPE_INSTALL",
")",
";",
"source",
".",
"startActivity",
"(",
"intent",
")",
";",
"}"
] |
Request for package install.
|
[
"Request",
"for",
"package",
"install",
"."
] |
bbfaaecdb8ecf0f2aa270d80c0b88d022dddda7c
|
https://github.com/yanzhenjie/AndPermission/blob/bbfaaecdb8ecf0f2aa270d80c0b88d022dddda7c/support/src/main/java/com/yanzhenjie/permission/bridge/BridgeActivity.java#L64-L68
|
16,809
|
yanzhenjie/AndPermission
|
support/src/main/java/com/yanzhenjie/permission/bridge/BridgeActivity.java
|
BridgeActivity.requestOverlay
|
static void requestOverlay(Source source) {
Intent intent = new Intent(source.getContext(), BridgeActivity.class);
intent.putExtra(KEY_TYPE, BridgeRequest.TYPE_OVERLAY);
source.startActivity(intent);
}
|
java
|
static void requestOverlay(Source source) {
Intent intent = new Intent(source.getContext(), BridgeActivity.class);
intent.putExtra(KEY_TYPE, BridgeRequest.TYPE_OVERLAY);
source.startActivity(intent);
}
|
[
"static",
"void",
"requestOverlay",
"(",
"Source",
"source",
")",
"{",
"Intent",
"intent",
"=",
"new",
"Intent",
"(",
"source",
".",
"getContext",
"(",
")",
",",
"BridgeActivity",
".",
"class",
")",
";",
"intent",
".",
"putExtra",
"(",
"KEY_TYPE",
",",
"BridgeRequest",
".",
"TYPE_OVERLAY",
")",
";",
"source",
".",
"startActivity",
"(",
"intent",
")",
";",
"}"
] |
Request for overlay.
|
[
"Request",
"for",
"overlay",
"."
] |
bbfaaecdb8ecf0f2aa270d80c0b88d022dddda7c
|
https://github.com/yanzhenjie/AndPermission/blob/bbfaaecdb8ecf0f2aa270d80c0b88d022dddda7c/support/src/main/java/com/yanzhenjie/permission/bridge/BridgeActivity.java#L73-L77
|
16,810
|
yanzhenjie/AndPermission
|
support/src/main/java/com/yanzhenjie/permission/bridge/BridgeActivity.java
|
BridgeActivity.requestAlertWindow
|
static void requestAlertWindow(Source source) {
Intent intent = new Intent(source.getContext(), BridgeActivity.class);
intent.putExtra(KEY_TYPE, BridgeRequest.TYPE_ALERT_WINDOW);
source.startActivity(intent);
}
|
java
|
static void requestAlertWindow(Source source) {
Intent intent = new Intent(source.getContext(), BridgeActivity.class);
intent.putExtra(KEY_TYPE, BridgeRequest.TYPE_ALERT_WINDOW);
source.startActivity(intent);
}
|
[
"static",
"void",
"requestAlertWindow",
"(",
"Source",
"source",
")",
"{",
"Intent",
"intent",
"=",
"new",
"Intent",
"(",
"source",
".",
"getContext",
"(",
")",
",",
"BridgeActivity",
".",
"class",
")",
";",
"intent",
".",
"putExtra",
"(",
"KEY_TYPE",
",",
"BridgeRequest",
".",
"TYPE_ALERT_WINDOW",
")",
";",
"source",
".",
"startActivity",
"(",
"intent",
")",
";",
"}"
] |
Request for alert window.
|
[
"Request",
"for",
"alert",
"window",
"."
] |
bbfaaecdb8ecf0f2aa270d80c0b88d022dddda7c
|
https://github.com/yanzhenjie/AndPermission/blob/bbfaaecdb8ecf0f2aa270d80c0b88d022dddda7c/support/src/main/java/com/yanzhenjie/permission/bridge/BridgeActivity.java#L82-L86
|
16,811
|
yanzhenjie/AndPermission
|
support/src/main/java/com/yanzhenjie/permission/bridge/BridgeActivity.java
|
BridgeActivity.requestNotify
|
static void requestNotify(Source source) {
Intent intent = new Intent(source.getContext(), BridgeActivity.class);
intent.putExtra(KEY_TYPE, BridgeRequest.TYPE_NOTIFY);
source.startActivity(intent);
}
|
java
|
static void requestNotify(Source source) {
Intent intent = new Intent(source.getContext(), BridgeActivity.class);
intent.putExtra(KEY_TYPE, BridgeRequest.TYPE_NOTIFY);
source.startActivity(intent);
}
|
[
"static",
"void",
"requestNotify",
"(",
"Source",
"source",
")",
"{",
"Intent",
"intent",
"=",
"new",
"Intent",
"(",
"source",
".",
"getContext",
"(",
")",
",",
"BridgeActivity",
".",
"class",
")",
";",
"intent",
".",
"putExtra",
"(",
"KEY_TYPE",
",",
"BridgeRequest",
".",
"TYPE_NOTIFY",
")",
";",
"source",
".",
"startActivity",
"(",
"intent",
")",
";",
"}"
] |
Request for notify.
|
[
"Request",
"for",
"notify",
"."
] |
bbfaaecdb8ecf0f2aa270d80c0b88d022dddda7c
|
https://github.com/yanzhenjie/AndPermission/blob/bbfaaecdb8ecf0f2aa270d80c0b88d022dddda7c/support/src/main/java/com/yanzhenjie/permission/bridge/BridgeActivity.java#L91-L95
|
16,812
|
yanzhenjie/AndPermission
|
support/src/main/java/com/yanzhenjie/permission/bridge/BridgeActivity.java
|
BridgeActivity.requestNotificationListener
|
static void requestNotificationListener(Source source) {
Intent intent = new Intent(source.getContext(), BridgeActivity.class);
intent.putExtra(KEY_TYPE, BridgeRequest.TYPE_NOTIFY_LISTENER);
source.startActivity(intent);
}
|
java
|
static void requestNotificationListener(Source source) {
Intent intent = new Intent(source.getContext(), BridgeActivity.class);
intent.putExtra(KEY_TYPE, BridgeRequest.TYPE_NOTIFY_LISTENER);
source.startActivity(intent);
}
|
[
"static",
"void",
"requestNotificationListener",
"(",
"Source",
"source",
")",
"{",
"Intent",
"intent",
"=",
"new",
"Intent",
"(",
"source",
".",
"getContext",
"(",
")",
",",
"BridgeActivity",
".",
"class",
")",
";",
"intent",
".",
"putExtra",
"(",
"KEY_TYPE",
",",
"BridgeRequest",
".",
"TYPE_NOTIFY_LISTENER",
")",
";",
"source",
".",
"startActivity",
"(",
"intent",
")",
";",
"}"
] |
Request for notification listener.
|
[
"Request",
"for",
"notification",
"listener",
"."
] |
bbfaaecdb8ecf0f2aa270d80c0b88d022dddda7c
|
https://github.com/yanzhenjie/AndPermission/blob/bbfaaecdb8ecf0f2aa270d80c0b88d022dddda7c/support/src/main/java/com/yanzhenjie/permission/bridge/BridgeActivity.java#L100-L104
|
16,813
|
yanzhenjie/AndPermission
|
support/src/main/java/com/yanzhenjie/permission/bridge/BridgeActivity.java
|
BridgeActivity.requestWriteSetting
|
static void requestWriteSetting(Source source) {
Intent intent = new Intent(source.getContext(), BridgeActivity.class);
intent.putExtra(KEY_TYPE, BridgeRequest.TYPE_WRITE_SETTING);
source.startActivity(intent);
}
|
java
|
static void requestWriteSetting(Source source) {
Intent intent = new Intent(source.getContext(), BridgeActivity.class);
intent.putExtra(KEY_TYPE, BridgeRequest.TYPE_WRITE_SETTING);
source.startActivity(intent);
}
|
[
"static",
"void",
"requestWriteSetting",
"(",
"Source",
"source",
")",
"{",
"Intent",
"intent",
"=",
"new",
"Intent",
"(",
"source",
".",
"getContext",
"(",
")",
",",
"BridgeActivity",
".",
"class",
")",
";",
"intent",
".",
"putExtra",
"(",
"KEY_TYPE",
",",
"BridgeRequest",
".",
"TYPE_WRITE_SETTING",
")",
";",
"source",
".",
"startActivity",
"(",
"intent",
")",
";",
"}"
] |
Request for write system setting.
|
[
"Request",
"for",
"write",
"system",
"setting",
"."
] |
bbfaaecdb8ecf0f2aa270d80c0b88d022dddda7c
|
https://github.com/yanzhenjie/AndPermission/blob/bbfaaecdb8ecf0f2aa270d80c0b88d022dddda7c/support/src/main/java/com/yanzhenjie/permission/bridge/BridgeActivity.java#L109-L113
|
16,814
|
yanzhenjie/AndPermission
|
support/src/main/java/com/yanzhenjie/permission/AndPermission.java
|
AndPermission.hasAlwaysDeniedPermission
|
private static boolean hasAlwaysDeniedPermission(Source source, String... deniedPermissions) {
for (String permission : deniedPermissions) {
if (!source.isShowRationalePermission(permission)) {
return true;
}
}
return false;
}
|
java
|
private static boolean hasAlwaysDeniedPermission(Source source, String... deniedPermissions) {
for (String permission : deniedPermissions) {
if (!source.isShowRationalePermission(permission)) {
return true;
}
}
return false;
}
|
[
"private",
"static",
"boolean",
"hasAlwaysDeniedPermission",
"(",
"Source",
"source",
",",
"String",
"...",
"deniedPermissions",
")",
"{",
"for",
"(",
"String",
"permission",
":",
"deniedPermissions",
")",
"{",
"if",
"(",
"!",
"source",
".",
"isShowRationalePermission",
"(",
"permission",
")",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
] |
Has always been denied permission.
|
[
"Has",
"always",
"been",
"denied",
"permission",
"."
] |
bbfaaecdb8ecf0f2aa270d80c0b88d022dddda7c
|
https://github.com/yanzhenjie/AndPermission/blob/bbfaaecdb8ecf0f2aa270d80c0b88d022dddda7c/support/src/main/java/com/yanzhenjie/permission/AndPermission.java#L197-L204
|
16,815
|
yanzhenjie/AndPermission
|
x/src/main/java/com/yanzhenjie/permission/install/BaseRequest.java
|
BaseRequest.install
|
final void install() {
Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Uri uri = AndPermission.getFileUri(mSource.getContext(), mFile);
intent.setDataAndType(uri, "application/vnd.android.package-archive");
mSource.startActivity(intent);
}
|
java
|
final void install() {
Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Uri uri = AndPermission.getFileUri(mSource.getContext(), mFile);
intent.setDataAndType(uri, "application/vnd.android.package-archive");
mSource.startActivity(intent);
}
|
[
"final",
"void",
"install",
"(",
")",
"{",
"Intent",
"intent",
"=",
"new",
"Intent",
"(",
"Intent",
".",
"ACTION_INSTALL_PACKAGE",
")",
";",
"intent",
".",
"setFlags",
"(",
"Intent",
".",
"FLAG_ACTIVITY_NEW_TASK",
")",
";",
"intent",
".",
"addFlags",
"(",
"Intent",
".",
"FLAG_GRANT_READ_URI_PERMISSION",
")",
";",
"Uri",
"uri",
"=",
"AndPermission",
".",
"getFileUri",
"(",
"mSource",
".",
"getContext",
"(",
")",
",",
"mFile",
")",
";",
"intent",
".",
"setDataAndType",
"(",
"uri",
",",
"\"application/vnd.android.package-archive\"",
")",
";",
"mSource",
".",
"startActivity",
"(",
"intent",
")",
";",
"}"
] |
Start the installation.
|
[
"Start",
"the",
"installation",
"."
] |
bbfaaecdb8ecf0f2aa270d80c0b88d022dddda7c
|
https://github.com/yanzhenjie/AndPermission/blob/bbfaaecdb8ecf0f2aa270d80c0b88d022dddda7c/x/src/main/java/com/yanzhenjie/permission/install/BaseRequest.java#L85-L92
|
16,816
|
yanzhenjie/AndPermission
|
supportSample/src/main/java/com/yanzhenjie/permission/sample/widget/AlertWindow.java
|
AlertWindow.show
|
public void show() {
if (isShowing) {
Log.w("AlertWindow", "AlertWindow is already displayed.");
} else {
isShowing = true;
mWindowManager.addView(mContentView, mParams);
}
}
|
java
|
public void show() {
if (isShowing) {
Log.w("AlertWindow", "AlertWindow is already displayed.");
} else {
isShowing = true;
mWindowManager.addView(mContentView, mParams);
}
}
|
[
"public",
"void",
"show",
"(",
")",
"{",
"if",
"(",
"isShowing",
")",
"{",
"Log",
".",
"w",
"(",
"\"AlertWindow\"",
",",
"\"AlertWindow is already displayed.\"",
")",
";",
"}",
"else",
"{",
"isShowing",
"=",
"true",
";",
"mWindowManager",
".",
"addView",
"(",
"mContentView",
",",
"mParams",
")",
";",
"}",
"}"
] |
Display the alert window.
|
[
"Display",
"the",
"alert",
"window",
"."
] |
bbfaaecdb8ecf0f2aa270d80c0b88d022dddda7c
|
https://github.com/yanzhenjie/AndPermission/blob/bbfaaecdb8ecf0f2aa270d80c0b88d022dddda7c/supportSample/src/main/java/com/yanzhenjie/permission/sample/widget/AlertWindow.java#L102-L109
|
16,817
|
yanzhenjie/AndPermission
|
x/src/main/java/com/yanzhenjie/permission/runtime/MRequest.java
|
MRequest.getRationalePermissions
|
private static List<String> getRationalePermissions(Source source, String... permissions) {
List<String> rationaleList = new ArrayList<>(1);
for (String permission : permissions) {
if (source.isShowRationalePermission(permission)) {
rationaleList.add(permission);
}
}
return rationaleList;
}
|
java
|
private static List<String> getRationalePermissions(Source source, String... permissions) {
List<String> rationaleList = new ArrayList<>(1);
for (String permission : permissions) {
if (source.isShowRationalePermission(permission)) {
rationaleList.add(permission);
}
}
return rationaleList;
}
|
[
"private",
"static",
"List",
"<",
"String",
">",
"getRationalePermissions",
"(",
"Source",
"source",
",",
"String",
"...",
"permissions",
")",
"{",
"List",
"<",
"String",
">",
"rationaleList",
"=",
"new",
"ArrayList",
"<>",
"(",
"1",
")",
";",
"for",
"(",
"String",
"permission",
":",
"permissions",
")",
"{",
"if",
"(",
"source",
".",
"isShowRationalePermission",
"(",
"permission",
")",
")",
"{",
"rationaleList",
".",
"add",
"(",
"permission",
")",
";",
"}",
"}",
"return",
"rationaleList",
";",
"}"
] |
Get permissions to show rationale.
|
[
"Get",
"permissions",
"to",
"show",
"rationale",
"."
] |
bbfaaecdb8ecf0f2aa270d80c0b88d022dddda7c
|
https://github.com/yanzhenjie/AndPermission/blob/bbfaaecdb8ecf0f2aa270d80c0b88d022dddda7c/x/src/main/java/com/yanzhenjie/permission/runtime/MRequest.java#L178-L186
|
16,818
|
yanzhenjie/AndPermission
|
support/src/main/java/com/yanzhenjie/permission/runtime/Runtime.java
|
Runtime.checkPermissions
|
private void checkPermissions(String... permissions) {
if (sAppPermissions == null) sAppPermissions = getManifestPermissions(mSource.getContext());
if (permissions.length == 0) {
throw new IllegalArgumentException("Please enter at least one permission.");
}
for (String p : permissions) {
if (!sAppPermissions.contains(p)) {
if (!(Permission.ADD_VOICEMAIL.equals(p) &&
sAppPermissions.contains(Permission.ADD_VOICEMAIL_MANIFEST))) {
throw new IllegalStateException(
String.format("The permission %1$s is not registered in manifest.xml", p));
}
}
}
}
|
java
|
private void checkPermissions(String... permissions) {
if (sAppPermissions == null) sAppPermissions = getManifestPermissions(mSource.getContext());
if (permissions.length == 0) {
throw new IllegalArgumentException("Please enter at least one permission.");
}
for (String p : permissions) {
if (!sAppPermissions.contains(p)) {
if (!(Permission.ADD_VOICEMAIL.equals(p) &&
sAppPermissions.contains(Permission.ADD_VOICEMAIL_MANIFEST))) {
throw new IllegalStateException(
String.format("The permission %1$s is not registered in manifest.xml", p));
}
}
}
}
|
[
"private",
"void",
"checkPermissions",
"(",
"String",
"...",
"permissions",
")",
"{",
"if",
"(",
"sAppPermissions",
"==",
"null",
")",
"sAppPermissions",
"=",
"getManifestPermissions",
"(",
"mSource",
".",
"getContext",
"(",
")",
")",
";",
"if",
"(",
"permissions",
".",
"length",
"==",
"0",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Please enter at least one permission.\"",
")",
";",
"}",
"for",
"(",
"String",
"p",
":",
"permissions",
")",
"{",
"if",
"(",
"!",
"sAppPermissions",
".",
"contains",
"(",
"p",
")",
")",
"{",
"if",
"(",
"!",
"(",
"Permission",
".",
"ADD_VOICEMAIL",
".",
"equals",
"(",
"p",
")",
"&&",
"sAppPermissions",
".",
"contains",
"(",
"Permission",
".",
"ADD_VOICEMAIL_MANIFEST",
")",
")",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"String",
".",
"format",
"(",
"\"The permission %1$s is not registered in manifest.xml\"",
",",
"p",
")",
")",
";",
"}",
"}",
"}",
"}"
] |
Check if the permissions are valid and each permission has been registered in manifest.xml. This method will
throw a exception if permissions are invalid or there is any permission which is not registered in manifest.xml.
@param permissions permissions which will be checked.
|
[
"Check",
"if",
"the",
"permissions",
"are",
"valid",
"and",
"each",
"permission",
"has",
"been",
"registered",
"in",
"manifest",
".",
"xml",
".",
"This",
"method",
"will",
"throw",
"a",
"exception",
"if",
"permissions",
"are",
"invalid",
"or",
"there",
"is",
"any",
"permission",
"which",
"is",
"not",
"registered",
"in",
"manifest",
".",
"xml",
"."
] |
bbfaaecdb8ecf0f2aa270d80c0b88d022dddda7c
|
https://github.com/yanzhenjie/AndPermission/blob/bbfaaecdb8ecf0f2aa270d80c0b88d022dddda7c/support/src/main/java/com/yanzhenjie/permission/runtime/Runtime.java#L92-L108
|
16,819
|
yanzhenjie/AndPermission
|
support/src/main/java/com/yanzhenjie/permission/runtime/Runtime.java
|
Runtime.getManifestPermissions
|
private static List<String> getManifestPermissions(Context context) {
try {
PackageInfo packageInfo = context.getPackageManager()
.getPackageInfo(context.getPackageName(), PackageManager.GET_PERMISSIONS);
String[] permissions = packageInfo.requestedPermissions;
if (permissions == null || permissions.length == 0) {
throw new IllegalStateException("You did not register any permissions in the manifest.xml.");
}
return Collections.unmodifiableList(Arrays.asList(permissions));
} catch (PackageManager.NameNotFoundException e) {
throw new AssertionError("Package name cannot be found.");
}
}
|
java
|
private static List<String> getManifestPermissions(Context context) {
try {
PackageInfo packageInfo = context.getPackageManager()
.getPackageInfo(context.getPackageName(), PackageManager.GET_PERMISSIONS);
String[] permissions = packageInfo.requestedPermissions;
if (permissions == null || permissions.length == 0) {
throw new IllegalStateException("You did not register any permissions in the manifest.xml.");
}
return Collections.unmodifiableList(Arrays.asList(permissions));
} catch (PackageManager.NameNotFoundException e) {
throw new AssertionError("Package name cannot be found.");
}
}
|
[
"private",
"static",
"List",
"<",
"String",
">",
"getManifestPermissions",
"(",
"Context",
"context",
")",
"{",
"try",
"{",
"PackageInfo",
"packageInfo",
"=",
"context",
".",
"getPackageManager",
"(",
")",
".",
"getPackageInfo",
"(",
"context",
".",
"getPackageName",
"(",
")",
",",
"PackageManager",
".",
"GET_PERMISSIONS",
")",
";",
"String",
"[",
"]",
"permissions",
"=",
"packageInfo",
".",
"requestedPermissions",
";",
"if",
"(",
"permissions",
"==",
"null",
"||",
"permissions",
".",
"length",
"==",
"0",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"You did not register any permissions in the manifest.xml.\"",
")",
";",
"}",
"return",
"Collections",
".",
"unmodifiableList",
"(",
"Arrays",
".",
"asList",
"(",
"permissions",
")",
")",
";",
"}",
"catch",
"(",
"PackageManager",
".",
"NameNotFoundException",
"e",
")",
"{",
"throw",
"new",
"AssertionError",
"(",
"\"Package name cannot be found.\"",
")",
";",
"}",
"}"
] |
Get a list of permissions in the manifest.
|
[
"Get",
"a",
"list",
"of",
"permissions",
"in",
"the",
"manifest",
"."
] |
bbfaaecdb8ecf0f2aa270d80c0b88d022dddda7c
|
https://github.com/yanzhenjie/AndPermission/blob/bbfaaecdb8ecf0f2aa270d80c0b88d022dddda7c/support/src/main/java/com/yanzhenjie/permission/runtime/Runtime.java#L113-L125
|
16,820
|
yanzhenjie/AndPermission
|
supportSample/src/main/java/com/yanzhenjie/permission/sample/app/MainActivity.java
|
MainActivity.showSettingDialog
|
public void showSettingDialog(Context context, final List<String> permissions) {
List<String> permissionNames = Permission.transformText(context, permissions);
String message = context.getString(R.string.message_permission_always_failed,
TextUtils.join("\n", permissionNames));
new AlertDialog.Builder(context).setCancelable(false)
.setTitle(R.string.title_dialog)
.setMessage(message)
.setPositiveButton(R.string.setting, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
setPermission();
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
})
.show();
}
|
java
|
public void showSettingDialog(Context context, final List<String> permissions) {
List<String> permissionNames = Permission.transformText(context, permissions);
String message = context.getString(R.string.message_permission_always_failed,
TextUtils.join("\n", permissionNames));
new AlertDialog.Builder(context).setCancelable(false)
.setTitle(R.string.title_dialog)
.setMessage(message)
.setPositiveButton(R.string.setting, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
setPermission();
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
})
.show();
}
|
[
"public",
"void",
"showSettingDialog",
"(",
"Context",
"context",
",",
"final",
"List",
"<",
"String",
">",
"permissions",
")",
"{",
"List",
"<",
"String",
">",
"permissionNames",
"=",
"Permission",
".",
"transformText",
"(",
"context",
",",
"permissions",
")",
";",
"String",
"message",
"=",
"context",
".",
"getString",
"(",
"R",
".",
"string",
".",
"message_permission_always_failed",
",",
"TextUtils",
".",
"join",
"(",
"\"\\n\"",
",",
"permissionNames",
")",
")",
";",
"new",
"AlertDialog",
".",
"Builder",
"(",
"context",
")",
".",
"setCancelable",
"(",
"false",
")",
".",
"setTitle",
"(",
"R",
".",
"string",
".",
"title_dialog",
")",
".",
"setMessage",
"(",
"message",
")",
".",
"setPositiveButton",
"(",
"R",
".",
"string",
".",
"setting",
",",
"new",
"DialogInterface",
".",
"OnClickListener",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"onClick",
"(",
"DialogInterface",
"dialog",
",",
"int",
"which",
")",
"{",
"setPermission",
"(",
")",
";",
"}",
"}",
")",
".",
"setNegativeButton",
"(",
"R",
".",
"string",
".",
"cancel",
",",
"new",
"DialogInterface",
".",
"OnClickListener",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"onClick",
"(",
"DialogInterface",
"dialog",
",",
"int",
"which",
")",
"{",
"}",
"}",
")",
".",
"show",
"(",
")",
";",
"}"
] |
Display setting dialog.
|
[
"Display",
"setting",
"dialog",
"."
] |
bbfaaecdb8ecf0f2aa270d80c0b88d022dddda7c
|
https://github.com/yanzhenjie/AndPermission/blob/bbfaaecdb8ecf0f2aa270d80c0b88d022dddda7c/supportSample/src/main/java/com/yanzhenjie/permission/sample/app/MainActivity.java#L347-L367
|
16,821
|
yanzhenjie/AndPermission
|
supportSample/src/main/java/com/yanzhenjie/permission/sample/app/MainActivity.java
|
MainActivity.requestNotification
|
private void requestNotification() {
AndPermission.with(this)
.notification()
.permission()
.rationale(new NotifyRationale())
.onGranted(new Action<Void>() {
@Override
public void onAction(Void data) {
toast(R.string.successfully);
}
})
.onDenied(new Action<Void>() {
@Override
public void onAction(Void data) {
toast(R.string.failure);
}
})
.start();
}
|
java
|
private void requestNotification() {
AndPermission.with(this)
.notification()
.permission()
.rationale(new NotifyRationale())
.onGranted(new Action<Void>() {
@Override
public void onAction(Void data) {
toast(R.string.successfully);
}
})
.onDenied(new Action<Void>() {
@Override
public void onAction(Void data) {
toast(R.string.failure);
}
})
.start();
}
|
[
"private",
"void",
"requestNotification",
"(",
")",
"{",
"AndPermission",
".",
"with",
"(",
"this",
")",
".",
"notification",
"(",
")",
".",
"permission",
"(",
")",
".",
"rationale",
"(",
"new",
"NotifyRationale",
"(",
")",
")",
".",
"onGranted",
"(",
"new",
"Action",
"<",
"Void",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"onAction",
"(",
"Void",
"data",
")",
"{",
"toast",
"(",
"R",
".",
"string",
".",
"successfully",
")",
";",
"}",
"}",
")",
".",
"onDenied",
"(",
"new",
"Action",
"<",
"Void",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"onAction",
"(",
"Void",
"data",
")",
"{",
"toast",
"(",
"R",
".",
"string",
".",
"failure",
")",
";",
"}",
"}",
")",
".",
"start",
"(",
")",
";",
"}"
] |
Request notification permission.
|
[
"Request",
"notification",
"permission",
"."
] |
bbfaaecdb8ecf0f2aa270d80c0b88d022dddda7c
|
https://github.com/yanzhenjie/AndPermission/blob/bbfaaecdb8ecf0f2aa270d80c0b88d022dddda7c/supportSample/src/main/java/com/yanzhenjie/permission/sample/app/MainActivity.java#L389-L407
|
16,822
|
yanzhenjie/AndPermission
|
supportSample/src/main/java/com/yanzhenjie/permission/sample/app/MainActivity.java
|
MainActivity.requestNotificationListener
|
private void requestNotificationListener() {
AndPermission.with(this)
.notification()
.listener()
.rationale(new NotifyListenerRationale())
.onGranted(new Action<Void>() {
@Override
public void onAction(Void data) {
toast(R.string.successfully);
}
})
.onDenied(new Action<Void>() {
@Override
public void onAction(Void data) {
toast(R.string.failure);
}
})
.start();
}
|
java
|
private void requestNotificationListener() {
AndPermission.with(this)
.notification()
.listener()
.rationale(new NotifyListenerRationale())
.onGranted(new Action<Void>() {
@Override
public void onAction(Void data) {
toast(R.string.successfully);
}
})
.onDenied(new Action<Void>() {
@Override
public void onAction(Void data) {
toast(R.string.failure);
}
})
.start();
}
|
[
"private",
"void",
"requestNotificationListener",
"(",
")",
"{",
"AndPermission",
".",
"with",
"(",
"this",
")",
".",
"notification",
"(",
")",
".",
"listener",
"(",
")",
".",
"rationale",
"(",
"new",
"NotifyListenerRationale",
"(",
")",
")",
".",
"onGranted",
"(",
"new",
"Action",
"<",
"Void",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"onAction",
"(",
"Void",
"data",
")",
"{",
"toast",
"(",
"R",
".",
"string",
".",
"successfully",
")",
";",
"}",
"}",
")",
".",
"onDenied",
"(",
"new",
"Action",
"<",
"Void",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"onAction",
"(",
"Void",
"data",
")",
"{",
"toast",
"(",
"R",
".",
"string",
".",
"failure",
")",
";",
"}",
"}",
")",
".",
"start",
"(",
")",
";",
"}"
] |
Request notification listener.
|
[
"Request",
"notification",
"listener",
"."
] |
bbfaaecdb8ecf0f2aa270d80c0b88d022dddda7c
|
https://github.com/yanzhenjie/AndPermission/blob/bbfaaecdb8ecf0f2aa270d80c0b88d022dddda7c/supportSample/src/main/java/com/yanzhenjie/permission/sample/app/MainActivity.java#L412-L430
|
16,823
|
yanzhenjie/AndPermission
|
supportSample/src/main/java/com/yanzhenjie/permission/sample/app/MainActivity.java
|
MainActivity.requestPermissionForInstallPackage
|
private void requestPermissionForInstallPackage() {
AndPermission.with(this)
.runtime()
.permission(Permission.Group.STORAGE)
.rationale(new RuntimeRationale())
.onGranted(new Action<List<String>>() {
@Override
public void onAction(List<String> data) {
new WriteApkTask(MainActivity.this, new Runnable() {
@Override
public void run() {
installPackage();
}
}).execute();
}
})
.onDenied(new Action<List<String>>() {
@Override
public void onAction(List<String> data) {
toast(R.string.message_install_failed);
}
})
.start();
}
|
java
|
private void requestPermissionForInstallPackage() {
AndPermission.with(this)
.runtime()
.permission(Permission.Group.STORAGE)
.rationale(new RuntimeRationale())
.onGranted(new Action<List<String>>() {
@Override
public void onAction(List<String> data) {
new WriteApkTask(MainActivity.this, new Runnable() {
@Override
public void run() {
installPackage();
}
}).execute();
}
})
.onDenied(new Action<List<String>>() {
@Override
public void onAction(List<String> data) {
toast(R.string.message_install_failed);
}
})
.start();
}
|
[
"private",
"void",
"requestPermissionForInstallPackage",
"(",
")",
"{",
"AndPermission",
".",
"with",
"(",
"this",
")",
".",
"runtime",
"(",
")",
".",
"permission",
"(",
"Permission",
".",
"Group",
".",
"STORAGE",
")",
".",
"rationale",
"(",
"new",
"RuntimeRationale",
"(",
")",
")",
".",
"onGranted",
"(",
"new",
"Action",
"<",
"List",
"<",
"String",
">",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"onAction",
"(",
"List",
"<",
"String",
">",
"data",
")",
"{",
"new",
"WriteApkTask",
"(",
"MainActivity",
".",
"this",
",",
"new",
"Runnable",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"run",
"(",
")",
"{",
"installPackage",
"(",
")",
";",
"}",
"}",
")",
".",
"execute",
"(",
")",
";",
"}",
"}",
")",
".",
"onDenied",
"(",
"new",
"Action",
"<",
"List",
"<",
"String",
">",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"onAction",
"(",
"List",
"<",
"String",
">",
"data",
")",
"{",
"toast",
"(",
"R",
".",
"string",
".",
"message_install_failed",
")",
";",
"}",
"}",
")",
".",
"start",
"(",
")",
";",
"}"
] |
Request to read and write external storage permissions.
|
[
"Request",
"to",
"read",
"and",
"write",
"external",
"storage",
"permissions",
"."
] |
bbfaaecdb8ecf0f2aa270d80c0b88d022dddda7c
|
https://github.com/yanzhenjie/AndPermission/blob/bbfaaecdb8ecf0f2aa270d80c0b88d022dddda7c/supportSample/src/main/java/com/yanzhenjie/permission/sample/app/MainActivity.java#L435-L458
|
16,824
|
yanzhenjie/AndPermission
|
supportSample/src/main/java/com/yanzhenjie/permission/sample/app/MainActivity.java
|
MainActivity.createMenu
|
private PopupMenu createMenu(View v, String[] menuArray) {
PopupMenu popupMenu = new PopupMenu(this, v);
Menu menu = popupMenu.getMenu();
for (int i = 0; i < menuArray.length; i++) {
String menuText = menuArray[i];
menu.add(0, i, i, menuText);
}
return popupMenu;
}
|
java
|
private PopupMenu createMenu(View v, String[] menuArray) {
PopupMenu popupMenu = new PopupMenu(this, v);
Menu menu = popupMenu.getMenu();
for (int i = 0; i < menuArray.length; i++) {
String menuText = menuArray[i];
menu.add(0, i, i, menuText);
}
return popupMenu;
}
|
[
"private",
"PopupMenu",
"createMenu",
"(",
"View",
"v",
",",
"String",
"[",
"]",
"menuArray",
")",
"{",
"PopupMenu",
"popupMenu",
"=",
"new",
"PopupMenu",
"(",
"this",
",",
"v",
")",
";",
"Menu",
"menu",
"=",
"popupMenu",
".",
"getMenu",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"menuArray",
".",
"length",
";",
"i",
"++",
")",
"{",
"String",
"menuText",
"=",
"menuArray",
"[",
"i",
"]",
";",
"menu",
".",
"add",
"(",
"0",
",",
"i",
",",
"i",
",",
"menuText",
")",
";",
"}",
"return",
"popupMenu",
";",
"}"
] |
Create menu.
|
[
"Create",
"menu",
"."
] |
bbfaaecdb8ecf0f2aa270d80c0b88d022dddda7c
|
https://github.com/yanzhenjie/AndPermission/blob/bbfaaecdb8ecf0f2aa270d80c0b88d022dddda7c/supportSample/src/main/java/com/yanzhenjie/permission/sample/app/MainActivity.java#L526-L534
|
16,825
|
web3j/web3j
|
crypto/src/main/java/org/web3j/crypto/ContractUtils.java
|
ContractUtils.generateContractAddress
|
public static byte[] generateContractAddress(byte[] address, BigInteger nonce) {
List<RlpType> values = new ArrayList<>();
values.add(RlpString.create(address));
values.add(RlpString.create(nonce));
RlpList rlpList = new RlpList(values);
byte[] encoded = RlpEncoder.encode(rlpList);
byte[] hashed = Hash.sha3(encoded);
return Arrays.copyOfRange(hashed, 12, hashed.length);
}
|
java
|
public static byte[] generateContractAddress(byte[] address, BigInteger nonce) {
List<RlpType> values = new ArrayList<>();
values.add(RlpString.create(address));
values.add(RlpString.create(nonce));
RlpList rlpList = new RlpList(values);
byte[] encoded = RlpEncoder.encode(rlpList);
byte[] hashed = Hash.sha3(encoded);
return Arrays.copyOfRange(hashed, 12, hashed.length);
}
|
[
"public",
"static",
"byte",
"[",
"]",
"generateContractAddress",
"(",
"byte",
"[",
"]",
"address",
",",
"BigInteger",
"nonce",
")",
"{",
"List",
"<",
"RlpType",
">",
"values",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"values",
".",
"add",
"(",
"RlpString",
".",
"create",
"(",
"address",
")",
")",
";",
"values",
".",
"add",
"(",
"RlpString",
".",
"create",
"(",
"nonce",
")",
")",
";",
"RlpList",
"rlpList",
"=",
"new",
"RlpList",
"(",
"values",
")",
";",
"byte",
"[",
"]",
"encoded",
"=",
"RlpEncoder",
".",
"encode",
"(",
"rlpList",
")",
";",
"byte",
"[",
"]",
"hashed",
"=",
"Hash",
".",
"sha3",
"(",
"encoded",
")",
";",
"return",
"Arrays",
".",
"copyOfRange",
"(",
"hashed",
",",
"12",
",",
"hashed",
".",
"length",
")",
";",
"}"
] |
Generate a smart contract address. This enables you to identify what address a
smart contract will be deployed to on the network.
@param address of sender
@param nonce of transaction
@return the generated smart contract address
|
[
"Generate",
"a",
"smart",
"contract",
"address",
".",
"This",
"enables",
"you",
"to",
"identify",
"what",
"address",
"a",
"smart",
"contract",
"will",
"be",
"deployed",
"to",
"on",
"the",
"network",
"."
] |
f99ceb19cdd65895c18e0a565034767ca18ea9fc
|
https://github.com/web3j/web3j/blob/f99ceb19cdd65895c18e0a565034767ca18ea9fc/crypto/src/main/java/org/web3j/crypto/ContractUtils.java#L27-L37
|
16,826
|
web3j/web3j
|
crypto/src/main/java/org/web3j/crypto/MnemonicUtils.java
|
MnemonicUtils.generateMnemonic
|
public static String generateMnemonic(byte[] initialEntropy) {
validateEntropy(initialEntropy);
final List<String> words = getWords();
int ent = initialEntropy.length * 8;
int checksumLength = ent / 32;
byte checksum = calculateChecksum(initialEntropy);
boolean[] bits = convertToBits(initialEntropy, checksum);
int iterations = (ent + checksumLength) / 11;
StringBuilder mnemonicBuilder = new StringBuilder();
for (int i = 0; i < iterations; i++) {
int index = toInt(nextElevenBits(bits, i));
mnemonicBuilder.append(words.get(index));
boolean notLastIteration = i < iterations - 1;
if (notLastIteration) {
mnemonicBuilder.append(" ");
}
}
return mnemonicBuilder.toString();
}
|
java
|
public static String generateMnemonic(byte[] initialEntropy) {
validateEntropy(initialEntropy);
final List<String> words = getWords();
int ent = initialEntropy.length * 8;
int checksumLength = ent / 32;
byte checksum = calculateChecksum(initialEntropy);
boolean[] bits = convertToBits(initialEntropy, checksum);
int iterations = (ent + checksumLength) / 11;
StringBuilder mnemonicBuilder = new StringBuilder();
for (int i = 0; i < iterations; i++) {
int index = toInt(nextElevenBits(bits, i));
mnemonicBuilder.append(words.get(index));
boolean notLastIteration = i < iterations - 1;
if (notLastIteration) {
mnemonicBuilder.append(" ");
}
}
return mnemonicBuilder.toString();
}
|
[
"public",
"static",
"String",
"generateMnemonic",
"(",
"byte",
"[",
"]",
"initialEntropy",
")",
"{",
"validateEntropy",
"(",
"initialEntropy",
")",
";",
"final",
"List",
"<",
"String",
">",
"words",
"=",
"getWords",
"(",
")",
";",
"int",
"ent",
"=",
"initialEntropy",
".",
"length",
"*",
"8",
";",
"int",
"checksumLength",
"=",
"ent",
"/",
"32",
";",
"byte",
"checksum",
"=",
"calculateChecksum",
"(",
"initialEntropy",
")",
";",
"boolean",
"[",
"]",
"bits",
"=",
"convertToBits",
"(",
"initialEntropy",
",",
"checksum",
")",
";",
"int",
"iterations",
"=",
"(",
"ent",
"+",
"checksumLength",
")",
"/",
"11",
";",
"StringBuilder",
"mnemonicBuilder",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"iterations",
";",
"i",
"++",
")",
"{",
"int",
"index",
"=",
"toInt",
"(",
"nextElevenBits",
"(",
"bits",
",",
"i",
")",
")",
";",
"mnemonicBuilder",
".",
"append",
"(",
"words",
".",
"get",
"(",
"index",
")",
")",
";",
"boolean",
"notLastIteration",
"=",
"i",
"<",
"iterations",
"-",
"1",
";",
"if",
"(",
"notLastIteration",
")",
"{",
"mnemonicBuilder",
".",
"append",
"(",
"\" \"",
")",
";",
"}",
"}",
"return",
"mnemonicBuilder",
".",
"toString",
"(",
")",
";",
"}"
] |
The mnemonic must encode entropy in a multiple of 32 bits. With more entropy security is
improved but the sentence length increases. We refer to the initial entropy length as ENT.
The allowed size of ENT is 128-256 bits.
<h3>Mnemonic generation algorithm</h3>
Given a randomly generated initial entropy of size ENT, first a checksum is generated by
taking the first {@code ENT / 32} bits of its SHA256 hash. This checksum is appended to
the end of the initial entropy. Next, these concatenated bits are split into groups of
11 bits, each encoding a number from 0-2047, serving as an index into a wordlist. Finally,
we convert these numbers into words and use the joined words as a mnemonic sentence.
@param initialEntropy The initial entropy to generate mnemonic from
@return The generated mnemonic
@throws IllegalArgumentException If the given entropy is invalid
@throws IllegalStateException If the word list has not been loaded
|
[
"The",
"mnemonic",
"must",
"encode",
"entropy",
"in",
"a",
"multiple",
"of",
"32",
"bits",
".",
"With",
"more",
"entropy",
"security",
"is",
"improved",
"but",
"the",
"sentence",
"length",
"increases",
".",
"We",
"refer",
"to",
"the",
"initial",
"entropy",
"length",
"as",
"ENT",
".",
"The",
"allowed",
"size",
"of",
"ENT",
"is",
"128",
"-",
"256",
"bits",
"."
] |
f99ceb19cdd65895c18e0a565034767ca18ea9fc
|
https://github.com/web3j/web3j/blob/f99ceb19cdd65895c18e0a565034767ca18ea9fc/crypto/src/main/java/org/web3j/crypto/MnemonicUtils.java#L51-L74
|
16,827
|
web3j/web3j
|
crypto/src/main/java/org/web3j/crypto/MnemonicUtils.java
|
MnemonicUtils.generateEntropy
|
public static byte[] generateEntropy(String mnemonic) {
final BitSet bits = new BitSet();
final int size = mnemonicToBits(mnemonic, bits);
if (size == 0) {
throw new IllegalArgumentException("Empty mnemonic");
}
final int ent = 32 * size / 33;
if (ent % 8 != 0) {
throw new IllegalArgumentException("Wrong mnemonic size");
}
final byte[] entropy = new byte[ent / 8];
for (int i = 0; i < entropy.length; i++) {
entropy[i] = readByte(bits, i);
}
validateEntropy(entropy);
final byte expectedChecksum = calculateChecksum(entropy);
final byte actualChecksum = readByte(bits, entropy.length);
if (expectedChecksum != actualChecksum) {
throw new IllegalArgumentException("Wrong checksum");
}
return entropy;
}
|
java
|
public static byte[] generateEntropy(String mnemonic) {
final BitSet bits = new BitSet();
final int size = mnemonicToBits(mnemonic, bits);
if (size == 0) {
throw new IllegalArgumentException("Empty mnemonic");
}
final int ent = 32 * size / 33;
if (ent % 8 != 0) {
throw new IllegalArgumentException("Wrong mnemonic size");
}
final byte[] entropy = new byte[ent / 8];
for (int i = 0; i < entropy.length; i++) {
entropy[i] = readByte(bits, i);
}
validateEntropy(entropy);
final byte expectedChecksum = calculateChecksum(entropy);
final byte actualChecksum = readByte(bits, entropy.length);
if (expectedChecksum != actualChecksum) {
throw new IllegalArgumentException("Wrong checksum");
}
return entropy;
}
|
[
"public",
"static",
"byte",
"[",
"]",
"generateEntropy",
"(",
"String",
"mnemonic",
")",
"{",
"final",
"BitSet",
"bits",
"=",
"new",
"BitSet",
"(",
")",
";",
"final",
"int",
"size",
"=",
"mnemonicToBits",
"(",
"mnemonic",
",",
"bits",
")",
";",
"if",
"(",
"size",
"==",
"0",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Empty mnemonic\"",
")",
";",
"}",
"final",
"int",
"ent",
"=",
"32",
"*",
"size",
"/",
"33",
";",
"if",
"(",
"ent",
"%",
"8",
"!=",
"0",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Wrong mnemonic size\"",
")",
";",
"}",
"final",
"byte",
"[",
"]",
"entropy",
"=",
"new",
"byte",
"[",
"ent",
"/",
"8",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"entropy",
".",
"length",
";",
"i",
"++",
")",
"{",
"entropy",
"[",
"i",
"]",
"=",
"readByte",
"(",
"bits",
",",
"i",
")",
";",
"}",
"validateEntropy",
"(",
"entropy",
")",
";",
"final",
"byte",
"expectedChecksum",
"=",
"calculateChecksum",
"(",
"entropy",
")",
";",
"final",
"byte",
"actualChecksum",
"=",
"readByte",
"(",
"bits",
",",
"entropy",
".",
"length",
")",
";",
"if",
"(",
"expectedChecksum",
"!=",
"actualChecksum",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Wrong checksum\"",
")",
";",
"}",
"return",
"entropy",
";",
"}"
] |
Create entropy from the mnemonic.
@param mnemonic The input mnemonic which should be 128-160 bits in length containing
only valid words
@return Byte array representation of the entropy
|
[
"Create",
"entropy",
"from",
"the",
"mnemonic",
"."
] |
f99ceb19cdd65895c18e0a565034767ca18ea9fc
|
https://github.com/web3j/web3j/blob/f99ceb19cdd65895c18e0a565034767ca18ea9fc/crypto/src/main/java/org/web3j/crypto/MnemonicUtils.java#L82-L106
|
16,828
|
web3j/web3j
|
core/src/main/java/org/web3j/utils/Async.java
|
Async.defaultExecutorService
|
public static ScheduledExecutorService defaultExecutorService() {
ScheduledExecutorService scheduledExecutorService =
Executors.newScheduledThreadPool(getCpuCount());
Runtime.getRuntime().addShutdownHook(new Thread(() -> shutdown(scheduledExecutorService)));
return scheduledExecutorService;
}
|
java
|
public static ScheduledExecutorService defaultExecutorService() {
ScheduledExecutorService scheduledExecutorService =
Executors.newScheduledThreadPool(getCpuCount());
Runtime.getRuntime().addShutdownHook(new Thread(() -> shutdown(scheduledExecutorService)));
return scheduledExecutorService;
}
|
[
"public",
"static",
"ScheduledExecutorService",
"defaultExecutorService",
"(",
")",
"{",
"ScheduledExecutorService",
"scheduledExecutorService",
"=",
"Executors",
".",
"newScheduledThreadPool",
"(",
"getCpuCount",
"(",
")",
")",
";",
"Runtime",
".",
"getRuntime",
"(",
")",
".",
"addShutdownHook",
"(",
"new",
"Thread",
"(",
"(",
")",
"->",
"shutdown",
"(",
"scheduledExecutorService",
")",
")",
")",
";",
"return",
"scheduledExecutorService",
";",
"}"
] |
Provide a new ScheduledExecutorService instance.
<p>A shutdown hook is created to terminate the thread pool on application termination.
@return new ScheduledExecutorService
|
[
"Provide",
"a",
"new",
"ScheduledExecutorService",
"instance",
"."
] |
f99ceb19cdd65895c18e0a565034767ca18ea9fc
|
https://github.com/web3j/web3j/blob/f99ceb19cdd65895c18e0a565034767ca18ea9fc/core/src/main/java/org/web3j/utils/Async.java#L46-L53
|
16,829
|
web3j/web3j
|
abi/src/main/java/org/web3j/abi/TypeDecoder.java
|
TypeDecoder.decodeStaticArray
|
@SuppressWarnings("unchecked")
static <T extends Type> T decodeStaticArray(
String input, int offset, TypeReference<T> typeReference, int length) {
BiFunction<List<T>, String, T> function = (elements, typeName) -> {
if (elements.isEmpty()) {
throw new UnsupportedOperationException("Zero length fixed array is invalid type");
} else {
return instantiateStaticArray(typeReference, elements, length);
}
};
return decodeArrayElements(input, offset, typeReference, length, function);
}
|
java
|
@SuppressWarnings("unchecked")
static <T extends Type> T decodeStaticArray(
String input, int offset, TypeReference<T> typeReference, int length) {
BiFunction<List<T>, String, T> function = (elements, typeName) -> {
if (elements.isEmpty()) {
throw new UnsupportedOperationException("Zero length fixed array is invalid type");
} else {
return instantiateStaticArray(typeReference, elements, length);
}
};
return decodeArrayElements(input, offset, typeReference, length, function);
}
|
[
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"static",
"<",
"T",
"extends",
"Type",
">",
"T",
"decodeStaticArray",
"(",
"String",
"input",
",",
"int",
"offset",
",",
"TypeReference",
"<",
"T",
">",
"typeReference",
",",
"int",
"length",
")",
"{",
"BiFunction",
"<",
"List",
"<",
"T",
">",
",",
"String",
",",
"T",
">",
"function",
"=",
"(",
"elements",
",",
"typeName",
")",
"->",
"{",
"if",
"(",
"elements",
".",
"isEmpty",
"(",
")",
")",
"{",
"throw",
"new",
"UnsupportedOperationException",
"(",
"\"Zero length fixed array is invalid type\"",
")",
";",
"}",
"else",
"{",
"return",
"instantiateStaticArray",
"(",
"typeReference",
",",
"elements",
",",
"length",
")",
";",
"}",
"}",
";",
"return",
"decodeArrayElements",
"(",
"input",
",",
"offset",
",",
"typeReference",
",",
"length",
",",
"function",
")",
";",
"}"
] |
Static array length cannot be passed as a type.
|
[
"Static",
"array",
"length",
"cannot",
"be",
"passed",
"as",
"a",
"type",
"."
] |
f99ceb19cdd65895c18e0a565034767ca18ea9fc
|
https://github.com/web3j/web3j/blob/f99ceb19cdd65895c18e0a565034767ca18ea9fc/abi/src/main/java/org/web3j/abi/TypeDecoder.java#L202-L215
|
16,830
|
web3j/web3j
|
core/src/main/java/org/web3j/tx/Contract.java
|
Contract.isValid
|
public boolean isValid() throws IOException {
if (contractBinary.equals(BIN_NOT_PROVIDED)) {
throw new UnsupportedOperationException(
"Contract binary not present in contract wrapper, "
+ "please generate your wrapper using -abiFile=<file>");
}
if (contractAddress.equals("")) {
throw new UnsupportedOperationException(
"Contract binary not present, you will need to regenerate your smart "
+ "contract wrapper with web3j v2.2.0+");
}
EthGetCode ethGetCode = web3j
.ethGetCode(contractAddress, DefaultBlockParameterName.LATEST)
.send();
if (ethGetCode.hasError()) {
return false;
}
String code = Numeric.cleanHexPrefix(ethGetCode.getCode());
int metadataIndex = code.indexOf("a165627a7a72305820");
if (metadataIndex != -1) {
code = code.substring(0, metadataIndex);
}
// There may be multiple contracts in the Solidity bytecode, hence we only check for a
// match with a subset
return !code.isEmpty() && contractBinary.contains(code);
}
|
java
|
public boolean isValid() throws IOException {
if (contractBinary.equals(BIN_NOT_PROVIDED)) {
throw new UnsupportedOperationException(
"Contract binary not present in contract wrapper, "
+ "please generate your wrapper using -abiFile=<file>");
}
if (contractAddress.equals("")) {
throw new UnsupportedOperationException(
"Contract binary not present, you will need to regenerate your smart "
+ "contract wrapper with web3j v2.2.0+");
}
EthGetCode ethGetCode = web3j
.ethGetCode(contractAddress, DefaultBlockParameterName.LATEST)
.send();
if (ethGetCode.hasError()) {
return false;
}
String code = Numeric.cleanHexPrefix(ethGetCode.getCode());
int metadataIndex = code.indexOf("a165627a7a72305820");
if (metadataIndex != -1) {
code = code.substring(0, metadataIndex);
}
// There may be multiple contracts in the Solidity bytecode, hence we only check for a
// match with a subset
return !code.isEmpty() && contractBinary.contains(code);
}
|
[
"public",
"boolean",
"isValid",
"(",
")",
"throws",
"IOException",
"{",
"if",
"(",
"contractBinary",
".",
"equals",
"(",
"BIN_NOT_PROVIDED",
")",
")",
"{",
"throw",
"new",
"UnsupportedOperationException",
"(",
"\"Contract binary not present in contract wrapper, \"",
"+",
"\"please generate your wrapper using -abiFile=<file>\"",
")",
";",
"}",
"if",
"(",
"contractAddress",
".",
"equals",
"(",
"\"\"",
")",
")",
"{",
"throw",
"new",
"UnsupportedOperationException",
"(",
"\"Contract binary not present, you will need to regenerate your smart \"",
"+",
"\"contract wrapper with web3j v2.2.0+\"",
")",
";",
"}",
"EthGetCode",
"ethGetCode",
"=",
"web3j",
".",
"ethGetCode",
"(",
"contractAddress",
",",
"DefaultBlockParameterName",
".",
"LATEST",
")",
".",
"send",
"(",
")",
";",
"if",
"(",
"ethGetCode",
".",
"hasError",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"String",
"code",
"=",
"Numeric",
".",
"cleanHexPrefix",
"(",
"ethGetCode",
".",
"getCode",
"(",
")",
")",
";",
"int",
"metadataIndex",
"=",
"code",
".",
"indexOf",
"(",
"\"a165627a7a72305820\"",
")",
";",
"if",
"(",
"metadataIndex",
"!=",
"-",
"1",
")",
"{",
"code",
"=",
"code",
".",
"substring",
"(",
"0",
",",
"metadataIndex",
")",
";",
"}",
"// There may be multiple contracts in the Solidity bytecode, hence we only check for a",
"// match with a subset",
"return",
"!",
"code",
".",
"isEmpty",
"(",
")",
"&&",
"contractBinary",
".",
"contains",
"(",
"code",
")",
";",
"}"
] |
Check that the contract deployed at the address associated with this smart contract wrapper
is in fact the contract you believe it is.
<p>This method uses the
<a href="https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_getcode">eth_getCode</a> method
to get the contract byte code and validates it against the byte code stored in this smart
contract wrapper.
@return true if the contract is valid
@throws IOException if unable to connect to web3j node
|
[
"Check",
"that",
"the",
"contract",
"deployed",
"at",
"the",
"address",
"associated",
"with",
"this",
"smart",
"contract",
"wrapper",
"is",
"in",
"fact",
"the",
"contract",
"you",
"believe",
"it",
"is",
"."
] |
f99ceb19cdd65895c18e0a565034767ca18ea9fc
|
https://github.com/web3j/web3j/blob/f99ceb19cdd65895c18e0a565034767ca18ea9fc/core/src/main/java/org/web3j/tx/Contract.java#L164-L192
|
16,831
|
web3j/web3j
|
core/src/main/java/org/web3j/tx/Contract.java
|
Contract.executeCall
|
private List<Type> executeCall(
Function function) throws IOException {
String encodedFunction = FunctionEncoder.encode(function);
org.web3j.protocol.core.methods.response.EthCall ethCall = web3j.ethCall(
Transaction.createEthCallTransaction(
transactionManager.getFromAddress(), contractAddress, encodedFunction),
defaultBlockParameter)
.send();
String value = ethCall.getValue();
return FunctionReturnDecoder.decode(value, function.getOutputParameters());
}
|
java
|
private List<Type> executeCall(
Function function) throws IOException {
String encodedFunction = FunctionEncoder.encode(function);
org.web3j.protocol.core.methods.response.EthCall ethCall = web3j.ethCall(
Transaction.createEthCallTransaction(
transactionManager.getFromAddress(), contractAddress, encodedFunction),
defaultBlockParameter)
.send();
String value = ethCall.getValue();
return FunctionReturnDecoder.decode(value, function.getOutputParameters());
}
|
[
"private",
"List",
"<",
"Type",
">",
"executeCall",
"(",
"Function",
"function",
")",
"throws",
"IOException",
"{",
"String",
"encodedFunction",
"=",
"FunctionEncoder",
".",
"encode",
"(",
"function",
")",
";",
"org",
".",
"web3j",
".",
"protocol",
".",
"core",
".",
"methods",
".",
"response",
".",
"EthCall",
"ethCall",
"=",
"web3j",
".",
"ethCall",
"(",
"Transaction",
".",
"createEthCallTransaction",
"(",
"transactionManager",
".",
"getFromAddress",
"(",
")",
",",
"contractAddress",
",",
"encodedFunction",
")",
",",
"defaultBlockParameter",
")",
".",
"send",
"(",
")",
";",
"String",
"value",
"=",
"ethCall",
".",
"getValue",
"(",
")",
";",
"return",
"FunctionReturnDecoder",
".",
"decode",
"(",
"value",
",",
"function",
".",
"getOutputParameters",
"(",
")",
")",
";",
"}"
] |
Execute constant function call - i.e. a call that does not change state of the contract
@param function to call
@return {@link List} of values returned by function call
|
[
"Execute",
"constant",
"function",
"call",
"-",
"i",
".",
"e",
".",
"a",
"call",
"that",
"does",
"not",
"change",
"state",
"of",
"the",
"contract"
] |
f99ceb19cdd65895c18e0a565034767ca18ea9fc
|
https://github.com/web3j/web3j/blob/f99ceb19cdd65895c18e0a565034767ca18ea9fc/core/src/main/java/org/web3j/tx/Contract.java#L221-L232
|
16,832
|
web3j/web3j
|
core/src/main/java/org/web3j/tx/Contract.java
|
Contract.executeTransaction
|
TransactionReceipt executeTransaction(
String data, BigInteger weiValue, String funcName)
throws TransactionException, IOException {
TransactionReceipt receipt = send(contractAddress, data, weiValue,
gasProvider.getGasPrice(funcName),
gasProvider.getGasLimit(funcName));
if (!receipt.isStatusOK()) {
throw new TransactionException(
String.format(
"Transaction has failed with status: %s. "
+ "Gas used: %d. (not-enough gas?)",
receipt.getStatus(),
receipt.getGasUsed()));
}
return receipt;
}
|
java
|
TransactionReceipt executeTransaction(
String data, BigInteger weiValue, String funcName)
throws TransactionException, IOException {
TransactionReceipt receipt = send(contractAddress, data, weiValue,
gasProvider.getGasPrice(funcName),
gasProvider.getGasLimit(funcName));
if (!receipt.isStatusOK()) {
throw new TransactionException(
String.format(
"Transaction has failed with status: %s. "
+ "Gas used: %d. (not-enough gas?)",
receipt.getStatus(),
receipt.getGasUsed()));
}
return receipt;
}
|
[
"TransactionReceipt",
"executeTransaction",
"(",
"String",
"data",
",",
"BigInteger",
"weiValue",
",",
"String",
"funcName",
")",
"throws",
"TransactionException",
",",
"IOException",
"{",
"TransactionReceipt",
"receipt",
"=",
"send",
"(",
"contractAddress",
",",
"data",
",",
"weiValue",
",",
"gasProvider",
".",
"getGasPrice",
"(",
"funcName",
")",
",",
"gasProvider",
".",
"getGasLimit",
"(",
"funcName",
")",
")",
";",
"if",
"(",
"!",
"receipt",
".",
"isStatusOK",
"(",
")",
")",
"{",
"throw",
"new",
"TransactionException",
"(",
"String",
".",
"format",
"(",
"\"Transaction has failed with status: %s. \"",
"+",
"\"Gas used: %d. (not-enough gas?)\"",
",",
"receipt",
".",
"getStatus",
"(",
")",
",",
"receipt",
".",
"getGasUsed",
"(",
")",
")",
")",
";",
"}",
"return",
"receipt",
";",
"}"
] |
Given the duration required to execute a transaction.
@param data to send in transaction
@param weiValue in Wei to send in transaction
@return {@link Optional} containing our transaction receipt
@throws IOException if the call to the node fails
@throws TransactionException if the transaction was not mined while waiting
|
[
"Given",
"the",
"duration",
"required",
"to",
"execute",
"a",
"transaction",
"."
] |
f99ceb19cdd65895c18e0a565034767ca18ea9fc
|
https://github.com/web3j/web3j/blob/f99ceb19cdd65895c18e0a565034767ca18ea9fc/core/src/main/java/org/web3j/tx/Contract.java#L291-L309
|
16,833
|
web3j/web3j
|
abi/src/main/java/org/web3j/abi/FunctionReturnDecoder.java
|
FunctionReturnDecoder.decode
|
public static List<Type> decode(
String rawInput, List<TypeReference<Type>> outputParameters) {
String input = Numeric.cleanHexPrefix(rawInput);
if (Strings.isEmpty(input)) {
return Collections.emptyList();
} else {
return build(input, outputParameters);
}
}
|
java
|
public static List<Type> decode(
String rawInput, List<TypeReference<Type>> outputParameters) {
String input = Numeric.cleanHexPrefix(rawInput);
if (Strings.isEmpty(input)) {
return Collections.emptyList();
} else {
return build(input, outputParameters);
}
}
|
[
"public",
"static",
"List",
"<",
"Type",
">",
"decode",
"(",
"String",
"rawInput",
",",
"List",
"<",
"TypeReference",
"<",
"Type",
">",
">",
"outputParameters",
")",
"{",
"String",
"input",
"=",
"Numeric",
".",
"cleanHexPrefix",
"(",
"rawInput",
")",
";",
"if",
"(",
"Strings",
".",
"isEmpty",
"(",
"input",
")",
")",
"{",
"return",
"Collections",
".",
"emptyList",
"(",
")",
";",
"}",
"else",
"{",
"return",
"build",
"(",
"input",
",",
"outputParameters",
")",
";",
"}",
"}"
] |
Decode ABI encoded return values from smart contract function call.
@param rawInput ABI encoded input
@param outputParameters list of return types as {@link TypeReference}
@return {@link List} of values returned by function, {@link Collections#emptyList()} if
invalid response
|
[
"Decode",
"ABI",
"encoded",
"return",
"values",
"from",
"smart",
"contract",
"function",
"call",
"."
] |
f99ceb19cdd65895c18e0a565034767ca18ea9fc
|
https://github.com/web3j/web3j/blob/f99ceb19cdd65895c18e0a565034767ca18ea9fc/abi/src/main/java/org/web3j/abi/FunctionReturnDecoder.java#L36-L45
|
16,834
|
web3j/web3j
|
core/src/main/java/org/web3j/ens/EnsResolver.java
|
EnsResolver.obtainPublicResolver
|
public PublicResolver obtainPublicResolver(String ensName) {
if (isValidEnsName(ensName)) {
try {
if (!isSynced()) {
throw new EnsResolutionException("Node is not currently synced");
} else {
return lookupResolver(ensName);
}
} catch (Exception e) {
throw new EnsResolutionException("Unable to determine sync status of node", e);
}
} else {
throw new EnsResolutionException("EnsName is invalid: " + ensName);
}
}
|
java
|
public PublicResolver obtainPublicResolver(String ensName) {
if (isValidEnsName(ensName)) {
try {
if (!isSynced()) {
throw new EnsResolutionException("Node is not currently synced");
} else {
return lookupResolver(ensName);
}
} catch (Exception e) {
throw new EnsResolutionException("Unable to determine sync status of node", e);
}
} else {
throw new EnsResolutionException("EnsName is invalid: " + ensName);
}
}
|
[
"public",
"PublicResolver",
"obtainPublicResolver",
"(",
"String",
"ensName",
")",
"{",
"if",
"(",
"isValidEnsName",
"(",
"ensName",
")",
")",
"{",
"try",
"{",
"if",
"(",
"!",
"isSynced",
"(",
")",
")",
"{",
"throw",
"new",
"EnsResolutionException",
"(",
"\"Node is not currently synced\"",
")",
";",
"}",
"else",
"{",
"return",
"lookupResolver",
"(",
"ensName",
")",
";",
"}",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"throw",
"new",
"EnsResolutionException",
"(",
"\"Unable to determine sync status of node\"",
",",
"e",
")",
";",
"}",
"}",
"else",
"{",
"throw",
"new",
"EnsResolutionException",
"(",
"\"EnsName is invalid: \"",
"+",
"ensName",
")",
";",
"}",
"}"
] |
Provides an access to a valid public resolver in order to access other API methods.
@param ensName our user input ENS name
@return PublicResolver
|
[
"Provides",
"an",
"access",
"to",
"a",
"valid",
"public",
"resolver",
"in",
"order",
"to",
"access",
"other",
"API",
"methods",
"."
] |
f99ceb19cdd65895c18e0a565034767ca18ea9fc
|
https://github.com/web3j/web3j/blob/f99ceb19cdd65895c18e0a565034767ca18ea9fc/core/src/main/java/org/web3j/ens/EnsResolver.java#L52-L67
|
16,835
|
web3j/web3j
|
core/src/main/java/org/web3j/tx/Transfer.java
|
Transfer.sendFunds
|
public RemoteCall<TransactionReceipt> sendFunds(
String toAddress, BigDecimal value, Convert.Unit unit) {
return new RemoteCall<>(() -> send(toAddress, value, unit));
}
|
java
|
public RemoteCall<TransactionReceipt> sendFunds(
String toAddress, BigDecimal value, Convert.Unit unit) {
return new RemoteCall<>(() -> send(toAddress, value, unit));
}
|
[
"public",
"RemoteCall",
"<",
"TransactionReceipt",
">",
"sendFunds",
"(",
"String",
"toAddress",
",",
"BigDecimal",
"value",
",",
"Convert",
".",
"Unit",
"unit",
")",
"{",
"return",
"new",
"RemoteCall",
"<>",
"(",
"(",
")",
"->",
"send",
"(",
"toAddress",
",",
"value",
",",
"unit",
")",
")",
";",
"}"
] |
Execute the provided function as a transaction asynchronously. This is intended for one-off
fund transfers. For multiple, create an instance.
@param toAddress destination address
@param value amount to send
@param unit of specified send
@return {@link RemoteCall} containing executing transaction
|
[
"Execute",
"the",
"provided",
"function",
"as",
"a",
"transaction",
"asynchronously",
".",
"This",
"is",
"intended",
"for",
"one",
"-",
"off",
"fund",
"transfers",
".",
"For",
"multiple",
"create",
"an",
"instance",
"."
] |
f99ceb19cdd65895c18e0a565034767ca18ea9fc
|
https://github.com/web3j/web3j/blob/f99ceb19cdd65895c18e0a565034767ca18ea9fc/core/src/main/java/org/web3j/tx/Transfer.java#L89-L92
|
16,836
|
web3j/web3j
|
crypto/src/main/java/org/web3j/crypto/Sign.java
|
Sign.signedMessageToKey
|
public static BigInteger signedMessageToKey(
byte[] message, SignatureData signatureData) throws SignatureException {
return signedMessageHashToKey(Hash.sha3(message), signatureData);
}
|
java
|
public static BigInteger signedMessageToKey(
byte[] message, SignatureData signatureData) throws SignatureException {
return signedMessageHashToKey(Hash.sha3(message), signatureData);
}
|
[
"public",
"static",
"BigInteger",
"signedMessageToKey",
"(",
"byte",
"[",
"]",
"message",
",",
"SignatureData",
"signatureData",
")",
"throws",
"SignatureException",
"{",
"return",
"signedMessageHashToKey",
"(",
"Hash",
".",
"sha3",
"(",
"message",
")",
",",
"signatureData",
")",
";",
"}"
] |
Given an arbitrary piece of text and an Ethereum message signature encoded in bytes,
returns the public key that was used to sign it. This can then be compared to the expected
public key to determine if the signature was correct.
@param message RLP encoded message.
@param signatureData The message signature components
@return the public key used to sign the message
@throws SignatureException If the public key could not be recovered or if there was a
signature format error.
|
[
"Given",
"an",
"arbitrary",
"piece",
"of",
"text",
"and",
"an",
"Ethereum",
"message",
"signature",
"encoded",
"in",
"bytes",
"returns",
"the",
"public",
"key",
"that",
"was",
"used",
"to",
"sign",
"it",
".",
"This",
"can",
"then",
"be",
"compared",
"to",
"the",
"expected",
"public",
"key",
"to",
"determine",
"if",
"the",
"signature",
"was",
"correct",
"."
] |
f99ceb19cdd65895c18e0a565034767ca18ea9fc
|
https://github.com/web3j/web3j/blob/f99ceb19cdd65895c18e0a565034767ca18ea9fc/crypto/src/main/java/org/web3j/crypto/Sign.java#L191-L194
|
16,837
|
web3j/web3j
|
crypto/src/main/java/org/web3j/crypto/Sign.java
|
Sign.signedPrefixedMessageToKey
|
public static BigInteger signedPrefixedMessageToKey(
byte[] message, SignatureData signatureData) throws SignatureException {
return signedMessageHashToKey(getEthereumMessageHash(message), signatureData);
}
|
java
|
public static BigInteger signedPrefixedMessageToKey(
byte[] message, SignatureData signatureData) throws SignatureException {
return signedMessageHashToKey(getEthereumMessageHash(message), signatureData);
}
|
[
"public",
"static",
"BigInteger",
"signedPrefixedMessageToKey",
"(",
"byte",
"[",
"]",
"message",
",",
"SignatureData",
"signatureData",
")",
"throws",
"SignatureException",
"{",
"return",
"signedMessageHashToKey",
"(",
"getEthereumMessageHash",
"(",
"message",
")",
",",
"signatureData",
")",
";",
"}"
] |
Given an arbitrary message and an Ethereum message signature encoded in bytes,
returns the public key that was used to sign it. This can then be compared to the
expected public key to determine if the signature was correct.
@param message The message.
@param signatureData The message signature components
@return the public key used to sign the message
@throws SignatureException If the public key could not be recovered or if there was a
signature format error.
|
[
"Given",
"an",
"arbitrary",
"message",
"and",
"an",
"Ethereum",
"message",
"signature",
"encoded",
"in",
"bytes",
"returns",
"the",
"public",
"key",
"that",
"was",
"used",
"to",
"sign",
"it",
".",
"This",
"can",
"then",
"be",
"compared",
"to",
"the",
"expected",
"public",
"key",
"to",
"determine",
"if",
"the",
"signature",
"was",
"correct",
"."
] |
f99ceb19cdd65895c18e0a565034767ca18ea9fc
|
https://github.com/web3j/web3j/blob/f99ceb19cdd65895c18e0a565034767ca18ea9fc/crypto/src/main/java/org/web3j/crypto/Sign.java#L207-L210
|
16,838
|
web3j/web3j
|
crypto/src/main/java/org/web3j/crypto/Sign.java
|
Sign.publicKeyFromPrivate
|
public static BigInteger publicKeyFromPrivate(BigInteger privKey) {
ECPoint point = publicPointFromPrivate(privKey);
byte[] encoded = point.getEncoded(false);
return new BigInteger(1, Arrays.copyOfRange(encoded, 1, encoded.length)); // remove prefix
}
|
java
|
public static BigInteger publicKeyFromPrivate(BigInteger privKey) {
ECPoint point = publicPointFromPrivate(privKey);
byte[] encoded = point.getEncoded(false);
return new BigInteger(1, Arrays.copyOfRange(encoded, 1, encoded.length)); // remove prefix
}
|
[
"public",
"static",
"BigInteger",
"publicKeyFromPrivate",
"(",
"BigInteger",
"privKey",
")",
"{",
"ECPoint",
"point",
"=",
"publicPointFromPrivate",
"(",
"privKey",
")",
";",
"byte",
"[",
"]",
"encoded",
"=",
"point",
".",
"getEncoded",
"(",
"false",
")",
";",
"return",
"new",
"BigInteger",
"(",
"1",
",",
"Arrays",
".",
"copyOfRange",
"(",
"encoded",
",",
"1",
",",
"encoded",
".",
"length",
")",
")",
";",
"// remove prefix",
"}"
] |
Returns public key from the given private key.
@param privKey the private key to derive the public key from
@return BigInteger encoded public key
|
[
"Returns",
"public",
"key",
"from",
"the",
"given",
"private",
"key",
"."
] |
f99ceb19cdd65895c18e0a565034767ca18ea9fc
|
https://github.com/web3j/web3j/blob/f99ceb19cdd65895c18e0a565034767ca18ea9fc/crypto/src/main/java/org/web3j/crypto/Sign.java#L245-L250
|
16,839
|
web3j/web3j
|
core/src/main/java/org/web3j/protocol/websocket/WebSocketService.java
|
WebSocketService.connect
|
public void connect() throws ConnectException {
try {
connectToWebSocket();
setWebSocketListener();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
log.warn("Interrupted while connecting via WebSocket protocol");
}
}
|
java
|
public void connect() throws ConnectException {
try {
connectToWebSocket();
setWebSocketListener();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
log.warn("Interrupted while connecting via WebSocket protocol");
}
}
|
[
"public",
"void",
"connect",
"(",
")",
"throws",
"ConnectException",
"{",
"try",
"{",
"connectToWebSocket",
"(",
")",
";",
"setWebSocketListener",
"(",
")",
";",
"}",
"catch",
"(",
"InterruptedException",
"e",
")",
"{",
"Thread",
".",
"currentThread",
"(",
")",
".",
"interrupt",
"(",
")",
";",
"log",
".",
"warn",
"(",
"\"Interrupted while connecting via WebSocket protocol\"",
")",
";",
"}",
"}"
] |
Connect to a WebSocket server.
@throws ConnectException thrown if failed to connect to the server via WebSocket protocol
|
[
"Connect",
"to",
"a",
"WebSocket",
"server",
"."
] |
f99ceb19cdd65895c18e0a565034767ca18ea9fc
|
https://github.com/web3j/web3j/blob/f99ceb19cdd65895c18e0a565034767ca18ea9fc/core/src/main/java/org/web3j/protocol/websocket/WebSocketService.java#L92-L100
|
16,840
|
web3j/web3j
|
utils/src/main/java/org/web3j/crypto/Hash.java
|
Hash.sha3String
|
public static String sha3String(String utf8String) {
return Numeric.toHexString(sha3(utf8String.getBytes(StandardCharsets.UTF_8)));
}
|
java
|
public static String sha3String(String utf8String) {
return Numeric.toHexString(sha3(utf8String.getBytes(StandardCharsets.UTF_8)));
}
|
[
"public",
"static",
"String",
"sha3String",
"(",
"String",
"utf8String",
")",
"{",
"return",
"Numeric",
".",
"toHexString",
"(",
"sha3",
"(",
"utf8String",
".",
"getBytes",
"(",
"StandardCharsets",
".",
"UTF_8",
")",
")",
")",
";",
"}"
] |
Keccak-256 hash function that operates on a UTF-8 encoded String.
@param utf8String UTF-8 encoded string
@return hash value as hex encoded string
|
[
"Keccak",
"-",
"256",
"hash",
"function",
"that",
"operates",
"on",
"a",
"UTF",
"-",
"8",
"encoded",
"String",
"."
] |
f99ceb19cdd65895c18e0a565034767ca18ea9fc
|
https://github.com/web3j/web3j/blob/f99ceb19cdd65895c18e0a565034767ca18ea9fc/utils/src/main/java/org/web3j/crypto/Hash.java#L63-L65
|
16,841
|
web3j/web3j
|
crypto/src/main/java/org/web3j/crypto/ECKeyPair.java
|
ECKeyPair.sign
|
public ECDSASignature sign(byte[] transactionHash) {
ECDSASigner signer = new ECDSASigner(new HMacDSAKCalculator(new SHA256Digest()));
ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(privateKey, Sign.CURVE);
signer.init(true, privKey);
BigInteger[] components = signer.generateSignature(transactionHash);
return new ECDSASignature(components[0], components[1]).toCanonicalised();
}
|
java
|
public ECDSASignature sign(byte[] transactionHash) {
ECDSASigner signer = new ECDSASigner(new HMacDSAKCalculator(new SHA256Digest()));
ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(privateKey, Sign.CURVE);
signer.init(true, privKey);
BigInteger[] components = signer.generateSignature(transactionHash);
return new ECDSASignature(components[0], components[1]).toCanonicalised();
}
|
[
"public",
"ECDSASignature",
"sign",
"(",
"byte",
"[",
"]",
"transactionHash",
")",
"{",
"ECDSASigner",
"signer",
"=",
"new",
"ECDSASigner",
"(",
"new",
"HMacDSAKCalculator",
"(",
"new",
"SHA256Digest",
"(",
")",
")",
")",
";",
"ECPrivateKeyParameters",
"privKey",
"=",
"new",
"ECPrivateKeyParameters",
"(",
"privateKey",
",",
"Sign",
".",
"CURVE",
")",
";",
"signer",
".",
"init",
"(",
"true",
",",
"privKey",
")",
";",
"BigInteger",
"[",
"]",
"components",
"=",
"signer",
".",
"generateSignature",
"(",
"transactionHash",
")",
";",
"return",
"new",
"ECDSASignature",
"(",
"components",
"[",
"0",
"]",
",",
"components",
"[",
"1",
"]",
")",
".",
"toCanonicalised",
"(",
")",
";",
"}"
] |
Sign a hash with the private key of this key pair.
@param transactionHash the hash to sign
@return An {@link ECDSASignature} of the hash
|
[
"Sign",
"a",
"hash",
"with",
"the",
"private",
"key",
"of",
"this",
"key",
"pair",
"."
] |
f99ceb19cdd65895c18e0a565034767ca18ea9fc
|
https://github.com/web3j/web3j/blob/f99ceb19cdd65895c18e0a565034767ca18ea9fc/crypto/src/main/java/org/web3j/crypto/ECKeyPair.java#L41-L49
|
16,842
|
lingochamp/okdownload
|
okdownload/src/main/java/com/liulishuo/okdownload/DownloadSerialQueue.java
|
DownloadSerialQueue.pause
|
public synchronized void pause() {
if (paused) {
Util.w(TAG, "require pause this queue(remain " + taskList.size() + "), but"
+ "it has already been paused");
return;
}
paused = true;
if (runningTask != null) {
runningTask.cancel();
taskList.add(0, runningTask);
runningTask = null;
}
}
|
java
|
public synchronized void pause() {
if (paused) {
Util.w(TAG, "require pause this queue(remain " + taskList.size() + "), but"
+ "it has already been paused");
return;
}
paused = true;
if (runningTask != null) {
runningTask.cancel();
taskList.add(0, runningTask);
runningTask = null;
}
}
|
[
"public",
"synchronized",
"void",
"pause",
"(",
")",
"{",
"if",
"(",
"paused",
")",
"{",
"Util",
".",
"w",
"(",
"TAG",
",",
"\"require pause this queue(remain \"",
"+",
"taskList",
".",
"size",
"(",
")",
"+",
"\"), but\"",
"+",
"\"it has already been paused\"",
")",
";",
"return",
";",
"}",
"paused",
"=",
"true",
";",
"if",
"(",
"runningTask",
"!=",
"null",
")",
"{",
"runningTask",
".",
"cancel",
"(",
")",
";",
"taskList",
".",
"add",
"(",
"0",
",",
"runningTask",
")",
";",
"runningTask",
"=",
"null",
";",
"}",
"}"
] |
Pause the queue.
@see #resume()
|
[
"Pause",
"the",
"queue",
"."
] |
403e2c814556ef7f2fade1f5bee83a02a5eaecb2
|
https://github.com/lingochamp/okdownload/blob/403e2c814556ef7f2fade1f5bee83a02a5eaecb2/okdownload/src/main/java/com/liulishuo/okdownload/DownloadSerialQueue.java#L97-L110
|
16,843
|
lingochamp/okdownload
|
okdownload/src/main/java/com/liulishuo/okdownload/DownloadSerialQueue.java
|
DownloadSerialQueue.resume
|
public synchronized void resume() {
if (!paused) {
Util.w(TAG, "require resume this queue(remain " + taskList.size() + "), but it is"
+ " still running");
return;
}
paused = false;
if (!taskList.isEmpty() && !looping) {
looping = true;
startNewLooper();
}
}
|
java
|
public synchronized void resume() {
if (!paused) {
Util.w(TAG, "require resume this queue(remain " + taskList.size() + "), but it is"
+ " still running");
return;
}
paused = false;
if (!taskList.isEmpty() && !looping) {
looping = true;
startNewLooper();
}
}
|
[
"public",
"synchronized",
"void",
"resume",
"(",
")",
"{",
"if",
"(",
"!",
"paused",
")",
"{",
"Util",
".",
"w",
"(",
"TAG",
",",
"\"require resume this queue(remain \"",
"+",
"taskList",
".",
"size",
"(",
")",
"+",
"\"), but it is\"",
"+",
"\" still running\"",
")",
";",
"return",
";",
"}",
"paused",
"=",
"false",
";",
"if",
"(",
"!",
"taskList",
".",
"isEmpty",
"(",
")",
"&&",
"!",
"looping",
")",
"{",
"looping",
"=",
"true",
";",
"startNewLooper",
"(",
")",
";",
"}",
"}"
] |
Resume the queue if the queue is paused.
@see #pause()
|
[
"Resume",
"the",
"queue",
"if",
"the",
"queue",
"is",
"paused",
"."
] |
403e2c814556ef7f2fade1f5bee83a02a5eaecb2
|
https://github.com/lingochamp/okdownload/blob/403e2c814556ef7f2fade1f5bee83a02a5eaecb2/okdownload/src/main/java/com/liulishuo/okdownload/DownloadSerialQueue.java#L117-L129
|
16,844
|
lingochamp/okdownload
|
okdownload/src/main/java/com/liulishuo/okdownload/core/breakpoint/BreakpointInfo.java
|
BreakpointInfo.copyWithReplaceIdAndUrl
|
public BreakpointInfo copyWithReplaceIdAndUrl(int replaceId, String newUrl) {
final BreakpointInfo info = new BreakpointInfo(replaceId, newUrl, parentFile,
filenameHolder.get(), taskOnlyProvidedParentPath);
info.chunked = this.chunked;
for (BlockInfo blockInfo : blockInfoList) {
info.blockInfoList.add(blockInfo.copy());
}
return info;
}
|
java
|
public BreakpointInfo copyWithReplaceIdAndUrl(int replaceId, String newUrl) {
final BreakpointInfo info = new BreakpointInfo(replaceId, newUrl, parentFile,
filenameHolder.get(), taskOnlyProvidedParentPath);
info.chunked = this.chunked;
for (BlockInfo blockInfo : blockInfoList) {
info.blockInfoList.add(blockInfo.copy());
}
return info;
}
|
[
"public",
"BreakpointInfo",
"copyWithReplaceIdAndUrl",
"(",
"int",
"replaceId",
",",
"String",
"newUrl",
")",
"{",
"final",
"BreakpointInfo",
"info",
"=",
"new",
"BreakpointInfo",
"(",
"replaceId",
",",
"newUrl",
",",
"parentFile",
",",
"filenameHolder",
".",
"get",
"(",
")",
",",
"taskOnlyProvidedParentPath",
")",
";",
"info",
".",
"chunked",
"=",
"this",
".",
"chunked",
";",
"for",
"(",
"BlockInfo",
"blockInfo",
":",
"blockInfoList",
")",
"{",
"info",
".",
"blockInfoList",
".",
"add",
"(",
"blockInfo",
".",
"copy",
"(",
")",
")",
";",
"}",
"return",
"info",
";",
"}"
] |
You can use this method to replace url for using breakpoint info from another task.
|
[
"You",
"can",
"use",
"this",
"method",
"to",
"replace",
"url",
"for",
"using",
"breakpoint",
"info",
"from",
"another",
"task",
"."
] |
403e2c814556ef7f2fade1f5bee83a02a5eaecb2
|
https://github.com/lingochamp/okdownload/blob/403e2c814556ef7f2fade1f5bee83a02a5eaecb2/okdownload/src/main/java/com/liulishuo/okdownload/core/breakpoint/BreakpointInfo.java#L202-L210
|
16,845
|
lingochamp/okdownload
|
okdownload/src/main/java/com/liulishuo/okdownload/DownloadTask.java
|
DownloadTask.getInfo
|
@Nullable public BreakpointInfo getInfo() {
if (info == null) info = OkDownload.with().breakpointStore().get(id);
return info;
}
|
java
|
@Nullable public BreakpointInfo getInfo() {
if (info == null) info = OkDownload.with().breakpointStore().get(id);
return info;
}
|
[
"@",
"Nullable",
"public",
"BreakpointInfo",
"getInfo",
"(",
")",
"{",
"if",
"(",
"info",
"==",
"null",
")",
"info",
"=",
"OkDownload",
".",
"with",
"(",
")",
".",
"breakpointStore",
"(",
")",
".",
"get",
"(",
"id",
")",
";",
"return",
"info",
";",
"}"
] |
Get the breakpoint info of this task.
@return {@code null} Only if there isn't any info for this task yet, otherwise you can get
the info for the task.
|
[
"Get",
"the",
"breakpoint",
"info",
"of",
"this",
"task",
"."
] |
403e2c814556ef7f2fade1f5bee83a02a5eaecb2
|
https://github.com/lingochamp/okdownload/blob/403e2c814556ef7f2fade1f5bee83a02a5eaecb2/okdownload/src/main/java/com/liulishuo/okdownload/DownloadTask.java#L429-L432
|
16,846
|
lingochamp/okdownload
|
okdownload/src/main/java/com/liulishuo/okdownload/core/download/ConnectTrial.java
|
ConnectTrial.trialHeadMethodForInstanceLength
|
void trialHeadMethodForInstanceLength() throws IOException {
final DownloadConnection connection = OkDownload.with().connectionFactory()
.create(task.getUrl());
final DownloadListener listener = OkDownload.with().callbackDispatcher().dispatch();
try {
connection.setRequestMethod(METHOD_HEAD);
final Map<String, List<String>> userHeader = task.getHeaderMapFields();
if (userHeader != null) Util.addUserRequestHeaderField(userHeader, connection);
listener.connectTrialStart(task, connection.getRequestProperties());
final DownloadConnection.Connected connectedForContentLength = connection.execute();
listener.connectTrialEnd(task, connectedForContentLength.getResponseCode(),
connectedForContentLength.getResponseHeaderFields());
this.instanceLength = Util.parseContentLength(
connectedForContentLength.getResponseHeaderField(CONTENT_LENGTH));
} finally {
connection.release();
}
}
|
java
|
void trialHeadMethodForInstanceLength() throws IOException {
final DownloadConnection connection = OkDownload.with().connectionFactory()
.create(task.getUrl());
final DownloadListener listener = OkDownload.with().callbackDispatcher().dispatch();
try {
connection.setRequestMethod(METHOD_HEAD);
final Map<String, List<String>> userHeader = task.getHeaderMapFields();
if (userHeader != null) Util.addUserRequestHeaderField(userHeader, connection);
listener.connectTrialStart(task, connection.getRequestProperties());
final DownloadConnection.Connected connectedForContentLength = connection.execute();
listener.connectTrialEnd(task, connectedForContentLength.getResponseCode(),
connectedForContentLength.getResponseHeaderFields());
this.instanceLength = Util.parseContentLength(
connectedForContentLength.getResponseHeaderField(CONTENT_LENGTH));
} finally {
connection.release();
}
}
|
[
"void",
"trialHeadMethodForInstanceLength",
"(",
")",
"throws",
"IOException",
"{",
"final",
"DownloadConnection",
"connection",
"=",
"OkDownload",
".",
"with",
"(",
")",
".",
"connectionFactory",
"(",
")",
".",
"create",
"(",
"task",
".",
"getUrl",
"(",
")",
")",
";",
"final",
"DownloadListener",
"listener",
"=",
"OkDownload",
".",
"with",
"(",
")",
".",
"callbackDispatcher",
"(",
")",
".",
"dispatch",
"(",
")",
";",
"try",
"{",
"connection",
".",
"setRequestMethod",
"(",
"METHOD_HEAD",
")",
";",
"final",
"Map",
"<",
"String",
",",
"List",
"<",
"String",
">",
">",
"userHeader",
"=",
"task",
".",
"getHeaderMapFields",
"(",
")",
";",
"if",
"(",
"userHeader",
"!=",
"null",
")",
"Util",
".",
"addUserRequestHeaderField",
"(",
"userHeader",
",",
"connection",
")",
";",
"listener",
".",
"connectTrialStart",
"(",
"task",
",",
"connection",
".",
"getRequestProperties",
"(",
")",
")",
";",
"final",
"DownloadConnection",
".",
"Connected",
"connectedForContentLength",
"=",
"connection",
".",
"execute",
"(",
")",
";",
"listener",
".",
"connectTrialEnd",
"(",
"task",
",",
"connectedForContentLength",
".",
"getResponseCode",
"(",
")",
",",
"connectedForContentLength",
".",
"getResponseHeaderFields",
"(",
")",
")",
";",
"this",
".",
"instanceLength",
"=",
"Util",
".",
"parseContentLength",
"(",
"connectedForContentLength",
".",
"getResponseHeaderField",
"(",
"CONTENT_LENGTH",
")",
")",
";",
"}",
"finally",
"{",
"connection",
".",
"release",
"(",
")",
";",
"}",
"}"
] |
right one.
|
[
"right",
"one",
"."
] |
403e2c814556ef7f2fade1f5bee83a02a5eaecb2
|
https://github.com/lingochamp/okdownload/blob/403e2c814556ef7f2fade1f5bee83a02a5eaecb2/okdownload/src/main/java/com/liulishuo/okdownload/core/download/ConnectTrial.java#L294-L313
|
16,847
|
lingochamp/okdownload
|
okdownload/src/main/java/com/liulishuo/okdownload/DownloadContext.java
|
DownloadContext.start
|
public void start(@Nullable final DownloadListener listener, boolean isSerial) {
final long startTime = SystemClock.uptimeMillis();
Util.d(TAG, "start " + isSerial);
started = true;
final DownloadListener targetListener;
if (contextListener != null) {
targetListener = new DownloadListenerBunch.Builder()
.append(listener)
.append(new QueueAttachListener(this, contextListener, tasks.length))
.build();
} else {
targetListener = listener;
}
if (isSerial) {
final List<DownloadTask> scheduleTaskList = new ArrayList<>();
Collections.addAll(scheduleTaskList, tasks);
Collections.sort(scheduleTaskList);
executeOnSerialExecutor(new Runnable() {
@Override public void run() {
for (DownloadTask task : scheduleTaskList) {
if (!isStarted()) {
callbackQueueEndOnSerialLoop(task.isAutoCallbackToUIThread());
break;
}
task.execute(targetListener);
}
}
});
} else {
DownloadTask.enqueue(tasks, targetListener);
}
Util.d(TAG,
"start finish " + isSerial + " " + (SystemClock.uptimeMillis() - startTime) + "ms");
}
|
java
|
public void start(@Nullable final DownloadListener listener, boolean isSerial) {
final long startTime = SystemClock.uptimeMillis();
Util.d(TAG, "start " + isSerial);
started = true;
final DownloadListener targetListener;
if (contextListener != null) {
targetListener = new DownloadListenerBunch.Builder()
.append(listener)
.append(new QueueAttachListener(this, contextListener, tasks.length))
.build();
} else {
targetListener = listener;
}
if (isSerial) {
final List<DownloadTask> scheduleTaskList = new ArrayList<>();
Collections.addAll(scheduleTaskList, tasks);
Collections.sort(scheduleTaskList);
executeOnSerialExecutor(new Runnable() {
@Override public void run() {
for (DownloadTask task : scheduleTaskList) {
if (!isStarted()) {
callbackQueueEndOnSerialLoop(task.isAutoCallbackToUIThread());
break;
}
task.execute(targetListener);
}
}
});
} else {
DownloadTask.enqueue(tasks, targetListener);
}
Util.d(TAG,
"start finish " + isSerial + " " + (SystemClock.uptimeMillis() - startTime) + "ms");
}
|
[
"public",
"void",
"start",
"(",
"@",
"Nullable",
"final",
"DownloadListener",
"listener",
",",
"boolean",
"isSerial",
")",
"{",
"final",
"long",
"startTime",
"=",
"SystemClock",
".",
"uptimeMillis",
"(",
")",
";",
"Util",
".",
"d",
"(",
"TAG",
",",
"\"start \"",
"+",
"isSerial",
")",
";",
"started",
"=",
"true",
";",
"final",
"DownloadListener",
"targetListener",
";",
"if",
"(",
"contextListener",
"!=",
"null",
")",
"{",
"targetListener",
"=",
"new",
"DownloadListenerBunch",
".",
"Builder",
"(",
")",
".",
"append",
"(",
"listener",
")",
".",
"append",
"(",
"new",
"QueueAttachListener",
"(",
"this",
",",
"contextListener",
",",
"tasks",
".",
"length",
")",
")",
".",
"build",
"(",
")",
";",
"}",
"else",
"{",
"targetListener",
"=",
"listener",
";",
"}",
"if",
"(",
"isSerial",
")",
"{",
"final",
"List",
"<",
"DownloadTask",
">",
"scheduleTaskList",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"Collections",
".",
"addAll",
"(",
"scheduleTaskList",
",",
"tasks",
")",
";",
"Collections",
".",
"sort",
"(",
"scheduleTaskList",
")",
";",
"executeOnSerialExecutor",
"(",
"new",
"Runnable",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"run",
"(",
")",
"{",
"for",
"(",
"DownloadTask",
"task",
":",
"scheduleTaskList",
")",
"{",
"if",
"(",
"!",
"isStarted",
"(",
")",
")",
"{",
"callbackQueueEndOnSerialLoop",
"(",
"task",
".",
"isAutoCallbackToUIThread",
"(",
")",
")",
";",
"break",
";",
"}",
"task",
".",
"execute",
"(",
"targetListener",
")",
";",
"}",
"}",
"}",
")",
";",
"}",
"else",
"{",
"DownloadTask",
".",
"enqueue",
"(",
"tasks",
",",
"targetListener",
")",
";",
"}",
"Util",
".",
"d",
"(",
"TAG",
",",
"\"start finish \"",
"+",
"isSerial",
"+",
"\" \"",
"+",
"(",
"SystemClock",
".",
"uptimeMillis",
"(",
")",
"-",
"startTime",
")",
"+",
"\"ms\"",
")",
";",
"}"
] |
Start queue.
@param listener the listener for each task, if you have already provided
{@link #contextListener}, it's accept {@code null} for each task's listener.
@param isSerial whether download queue serial or parallel.
|
[
"Start",
"queue",
"."
] |
403e2c814556ef7f2fade1f5bee83a02a5eaecb2
|
https://github.com/lingochamp/okdownload/blob/403e2c814556ef7f2fade1f5bee83a02a5eaecb2/okdownload/src/main/java/com/liulishuo/okdownload/DownloadContext.java#L99-L133
|
16,848
|
lingochamp/okdownload
|
okdownload-breakpoint-sqlite/src/main/java/com/liulishuo/okdownload/core/breakpoint/RemitStoreOnSQLite.java
|
RemitStoreOnSQLite.syncCacheToDB
|
@Override public void syncCacheToDB(List<Integer> idList) throws IOException {
final SQLiteDatabase database = sqLiteHelper.getWritableDatabase();
database.beginTransaction();
try {
for (Integer id : idList) {
syncCacheToDB(id);
}
database.setTransactionSuccessful();
} finally {
database.endTransaction();
}
}
|
java
|
@Override public void syncCacheToDB(List<Integer> idList) throws IOException {
final SQLiteDatabase database = sqLiteHelper.getWritableDatabase();
database.beginTransaction();
try {
for (Integer id : idList) {
syncCacheToDB(id);
}
database.setTransactionSuccessful();
} finally {
database.endTransaction();
}
}
|
[
"@",
"Override",
"public",
"void",
"syncCacheToDB",
"(",
"List",
"<",
"Integer",
">",
"idList",
")",
"throws",
"IOException",
"{",
"final",
"SQLiteDatabase",
"database",
"=",
"sqLiteHelper",
".",
"getWritableDatabase",
"(",
")",
";",
"database",
".",
"beginTransaction",
"(",
")",
";",
"try",
"{",
"for",
"(",
"Integer",
"id",
":",
"idList",
")",
"{",
"syncCacheToDB",
"(",
"id",
")",
";",
"}",
"database",
".",
"setTransactionSuccessful",
"(",
")",
";",
"}",
"finally",
"{",
"database",
".",
"endTransaction",
"(",
")",
";",
"}",
"}"
] |
following accept database operation what is controlled by helper.
|
[
"following",
"accept",
"database",
"operation",
"what",
"is",
"controlled",
"by",
"helper",
"."
] |
403e2c814556ef7f2fade1f5bee83a02a5eaecb2
|
https://github.com/lingochamp/okdownload/blob/403e2c814556ef7f2fade1f5bee83a02a5eaecb2/okdownload-breakpoint-sqlite/src/main/java/com/liulishuo/okdownload/core/breakpoint/RemitStoreOnSQLite.java#L142-L153
|
16,849
|
lingochamp/okdownload
|
okdownload/src/main/java/com/liulishuo/okdownload/SpeedCalculator.java
|
SpeedCalculator.getBytesPerSecondAndFlush
|
public synchronized long getBytesPerSecondAndFlush() {
final long interval = nowMillis() - timestamp;
if (interval < 1000 && bytesPerSecond != 0) return bytesPerSecond;
// the first time we using 500 milliseconds to let speed valid more quick
if (bytesPerSecond == 0 && interval < 500) return 0;
return getInstantBytesPerSecondAndFlush();
}
|
java
|
public synchronized long getBytesPerSecondAndFlush() {
final long interval = nowMillis() - timestamp;
if (interval < 1000 && bytesPerSecond != 0) return bytesPerSecond;
// the first time we using 500 milliseconds to let speed valid more quick
if (bytesPerSecond == 0 && interval < 500) return 0;
return getInstantBytesPerSecondAndFlush();
}
|
[
"public",
"synchronized",
"long",
"getBytesPerSecondAndFlush",
"(",
")",
"{",
"final",
"long",
"interval",
"=",
"nowMillis",
"(",
")",
"-",
"timestamp",
";",
"if",
"(",
"interval",
"<",
"1000",
"&&",
"bytesPerSecond",
"!=",
"0",
")",
"return",
"bytesPerSecond",
";",
"// the first time we using 500 milliseconds to let speed valid more quick",
"if",
"(",
"bytesPerSecond",
"==",
"0",
"&&",
"interval",
"<",
"500",
")",
"return",
"0",
";",
"return",
"getInstantBytesPerSecondAndFlush",
"(",
")",
";",
"}"
] |
Get bytes per-second and only if duration is greater than or equal to 1 second will flush and
re-calculate speed.
|
[
"Get",
"bytes",
"per",
"-",
"second",
"and",
"only",
"if",
"duration",
"is",
"greater",
"than",
"or",
"equal",
"to",
"1",
"second",
"will",
"flush",
"and",
"re",
"-",
"calculate",
"speed",
"."
] |
403e2c814556ef7f2fade1f5bee83a02a5eaecb2
|
https://github.com/lingochamp/okdownload/blob/403e2c814556ef7f2fade1f5bee83a02a5eaecb2/okdownload/src/main/java/com/liulishuo/okdownload/SpeedCalculator.java#L83-L91
|
16,850
|
lingochamp/okdownload
|
okdownload-filedownloader/src/main/java/com/liulishuo/filedownloader/notification/FileDownloadNotificationHelper.java
|
FileDownloadNotificationHelper.showProgress
|
public void showProgress(final int id, final int sofar, final int total) {
final T notification = get(id);
if (notification == null) {
return;
}
notification.updateStatus(FileDownloadStatus.progress);
notification.update(sofar, total);
}
|
java
|
public void showProgress(final int id, final int sofar, final int total) {
final T notification = get(id);
if (notification == null) {
return;
}
notification.updateStatus(FileDownloadStatus.progress);
notification.update(sofar, total);
}
|
[
"public",
"void",
"showProgress",
"(",
"final",
"int",
"id",
",",
"final",
"int",
"sofar",
",",
"final",
"int",
"total",
")",
"{",
"final",
"T",
"notification",
"=",
"get",
"(",
"id",
")",
";",
"if",
"(",
"notification",
"==",
"null",
")",
"{",
"return",
";",
"}",
"notification",
".",
"updateStatus",
"(",
"FileDownloadStatus",
".",
"progress",
")",
";",
"notification",
".",
"update",
"(",
"sofar",
",",
"total",
")",
";",
"}"
] |
Show the notification with the exact progress.
@param id The download id.
@param sofar The downloaded bytes so far.
@param total The total bytes of this task.
|
[
"Show",
"the",
"notification",
"with",
"the",
"exact",
"progress",
"."
] |
403e2c814556ef7f2fade1f5bee83a02a5eaecb2
|
https://github.com/lingochamp/okdownload/blob/403e2c814556ef7f2fade1f5bee83a02a5eaecb2/okdownload-filedownloader/src/main/java/com/liulishuo/filedownloader/notification/FileDownloadNotificationHelper.java#L79-L88
|
16,851
|
lingochamp/okdownload
|
okdownload-filedownloader/src/main/java/com/liulishuo/filedownloader/notification/FileDownloadNotificationHelper.java
|
FileDownloadNotificationHelper.showIndeterminate
|
public void showIndeterminate(final int id, int status) {
final BaseNotificationItem notification = get(id);
if (notification == null) {
return;
}
notification.updateStatus(status);
notification.show(false);
}
|
java
|
public void showIndeterminate(final int id, int status) {
final BaseNotificationItem notification = get(id);
if (notification == null) {
return;
}
notification.updateStatus(status);
notification.show(false);
}
|
[
"public",
"void",
"showIndeterminate",
"(",
"final",
"int",
"id",
",",
"int",
"status",
")",
"{",
"final",
"BaseNotificationItem",
"notification",
"=",
"get",
"(",
"id",
")",
";",
"if",
"(",
"notification",
"==",
"null",
")",
"{",
"return",
";",
"}",
"notification",
".",
"updateStatus",
"(",
"status",
")",
";",
"notification",
".",
"show",
"(",
"false",
")",
";",
"}"
] |
Show the notification with indeterminate progress.
@param id The download id.
@param status {@link FileDownloadStatus}
|
[
"Show",
"the",
"notification",
"with",
"indeterminate",
"progress",
"."
] |
403e2c814556ef7f2fade1f5bee83a02a5eaecb2
|
https://github.com/lingochamp/okdownload/blob/403e2c814556ef7f2fade1f5bee83a02a5eaecb2/okdownload-filedownloader/src/main/java/com/liulishuo/filedownloader/notification/FileDownloadNotificationHelper.java#L96-L105
|
16,852
|
lingochamp/okdownload
|
okdownload-filedownloader/src/main/java/com/liulishuo/filedownloader/notification/FileDownloadNotificationHelper.java
|
FileDownloadNotificationHelper.cancel
|
public void cancel(final int id) {
final BaseNotificationItem notification = remove(id);
if (notification == null) {
return;
}
notification.cancel();
}
|
java
|
public void cancel(final int id) {
final BaseNotificationItem notification = remove(id);
if (notification == null) {
return;
}
notification.cancel();
}
|
[
"public",
"void",
"cancel",
"(",
"final",
"int",
"id",
")",
"{",
"final",
"BaseNotificationItem",
"notification",
"=",
"remove",
"(",
"id",
")",
";",
"if",
"(",
"notification",
"==",
"null",
")",
"{",
"return",
";",
"}",
"notification",
".",
"cancel",
"(",
")",
";",
"}"
] |
Cancel the notification by notification id.
@param id The download id.
|
[
"Cancel",
"the",
"notification",
"by",
"notification",
"id",
"."
] |
403e2c814556ef7f2fade1f5bee83a02a5eaecb2
|
https://github.com/lingochamp/okdownload/blob/403e2c814556ef7f2fade1f5bee83a02a5eaecb2/okdownload-filedownloader/src/main/java/com/liulishuo/filedownloader/notification/FileDownloadNotificationHelper.java#L112-L120
|
16,853
|
lingochamp/okdownload
|
okdownload-filedownloader/src/main/java/com/liulishuo/filedownloader/FileDownloadList.java
|
FileDownloadList.addQueueTask
|
void addQueueTask(final DownloadTaskAdapter task) {
if (task.isMarkedAdded2List()) {
Util.w(TAG, "queue task: " + task + " has been marked");
return;
}
synchronized (list) {
task.markAdded2List();
task.assembleDownloadTask();
list.add(task);
Util.d(TAG, "add list in all " + task + " " + list.size());
}
}
|
java
|
void addQueueTask(final DownloadTaskAdapter task) {
if (task.isMarkedAdded2List()) {
Util.w(TAG, "queue task: " + task + " has been marked");
return;
}
synchronized (list) {
task.markAdded2List();
task.assembleDownloadTask();
list.add(task);
Util.d(TAG, "add list in all " + task + " " + list.size());
}
}
|
[
"void",
"addQueueTask",
"(",
"final",
"DownloadTaskAdapter",
"task",
")",
"{",
"if",
"(",
"task",
".",
"isMarkedAdded2List",
"(",
")",
")",
"{",
"Util",
".",
"w",
"(",
"TAG",
",",
"\"queue task: \"",
"+",
"task",
"+",
"\" has been marked\"",
")",
";",
"return",
";",
"}",
"synchronized",
"(",
"list",
")",
"{",
"task",
".",
"markAdded2List",
"(",
")",
";",
"task",
".",
"assembleDownloadTask",
"(",
")",
";",
"list",
".",
"add",
"(",
"task",
")",
";",
"Util",
".",
"d",
"(",
"TAG",
",",
"\"add list in all \"",
"+",
"task",
"+",
"\" \"",
"+",
"list",
".",
"size",
"(",
")",
")",
";",
"}",
"}"
] |
This method generally used for enqueuing the task which will be assembled by a queue.
@see BaseDownloadTask.InQueueTask#enqueue()
|
[
"This",
"method",
"generally",
"used",
"for",
"enqueuing",
"the",
"task",
"which",
"will",
"be",
"assembled",
"by",
"a",
"queue",
"."
] |
403e2c814556ef7f2fade1f5bee83a02a5eaecb2
|
https://github.com/lingochamp/okdownload/blob/403e2c814556ef7f2fade1f5bee83a02a5eaecb2/okdownload-filedownloader/src/main/java/com/liulishuo/filedownloader/FileDownloadList.java#L112-L124
|
16,854
|
powermock/powermock
|
powermock-modules/powermock-module-javaagent/src/main/java/sun/tools/attach/LinuxVirtualMachine.java
|
LinuxVirtualMachine.findSocketFile
|
private String findSocketFile(int pid) {
File f = new File(tmpdir, ".java_pid" + pid);
if (!f.exists()) {
return null;
}
return f.getPath();
}
|
java
|
private String findSocketFile(int pid) {
File f = new File(tmpdir, ".java_pid" + pid);
if (!f.exists()) {
return null;
}
return f.getPath();
}
|
[
"private",
"String",
"findSocketFile",
"(",
"int",
"pid",
")",
"{",
"File",
"f",
"=",
"new",
"File",
"(",
"tmpdir",
",",
"\".java_pid\"",
"+",
"pid",
")",
";",
"if",
"(",
"!",
"f",
".",
"exists",
"(",
")",
")",
"{",
"return",
"null",
";",
"}",
"return",
"f",
".",
"getPath",
"(",
")",
";",
"}"
] |
Return the socket file for the given process.
|
[
"Return",
"the",
"socket",
"file",
"for",
"the",
"given",
"process",
"."
] |
e8cd68026c284c6a7efe66959809eeebd8d1f9ad
|
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-modules/powermock-module-javaagent/src/main/java/sun/tools/attach/LinuxVirtualMachine.java#L272-L278
|
16,855
|
powermock/powermock
|
powermock-modules/powermock-module-javaagent/src/main/java/sun/tools/attach/LinuxVirtualMachine.java
|
LinuxVirtualMachine.createAttachFile
|
private File createAttachFile(int pid) throws IOException {
String fn = ".attach_pid" + pid;
String path = "/proc/" + pid + "/cwd/" + fn;
File f = new File(path);
try {
f.createNewFile();
} catch (IOException x) {
f = new File(tmpdir, fn);
f.createNewFile();
}
return f;
}
|
java
|
private File createAttachFile(int pid) throws IOException {
String fn = ".attach_pid" + pid;
String path = "/proc/" + pid + "/cwd/" + fn;
File f = new File(path);
try {
f.createNewFile();
} catch (IOException x) {
f = new File(tmpdir, fn);
f.createNewFile();
}
return f;
}
|
[
"private",
"File",
"createAttachFile",
"(",
"int",
"pid",
")",
"throws",
"IOException",
"{",
"String",
"fn",
"=",
"\".attach_pid\"",
"+",
"pid",
";",
"String",
"path",
"=",
"\"/proc/\"",
"+",
"pid",
"+",
"\"/cwd/\"",
"+",
"fn",
";",
"File",
"f",
"=",
"new",
"File",
"(",
"path",
")",
";",
"try",
"{",
"f",
".",
"createNewFile",
"(",
")",
";",
"}",
"catch",
"(",
"IOException",
"x",
")",
"{",
"f",
"=",
"new",
"File",
"(",
"tmpdir",
",",
"fn",
")",
";",
"f",
".",
"createNewFile",
"(",
")",
";",
"}",
"return",
"f",
";",
"}"
] |
checks for the file.
|
[
"checks",
"for",
"the",
"file",
"."
] |
e8cd68026c284c6a7efe66959809eeebd8d1f9ad
|
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-modules/powermock-module-javaagent/src/main/java/sun/tools/attach/LinuxVirtualMachine.java#L284-L295
|
16,856
|
powermock/powermock
|
powermock-core/src/main/java/org/powermock/core/MockRepository.java
|
MockRepository.clear
|
public synchronized static void clear() {
newSubstitutions.clear();
classMocks.clear();
instanceMocks.clear();
objectsToAutomaticallyReplayAndVerify.clear();
additionalState.clear();
suppressConstructor.clear();
suppressMethod.clear();
substituteReturnValues.clear();
suppressField.clear();
suppressFieldTypes.clear();
methodProxies.clear();
for (Runnable runnable : afterMethodRunners) {
runnable.run();
}
afterMethodRunners.clear();
}
|
java
|
public synchronized static void clear() {
newSubstitutions.clear();
classMocks.clear();
instanceMocks.clear();
objectsToAutomaticallyReplayAndVerify.clear();
additionalState.clear();
suppressConstructor.clear();
suppressMethod.clear();
substituteReturnValues.clear();
suppressField.clear();
suppressFieldTypes.clear();
methodProxies.clear();
for (Runnable runnable : afterMethodRunners) {
runnable.run();
}
afterMethodRunners.clear();
}
|
[
"public",
"synchronized",
"static",
"void",
"clear",
"(",
")",
"{",
"newSubstitutions",
".",
"clear",
"(",
")",
";",
"classMocks",
".",
"clear",
"(",
")",
";",
"instanceMocks",
".",
"clear",
"(",
")",
";",
"objectsToAutomaticallyReplayAndVerify",
".",
"clear",
"(",
")",
";",
"additionalState",
".",
"clear",
"(",
")",
";",
"suppressConstructor",
".",
"clear",
"(",
")",
";",
"suppressMethod",
".",
"clear",
"(",
")",
";",
"substituteReturnValues",
".",
"clear",
"(",
")",
";",
"suppressField",
".",
"clear",
"(",
")",
";",
"suppressFieldTypes",
".",
"clear",
"(",
")",
";",
"methodProxies",
".",
"clear",
"(",
")",
";",
"for",
"(",
"Runnable",
"runnable",
":",
"afterMethodRunners",
")",
"{",
"runnable",
".",
"run",
"(",
")",
";",
"}",
"afterMethodRunners",
".",
"clear",
"(",
")",
";",
"}"
] |
Clear all state of the mock repository except for static initializers.
The reason for not clearing static initializers is that when running in a
suite with many tests the clear method is invoked after each test. This
means that before the test that needs to suppress the static initializer
has been reach the state of the MockRepository would have been wiped out.
This is generally not a problem because most state will be added again
but suppression of static initializers are different because this state
can only be set once per class per CL. That's why we cannot remove this
state.
|
[
"Clear",
"all",
"state",
"of",
"the",
"mock",
"repository",
"except",
"for",
"static",
"initializers",
".",
"The",
"reason",
"for",
"not",
"clearing",
"static",
"initializers",
"is",
"that",
"when",
"running",
"in",
"a",
"suite",
"with",
"many",
"tests",
"the",
"clear",
"method",
"is",
"invoked",
"after",
"each",
"test",
".",
"This",
"means",
"that",
"before",
"the",
"test",
"that",
"needs",
"to",
"suppress",
"the",
"static",
"initializer",
"has",
"been",
"reach",
"the",
"state",
"of",
"the",
"MockRepository",
"would",
"have",
"been",
"wiped",
"out",
".",
"This",
"is",
"generally",
"not",
"a",
"problem",
"because",
"most",
"state",
"will",
"be",
"added",
"again",
"but",
"suppression",
"of",
"static",
"initializers",
"are",
"different",
"because",
"this",
"state",
"can",
"only",
"be",
"set",
"once",
"per",
"class",
"per",
"CL",
".",
"That",
"s",
"why",
"we",
"cannot",
"remove",
"this",
"state",
"."
] |
e8cd68026c284c6a7efe66959809eeebd8d1f9ad
|
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-core/src/main/java/org/powermock/core/MockRepository.java#L112-L128
|
16,857
|
powermock/powermock
|
powermock-core/src/main/java/org/powermock/core/MockRepository.java
|
MockRepository.remove
|
public static void remove(Object mock) {
if (mock instanceof Class<?>) {
if (newSubstitutions.containsKey(mock)) {
newSubstitutions.remove(mock);
}
if (classMocks.containsKey(mock)) {
classMocks.remove(mock);
}
} else if (instanceMocks.containsKey(mock)) {
instanceMocks.remove(mock);
}
}
|
java
|
public static void remove(Object mock) {
if (mock instanceof Class<?>) {
if (newSubstitutions.containsKey(mock)) {
newSubstitutions.remove(mock);
}
if (classMocks.containsKey(mock)) {
classMocks.remove(mock);
}
} else if (instanceMocks.containsKey(mock)) {
instanceMocks.remove(mock);
}
}
|
[
"public",
"static",
"void",
"remove",
"(",
"Object",
"mock",
")",
"{",
"if",
"(",
"mock",
"instanceof",
"Class",
"<",
"?",
">",
")",
"{",
"if",
"(",
"newSubstitutions",
".",
"containsKey",
"(",
"mock",
")",
")",
"{",
"newSubstitutions",
".",
"remove",
"(",
"mock",
")",
";",
"}",
"if",
"(",
"classMocks",
".",
"containsKey",
"(",
"mock",
")",
")",
"{",
"classMocks",
".",
"remove",
"(",
"mock",
")",
";",
"}",
"}",
"else",
"if",
"(",
"instanceMocks",
".",
"containsKey",
"(",
"mock",
")",
")",
"{",
"instanceMocks",
".",
"remove",
"(",
"mock",
")",
";",
"}",
"}"
] |
Removes an object from the MockRepository if it exists.
|
[
"Removes",
"an",
"object",
"from",
"the",
"MockRepository",
"if",
"it",
"exists",
"."
] |
e8cd68026c284c6a7efe66959809eeebd8d1f9ad
|
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-core/src/main/java/org/powermock/core/MockRepository.java#L133-L144
|
16,858
|
powermock/powermock
|
powermock-core/src/main/java/org/powermock/core/MockRepository.java
|
MockRepository.putAdditionalState
|
public static synchronized Object putAdditionalState(String key, Object value) {
return additionalState.put(key, value);
}
|
java
|
public static synchronized Object putAdditionalState(String key, Object value) {
return additionalState.put(key, value);
}
|
[
"public",
"static",
"synchronized",
"Object",
"putAdditionalState",
"(",
"String",
"key",
",",
"Object",
"value",
")",
"{",
"return",
"additionalState",
".",
"put",
"(",
"key",
",",
"value",
")",
";",
"}"
] |
When a mock framework API needs to store additional state not applicable
for the other methods, it may use this method to do so.
@param key
The key under which the <tt>value</tt> is stored.
@param value
The value to store under the specified <tt>key</tt>.
@return The previous object under the specified <tt>key</tt> or
{@code null}.
|
[
"When",
"a",
"mock",
"framework",
"API",
"needs",
"to",
"store",
"additional",
"state",
"not",
"applicable",
"for",
"the",
"other",
"methods",
"it",
"may",
"use",
"this",
"method",
"to",
"do",
"so",
"."
] |
e8cd68026c284c6a7efe66959809eeebd8d1f9ad
|
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-core/src/main/java/org/powermock/core/MockRepository.java#L240-L242
|
16,859
|
powermock/powermock
|
powermock-core/src/main/java/org/powermock/core/MockRepository.java
|
MockRepository.getAdditionalState
|
@SuppressWarnings("unchecked")
public static synchronized <T> T getAdditionalState(String key) {
return (T) additionalState.get(key);
}
|
java
|
@SuppressWarnings("unchecked")
public static synchronized <T> T getAdditionalState(String key) {
return (T) additionalState.get(key);
}
|
[
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"static",
"synchronized",
"<",
"T",
">",
"T",
"getAdditionalState",
"(",
"String",
"key",
")",
"{",
"return",
"(",
"T",
")",
"additionalState",
".",
"get",
"(",
"key",
")",
";",
"}"
] |
Retrieve state based on the supplied key.
|
[
"Retrieve",
"state",
"based",
"on",
"the",
"supplied",
"key",
"."
] |
e8cd68026c284c6a7efe66959809eeebd8d1f9ad
|
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-core/src/main/java/org/powermock/core/MockRepository.java#L255-L258
|
16,860
|
powermock/powermock
|
powermock-core/src/main/java/org/powermock/core/MockRepository.java
|
MockRepository.putMethodProxy
|
public static synchronized InvocationHandler putMethodProxy(Method method, InvocationHandler invocationHandler) {
return methodProxies.put(method, invocationHandler);
}
|
java
|
public static synchronized InvocationHandler putMethodProxy(Method method, InvocationHandler invocationHandler) {
return methodProxies.put(method, invocationHandler);
}
|
[
"public",
"static",
"synchronized",
"InvocationHandler",
"putMethodProxy",
"(",
"Method",
"method",
",",
"InvocationHandler",
"invocationHandler",
")",
"{",
"return",
"methodProxies",
".",
"put",
"(",
"method",
",",
"invocationHandler",
")",
";",
"}"
] |
Set a proxy for a method. Whenever this method is called the invocation
handler will be invoked instead.
@return The method proxy if any.
|
[
"Set",
"a",
"proxy",
"for",
"a",
"method",
".",
"Whenever",
"this",
"method",
"is",
"called",
"the",
"invocation",
"handler",
"will",
"be",
"invoked",
"instead",
"."
] |
e8cd68026c284c6a7efe66959809eeebd8d1f9ad
|
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-core/src/main/java/org/powermock/core/MockRepository.java#L381-L383
|
16,861
|
powermock/powermock
|
powermock-core/src/main/java/org/powermock/core/transformers/javassist/support/PowerMockExpressionEditor.java
|
PowerMockExpressionEditor.addNewDeferConstructor
|
private void addNewDeferConstructor(final CtClass clazz) throws CannotCompileException {
final CtClass superClass;
try {
superClass = clazz.getSuperclass();
} catch (NotFoundException e1) {
throw new IllegalArgumentException("Internal error: Failed to get superclass for " + clazz.getName() + " when about to create a new default constructor.");
}
ClassPool classPool = clazz.getClassPool();
/*
* To make a unique defer constructor we create a new constructor
* with one argument (IndicateReloadClass). So we get this class a
* Javassist class below.
*/
final CtClass constructorType;
try {
constructorType = classPool.get(IndicateReloadClass.class.getName());
} catch (NotFoundException e) {
throw new IllegalArgumentException("Internal error: failed to get the " + IndicateReloadClass.class.getName()
+ " when added defer constructor.");
}
clazz.defrost();
if (superClass.getName().equals(Object.class.getName())) {
try {
clazz.addConstructor(CtNewConstructor.make(new CtClass[]{constructorType}, new CtClass[0], "{super();}", clazz));
} catch (DuplicateMemberException e) {
// OK, the constructor has already been added.
}
} else {
addNewDeferConstructor(superClass);
try {
clazz.addConstructor(CtNewConstructor.make(new CtClass[]{constructorType}, new CtClass[0], "{super($$);}", clazz));
} catch (DuplicateMemberException e) {
// OK, the constructor has already been added.
}
}
}
|
java
|
private void addNewDeferConstructor(final CtClass clazz) throws CannotCompileException {
final CtClass superClass;
try {
superClass = clazz.getSuperclass();
} catch (NotFoundException e1) {
throw new IllegalArgumentException("Internal error: Failed to get superclass for " + clazz.getName() + " when about to create a new default constructor.");
}
ClassPool classPool = clazz.getClassPool();
/*
* To make a unique defer constructor we create a new constructor
* with one argument (IndicateReloadClass). So we get this class a
* Javassist class below.
*/
final CtClass constructorType;
try {
constructorType = classPool.get(IndicateReloadClass.class.getName());
} catch (NotFoundException e) {
throw new IllegalArgumentException("Internal error: failed to get the " + IndicateReloadClass.class.getName()
+ " when added defer constructor.");
}
clazz.defrost();
if (superClass.getName().equals(Object.class.getName())) {
try {
clazz.addConstructor(CtNewConstructor.make(new CtClass[]{constructorType}, new CtClass[0], "{super();}", clazz));
} catch (DuplicateMemberException e) {
// OK, the constructor has already been added.
}
} else {
addNewDeferConstructor(superClass);
try {
clazz.addConstructor(CtNewConstructor.make(new CtClass[]{constructorType}, new CtClass[0], "{super($$);}", clazz));
} catch (DuplicateMemberException e) {
// OK, the constructor has already been added.
}
}
}
|
[
"private",
"void",
"addNewDeferConstructor",
"(",
"final",
"CtClass",
"clazz",
")",
"throws",
"CannotCompileException",
"{",
"final",
"CtClass",
"superClass",
";",
"try",
"{",
"superClass",
"=",
"clazz",
".",
"getSuperclass",
"(",
")",
";",
"}",
"catch",
"(",
"NotFoundException",
"e1",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Internal error: Failed to get superclass for \"",
"+",
"clazz",
".",
"getName",
"(",
")",
"+",
"\" when about to create a new default constructor.\"",
")",
";",
"}",
"ClassPool",
"classPool",
"=",
"clazz",
".",
"getClassPool",
"(",
")",
";",
"/*\n * To make a unique defer constructor we create a new constructor\n * with one argument (IndicateReloadClass). So we get this class a\n * Javassist class below.\n */",
"final",
"CtClass",
"constructorType",
";",
"try",
"{",
"constructorType",
"=",
"classPool",
".",
"get",
"(",
"IndicateReloadClass",
".",
"class",
".",
"getName",
"(",
")",
")",
";",
"}",
"catch",
"(",
"NotFoundException",
"e",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Internal error: failed to get the \"",
"+",
"IndicateReloadClass",
".",
"class",
".",
"getName",
"(",
")",
"+",
"\" when added defer constructor.\"",
")",
";",
"}",
"clazz",
".",
"defrost",
"(",
")",
";",
"if",
"(",
"superClass",
".",
"getName",
"(",
")",
".",
"equals",
"(",
"Object",
".",
"class",
".",
"getName",
"(",
")",
")",
")",
"{",
"try",
"{",
"clazz",
".",
"addConstructor",
"(",
"CtNewConstructor",
".",
"make",
"(",
"new",
"CtClass",
"[",
"]",
"{",
"constructorType",
"}",
",",
"new",
"CtClass",
"[",
"0",
"]",
",",
"\"{super();}\"",
",",
"clazz",
")",
")",
";",
"}",
"catch",
"(",
"DuplicateMemberException",
"e",
")",
"{",
"// OK, the constructor has already been added.",
"}",
"}",
"else",
"{",
"addNewDeferConstructor",
"(",
"superClass",
")",
";",
"try",
"{",
"clazz",
".",
"addConstructor",
"(",
"CtNewConstructor",
".",
"make",
"(",
"new",
"CtClass",
"[",
"]",
"{",
"constructorType",
"}",
",",
"new",
"CtClass",
"[",
"0",
"]",
",",
"\"{super($$);}\"",
",",
"clazz",
")",
")",
";",
"}",
"catch",
"(",
"DuplicateMemberException",
"e",
")",
"{",
"// OK, the constructor has already been added.",
"}",
"}",
"}"
] |
Create a defer constructor in the class which will be called when the
constructor is suppressed.
@param clazz The class whose super constructor will get a new defer
constructor if it doesn't already have one.
@throws CannotCompileException If an unexpected compilation error occurs.
|
[
"Create",
"a",
"defer",
"constructor",
"in",
"the",
"class",
"which",
"will",
"be",
"called",
"when",
"the",
"constructor",
"is",
"suppressed",
"."
] |
e8cd68026c284c6a7efe66959809eeebd8d1f9ad
|
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-core/src/main/java/org/powermock/core/transformers/javassist/support/PowerMockExpressionEditor.java#L210-L246
|
16,862
|
powermock/powermock
|
powermock-modules/powermock-module-junit4/src/main/java/org/powermock/modules/junit4/PowerMockRunner.java
|
PowerMockRunner.run
|
@Override
public void run(RunNotifier notifier) {
Description description = getDescription();
try {
super.run(notifier);
} finally {
try {
Whitebox.setInternalState(description, "fAnnotations", new Annotation[]{});
} catch (RuntimeException err) {
if (err.getCause() instanceof java.lang.NoSuchFieldException
&& err.getCause().getMessage().equals("modifiers")) {
// on JDK12 you cannot change 'modifiers'
} else {
throw err;
}
}
}
}
|
java
|
@Override
public void run(RunNotifier notifier) {
Description description = getDescription();
try {
super.run(notifier);
} finally {
try {
Whitebox.setInternalState(description, "fAnnotations", new Annotation[]{});
} catch (RuntimeException err) {
if (err.getCause() instanceof java.lang.NoSuchFieldException
&& err.getCause().getMessage().equals("modifiers")) {
// on JDK12 you cannot change 'modifiers'
} else {
throw err;
}
}
}
}
|
[
"@",
"Override",
"public",
"void",
"run",
"(",
"RunNotifier",
"notifier",
")",
"{",
"Description",
"description",
"=",
"getDescription",
"(",
")",
";",
"try",
"{",
"super",
".",
"run",
"(",
"notifier",
")",
";",
"}",
"finally",
"{",
"try",
"{",
"Whitebox",
".",
"setInternalState",
"(",
"description",
",",
"\"fAnnotations\"",
",",
"new",
"Annotation",
"[",
"]",
"{",
"}",
")",
";",
"}",
"catch",
"(",
"RuntimeException",
"err",
")",
"{",
"if",
"(",
"err",
".",
"getCause",
"(",
")",
"instanceof",
"java",
".",
"lang",
".",
"NoSuchFieldException",
"&&",
"err",
".",
"getCause",
"(",
")",
".",
"getMessage",
"(",
")",
".",
"equals",
"(",
"\"modifiers\"",
")",
")",
"{",
"// on JDK12 you cannot change 'modifiers'",
"}",
"else",
"{",
"throw",
"err",
";",
"}",
"}",
"}",
"}"
] |
Clean up some state to avoid OOM issues
|
[
"Clean",
"up",
"some",
"state",
"to",
"avoid",
"OOM",
"issues"
] |
e8cd68026c284c6a7efe66959809eeebd8d1f9ad
|
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-modules/powermock-module-junit4/src/main/java/org/powermock/modules/junit4/PowerMockRunner.java#L55-L72
|
16,863
|
powermock/powermock
|
powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java
|
WhiteboxImpl.getField
|
@SuppressWarnings({"unchecked", "rawtypes"})
public static Field getField(Class<?> type, String fieldName) {
LinkedList<Class<?>> examine = new LinkedList<Class<?>>();
examine.add(type);
Set<Class<?>> done = new HashSet<Class<?>>();
while (!examine.isEmpty()) {
Class<?> thisType = examine.removeFirst();
done.add(thisType);
final Field[] declaredField = thisType.getDeclaredFields();
for (Field field : declaredField) {
if (fieldName.equals(field.getName())) {
field.setAccessible(true);
return field;
}
}
Set<Class<?>> potential = new HashSet<Class<?>>();
final Class<?> clazz = thisType.getSuperclass();
if (clazz != null) {
potential.add(thisType.getSuperclass());
}
potential.addAll((Collection) Arrays.asList(thisType.getInterfaces()));
potential.removeAll(done);
examine.addAll(potential);
}
throwExceptionIfFieldWasNotFound(type, fieldName, null);
return null;
}
|
java
|
@SuppressWarnings({"unchecked", "rawtypes"})
public static Field getField(Class<?> type, String fieldName) {
LinkedList<Class<?>> examine = new LinkedList<Class<?>>();
examine.add(type);
Set<Class<?>> done = new HashSet<Class<?>>();
while (!examine.isEmpty()) {
Class<?> thisType = examine.removeFirst();
done.add(thisType);
final Field[] declaredField = thisType.getDeclaredFields();
for (Field field : declaredField) {
if (fieldName.equals(field.getName())) {
field.setAccessible(true);
return field;
}
}
Set<Class<?>> potential = new HashSet<Class<?>>();
final Class<?> clazz = thisType.getSuperclass();
if (clazz != null) {
potential.add(thisType.getSuperclass());
}
potential.addAll((Collection) Arrays.asList(thisType.getInterfaces()));
potential.removeAll(done);
examine.addAll(potential);
}
throwExceptionIfFieldWasNotFound(type, fieldName, null);
return null;
}
|
[
"@",
"SuppressWarnings",
"(",
"{",
"\"unchecked\"",
",",
"\"rawtypes\"",
"}",
")",
"public",
"static",
"Field",
"getField",
"(",
"Class",
"<",
"?",
">",
"type",
",",
"String",
"fieldName",
")",
"{",
"LinkedList",
"<",
"Class",
"<",
"?",
">",
">",
"examine",
"=",
"new",
"LinkedList",
"<",
"Class",
"<",
"?",
">",
">",
"(",
")",
";",
"examine",
".",
"add",
"(",
"type",
")",
";",
"Set",
"<",
"Class",
"<",
"?",
">",
">",
"done",
"=",
"new",
"HashSet",
"<",
"Class",
"<",
"?",
">",
">",
"(",
")",
";",
"while",
"(",
"!",
"examine",
".",
"isEmpty",
"(",
")",
")",
"{",
"Class",
"<",
"?",
">",
"thisType",
"=",
"examine",
".",
"removeFirst",
"(",
")",
";",
"done",
".",
"add",
"(",
"thisType",
")",
";",
"final",
"Field",
"[",
"]",
"declaredField",
"=",
"thisType",
".",
"getDeclaredFields",
"(",
")",
";",
"for",
"(",
"Field",
"field",
":",
"declaredField",
")",
"{",
"if",
"(",
"fieldName",
".",
"equals",
"(",
"field",
".",
"getName",
"(",
")",
")",
")",
"{",
"field",
".",
"setAccessible",
"(",
"true",
")",
";",
"return",
"field",
";",
"}",
"}",
"Set",
"<",
"Class",
"<",
"?",
">",
">",
"potential",
"=",
"new",
"HashSet",
"<",
"Class",
"<",
"?",
">",
">",
"(",
")",
";",
"final",
"Class",
"<",
"?",
">",
"clazz",
"=",
"thisType",
".",
"getSuperclass",
"(",
")",
";",
"if",
"(",
"clazz",
"!=",
"null",
")",
"{",
"potential",
".",
"add",
"(",
"thisType",
".",
"getSuperclass",
"(",
")",
")",
";",
"}",
"potential",
".",
"addAll",
"(",
"(",
"Collection",
")",
"Arrays",
".",
"asList",
"(",
"thisType",
".",
"getInterfaces",
"(",
")",
")",
")",
";",
"potential",
".",
"removeAll",
"(",
"done",
")",
";",
"examine",
".",
"addAll",
"(",
"potential",
")",
";",
"}",
"throwExceptionIfFieldWasNotFound",
"(",
"type",
",",
"fieldName",
",",
"null",
")",
";",
"return",
"null",
";",
"}"
] |
Convenience method to get a field from a class type.
The method will first try to look for a declared field in the same class.
If the method is not declared in this class it will look for the field in
the super class. This will continue throughout the whole class hierarchy.
If the field is not found an {@link IllegalArgumentException} is thrown.
@param type The type of the class where the method is located.
@param fieldName The method names.
@return A .
|
[
"Convenience",
"method",
"to",
"get",
"a",
"field",
"from",
"a",
"class",
"type",
"."
] |
e8cd68026c284c6a7efe66959809eeebd8d1f9ad
|
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java#L198-L225
|
16,864
|
powermock/powermock
|
powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java
|
WhiteboxImpl.newInstance
|
@SuppressWarnings("unchecked")
public static <T> T newInstance(Class<T> classToInstantiate) {
int modifiers = classToInstantiate.getModifiers();
final Object object;
if (Modifier.isInterface(modifiers)) {
object = Proxy.newProxyInstance(WhiteboxImpl.class.getClassLoader(), new Class<?>[]{classToInstantiate},
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return TypeUtils.getDefaultValue(method.getReturnType());
}
});
} else if (classToInstantiate.isArray()) {
object = Array.newInstance(classToInstantiate.getComponentType(), 0);
} else if (Modifier.isAbstract(modifiers)) {
throw new IllegalArgumentException(
"Cannot instantiate an abstract class. Please use the ConcreteClassGenerator in PowerMock support to generate a concrete class first.");
} else {
Objenesis objenesis = new ObjenesisStd();
ObjectInstantiator thingyInstantiator = objenesis.getInstantiatorOf(classToInstantiate);
object = thingyInstantiator.newInstance();
}
return (T) object;
}
|
java
|
@SuppressWarnings("unchecked")
public static <T> T newInstance(Class<T> classToInstantiate) {
int modifiers = classToInstantiate.getModifiers();
final Object object;
if (Modifier.isInterface(modifiers)) {
object = Proxy.newProxyInstance(WhiteboxImpl.class.getClassLoader(), new Class<?>[]{classToInstantiate},
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return TypeUtils.getDefaultValue(method.getReturnType());
}
});
} else if (classToInstantiate.isArray()) {
object = Array.newInstance(classToInstantiate.getComponentType(), 0);
} else if (Modifier.isAbstract(modifiers)) {
throw new IllegalArgumentException(
"Cannot instantiate an abstract class. Please use the ConcreteClassGenerator in PowerMock support to generate a concrete class first.");
} else {
Objenesis objenesis = new ObjenesisStd();
ObjectInstantiator thingyInstantiator = objenesis.getInstantiatorOf(classToInstantiate);
object = thingyInstantiator.newInstance();
}
return (T) object;
}
|
[
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"static",
"<",
"T",
">",
"T",
"newInstance",
"(",
"Class",
"<",
"T",
">",
"classToInstantiate",
")",
"{",
"int",
"modifiers",
"=",
"classToInstantiate",
".",
"getModifiers",
"(",
")",
";",
"final",
"Object",
"object",
";",
"if",
"(",
"Modifier",
".",
"isInterface",
"(",
"modifiers",
")",
")",
"{",
"object",
"=",
"Proxy",
".",
"newProxyInstance",
"(",
"WhiteboxImpl",
".",
"class",
".",
"getClassLoader",
"(",
")",
",",
"new",
"Class",
"<",
"?",
">",
"[",
"]",
"{",
"classToInstantiate",
"}",
",",
"new",
"InvocationHandler",
"(",
")",
"{",
"@",
"Override",
"public",
"Object",
"invoke",
"(",
"Object",
"proxy",
",",
"Method",
"method",
",",
"Object",
"[",
"]",
"args",
")",
"throws",
"Throwable",
"{",
"return",
"TypeUtils",
".",
"getDefaultValue",
"(",
"method",
".",
"getReturnType",
"(",
")",
")",
";",
"}",
"}",
")",
";",
"}",
"else",
"if",
"(",
"classToInstantiate",
".",
"isArray",
"(",
")",
")",
"{",
"object",
"=",
"Array",
".",
"newInstance",
"(",
"classToInstantiate",
".",
"getComponentType",
"(",
")",
",",
"0",
")",
";",
"}",
"else",
"if",
"(",
"Modifier",
".",
"isAbstract",
"(",
"modifiers",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Cannot instantiate an abstract class. Please use the ConcreteClassGenerator in PowerMock support to generate a concrete class first.\"",
")",
";",
"}",
"else",
"{",
"Objenesis",
"objenesis",
"=",
"new",
"ObjenesisStd",
"(",
")",
";",
"ObjectInstantiator",
"thingyInstantiator",
"=",
"objenesis",
".",
"getInstantiatorOf",
"(",
"classToInstantiate",
")",
";",
"object",
"=",
"thingyInstantiator",
".",
"newInstance",
"(",
")",
";",
"}",
"return",
"(",
"T",
")",
"object",
";",
"}"
] |
Create a new instance of a class without invoking its constructor.
No byte-code manipulation is needed to perform this operation and thus
it's not necessary use the {@code PowerMockRunner} or
{@code PrepareForTest} annotation to use this functionality.
@param <T> The type of the instance to create.
@param classToInstantiate The type of the instance to create.
@return A new instance of type T, created without invoking the
constructor.
|
[
"Create",
"a",
"new",
"instance",
"of",
"a",
"class",
"without",
"invoking",
"its",
"constructor",
"."
] |
e8cd68026c284c6a7efe66959809eeebd8d1f9ad
|
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java#L239-L263
|
16,865
|
powermock/powermock
|
powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java
|
WhiteboxImpl.setInternalState
|
public static void setInternalState(Object object, String fieldName, Object value, Class<?> where) {
if (object == null || fieldName == null || fieldName.equals("") || fieldName.startsWith(" ")) {
throw new IllegalArgumentException("object, field name, and \"where\" must not be empty or null.");
}
final Field field = getField(fieldName, where);
try {
field.set(object, value);
} catch (Exception e) {
throw new RuntimeException("Internal Error: Failed to set field in method setInternalState.", e);
}
}
|
java
|
public static void setInternalState(Object object, String fieldName, Object value, Class<?> where) {
if (object == null || fieldName == null || fieldName.equals("") || fieldName.startsWith(" ")) {
throw new IllegalArgumentException("object, field name, and \"where\" must not be empty or null.");
}
final Field field = getField(fieldName, where);
try {
field.set(object, value);
} catch (Exception e) {
throw new RuntimeException("Internal Error: Failed to set field in method setInternalState.", e);
}
}
|
[
"public",
"static",
"void",
"setInternalState",
"(",
"Object",
"object",
",",
"String",
"fieldName",
",",
"Object",
"value",
",",
"Class",
"<",
"?",
">",
"where",
")",
"{",
"if",
"(",
"object",
"==",
"null",
"||",
"fieldName",
"==",
"null",
"||",
"fieldName",
".",
"equals",
"(",
"\"\"",
")",
"||",
"fieldName",
".",
"startsWith",
"(",
"\" \"",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"object, field name, and \\\"where\\\" must not be empty or null.\"",
")",
";",
"}",
"final",
"Field",
"field",
"=",
"getField",
"(",
"fieldName",
",",
"where",
")",
";",
"try",
"{",
"field",
".",
"set",
"(",
"object",
",",
"value",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"Internal Error: Failed to set field in method setInternalState.\"",
",",
"e",
")",
";",
"}",
"}"
] |
Set the value of a field using reflection. Use this method when you need
to specify in which class the field is declared. This is useful if you
have two fields in a class hierarchy that has the same name but you like
to modify the latter.
@param object the object to modify
@param fieldName the name of the field
@param value the new value of the field
@param where which class the field is defined
|
[
"Set",
"the",
"value",
"of",
"a",
"field",
"using",
"reflection",
".",
"Use",
"this",
"method",
"when",
"you",
"need",
"to",
"specify",
"in",
"which",
"class",
"the",
"field",
"is",
"declared",
".",
"This",
"is",
"useful",
"if",
"you",
"have",
"two",
"fields",
"in",
"a",
"class",
"hierarchy",
"that",
"has",
"the",
"same",
"name",
"but",
"you",
"like",
"to",
"modify",
"the",
"latter",
"."
] |
e8cd68026c284c6a7efe66959809eeebd8d1f9ad
|
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java#L399-L410
|
16,866
|
powermock/powermock
|
powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java
|
WhiteboxImpl.findField
|
private static Field findField(Object object, FieldMatcherStrategy strategy, Class<?> where) {
return findSingleFieldUsingStrategy(strategy, object, false, where);
}
|
java
|
private static Field findField(Object object, FieldMatcherStrategy strategy, Class<?> where) {
return findSingleFieldUsingStrategy(strategy, object, false, where);
}
|
[
"private",
"static",
"Field",
"findField",
"(",
"Object",
"object",
",",
"FieldMatcherStrategy",
"strategy",
",",
"Class",
"<",
"?",
">",
"where",
")",
"{",
"return",
"findSingleFieldUsingStrategy",
"(",
"strategy",
",",
"object",
",",
"false",
",",
"where",
")",
";",
"}"
] |
Find field.
@param object the object
@param strategy the strategy
@param where the where
@return the field
|
[
"Find",
"field",
"."
] |
e8cd68026c284c6a7efe66959809eeebd8d1f9ad
|
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java#L465-L467
|
16,867
|
powermock/powermock
|
powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java
|
WhiteboxImpl.findAllFieldsUsingStrategy
|
private static Set<Field> findAllFieldsUsingStrategy(FieldMatcherStrategy strategy, Object object,
boolean checkHierarchy, Class<?> startClass) {
assertObjectInGetInternalStateIsNotNull(object);
final Set<Field> foundFields = new LinkedHashSet<Field>();
while (startClass != null) {
final Field[] declaredFields = startClass.getDeclaredFields();
for (Field field : declaredFields) {
if (strategy.matches(field) && hasFieldProperModifier(object, field)) {
// TODO replace by the class
try {
field.setAccessible(true);
foundFields.add(field);
} catch (Exception ignored) {
// the InaccessibleObjectException is thrown in Java 9 in case
// if a field is private and a module is not open
}
}
}
if (!checkHierarchy) {
break;
}
startClass = startClass.getSuperclass();
}
return Collections.unmodifiableSet(foundFields);
}
|
java
|
private static Set<Field> findAllFieldsUsingStrategy(FieldMatcherStrategy strategy, Object object,
boolean checkHierarchy, Class<?> startClass) {
assertObjectInGetInternalStateIsNotNull(object);
final Set<Field> foundFields = new LinkedHashSet<Field>();
while (startClass != null) {
final Field[] declaredFields = startClass.getDeclaredFields();
for (Field field : declaredFields) {
if (strategy.matches(field) && hasFieldProperModifier(object, field)) {
// TODO replace by the class
try {
field.setAccessible(true);
foundFields.add(field);
} catch (Exception ignored) {
// the InaccessibleObjectException is thrown in Java 9 in case
// if a field is private and a module is not open
}
}
}
if (!checkHierarchy) {
break;
}
startClass = startClass.getSuperclass();
}
return Collections.unmodifiableSet(foundFields);
}
|
[
"private",
"static",
"Set",
"<",
"Field",
">",
"findAllFieldsUsingStrategy",
"(",
"FieldMatcherStrategy",
"strategy",
",",
"Object",
"object",
",",
"boolean",
"checkHierarchy",
",",
"Class",
"<",
"?",
">",
"startClass",
")",
"{",
"assertObjectInGetInternalStateIsNotNull",
"(",
"object",
")",
";",
"final",
"Set",
"<",
"Field",
">",
"foundFields",
"=",
"new",
"LinkedHashSet",
"<",
"Field",
">",
"(",
")",
";",
"while",
"(",
"startClass",
"!=",
"null",
")",
"{",
"final",
"Field",
"[",
"]",
"declaredFields",
"=",
"startClass",
".",
"getDeclaredFields",
"(",
")",
";",
"for",
"(",
"Field",
"field",
":",
"declaredFields",
")",
"{",
"if",
"(",
"strategy",
".",
"matches",
"(",
"field",
")",
"&&",
"hasFieldProperModifier",
"(",
"object",
",",
"field",
")",
")",
"{",
"// TODO replace by the class ",
"try",
"{",
"field",
".",
"setAccessible",
"(",
"true",
")",
";",
"foundFields",
".",
"add",
"(",
"field",
")",
";",
"}",
"catch",
"(",
"Exception",
"ignored",
")",
"{",
"// the InaccessibleObjectException is thrown in Java 9 in case",
"// if a field is private and a module is not open",
"}",
"}",
"}",
"if",
"(",
"!",
"checkHierarchy",
")",
"{",
"break",
";",
"}",
"startClass",
"=",
"startClass",
".",
"getSuperclass",
"(",
")",
";",
"}",
"return",
"Collections",
".",
"unmodifiableSet",
"(",
"foundFields",
")",
";",
"}"
] |
Find all fields using strategy.
@param strategy the strategy
@param object the object
@param checkHierarchy the check hierarchy
@param startClass the start class
@return the set
|
[
"Find",
"all",
"fields",
"using",
"strategy",
"."
] |
e8cd68026c284c6a7efe66959809eeebd8d1f9ad
|
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java#L516-L541
|
16,868
|
powermock/powermock
|
powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java
|
WhiteboxImpl.invokeMethod
|
@SuppressWarnings("unchecked")
public static synchronized <T> T invokeMethod(Object tested, Object... arguments) throws Exception {
return (T) doInvokeMethod(tested, null, null, arguments);
}
|
java
|
@SuppressWarnings("unchecked")
public static synchronized <T> T invokeMethod(Object tested, Object... arguments) throws Exception {
return (T) doInvokeMethod(tested, null, null, arguments);
}
|
[
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"static",
"synchronized",
"<",
"T",
">",
"T",
"invokeMethod",
"(",
"Object",
"tested",
",",
"Object",
"...",
"arguments",
")",
"throws",
"Exception",
"{",
"return",
"(",
"T",
")",
"doInvokeMethod",
"(",
"tested",
",",
"null",
",",
"null",
",",
"arguments",
")",
";",
"}"
] |
Invoke a private or inner class method without the need to specify the
method name. This is thus a more refactor friendly version of the
@param <T> the generic type
@param tested the tested
@param arguments the arguments
@return the t
@throws Exception the exception
{@link #invokeMethod(Object, String, Object...)} method and
is recommend over this method for that reason. This method
might be useful to test private methods.
|
[
"Invoke",
"a",
"private",
"or",
"inner",
"class",
"method",
"without",
"the",
"need",
"to",
"specify",
"the",
"method",
"name",
".",
"This",
"is",
"thus",
"a",
"more",
"refactor",
"friendly",
"version",
"of",
"the"
] |
e8cd68026c284c6a7efe66959809eeebd8d1f9ad
|
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java#L644-L647
|
16,869
|
powermock/powermock
|
powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java
|
WhiteboxImpl.invokeMethod
|
@SuppressWarnings("unchecked")
public static synchronized <T> T invokeMethod(Object tested, Class<?> declaringClass, String methodToExecute,
Object... arguments) throws Exception {
return (T) doInvokeMethod(tested, declaringClass, methodToExecute, arguments);
}
|
java
|
@SuppressWarnings("unchecked")
public static synchronized <T> T invokeMethod(Object tested, Class<?> declaringClass, String methodToExecute,
Object... arguments) throws Exception {
return (T) doInvokeMethod(tested, declaringClass, methodToExecute, arguments);
}
|
[
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"static",
"synchronized",
"<",
"T",
">",
"T",
"invokeMethod",
"(",
"Object",
"tested",
",",
"Class",
"<",
"?",
">",
"declaringClass",
",",
"String",
"methodToExecute",
",",
"Object",
"...",
"arguments",
")",
"throws",
"Exception",
"{",
"return",
"(",
"T",
")",
"doInvokeMethod",
"(",
"tested",
",",
"declaringClass",
",",
"methodToExecute",
",",
"arguments",
")",
";",
"}"
] |
Invoke a private or inner class method in that is located in a subclass
of the tested instance. This might be useful to test private methods.
@param <T> the generic type
@param tested the tested
@param declaringClass the declaring class
@param methodToExecute the method to execute
@param arguments the arguments
@return the t
@throws Exception Exception that may occur when invoking this method.
|
[
"Invoke",
"a",
"private",
"or",
"inner",
"class",
"method",
"in",
"that",
"is",
"located",
"in",
"a",
"subclass",
"of",
"the",
"tested",
"instance",
".",
"This",
"might",
"be",
"useful",
"to",
"test",
"private",
"methods",
"."
] |
e8cd68026c284c6a7efe66959809eeebd8d1f9ad
|
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java#L747-L751
|
16,870
|
powermock/powermock
|
powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java
|
WhiteboxImpl.invokeMethod
|
@SuppressWarnings("unchecked")
public static synchronized <T> T invokeMethod(Object object, Class<?> declaringClass, String methodToExecute,
Class<?>[] parameterTypes, Object... arguments) throws Exception {
if (object == null) {
throw new IllegalArgumentException("object cannot be null");
}
final Method methodToInvoke = getMethod(declaringClass, methodToExecute, parameterTypes);
// Invoke method
return (T) performMethodInvocation(object, methodToInvoke, arguments);
}
|
java
|
@SuppressWarnings("unchecked")
public static synchronized <T> T invokeMethod(Object object, Class<?> declaringClass, String methodToExecute,
Class<?>[] parameterTypes, Object... arguments) throws Exception {
if (object == null) {
throw new IllegalArgumentException("object cannot be null");
}
final Method methodToInvoke = getMethod(declaringClass, methodToExecute, parameterTypes);
// Invoke method
return (T) performMethodInvocation(object, methodToInvoke, arguments);
}
|
[
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"static",
"synchronized",
"<",
"T",
">",
"T",
"invokeMethod",
"(",
"Object",
"object",
",",
"Class",
"<",
"?",
">",
"declaringClass",
",",
"String",
"methodToExecute",
",",
"Class",
"<",
"?",
">",
"[",
"]",
"parameterTypes",
",",
"Object",
"...",
"arguments",
")",
"throws",
"Exception",
"{",
"if",
"(",
"object",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"object cannot be null\"",
")",
";",
"}",
"final",
"Method",
"methodToInvoke",
"=",
"getMethod",
"(",
"declaringClass",
",",
"methodToExecute",
",",
"parameterTypes",
")",
";",
"// Invoke method",
"return",
"(",
"T",
")",
"performMethodInvocation",
"(",
"object",
",",
"methodToInvoke",
",",
"arguments",
")",
";",
"}"
] |
Invoke a private method in that is located in a subclass of an instance.
This might be useful to test overloaded private methods.
Use this for overloaded methods only, if possible use
@param <T> the generic type
@param object the object
@param declaringClass the declaring class
@param methodToExecute the method to execute
@param parameterTypes the parameter types
@param arguments the arguments
@return the t
@throws Exception Exception that may occur when invoking this method.
{@link #invokeMethod(Object, Object...)} or
{@link #invokeMethod(Object, String, Object...)} instead.
|
[
"Invoke",
"a",
"private",
"method",
"in",
"that",
"is",
"located",
"in",
"a",
"subclass",
"of",
"an",
"instance",
".",
"This",
"might",
"be",
"useful",
"to",
"test",
"overloaded",
"private",
"methods",
"."
] |
e8cd68026c284c6a7efe66959809eeebd8d1f9ad
|
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java#L770-L780
|
16,871
|
powermock/powermock
|
powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java
|
WhiteboxImpl.doInvokeMethod
|
@SuppressWarnings("unchecked")
private static <T> T doInvokeMethod(Object tested, Class<?> declaringClass, String methodToExecute,
Object... arguments) throws Exception {
Method methodToInvoke = findMethodOrThrowException(tested, declaringClass, methodToExecute, arguments);
// Invoke test
return (T) performMethodInvocation(tested, methodToInvoke, arguments);
}
|
java
|
@SuppressWarnings("unchecked")
private static <T> T doInvokeMethod(Object tested, Class<?> declaringClass, String methodToExecute,
Object... arguments) throws Exception {
Method methodToInvoke = findMethodOrThrowException(tested, declaringClass, methodToExecute, arguments);
// Invoke test
return (T) performMethodInvocation(tested, methodToInvoke, arguments);
}
|
[
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"private",
"static",
"<",
"T",
">",
"T",
"doInvokeMethod",
"(",
"Object",
"tested",
",",
"Class",
"<",
"?",
">",
"declaringClass",
",",
"String",
"methodToExecute",
",",
"Object",
"...",
"arguments",
")",
"throws",
"Exception",
"{",
"Method",
"methodToInvoke",
"=",
"findMethodOrThrowException",
"(",
"tested",
",",
"declaringClass",
",",
"methodToExecute",
",",
"arguments",
")",
";",
"// Invoke test",
"return",
"(",
"T",
")",
"performMethodInvocation",
"(",
"tested",
",",
"methodToInvoke",
",",
"arguments",
")",
";",
"}"
] |
Do invoke method.
@param <T> the generic type
@param tested the tested
@param declaringClass the declaring class
@param methodToExecute the method to execute
@param arguments the arguments
@return the t
@throws Exception the exception
|
[
"Do",
"invoke",
"method",
"."
] |
e8cd68026c284c6a7efe66959809eeebd8d1f9ad
|
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java#L810-L817
|
16,872
|
powermock/powermock
|
powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java
|
WhiteboxImpl.findMethodOrThrowException
|
public static Method findMethodOrThrowException(Object tested, Class<?> declaringClass, String methodToExecute,
Object[] arguments){
if (tested == null) {
throw new IllegalArgumentException("The object to perform the operation on cannot be null.");
}
/*
* Get methods from the type if it's not mocked or from the super type
* if the tested object is mocked.
*/
Class<?> testedType = null;
if (isClass(tested)) {
testedType = (Class<?>) tested;
} else {
testedType = tested.getClass();
}
Method[] methods = null;
if (declaringClass == null) {
methods = getAllMethods(testedType);
} else {
methods = declaringClass.getDeclaredMethods();
}
Method potentialMethodToInvoke = null;
for (Method method : methods) {
if (methodToExecute == null || method.getName().equals(methodToExecute)) {
Class<?>[] paramTypes = method.getParameterTypes();
if ((arguments != null && (paramTypes.length == arguments.length))) {
if (paramTypes.length == 0) {
potentialMethodToInvoke = method;
break;
}
boolean methodFound = checkArgumentTypesMatchParameterTypes(method.isVarArgs(), paramTypes, arguments);
if (methodFound) {
if (potentialMethodToInvoke == null) {
potentialMethodToInvoke = method;
} else if (potentialMethodToInvoke.getName().equals(method.getName())) {
if (areAllArgumentsOfSameType(arguments) && potentialMethodToInvoke.getDeclaringClass() != method.getDeclaringClass()) {
// We've already found the method which means that "potentialMethodToInvoke" overrides "method".
return potentialMethodToInvoke;
} else {
// We've found an overloaded method
return getBestMethodCandidate(getType(tested), method.getName(), getTypes(arguments), false);
}
} else {
// A special case to be backward compatible
Method bestCandidateMethod = getMethodWithMostSpecificParameterTypes(method, potentialMethodToInvoke);
if (bestCandidateMethod != null) {
potentialMethodToInvoke = bestCandidateMethod;
continue;
}
/*
* We've already found a method match before, this
* means that PowerMock cannot determine which
* method to expect since there are two methods with
* the same name and the same number of arguments
* but one is using wrapper types.
*/
throwExceptionWhenMultipleMethodMatchesFound("argument parameter types", new Method[]{
potentialMethodToInvoke, method});
}
}
} else if (isPotentialVarArgsMethod(method, arguments)) {
if (potentialMethodToInvoke == null) {
potentialMethodToInvoke = method;
} else {
/*
* We've already found a method match before, this means
* that PowerMock cannot determine which method to
* expect since there are two methods with the same name
* and the same number of arguments but one is using
* wrapper types.
*/
throwExceptionWhenMultipleMethodMatchesFound("argument parameter types", new Method[]{
potentialMethodToInvoke, method});
}
break;
} else if (arguments != null && (paramTypes.length != arguments.length)) {
continue;
} else if (arguments == null && paramTypes.length == 1 && !paramTypes[0].isPrimitive()) {
potentialMethodToInvoke = method;
}
}
}
WhiteboxImpl.throwExceptionIfMethodWasNotFound(getType(tested), methodToExecute, potentialMethodToInvoke,
arguments);
return potentialMethodToInvoke;
}
|
java
|
public static Method findMethodOrThrowException(Object tested, Class<?> declaringClass, String methodToExecute,
Object[] arguments){
if (tested == null) {
throw new IllegalArgumentException("The object to perform the operation on cannot be null.");
}
/*
* Get methods from the type if it's not mocked or from the super type
* if the tested object is mocked.
*/
Class<?> testedType = null;
if (isClass(tested)) {
testedType = (Class<?>) tested;
} else {
testedType = tested.getClass();
}
Method[] methods = null;
if (declaringClass == null) {
methods = getAllMethods(testedType);
} else {
methods = declaringClass.getDeclaredMethods();
}
Method potentialMethodToInvoke = null;
for (Method method : methods) {
if (methodToExecute == null || method.getName().equals(methodToExecute)) {
Class<?>[] paramTypes = method.getParameterTypes();
if ((arguments != null && (paramTypes.length == arguments.length))) {
if (paramTypes.length == 0) {
potentialMethodToInvoke = method;
break;
}
boolean methodFound = checkArgumentTypesMatchParameterTypes(method.isVarArgs(), paramTypes, arguments);
if (methodFound) {
if (potentialMethodToInvoke == null) {
potentialMethodToInvoke = method;
} else if (potentialMethodToInvoke.getName().equals(method.getName())) {
if (areAllArgumentsOfSameType(arguments) && potentialMethodToInvoke.getDeclaringClass() != method.getDeclaringClass()) {
// We've already found the method which means that "potentialMethodToInvoke" overrides "method".
return potentialMethodToInvoke;
} else {
// We've found an overloaded method
return getBestMethodCandidate(getType(tested), method.getName(), getTypes(arguments), false);
}
} else {
// A special case to be backward compatible
Method bestCandidateMethod = getMethodWithMostSpecificParameterTypes(method, potentialMethodToInvoke);
if (bestCandidateMethod != null) {
potentialMethodToInvoke = bestCandidateMethod;
continue;
}
/*
* We've already found a method match before, this
* means that PowerMock cannot determine which
* method to expect since there are two methods with
* the same name and the same number of arguments
* but one is using wrapper types.
*/
throwExceptionWhenMultipleMethodMatchesFound("argument parameter types", new Method[]{
potentialMethodToInvoke, method});
}
}
} else if (isPotentialVarArgsMethod(method, arguments)) {
if (potentialMethodToInvoke == null) {
potentialMethodToInvoke = method;
} else {
/*
* We've already found a method match before, this means
* that PowerMock cannot determine which method to
* expect since there are two methods with the same name
* and the same number of arguments but one is using
* wrapper types.
*/
throwExceptionWhenMultipleMethodMatchesFound("argument parameter types", new Method[]{
potentialMethodToInvoke, method});
}
break;
} else if (arguments != null && (paramTypes.length != arguments.length)) {
continue;
} else if (arguments == null && paramTypes.length == 1 && !paramTypes[0].isPrimitive()) {
potentialMethodToInvoke = method;
}
}
}
WhiteboxImpl.throwExceptionIfMethodWasNotFound(getType(tested), methodToExecute, potentialMethodToInvoke,
arguments);
return potentialMethodToInvoke;
}
|
[
"public",
"static",
"Method",
"findMethodOrThrowException",
"(",
"Object",
"tested",
",",
"Class",
"<",
"?",
">",
"declaringClass",
",",
"String",
"methodToExecute",
",",
"Object",
"[",
"]",
"arguments",
")",
"{",
"if",
"(",
"tested",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"The object to perform the operation on cannot be null.\"",
")",
";",
"}",
"/*\n * Get methods from the type if it's not mocked or from the super type\n * if the tested object is mocked.\n */",
"Class",
"<",
"?",
">",
"testedType",
"=",
"null",
";",
"if",
"(",
"isClass",
"(",
"tested",
")",
")",
"{",
"testedType",
"=",
"(",
"Class",
"<",
"?",
">",
")",
"tested",
";",
"}",
"else",
"{",
"testedType",
"=",
"tested",
".",
"getClass",
"(",
")",
";",
"}",
"Method",
"[",
"]",
"methods",
"=",
"null",
";",
"if",
"(",
"declaringClass",
"==",
"null",
")",
"{",
"methods",
"=",
"getAllMethods",
"(",
"testedType",
")",
";",
"}",
"else",
"{",
"methods",
"=",
"declaringClass",
".",
"getDeclaredMethods",
"(",
")",
";",
"}",
"Method",
"potentialMethodToInvoke",
"=",
"null",
";",
"for",
"(",
"Method",
"method",
":",
"methods",
")",
"{",
"if",
"(",
"methodToExecute",
"==",
"null",
"||",
"method",
".",
"getName",
"(",
")",
".",
"equals",
"(",
"methodToExecute",
")",
")",
"{",
"Class",
"<",
"?",
">",
"[",
"]",
"paramTypes",
"=",
"method",
".",
"getParameterTypes",
"(",
")",
";",
"if",
"(",
"(",
"arguments",
"!=",
"null",
"&&",
"(",
"paramTypes",
".",
"length",
"==",
"arguments",
".",
"length",
")",
")",
")",
"{",
"if",
"(",
"paramTypes",
".",
"length",
"==",
"0",
")",
"{",
"potentialMethodToInvoke",
"=",
"method",
";",
"break",
";",
"}",
"boolean",
"methodFound",
"=",
"checkArgumentTypesMatchParameterTypes",
"(",
"method",
".",
"isVarArgs",
"(",
")",
",",
"paramTypes",
",",
"arguments",
")",
";",
"if",
"(",
"methodFound",
")",
"{",
"if",
"(",
"potentialMethodToInvoke",
"==",
"null",
")",
"{",
"potentialMethodToInvoke",
"=",
"method",
";",
"}",
"else",
"if",
"(",
"potentialMethodToInvoke",
".",
"getName",
"(",
")",
".",
"equals",
"(",
"method",
".",
"getName",
"(",
")",
")",
")",
"{",
"if",
"(",
"areAllArgumentsOfSameType",
"(",
"arguments",
")",
"&&",
"potentialMethodToInvoke",
".",
"getDeclaringClass",
"(",
")",
"!=",
"method",
".",
"getDeclaringClass",
"(",
")",
")",
"{",
"// We've already found the method which means that \"potentialMethodToInvoke\" overrides \"method\".",
"return",
"potentialMethodToInvoke",
";",
"}",
"else",
"{",
"// We've found an overloaded method",
"return",
"getBestMethodCandidate",
"(",
"getType",
"(",
"tested",
")",
",",
"method",
".",
"getName",
"(",
")",
",",
"getTypes",
"(",
"arguments",
")",
",",
"false",
")",
";",
"}",
"}",
"else",
"{",
"// A special case to be backward compatible",
"Method",
"bestCandidateMethod",
"=",
"getMethodWithMostSpecificParameterTypes",
"(",
"method",
",",
"potentialMethodToInvoke",
")",
";",
"if",
"(",
"bestCandidateMethod",
"!=",
"null",
")",
"{",
"potentialMethodToInvoke",
"=",
"bestCandidateMethod",
";",
"continue",
";",
"}",
"/*\n * We've already found a method match before, this\n * means that PowerMock cannot determine which\n * method to expect since there are two methods with\n * the same name and the same number of arguments\n * but one is using wrapper types.\n */",
"throwExceptionWhenMultipleMethodMatchesFound",
"(",
"\"argument parameter types\"",
",",
"new",
"Method",
"[",
"]",
"{",
"potentialMethodToInvoke",
",",
"method",
"}",
")",
";",
"}",
"}",
"}",
"else",
"if",
"(",
"isPotentialVarArgsMethod",
"(",
"method",
",",
"arguments",
")",
")",
"{",
"if",
"(",
"potentialMethodToInvoke",
"==",
"null",
")",
"{",
"potentialMethodToInvoke",
"=",
"method",
";",
"}",
"else",
"{",
"/*\n * We've already found a method match before, this means\n * that PowerMock cannot determine which method to\n * expect since there are two methods with the same name\n * and the same number of arguments but one is using\n * wrapper types.\n */",
"throwExceptionWhenMultipleMethodMatchesFound",
"(",
"\"argument parameter types\"",
",",
"new",
"Method",
"[",
"]",
"{",
"potentialMethodToInvoke",
",",
"method",
"}",
")",
";",
"}",
"break",
";",
"}",
"else",
"if",
"(",
"arguments",
"!=",
"null",
"&&",
"(",
"paramTypes",
".",
"length",
"!=",
"arguments",
".",
"length",
")",
")",
"{",
"continue",
";",
"}",
"else",
"if",
"(",
"arguments",
"==",
"null",
"&&",
"paramTypes",
".",
"length",
"==",
"1",
"&&",
"!",
"paramTypes",
"[",
"0",
"]",
".",
"isPrimitive",
"(",
")",
")",
"{",
"potentialMethodToInvoke",
"=",
"method",
";",
"}",
"}",
"}",
"WhiteboxImpl",
".",
"throwExceptionIfMethodWasNotFound",
"(",
"getType",
"(",
"tested",
")",
",",
"methodToExecute",
",",
"potentialMethodToInvoke",
",",
"arguments",
")",
";",
"return",
"potentialMethodToInvoke",
";",
"}"
] |
Finds and returns a certain method. If the method couldn't be found this
method delegates to
@param tested The instance or class containing the method.
@param declaringClass The class where the method is supposed to be declared (may be
{@code null}).
@param methodToExecute The method name. If {@code null} then method will be
looked up based on the argument types only.
@param arguments The arguments of the methods.
@return A single method.
@throws MethodNotFoundException if no method was found.
@throws TooManyMethodsFoundException if too methods matched.
@throws IllegalArgumentException if {@code tested} is null.
|
[
"Finds",
"and",
"returns",
"a",
"certain",
"method",
".",
"If",
"the",
"method",
"couldn",
"t",
"be",
"found",
"this",
"method",
"delegates",
"to"
] |
e8cd68026c284c6a7efe66959809eeebd8d1f9ad
|
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java#L834-L922
|
16,873
|
powermock/powermock
|
powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java
|
WhiteboxImpl.getTypes
|
private static Class<?>[] getTypes(Object[] arguments) {
Class<?>[] classes = new Class<?>[arguments.length];
for (int i = 0; i < arguments.length; i++) {
classes[i] = getType(arguments[i]);
}
return classes;
}
|
java
|
private static Class<?>[] getTypes(Object[] arguments) {
Class<?>[] classes = new Class<?>[arguments.length];
for (int i = 0; i < arguments.length; i++) {
classes[i] = getType(arguments[i]);
}
return classes;
}
|
[
"private",
"static",
"Class",
"<",
"?",
">",
"[",
"]",
"getTypes",
"(",
"Object",
"[",
"]",
"arguments",
")",
"{",
"Class",
"<",
"?",
">",
"[",
"]",
"classes",
"=",
"new",
"Class",
"<",
"?",
">",
"[",
"arguments",
".",
"length",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"arguments",
".",
"length",
";",
"i",
"++",
")",
"{",
"classes",
"[",
"i",
"]",
"=",
"getType",
"(",
"arguments",
"[",
"i",
"]",
")",
";",
"}",
"return",
"classes",
";",
"}"
] |
Gets the types.
@param arguments the arguments
@return the types
|
[
"Gets",
"the",
"types",
"."
] |
e8cd68026c284c6a7efe66959809eeebd8d1f9ad
|
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java#L975-L981
|
16,874
|
powermock/powermock
|
powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java
|
WhiteboxImpl.getBestMethodCandidate
|
public static Method getBestMethodCandidate(Class<?> cls, String methodName, Class<?>[] signature,
boolean exactParameterTypeMatch) {
final Method foundMethod;
final Method[] methods = getMethods(cls, methodName, signature, exactParameterTypeMatch);
if (methods.length == 1) {
foundMethod = methods[0];
} else {
// We've found overloaded methods, we need to find the best one to invoke.
Arrays.sort(methods, ComparatorFactory.createMethodComparator());
foundMethod = methods[0];
}
return foundMethod;
}
|
java
|
public static Method getBestMethodCandidate(Class<?> cls, String methodName, Class<?>[] signature,
boolean exactParameterTypeMatch) {
final Method foundMethod;
final Method[] methods = getMethods(cls, methodName, signature, exactParameterTypeMatch);
if (methods.length == 1) {
foundMethod = methods[0];
} else {
// We've found overloaded methods, we need to find the best one to invoke.
Arrays.sort(methods, ComparatorFactory.createMethodComparator());
foundMethod = methods[0];
}
return foundMethod;
}
|
[
"public",
"static",
"Method",
"getBestMethodCandidate",
"(",
"Class",
"<",
"?",
">",
"cls",
",",
"String",
"methodName",
",",
"Class",
"<",
"?",
">",
"[",
"]",
"signature",
",",
"boolean",
"exactParameterTypeMatch",
")",
"{",
"final",
"Method",
"foundMethod",
";",
"final",
"Method",
"[",
"]",
"methods",
"=",
"getMethods",
"(",
"cls",
",",
"methodName",
",",
"signature",
",",
"exactParameterTypeMatch",
")",
";",
"if",
"(",
"methods",
".",
"length",
"==",
"1",
")",
"{",
"foundMethod",
"=",
"methods",
"[",
"0",
"]",
";",
"}",
"else",
"{",
"// We've found overloaded methods, we need to find the best one to invoke.",
"Arrays",
".",
"sort",
"(",
"methods",
",",
"ComparatorFactory",
".",
"createMethodComparator",
"(",
")",
")",
";",
"foundMethod",
"=",
"methods",
"[",
"0",
"]",
";",
"}",
"return",
"foundMethod",
";",
"}"
] |
Gets the best method candidate.
@param cls the cls
@param methodName the method name
@param signature the signature
@param exactParameterTypeMatch {@code true} if the {@code expectedTypes} must match
the parameter types must match exactly, {@code false} if
the {@code expectedTypes} are allowed to be converted
into primitive types if they are of a wrapped type and still
match.
@return the best method candidate
|
[
"Gets",
"the",
"best",
"method",
"candidate",
"."
] |
e8cd68026c284c6a7efe66959809eeebd8d1f9ad
|
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java#L996-L1008
|
16,875
|
powermock/powermock
|
powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java
|
WhiteboxImpl.filterPowerMockConstructor
|
static Constructor<?>[] filterPowerMockConstructor(Constructor<?>[] declaredConstructors) {
Set<Constructor<?>> constructors = new HashSet<Constructor<?>>();
for (Constructor<?> constructor : declaredConstructors) {
final Class<?>[] parameterTypes = constructor.getParameterTypes();
if (parameterTypes.length >= 1
&& parameterTypes[parameterTypes.length - 1].getName().equals(
"org.powermock.core.IndicateReloadClass")) {
continue;
} else {
constructors.add(constructor);
}
}
return constructors.toArray(new Constructor<?>[constructors.size()]);
}
|
java
|
static Constructor<?>[] filterPowerMockConstructor(Constructor<?>[] declaredConstructors) {
Set<Constructor<?>> constructors = new HashSet<Constructor<?>>();
for (Constructor<?> constructor : declaredConstructors) {
final Class<?>[] parameterTypes = constructor.getParameterTypes();
if (parameterTypes.length >= 1
&& parameterTypes[parameterTypes.length - 1].getName().equals(
"org.powermock.core.IndicateReloadClass")) {
continue;
} else {
constructors.add(constructor);
}
}
return constructors.toArray(new Constructor<?>[constructors.size()]);
}
|
[
"static",
"Constructor",
"<",
"?",
">",
"[",
"]",
"filterPowerMockConstructor",
"(",
"Constructor",
"<",
"?",
">",
"[",
"]",
"declaredConstructors",
")",
"{",
"Set",
"<",
"Constructor",
"<",
"?",
">",
">",
"constructors",
"=",
"new",
"HashSet",
"<",
"Constructor",
"<",
"?",
">",
">",
"(",
")",
";",
"for",
"(",
"Constructor",
"<",
"?",
">",
"constructor",
":",
"declaredConstructors",
")",
"{",
"final",
"Class",
"<",
"?",
">",
"[",
"]",
"parameterTypes",
"=",
"constructor",
".",
"getParameterTypes",
"(",
")",
";",
"if",
"(",
"parameterTypes",
".",
"length",
">=",
"1",
"&&",
"parameterTypes",
"[",
"parameterTypes",
".",
"length",
"-",
"1",
"]",
".",
"getName",
"(",
")",
".",
"equals",
"(",
"\"org.powermock.core.IndicateReloadClass\"",
")",
")",
"{",
"continue",
";",
"}",
"else",
"{",
"constructors",
".",
"add",
"(",
"constructor",
")",
";",
"}",
"}",
"return",
"constructors",
".",
"toArray",
"(",
"new",
"Constructor",
"<",
"?",
">",
"[",
"constructors",
".",
"size",
"(",
")",
"]",
")",
";",
"}"
] |
Filter power mock constructor.
@param declaredConstructors the declared constructors
@return the constructor[]
|
[
"Filter",
"power",
"mock",
"constructor",
"."
] |
e8cd68026c284c6a7efe66959809eeebd8d1f9ad
|
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java#L1055-L1068
|
16,876
|
powermock/powermock
|
powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java
|
WhiteboxImpl.findUniqueConstructorOrThrowException
|
public static Constructor<?> findUniqueConstructorOrThrowException(Class<?> type, Object... arguments) {
return new ConstructorFinder(type, arguments).findConstructor();
}
|
java
|
public static Constructor<?> findUniqueConstructorOrThrowException(Class<?> type, Object... arguments) {
return new ConstructorFinder(type, arguments).findConstructor();
}
|
[
"public",
"static",
"Constructor",
"<",
"?",
">",
"findUniqueConstructorOrThrowException",
"(",
"Class",
"<",
"?",
">",
"type",
",",
"Object",
"...",
"arguments",
")",
"{",
"return",
"new",
"ConstructorFinder",
"(",
"type",
",",
"arguments",
")",
".",
"findConstructor",
"(",
")",
";",
"}"
] |
Finds and returns a certain constructor. If the constructor couldn't be
found this method delegates to
@param type The type where the constructor should be located.
@param arguments The arguments passed to the constructor.
@return The found constructor.
@throws ConstructorNotFoundException if no constructor was found.
@throws TooManyConstructorsFoundException if too constructors matched.
@throws IllegalArgumentException if {@code type} is null.
|
[
"Finds",
"and",
"returns",
"a",
"certain",
"constructor",
".",
"If",
"the",
"constructor",
"couldn",
"t",
"be",
"found",
"this",
"method",
"delegates",
"to"
] |
e8cd68026c284c6a7efe66959809eeebd8d1f9ad
|
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java#L1081-L1083
|
16,877
|
powermock/powermock
|
powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java
|
WhiteboxImpl.convertArgumentTypesToPrimitive
|
private static Class<?>[] convertArgumentTypesToPrimitive(Class<?>[] paramTypes, Object[] arguments) {
Class<?>[] types = new Class<?>[arguments.length];
for (int i = 0; i < arguments.length; i++) {
Class<?> argumentType = null;
if (arguments[i] == null) {
argumentType = paramTypes[i];
} else {
argumentType = getType(arguments[i]);
}
Class<?> primitiveWrapperType = PrimitiveWrapper.getPrimitiveFromWrapperType(argumentType);
if (primitiveWrapperType == null) {
types[i] = argumentType;
} else {
types[i] = primitiveWrapperType;
}
}
return types;
}
|
java
|
private static Class<?>[] convertArgumentTypesToPrimitive(Class<?>[] paramTypes, Object[] arguments) {
Class<?>[] types = new Class<?>[arguments.length];
for (int i = 0; i < arguments.length; i++) {
Class<?> argumentType = null;
if (arguments[i] == null) {
argumentType = paramTypes[i];
} else {
argumentType = getType(arguments[i]);
}
Class<?> primitiveWrapperType = PrimitiveWrapper.getPrimitiveFromWrapperType(argumentType);
if (primitiveWrapperType == null) {
types[i] = argumentType;
} else {
types[i] = primitiveWrapperType;
}
}
return types;
}
|
[
"private",
"static",
"Class",
"<",
"?",
">",
"[",
"]",
"convertArgumentTypesToPrimitive",
"(",
"Class",
"<",
"?",
">",
"[",
"]",
"paramTypes",
",",
"Object",
"[",
"]",
"arguments",
")",
"{",
"Class",
"<",
"?",
">",
"[",
"]",
"types",
"=",
"new",
"Class",
"<",
"?",
">",
"[",
"arguments",
".",
"length",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"arguments",
".",
"length",
";",
"i",
"++",
")",
"{",
"Class",
"<",
"?",
">",
"argumentType",
"=",
"null",
";",
"if",
"(",
"arguments",
"[",
"i",
"]",
"==",
"null",
")",
"{",
"argumentType",
"=",
"paramTypes",
"[",
"i",
"]",
";",
"}",
"else",
"{",
"argumentType",
"=",
"getType",
"(",
"arguments",
"[",
"i",
"]",
")",
";",
"}",
"Class",
"<",
"?",
">",
"primitiveWrapperType",
"=",
"PrimitiveWrapper",
".",
"getPrimitiveFromWrapperType",
"(",
"argumentType",
")",
";",
"if",
"(",
"primitiveWrapperType",
"==",
"null",
")",
"{",
"types",
"[",
"i",
"]",
"=",
"argumentType",
";",
"}",
"else",
"{",
"types",
"[",
"i",
"]",
"=",
"primitiveWrapperType",
";",
"}",
"}",
"return",
"types",
";",
"}"
] |
Convert argument types to primitive.
@param paramTypes the param types
@param arguments the arguments
@return the class[]
|
[
"Convert",
"argument",
"types",
"to",
"primitive",
"."
] |
e8cd68026c284c6a7efe66959809eeebd8d1f9ad
|
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java#L1092-L1109
|
16,878
|
powermock/powermock
|
powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java
|
WhiteboxImpl.throwExceptionIfMethodWasNotFound
|
public static void throwExceptionIfMethodWasNotFound(Class<?> type, String methodName, Method methodToMock,
Object... arguments) {
if (methodToMock == null) {
String methodNameData = "";
if (methodName != null) {
methodNameData = "with name '" + methodName + "' ";
}
throw new MethodNotFoundException("No method found " + methodNameData + "with parameter types: [ "
+ getArgumentTypesAsString(arguments) + " ] in class " + getOriginalUnmockedType(type)
.getName() + ".");
}
}
|
java
|
public static void throwExceptionIfMethodWasNotFound(Class<?> type, String methodName, Method methodToMock,
Object... arguments) {
if (methodToMock == null) {
String methodNameData = "";
if (methodName != null) {
methodNameData = "with name '" + methodName + "' ";
}
throw new MethodNotFoundException("No method found " + methodNameData + "with parameter types: [ "
+ getArgumentTypesAsString(arguments) + " ] in class " + getOriginalUnmockedType(type)
.getName() + ".");
}
}
|
[
"public",
"static",
"void",
"throwExceptionIfMethodWasNotFound",
"(",
"Class",
"<",
"?",
">",
"type",
",",
"String",
"methodName",
",",
"Method",
"methodToMock",
",",
"Object",
"...",
"arguments",
")",
"{",
"if",
"(",
"methodToMock",
"==",
"null",
")",
"{",
"String",
"methodNameData",
"=",
"\"\"",
";",
"if",
"(",
"methodName",
"!=",
"null",
")",
"{",
"methodNameData",
"=",
"\"with name '\"",
"+",
"methodName",
"+",
"\"' \"",
";",
"}",
"throw",
"new",
"MethodNotFoundException",
"(",
"\"No method found \"",
"+",
"methodNameData",
"+",
"\"with parameter types: [ \"",
"+",
"getArgumentTypesAsString",
"(",
"arguments",
")",
"+",
"\" ] in class \"",
"+",
"getOriginalUnmockedType",
"(",
"type",
")",
".",
"getName",
"(",
")",
"+",
"\".\"",
")",
";",
"}",
"}"
] |
Throw exception if method was not found.
@param type the type
@param methodName the method name
@param methodToMock the method to mock
@param arguments the arguments
|
[
"Throw",
"exception",
"if",
"method",
"was",
"not",
"found",
"."
] |
e8cd68026c284c6a7efe66959809eeebd8d1f9ad
|
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java#L1119-L1130
|
16,879
|
powermock/powermock
|
powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java
|
WhiteboxImpl.throwExceptionIfConstructorWasNotFound
|
static void throwExceptionIfConstructorWasNotFound(Class<?> type, Constructor<?> potentialConstructor,
Object... arguments) {
if (potentialConstructor == null) {
String message = "No constructor found in class '" + getOriginalUnmockedType(type).getName() + "' with "
+ "parameter types: [ " + getArgumentTypesAsString(arguments) + " ].";
throw new ConstructorNotFoundException(message);
}
}
|
java
|
static void throwExceptionIfConstructorWasNotFound(Class<?> type, Constructor<?> potentialConstructor,
Object... arguments) {
if (potentialConstructor == null) {
String message = "No constructor found in class '" + getOriginalUnmockedType(type).getName() + "' with "
+ "parameter types: [ " + getArgumentTypesAsString(arguments) + " ].";
throw new ConstructorNotFoundException(message);
}
}
|
[
"static",
"void",
"throwExceptionIfConstructorWasNotFound",
"(",
"Class",
"<",
"?",
">",
"type",
",",
"Constructor",
"<",
"?",
">",
"potentialConstructor",
",",
"Object",
"...",
"arguments",
")",
"{",
"if",
"(",
"potentialConstructor",
"==",
"null",
")",
"{",
"String",
"message",
"=",
"\"No constructor found in class '\"",
"+",
"getOriginalUnmockedType",
"(",
"type",
")",
".",
"getName",
"(",
")",
"+",
"\"' with \"",
"+",
"\"parameter types: [ \"",
"+",
"getArgumentTypesAsString",
"(",
"arguments",
")",
"+",
"\" ].\"",
";",
"throw",
"new",
"ConstructorNotFoundException",
"(",
"message",
")",
";",
"}",
"}"
] |
Throw exception if constructor was not found.
@param type the type
@param potentialConstructor the potential constructor
@param arguments the arguments
|
[
"Throw",
"exception",
"if",
"constructor",
"was",
"not",
"found",
"."
] |
e8cd68026c284c6a7efe66959809eeebd8d1f9ad
|
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java#L1153-L1160
|
16,880
|
powermock/powermock
|
powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java
|
WhiteboxImpl.getArgumentTypesAsString
|
static String getArgumentTypesAsString(Object... arguments) {
StringBuilder argumentsAsString = new StringBuilder();
final String noParameters = "<none>";
if (arguments != null && arguments.length != 0) {
for (int i = 0; i < arguments.length; i++) {
String argumentName = null;
Object argument = arguments[i];
if (argument instanceof Class<?>) {
argumentName = ((Class<?>) argument).getName();
} else if (argument instanceof Class<?>[] && arguments.length == 1) {
Class<?>[] argumentArray = (Class<?>[]) argument;
if (argumentArray.length > 0) {
for (int j = 0; j < argumentArray.length; j++) {
appendArgument(argumentsAsString, j,
argumentArray[j] == null ? "null" : getUnproxyType(argumentArray[j]).getName(),
argumentArray);
}
return argumentsAsString.toString();
} else {
argumentName = noParameters;
}
} else if (argument == null) {
argumentName = "null";
} else {
argumentName = getUnproxyType(argument).getName();
}
appendArgument(argumentsAsString, i, argumentName, arguments);
}
} else {
argumentsAsString.append("<none>");
}
return argumentsAsString.toString();
}
|
java
|
static String getArgumentTypesAsString(Object... arguments) {
StringBuilder argumentsAsString = new StringBuilder();
final String noParameters = "<none>";
if (arguments != null && arguments.length != 0) {
for (int i = 0; i < arguments.length; i++) {
String argumentName = null;
Object argument = arguments[i];
if (argument instanceof Class<?>) {
argumentName = ((Class<?>) argument).getName();
} else if (argument instanceof Class<?>[] && arguments.length == 1) {
Class<?>[] argumentArray = (Class<?>[]) argument;
if (argumentArray.length > 0) {
for (int j = 0; j < argumentArray.length; j++) {
appendArgument(argumentsAsString, j,
argumentArray[j] == null ? "null" : getUnproxyType(argumentArray[j]).getName(),
argumentArray);
}
return argumentsAsString.toString();
} else {
argumentName = noParameters;
}
} else if (argument == null) {
argumentName = "null";
} else {
argumentName = getUnproxyType(argument).getName();
}
appendArgument(argumentsAsString, i, argumentName, arguments);
}
} else {
argumentsAsString.append("<none>");
}
return argumentsAsString.toString();
}
|
[
"static",
"String",
"getArgumentTypesAsString",
"(",
"Object",
"...",
"arguments",
")",
"{",
"StringBuilder",
"argumentsAsString",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"final",
"String",
"noParameters",
"=",
"\"<none>\"",
";",
"if",
"(",
"arguments",
"!=",
"null",
"&&",
"arguments",
".",
"length",
"!=",
"0",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"arguments",
".",
"length",
";",
"i",
"++",
")",
"{",
"String",
"argumentName",
"=",
"null",
";",
"Object",
"argument",
"=",
"arguments",
"[",
"i",
"]",
";",
"if",
"(",
"argument",
"instanceof",
"Class",
"<",
"?",
">",
")",
"{",
"argumentName",
"=",
"(",
"(",
"Class",
"<",
"?",
">",
")",
"argument",
")",
".",
"getName",
"(",
")",
";",
"}",
"else",
"if",
"(",
"argument",
"instanceof",
"Class",
"<",
"?",
">",
"[",
"]",
"&&",
"arguments",
".",
"length",
"==",
"1",
")",
"{",
"Class",
"<",
"?",
">",
"[",
"]",
"argumentArray",
"=",
"(",
"Class",
"<",
"?",
">",
"[",
"]",
")",
"argument",
";",
"if",
"(",
"argumentArray",
".",
"length",
">",
"0",
")",
"{",
"for",
"(",
"int",
"j",
"=",
"0",
";",
"j",
"<",
"argumentArray",
".",
"length",
";",
"j",
"++",
")",
"{",
"appendArgument",
"(",
"argumentsAsString",
",",
"j",
",",
"argumentArray",
"[",
"j",
"]",
"==",
"null",
"?",
"\"null\"",
":",
"getUnproxyType",
"(",
"argumentArray",
"[",
"j",
"]",
")",
".",
"getName",
"(",
")",
",",
"argumentArray",
")",
";",
"}",
"return",
"argumentsAsString",
".",
"toString",
"(",
")",
";",
"}",
"else",
"{",
"argumentName",
"=",
"noParameters",
";",
"}",
"}",
"else",
"if",
"(",
"argument",
"==",
"null",
")",
"{",
"argumentName",
"=",
"\"null\"",
";",
"}",
"else",
"{",
"argumentName",
"=",
"getUnproxyType",
"(",
"argument",
")",
".",
"getName",
"(",
")",
";",
"}",
"appendArgument",
"(",
"argumentsAsString",
",",
"i",
",",
"argumentName",
",",
"arguments",
")",
";",
"}",
"}",
"else",
"{",
"argumentsAsString",
".",
"append",
"(",
"\"<none>\"",
")",
";",
"}",
"return",
"argumentsAsString",
".",
"toString",
"(",
")",
";",
"}"
] |
Gets the argument types as string.
@param arguments the arguments
@return the argument types as string
|
[
"Gets",
"the",
"argument",
"types",
"as",
"string",
"."
] |
e8cd68026c284c6a7efe66959809eeebd8d1f9ad
|
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java#L1168-L1201
|
16,881
|
powermock/powermock
|
powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java
|
WhiteboxImpl.appendArgument
|
private static void appendArgument(StringBuilder argumentsAsString, int index, String argumentName,
Object[] arguments) {
argumentsAsString.append(argumentName);
if (index != arguments.length - 1) {
argumentsAsString.append(", ");
}
}
|
java
|
private static void appendArgument(StringBuilder argumentsAsString, int index, String argumentName,
Object[] arguments) {
argumentsAsString.append(argumentName);
if (index != arguments.length - 1) {
argumentsAsString.append(", ");
}
}
|
[
"private",
"static",
"void",
"appendArgument",
"(",
"StringBuilder",
"argumentsAsString",
",",
"int",
"index",
",",
"String",
"argumentName",
",",
"Object",
"[",
"]",
"arguments",
")",
"{",
"argumentsAsString",
".",
"append",
"(",
"argumentName",
")",
";",
"if",
"(",
"index",
"!=",
"arguments",
".",
"length",
"-",
"1",
")",
"{",
"argumentsAsString",
".",
"append",
"(",
"\", \"",
")",
";",
"}",
"}"
] |
Append argument.
@param argumentsAsString the arguments as string
@param index the index
@param argumentName the argument name
@param arguments the arguments
|
[
"Append",
"argument",
"."
] |
e8cd68026c284c6a7efe66959809eeebd8d1f9ad
|
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java#L1211-L1217
|
16,882
|
powermock/powermock
|
powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java
|
WhiteboxImpl.invokeConstructor
|
public static <T> T invokeConstructor(Class<T> classThatContainsTheConstructorToTest, Object... arguments)
throws Exception {
if (classThatContainsTheConstructorToTest == null) {
throw new IllegalArgumentException("The class should contain the constructor cannot be null.");
}
Class<?>[] argumentTypes = null;
if (arguments == null) {
argumentTypes = new Class<?>[0];
} else {
argumentTypes = new Class<?>[arguments.length];
for (int i = 0; i < arguments.length; i++) {
argumentTypes[i] = getType(arguments[i]);
}
}
Constructor<T> constructor = null;
constructor = getBestCandidateConstructor(classThatContainsTheConstructorToTest, argumentTypes, arguments);
return createInstance(constructor, arguments);
}
|
java
|
public static <T> T invokeConstructor(Class<T> classThatContainsTheConstructorToTest, Object... arguments)
throws Exception {
if (classThatContainsTheConstructorToTest == null) {
throw new IllegalArgumentException("The class should contain the constructor cannot be null.");
}
Class<?>[] argumentTypes = null;
if (arguments == null) {
argumentTypes = new Class<?>[0];
} else {
argumentTypes = new Class<?>[arguments.length];
for (int i = 0; i < arguments.length; i++) {
argumentTypes[i] = getType(arguments[i]);
}
}
Constructor<T> constructor = null;
constructor = getBestCandidateConstructor(classThatContainsTheConstructorToTest, argumentTypes, arguments);
return createInstance(constructor, arguments);
}
|
[
"public",
"static",
"<",
"T",
">",
"T",
"invokeConstructor",
"(",
"Class",
"<",
"T",
">",
"classThatContainsTheConstructorToTest",
",",
"Object",
"...",
"arguments",
")",
"throws",
"Exception",
"{",
"if",
"(",
"classThatContainsTheConstructorToTest",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"The class should contain the constructor cannot be null.\"",
")",
";",
"}",
"Class",
"<",
"?",
">",
"[",
"]",
"argumentTypes",
"=",
"null",
";",
"if",
"(",
"arguments",
"==",
"null",
")",
"{",
"argumentTypes",
"=",
"new",
"Class",
"<",
"?",
">",
"[",
"0",
"]",
";",
"}",
"else",
"{",
"argumentTypes",
"=",
"new",
"Class",
"<",
"?",
">",
"[",
"arguments",
".",
"length",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"arguments",
".",
"length",
";",
"i",
"++",
")",
"{",
"argumentTypes",
"[",
"i",
"]",
"=",
"getType",
"(",
"arguments",
"[",
"i",
"]",
")",
";",
"}",
"}",
"Constructor",
"<",
"T",
">",
"constructor",
"=",
"null",
";",
"constructor",
"=",
"getBestCandidateConstructor",
"(",
"classThatContainsTheConstructorToTest",
",",
"argumentTypes",
",",
"arguments",
")",
";",
"return",
"createInstance",
"(",
"constructor",
",",
"arguments",
")",
";",
"}"
] |
Invoke a constructor. Useful for testing classes with a private
constructor.
@param <T> the generic type
@param classThatContainsTheConstructorToTest the class that contains the constructor to test
@param arguments the arguments
@return The object created after the constructor has been invoked.
@throws Exception If an exception occur when invoking the constructor.
|
[
"Invoke",
"a",
"constructor",
".",
"Useful",
"for",
"testing",
"classes",
"with",
"a",
"private",
"constructor",
"."
] |
e8cd68026c284c6a7efe66959809eeebd8d1f9ad
|
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java#L1275-L1297
|
16,883
|
powermock/powermock
|
powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java
|
WhiteboxImpl.getPotentialVarArgsConstructor
|
@SuppressWarnings("unchecked")
private static <T> Constructor<T> getPotentialVarArgsConstructor(Class<T> classThatContainsTheConstructorToTest,
Object... arguments) {
Constructor<T>[] declaredConstructors = (Constructor<T>[]) classThatContainsTheConstructorToTest
.getDeclaredConstructors();
for (Constructor<T> possibleVarArgsConstructor : declaredConstructors) {
if (possibleVarArgsConstructor.isVarArgs()) {
if (arguments == null || arguments.length == 0) {
return possibleVarArgsConstructor;
} else {
Class<?>[] parameterTypes = possibleVarArgsConstructor.getParameterTypes();
if (parameterTypes[parameterTypes.length - 1].getComponentType().isAssignableFrom(
getType(arguments[0]))) {
return possibleVarArgsConstructor;
}
}
}
}
return null;
}
|
java
|
@SuppressWarnings("unchecked")
private static <T> Constructor<T> getPotentialVarArgsConstructor(Class<T> classThatContainsTheConstructorToTest,
Object... arguments) {
Constructor<T>[] declaredConstructors = (Constructor<T>[]) classThatContainsTheConstructorToTest
.getDeclaredConstructors();
for (Constructor<T> possibleVarArgsConstructor : declaredConstructors) {
if (possibleVarArgsConstructor.isVarArgs()) {
if (arguments == null || arguments.length == 0) {
return possibleVarArgsConstructor;
} else {
Class<?>[] parameterTypes = possibleVarArgsConstructor.getParameterTypes();
if (parameterTypes[parameterTypes.length - 1].getComponentType().isAssignableFrom(
getType(arguments[0]))) {
return possibleVarArgsConstructor;
}
}
}
}
return null;
}
|
[
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"private",
"static",
"<",
"T",
">",
"Constructor",
"<",
"T",
">",
"getPotentialVarArgsConstructor",
"(",
"Class",
"<",
"T",
">",
"classThatContainsTheConstructorToTest",
",",
"Object",
"...",
"arguments",
")",
"{",
"Constructor",
"<",
"T",
">",
"[",
"]",
"declaredConstructors",
"=",
"(",
"Constructor",
"<",
"T",
">",
"[",
"]",
")",
"classThatContainsTheConstructorToTest",
".",
"getDeclaredConstructors",
"(",
")",
";",
"for",
"(",
"Constructor",
"<",
"T",
">",
"possibleVarArgsConstructor",
":",
"declaredConstructors",
")",
"{",
"if",
"(",
"possibleVarArgsConstructor",
".",
"isVarArgs",
"(",
")",
")",
"{",
"if",
"(",
"arguments",
"==",
"null",
"||",
"arguments",
".",
"length",
"==",
"0",
")",
"{",
"return",
"possibleVarArgsConstructor",
";",
"}",
"else",
"{",
"Class",
"<",
"?",
">",
"[",
"]",
"parameterTypes",
"=",
"possibleVarArgsConstructor",
".",
"getParameterTypes",
"(",
")",
";",
"if",
"(",
"parameterTypes",
"[",
"parameterTypes",
".",
"length",
"-",
"1",
"]",
".",
"getComponentType",
"(",
")",
".",
"isAssignableFrom",
"(",
"getType",
"(",
"arguments",
"[",
"0",
"]",
")",
")",
")",
"{",
"return",
"possibleVarArgsConstructor",
";",
"}",
"}",
"}",
"}",
"return",
"null",
";",
"}"
] |
Gets the potential var args constructor.
@param <T> the generic type
@param classThatContainsTheConstructorToTest the class that contains the constructor to test
@param arguments the arguments
@return the potential var args constructor
|
[
"Gets",
"the",
"potential",
"var",
"args",
"constructor",
"."
] |
e8cd68026c284c6a7efe66959809eeebd8d1f9ad
|
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java#L1366-L1385
|
16,884
|
powermock/powermock
|
powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java
|
WhiteboxImpl.createInstance
|
private static <T> T createInstance(Constructor<T> constructor, Object... arguments) throws Exception {
if (constructor == null) {
throw new IllegalArgumentException("Constructor cannot be null");
}
constructor.setAccessible(true);
T createdObject = null;
try {
if (constructor.isVarArgs()) {
Class<?>[] parameterTypes = constructor.getParameterTypes();
final int varArgsIndex = parameterTypes.length - 1;
Class<?> varArgsType = parameterTypes[varArgsIndex].getComponentType();
Object varArgsArrayInstance = createAndPopulateVarArgsArray(varArgsType, varArgsIndex, arguments);
Object[] completeArgumentList = new Object[parameterTypes.length];
System.arraycopy(arguments, 0, completeArgumentList, 0, varArgsIndex);
completeArgumentList[completeArgumentList.length - 1] = varArgsArrayInstance;
createdObject = constructor.newInstance(completeArgumentList);
} else {
createdObject = constructor.newInstance(arguments);
}
} catch (InvocationTargetException e) {
Throwable cause = e.getCause();
if (cause instanceof Exception) {
throw (Exception) cause;
} else if (cause instanceof Error) {
throw (Error) cause;
}
}
return createdObject;
}
|
java
|
private static <T> T createInstance(Constructor<T> constructor, Object... arguments) throws Exception {
if (constructor == null) {
throw new IllegalArgumentException("Constructor cannot be null");
}
constructor.setAccessible(true);
T createdObject = null;
try {
if (constructor.isVarArgs()) {
Class<?>[] parameterTypes = constructor.getParameterTypes();
final int varArgsIndex = parameterTypes.length - 1;
Class<?> varArgsType = parameterTypes[varArgsIndex].getComponentType();
Object varArgsArrayInstance = createAndPopulateVarArgsArray(varArgsType, varArgsIndex, arguments);
Object[] completeArgumentList = new Object[parameterTypes.length];
System.arraycopy(arguments, 0, completeArgumentList, 0, varArgsIndex);
completeArgumentList[completeArgumentList.length - 1] = varArgsArrayInstance;
createdObject = constructor.newInstance(completeArgumentList);
} else {
createdObject = constructor.newInstance(arguments);
}
} catch (InvocationTargetException e) {
Throwable cause = e.getCause();
if (cause instanceof Exception) {
throw (Exception) cause;
} else if (cause instanceof Error) {
throw (Error) cause;
}
}
return createdObject;
}
|
[
"private",
"static",
"<",
"T",
">",
"T",
"createInstance",
"(",
"Constructor",
"<",
"T",
">",
"constructor",
",",
"Object",
"...",
"arguments",
")",
"throws",
"Exception",
"{",
"if",
"(",
"constructor",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Constructor cannot be null\"",
")",
";",
"}",
"constructor",
".",
"setAccessible",
"(",
"true",
")",
";",
"T",
"createdObject",
"=",
"null",
";",
"try",
"{",
"if",
"(",
"constructor",
".",
"isVarArgs",
"(",
")",
")",
"{",
"Class",
"<",
"?",
">",
"[",
"]",
"parameterTypes",
"=",
"constructor",
".",
"getParameterTypes",
"(",
")",
";",
"final",
"int",
"varArgsIndex",
"=",
"parameterTypes",
".",
"length",
"-",
"1",
";",
"Class",
"<",
"?",
">",
"varArgsType",
"=",
"parameterTypes",
"[",
"varArgsIndex",
"]",
".",
"getComponentType",
"(",
")",
";",
"Object",
"varArgsArrayInstance",
"=",
"createAndPopulateVarArgsArray",
"(",
"varArgsType",
",",
"varArgsIndex",
",",
"arguments",
")",
";",
"Object",
"[",
"]",
"completeArgumentList",
"=",
"new",
"Object",
"[",
"parameterTypes",
".",
"length",
"]",
";",
"System",
".",
"arraycopy",
"(",
"arguments",
",",
"0",
",",
"completeArgumentList",
",",
"0",
",",
"varArgsIndex",
")",
";",
"completeArgumentList",
"[",
"completeArgumentList",
".",
"length",
"-",
"1",
"]",
"=",
"varArgsArrayInstance",
";",
"createdObject",
"=",
"constructor",
".",
"newInstance",
"(",
"completeArgumentList",
")",
";",
"}",
"else",
"{",
"createdObject",
"=",
"constructor",
".",
"newInstance",
"(",
"arguments",
")",
";",
"}",
"}",
"catch",
"(",
"InvocationTargetException",
"e",
")",
"{",
"Throwable",
"cause",
"=",
"e",
".",
"getCause",
"(",
")",
";",
"if",
"(",
"cause",
"instanceof",
"Exception",
")",
"{",
"throw",
"(",
"Exception",
")",
"cause",
";",
"}",
"else",
"if",
"(",
"cause",
"instanceof",
"Error",
")",
"{",
"throw",
"(",
"Error",
")",
"cause",
";",
"}",
"}",
"return",
"createdObject",
";",
"}"
] |
Creates the instance.
@param <T> the generic type
@param constructor the constructor
@param arguments the arguments
@return the t
@throws Exception the exception
|
[
"Creates",
"the",
"instance",
"."
] |
e8cd68026c284c6a7efe66959809eeebd8d1f9ad
|
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java#L1396-L1425
|
16,885
|
powermock/powermock
|
powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java
|
WhiteboxImpl.createAndPopulateVarArgsArray
|
private static Object createAndPopulateVarArgsArray(Class<?> varArgsType, int varArgsStartPosition,
Object... arguments) {
Object arrayInstance = Array.newInstance(varArgsType, arguments.length - varArgsStartPosition);
for (int i = varArgsStartPosition; i < arguments.length; i++) {
Array.set(arrayInstance, i - varArgsStartPosition, arguments[i]);
}
return arrayInstance;
}
|
java
|
private static Object createAndPopulateVarArgsArray(Class<?> varArgsType, int varArgsStartPosition,
Object... arguments) {
Object arrayInstance = Array.newInstance(varArgsType, arguments.length - varArgsStartPosition);
for (int i = varArgsStartPosition; i < arguments.length; i++) {
Array.set(arrayInstance, i - varArgsStartPosition, arguments[i]);
}
return arrayInstance;
}
|
[
"private",
"static",
"Object",
"createAndPopulateVarArgsArray",
"(",
"Class",
"<",
"?",
">",
"varArgsType",
",",
"int",
"varArgsStartPosition",
",",
"Object",
"...",
"arguments",
")",
"{",
"Object",
"arrayInstance",
"=",
"Array",
".",
"newInstance",
"(",
"varArgsType",
",",
"arguments",
".",
"length",
"-",
"varArgsStartPosition",
")",
";",
"for",
"(",
"int",
"i",
"=",
"varArgsStartPosition",
";",
"i",
"<",
"arguments",
".",
"length",
";",
"i",
"++",
")",
"{",
"Array",
".",
"set",
"(",
"arrayInstance",
",",
"i",
"-",
"varArgsStartPosition",
",",
"arguments",
"[",
"i",
"]",
")",
";",
"}",
"return",
"arrayInstance",
";",
"}"
] |
Creates the and populate var args array.
@param varArgsType the var args type
@param varArgsStartPosition the var args start position
@param arguments the arguments
@return the object
|
[
"Creates",
"the",
"and",
"populate",
"var",
"args",
"array",
"."
] |
e8cd68026c284c6a7efe66959809eeebd8d1f9ad
|
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java#L1435-L1442
|
16,886
|
powermock/powermock
|
powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java
|
WhiteboxImpl.throwExceptionWhenMultipleMethodMatchesFound
|
static void throwExceptionWhenMultipleMethodMatchesFound(String helpInfo, Method[] methods) {
if (methods == null || methods.length < 2) {
throw new IllegalArgumentException(
"Internal error: throwExceptionWhenMultipleMethodMatchesFound needs at least two methods.");
}
StringBuilder sb = new StringBuilder();
sb.append("Several matching methods found, please specify the ");
sb.append(helpInfo);
sb.append(" so that PowerMock can determine which method you're referring to.\n");
sb.append("Matching methods in class ").append(methods[0].getDeclaringClass().getName()).append(" were:\n");
for (Method method : methods) {
sb.append(method.getReturnType().getName()).append(" ");
sb.append(method.getName()).append("( ");
final Class<?>[] parameterTypes = method.getParameterTypes();
for (Class<?> paramType : parameterTypes) {
sb.append(paramType.getName()).append(".class ");
}
sb.append(")\n");
}
throw new TooManyMethodsFoundException(sb.toString());
}
|
java
|
static void throwExceptionWhenMultipleMethodMatchesFound(String helpInfo, Method[] methods) {
if (methods == null || methods.length < 2) {
throw new IllegalArgumentException(
"Internal error: throwExceptionWhenMultipleMethodMatchesFound needs at least two methods.");
}
StringBuilder sb = new StringBuilder();
sb.append("Several matching methods found, please specify the ");
sb.append(helpInfo);
sb.append(" so that PowerMock can determine which method you're referring to.\n");
sb.append("Matching methods in class ").append(methods[0].getDeclaringClass().getName()).append(" were:\n");
for (Method method : methods) {
sb.append(method.getReturnType().getName()).append(" ");
sb.append(method.getName()).append("( ");
final Class<?>[] parameterTypes = method.getParameterTypes();
for (Class<?> paramType : parameterTypes) {
sb.append(paramType.getName()).append(".class ");
}
sb.append(")\n");
}
throw new TooManyMethodsFoundException(sb.toString());
}
|
[
"static",
"void",
"throwExceptionWhenMultipleMethodMatchesFound",
"(",
"String",
"helpInfo",
",",
"Method",
"[",
"]",
"methods",
")",
"{",
"if",
"(",
"methods",
"==",
"null",
"||",
"methods",
".",
"length",
"<",
"2",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Internal error: throwExceptionWhenMultipleMethodMatchesFound needs at least two methods.\"",
")",
";",
"}",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"sb",
".",
"append",
"(",
"\"Several matching methods found, please specify the \"",
")",
";",
"sb",
".",
"append",
"(",
"helpInfo",
")",
";",
"sb",
".",
"append",
"(",
"\" so that PowerMock can determine which method you're referring to.\\n\"",
")",
";",
"sb",
".",
"append",
"(",
"\"Matching methods in class \"",
")",
".",
"append",
"(",
"methods",
"[",
"0",
"]",
".",
"getDeclaringClass",
"(",
")",
".",
"getName",
"(",
")",
")",
".",
"append",
"(",
"\" were:\\n\"",
")",
";",
"for",
"(",
"Method",
"method",
":",
"methods",
")",
"{",
"sb",
".",
"append",
"(",
"method",
".",
"getReturnType",
"(",
")",
".",
"getName",
"(",
")",
")",
".",
"append",
"(",
"\" \"",
")",
";",
"sb",
".",
"append",
"(",
"method",
".",
"getName",
"(",
")",
")",
".",
"append",
"(",
"\"( \"",
")",
";",
"final",
"Class",
"<",
"?",
">",
"[",
"]",
"parameterTypes",
"=",
"method",
".",
"getParameterTypes",
"(",
")",
";",
"for",
"(",
"Class",
"<",
"?",
">",
"paramType",
":",
"parameterTypes",
")",
"{",
"sb",
".",
"append",
"(",
"paramType",
".",
"getName",
"(",
")",
")",
".",
"append",
"(",
"\".class \"",
")",
";",
"}",
"sb",
".",
"append",
"(",
"\")\\n\"",
")",
";",
"}",
"throw",
"new",
"TooManyMethodsFoundException",
"(",
"sb",
".",
"toString",
"(",
")",
")",
";",
"}"
] |
Throw exception when multiple method matches found.
@param helpInfo the help info
@param methods the methods
|
[
"Throw",
"exception",
"when",
"multiple",
"method",
"matches",
"found",
"."
] |
e8cd68026c284c6a7efe66959809eeebd8d1f9ad
|
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java#L1660-L1681
|
16,887
|
powermock/powermock
|
powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java
|
WhiteboxImpl.throwExceptionWhenMultipleConstructorMatchesFound
|
static void throwExceptionWhenMultipleConstructorMatchesFound(Constructor<?>[] constructors) {
if (constructors == null || constructors.length < 2) {
throw new IllegalArgumentException(
"Internal error: throwExceptionWhenMultipleConstructorMatchesFound needs at least two constructors.");
}
StringBuilder sb = new StringBuilder();
sb.append("Several matching constructors found, please specify the argument parameter types so that PowerMock can determine which method you're referring to.\n");
sb.append("Matching constructors in class ").append(constructors[0].getDeclaringClass().getName())
.append(" were:\n");
for (Constructor<?> constructor : constructors) {
sb.append(constructor.getName()).append("( ");
final Class<?>[] parameterTypes = constructor.getParameterTypes();
for (Class<?> paramType : parameterTypes) {
sb.append(paramType.getName()).append(".class ");
}
sb.append(")\n");
}
throw new TooManyConstructorsFoundException(sb.toString());
}
|
java
|
static void throwExceptionWhenMultipleConstructorMatchesFound(Constructor<?>[] constructors) {
if (constructors == null || constructors.length < 2) {
throw new IllegalArgumentException(
"Internal error: throwExceptionWhenMultipleConstructorMatchesFound needs at least two constructors.");
}
StringBuilder sb = new StringBuilder();
sb.append("Several matching constructors found, please specify the argument parameter types so that PowerMock can determine which method you're referring to.\n");
sb.append("Matching constructors in class ").append(constructors[0].getDeclaringClass().getName())
.append(" were:\n");
for (Constructor<?> constructor : constructors) {
sb.append(constructor.getName()).append("( ");
final Class<?>[] parameterTypes = constructor.getParameterTypes();
for (Class<?> paramType : parameterTypes) {
sb.append(paramType.getName()).append(".class ");
}
sb.append(")\n");
}
throw new TooManyConstructorsFoundException(sb.toString());
}
|
[
"static",
"void",
"throwExceptionWhenMultipleConstructorMatchesFound",
"(",
"Constructor",
"<",
"?",
">",
"[",
"]",
"constructors",
")",
"{",
"if",
"(",
"constructors",
"==",
"null",
"||",
"constructors",
".",
"length",
"<",
"2",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Internal error: throwExceptionWhenMultipleConstructorMatchesFound needs at least two constructors.\"",
")",
";",
"}",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"sb",
".",
"append",
"(",
"\"Several matching constructors found, please specify the argument parameter types so that PowerMock can determine which method you're referring to.\\n\"",
")",
";",
"sb",
".",
"append",
"(",
"\"Matching constructors in class \"",
")",
".",
"append",
"(",
"constructors",
"[",
"0",
"]",
".",
"getDeclaringClass",
"(",
")",
".",
"getName",
"(",
")",
")",
".",
"append",
"(",
"\" were:\\n\"",
")",
";",
"for",
"(",
"Constructor",
"<",
"?",
">",
"constructor",
":",
"constructors",
")",
"{",
"sb",
".",
"append",
"(",
"constructor",
".",
"getName",
"(",
")",
")",
".",
"append",
"(",
"\"( \"",
")",
";",
"final",
"Class",
"<",
"?",
">",
"[",
"]",
"parameterTypes",
"=",
"constructor",
".",
"getParameterTypes",
"(",
")",
";",
"for",
"(",
"Class",
"<",
"?",
">",
"paramType",
":",
"parameterTypes",
")",
"{",
"sb",
".",
"append",
"(",
"paramType",
".",
"getName",
"(",
")",
")",
".",
"append",
"(",
"\".class \"",
")",
";",
"}",
"sb",
".",
"append",
"(",
"\")\\n\"",
")",
";",
"}",
"throw",
"new",
"TooManyConstructorsFoundException",
"(",
"sb",
".",
"toString",
"(",
")",
")",
";",
"}"
] |
Throw exception when multiple constructor matches found.
@param constructors the constructors
|
[
"Throw",
"exception",
"when",
"multiple",
"constructor",
"matches",
"found",
"."
] |
e8cd68026c284c6a7efe66959809eeebd8d1f9ad
|
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java#L1688-L1707
|
16,888
|
powermock/powermock
|
powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java
|
WhiteboxImpl.findMethodOrThrowException
|
@SuppressWarnings("all")
public static Method findMethodOrThrowException(Class<?> type, String methodName, Class<?>... parameterTypes) {
Method methodToMock = findMethod(type, methodName, parameterTypes);
throwExceptionIfMethodWasNotFound(type, methodName, methodToMock, (Object[]) parameterTypes);
return methodToMock;
}
|
java
|
@SuppressWarnings("all")
public static Method findMethodOrThrowException(Class<?> type, String methodName, Class<?>... parameterTypes) {
Method methodToMock = findMethod(type, methodName, parameterTypes);
throwExceptionIfMethodWasNotFound(type, methodName, methodToMock, (Object[]) parameterTypes);
return methodToMock;
}
|
[
"@",
"SuppressWarnings",
"(",
"\"all\"",
")",
"public",
"static",
"Method",
"findMethodOrThrowException",
"(",
"Class",
"<",
"?",
">",
"type",
",",
"String",
"methodName",
",",
"Class",
"<",
"?",
">",
"...",
"parameterTypes",
")",
"{",
"Method",
"methodToMock",
"=",
"findMethod",
"(",
"type",
",",
"methodName",
",",
"parameterTypes",
")",
";",
"throwExceptionIfMethodWasNotFound",
"(",
"type",
",",
"methodName",
",",
"methodToMock",
",",
"(",
"Object",
"[",
"]",
")",
"parameterTypes",
")",
";",
"return",
"methodToMock",
";",
"}"
] |
Find method or throw exception.
@param type the type
@param methodName the method name
@param parameterTypes the parameter types
@return the method
|
[
"Find",
"method",
"or",
"throw",
"exception",
"."
] |
e8cd68026c284c6a7efe66959809eeebd8d1f9ad
|
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java#L1717-L1722
|
16,889
|
powermock/powermock
|
powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java
|
WhiteboxImpl.performMethodInvocation
|
@SuppressWarnings("unchecked")
public static <T> T performMethodInvocation(Object tested, Method methodToInvoke, Object... arguments)
throws Exception {
final boolean accessible = methodToInvoke.isAccessible();
if (!accessible) {
methodToInvoke.setAccessible(true);
}
try {
if (isPotentialVarArgsMethod(methodToInvoke, arguments)) {
Class<?>[] parameterTypes = methodToInvoke.getParameterTypes();
final int varArgsIndex = parameterTypes.length - 1;
Class<?> varArgsType = parameterTypes[varArgsIndex].getComponentType();
Object varArgsArrayInstance = createAndPopulateVarArgsArray(varArgsType, varArgsIndex, arguments);
Object[] completeArgumentList = new Object[parameterTypes.length];
System.arraycopy(arguments, 0, completeArgumentList, 0, varArgsIndex);
completeArgumentList[completeArgumentList.length - 1] = varArgsArrayInstance;
return (T) methodToInvoke.invoke(tested, completeArgumentList);
} else {
return (T) methodToInvoke.invoke(tested, arguments == null ? new Object[]{arguments} : arguments);
}
} catch (InvocationTargetException e) {
Throwable cause = e.getCause();
if (cause instanceof Exception) {
throw (Exception) cause;
} else if (cause instanceof Error) {
throw (Error) cause;
} else {
throw new MethodInvocationException(cause);
}
} finally {
if (!accessible) {
methodToInvoke.setAccessible(false);
}
}
}
|
java
|
@SuppressWarnings("unchecked")
public static <T> T performMethodInvocation(Object tested, Method methodToInvoke, Object... arguments)
throws Exception {
final boolean accessible = methodToInvoke.isAccessible();
if (!accessible) {
methodToInvoke.setAccessible(true);
}
try {
if (isPotentialVarArgsMethod(methodToInvoke, arguments)) {
Class<?>[] parameterTypes = methodToInvoke.getParameterTypes();
final int varArgsIndex = parameterTypes.length - 1;
Class<?> varArgsType = parameterTypes[varArgsIndex].getComponentType();
Object varArgsArrayInstance = createAndPopulateVarArgsArray(varArgsType, varArgsIndex, arguments);
Object[] completeArgumentList = new Object[parameterTypes.length];
System.arraycopy(arguments, 0, completeArgumentList, 0, varArgsIndex);
completeArgumentList[completeArgumentList.length - 1] = varArgsArrayInstance;
return (T) methodToInvoke.invoke(tested, completeArgumentList);
} else {
return (T) methodToInvoke.invoke(tested, arguments == null ? new Object[]{arguments} : arguments);
}
} catch (InvocationTargetException e) {
Throwable cause = e.getCause();
if (cause instanceof Exception) {
throw (Exception) cause;
} else if (cause instanceof Error) {
throw (Error) cause;
} else {
throw new MethodInvocationException(cause);
}
} finally {
if (!accessible) {
methodToInvoke.setAccessible(false);
}
}
}
|
[
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"static",
"<",
"T",
">",
"T",
"performMethodInvocation",
"(",
"Object",
"tested",
",",
"Method",
"methodToInvoke",
",",
"Object",
"...",
"arguments",
")",
"throws",
"Exception",
"{",
"final",
"boolean",
"accessible",
"=",
"methodToInvoke",
".",
"isAccessible",
"(",
")",
";",
"if",
"(",
"!",
"accessible",
")",
"{",
"methodToInvoke",
".",
"setAccessible",
"(",
"true",
")",
";",
"}",
"try",
"{",
"if",
"(",
"isPotentialVarArgsMethod",
"(",
"methodToInvoke",
",",
"arguments",
")",
")",
"{",
"Class",
"<",
"?",
">",
"[",
"]",
"parameterTypes",
"=",
"methodToInvoke",
".",
"getParameterTypes",
"(",
")",
";",
"final",
"int",
"varArgsIndex",
"=",
"parameterTypes",
".",
"length",
"-",
"1",
";",
"Class",
"<",
"?",
">",
"varArgsType",
"=",
"parameterTypes",
"[",
"varArgsIndex",
"]",
".",
"getComponentType",
"(",
")",
";",
"Object",
"varArgsArrayInstance",
"=",
"createAndPopulateVarArgsArray",
"(",
"varArgsType",
",",
"varArgsIndex",
",",
"arguments",
")",
";",
"Object",
"[",
"]",
"completeArgumentList",
"=",
"new",
"Object",
"[",
"parameterTypes",
".",
"length",
"]",
";",
"System",
".",
"arraycopy",
"(",
"arguments",
",",
"0",
",",
"completeArgumentList",
",",
"0",
",",
"varArgsIndex",
")",
";",
"completeArgumentList",
"[",
"completeArgumentList",
".",
"length",
"-",
"1",
"]",
"=",
"varArgsArrayInstance",
";",
"return",
"(",
"T",
")",
"methodToInvoke",
".",
"invoke",
"(",
"tested",
",",
"completeArgumentList",
")",
";",
"}",
"else",
"{",
"return",
"(",
"T",
")",
"methodToInvoke",
".",
"invoke",
"(",
"tested",
",",
"arguments",
"==",
"null",
"?",
"new",
"Object",
"[",
"]",
"{",
"arguments",
"}",
":",
"arguments",
")",
";",
"}",
"}",
"catch",
"(",
"InvocationTargetException",
"e",
")",
"{",
"Throwable",
"cause",
"=",
"e",
".",
"getCause",
"(",
")",
";",
"if",
"(",
"cause",
"instanceof",
"Exception",
")",
"{",
"throw",
"(",
"Exception",
")",
"cause",
";",
"}",
"else",
"if",
"(",
"cause",
"instanceof",
"Error",
")",
"{",
"throw",
"(",
"Error",
")",
"cause",
";",
"}",
"else",
"{",
"throw",
"new",
"MethodInvocationException",
"(",
"cause",
")",
";",
"}",
"}",
"finally",
"{",
"if",
"(",
"!",
"accessible",
")",
"{",
"methodToInvoke",
".",
"setAccessible",
"(",
"false",
")",
";",
"}",
"}",
"}"
] |
Perform method invocation.
@param <T> the generic type
@param tested the tested
@param methodToInvoke the method to invoke
@param arguments the arguments
@return the t
@throws Exception the exception
|
[
"Perform",
"method",
"invocation",
"."
] |
e8cd68026c284c6a7efe66959809eeebd8d1f9ad
|
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java#L1836-L1870
|
16,890
|
powermock/powermock
|
powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java
|
WhiteboxImpl.getAllMethodExcept
|
public static <T> Method[] getAllMethodExcept(Class<T> type, String... methodNames) {
List<Method> methodsToMock = new LinkedList<Method>();
Method[] methods = getAllMethods(type);
iterateMethods:
for (Method method : methods) {
for (String methodName : methodNames) {
if (method.getName().equals(methodName)) {
continue iterateMethods;
}
}
methodsToMock.add(method);
}
return methodsToMock.toArray(new Method[0]);
}
|
java
|
public static <T> Method[] getAllMethodExcept(Class<T> type, String... methodNames) {
List<Method> methodsToMock = new LinkedList<Method>();
Method[] methods = getAllMethods(type);
iterateMethods:
for (Method method : methods) {
for (String methodName : methodNames) {
if (method.getName().equals(methodName)) {
continue iterateMethods;
}
}
methodsToMock.add(method);
}
return methodsToMock.toArray(new Method[0]);
}
|
[
"public",
"static",
"<",
"T",
">",
"Method",
"[",
"]",
"getAllMethodExcept",
"(",
"Class",
"<",
"T",
">",
"type",
",",
"String",
"...",
"methodNames",
")",
"{",
"List",
"<",
"Method",
">",
"methodsToMock",
"=",
"new",
"LinkedList",
"<",
"Method",
">",
"(",
")",
";",
"Method",
"[",
"]",
"methods",
"=",
"getAllMethods",
"(",
"type",
")",
";",
"iterateMethods",
":",
"for",
"(",
"Method",
"method",
":",
"methods",
")",
"{",
"for",
"(",
"String",
"methodName",
":",
"methodNames",
")",
"{",
"if",
"(",
"method",
".",
"getName",
"(",
")",
".",
"equals",
"(",
"methodName",
")",
")",
"{",
"continue",
"iterateMethods",
";",
"}",
"}",
"methodsToMock",
".",
"add",
"(",
"method",
")",
";",
"}",
"return",
"methodsToMock",
".",
"toArray",
"(",
"new",
"Method",
"[",
"0",
"]",
")",
";",
"}"
] |
Gets the all method except.
@param <T> the generic type
@param type the type
@param methodNames the method names
@return the all method except
|
[
"Gets",
"the",
"all",
"method",
"except",
"."
] |
e8cd68026c284c6a7efe66959809eeebd8d1f9ad
|
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java#L1880-L1893
|
16,891
|
powermock/powermock
|
powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java
|
WhiteboxImpl.getAllMethodsExcept
|
public static <T> Method[] getAllMethodsExcept(Class<T> type, String methodNameToExclude, Class<?>[] argumentTypes) {
Method[] methods = getAllMethods(type);
List<Method> methodList = new ArrayList<Method>();
outer:
for (Method method : methods) {
if (method.getName().equals(methodNameToExclude)) {
if (argumentTypes != null && argumentTypes.length > 0) {
final Class<?>[] args = method.getParameterTypes();
if (args != null && args.length == argumentTypes.length) {
for (int i = 0; i < args.length; i++) {
if (args[i].isAssignableFrom(getOriginalUnmockedType(argumentTypes[i]))) {
/*
* Method was not found thus it should not be
* mocked. Continue to investigate the next
* method.
*/
continue outer;
}
}
}
} else {
continue;
}
}
methodList.add(method);
}
return methodList.toArray(new Method[0]);
}
|
java
|
public static <T> Method[] getAllMethodsExcept(Class<T> type, String methodNameToExclude, Class<?>[] argumentTypes) {
Method[] methods = getAllMethods(type);
List<Method> methodList = new ArrayList<Method>();
outer:
for (Method method : methods) {
if (method.getName().equals(methodNameToExclude)) {
if (argumentTypes != null && argumentTypes.length > 0) {
final Class<?>[] args = method.getParameterTypes();
if (args != null && args.length == argumentTypes.length) {
for (int i = 0; i < args.length; i++) {
if (args[i].isAssignableFrom(getOriginalUnmockedType(argumentTypes[i]))) {
/*
* Method was not found thus it should not be
* mocked. Continue to investigate the next
* method.
*/
continue outer;
}
}
}
} else {
continue;
}
}
methodList.add(method);
}
return methodList.toArray(new Method[0]);
}
|
[
"public",
"static",
"<",
"T",
">",
"Method",
"[",
"]",
"getAllMethodsExcept",
"(",
"Class",
"<",
"T",
">",
"type",
",",
"String",
"methodNameToExclude",
",",
"Class",
"<",
"?",
">",
"[",
"]",
"argumentTypes",
")",
"{",
"Method",
"[",
"]",
"methods",
"=",
"getAllMethods",
"(",
"type",
")",
";",
"List",
"<",
"Method",
">",
"methodList",
"=",
"new",
"ArrayList",
"<",
"Method",
">",
"(",
")",
";",
"outer",
":",
"for",
"(",
"Method",
"method",
":",
"methods",
")",
"{",
"if",
"(",
"method",
".",
"getName",
"(",
")",
".",
"equals",
"(",
"methodNameToExclude",
")",
")",
"{",
"if",
"(",
"argumentTypes",
"!=",
"null",
"&&",
"argumentTypes",
".",
"length",
">",
"0",
")",
"{",
"final",
"Class",
"<",
"?",
">",
"[",
"]",
"args",
"=",
"method",
".",
"getParameterTypes",
"(",
")",
";",
"if",
"(",
"args",
"!=",
"null",
"&&",
"args",
".",
"length",
"==",
"argumentTypes",
".",
"length",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"args",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"args",
"[",
"i",
"]",
".",
"isAssignableFrom",
"(",
"getOriginalUnmockedType",
"(",
"argumentTypes",
"[",
"i",
"]",
")",
")",
")",
"{",
"/*\n * Method was not found thus it should not be\n * mocked. Continue to investigate the next\n * method.\n */",
"continue",
"outer",
";",
"}",
"}",
"}",
"}",
"else",
"{",
"continue",
";",
"}",
"}",
"methodList",
".",
"add",
"(",
"method",
")",
";",
"}",
"return",
"methodList",
".",
"toArray",
"(",
"new",
"Method",
"[",
"0",
"]",
")",
";",
"}"
] |
Gets the all metods except.
@param <T> the generic type
@param type the type
@param methodNameToExclude the method name to exclude
@param argumentTypes the argument types
@return the all metods except
|
[
"Gets",
"the",
"all",
"metods",
"except",
"."
] |
e8cd68026c284c6a7efe66959809eeebd8d1f9ad
|
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java#L1904-L1931
|
16,892
|
powermock/powermock
|
powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java
|
WhiteboxImpl.areAllMethodsStatic
|
public static boolean areAllMethodsStatic(Method... methods) {
for (Method method : methods) {
if (!Modifier.isStatic(method.getModifiers())) {
return false;
}
}
return true;
}
|
java
|
public static boolean areAllMethodsStatic(Method... methods) {
for (Method method : methods) {
if (!Modifier.isStatic(method.getModifiers())) {
return false;
}
}
return true;
}
|
[
"public",
"static",
"boolean",
"areAllMethodsStatic",
"(",
"Method",
"...",
"methods",
")",
"{",
"for",
"(",
"Method",
"method",
":",
"methods",
")",
"{",
"if",
"(",
"!",
"Modifier",
".",
"isStatic",
"(",
"method",
".",
"getModifiers",
"(",
")",
")",
")",
"{",
"return",
"false",
";",
"}",
"}",
"return",
"true",
";",
"}"
] |
Are all methods static.
@param methods the methods
@return true, if successful
|
[
"Are",
"all",
"methods",
"static",
"."
] |
e8cd68026c284c6a7efe66959809eeebd8d1f9ad
|
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java#L1939-L1946
|
16,893
|
powermock/powermock
|
powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java
|
WhiteboxImpl.areAllArgumentsOfSameType
|
static boolean areAllArgumentsOfSameType(Object[] arguments) {
if (arguments == null || arguments.length <= 1) {
return true;
}
// Handle null values
int index = 0;
Object object = null;
while (object == null && index < arguments.length) {
object = arguments[index++];
}
if (object == null) {
return true;
}
// End of handling null values
final Class<?> firstArgumentType = getType(object);
for (int i = index; i < arguments.length; i++) {
final Object argument = arguments[i];
if (argument != null && !getType(argument).isAssignableFrom(firstArgumentType)) {
return false;
}
}
return true;
}
|
java
|
static boolean areAllArgumentsOfSameType(Object[] arguments) {
if (arguments == null || arguments.length <= 1) {
return true;
}
// Handle null values
int index = 0;
Object object = null;
while (object == null && index < arguments.length) {
object = arguments[index++];
}
if (object == null) {
return true;
}
// End of handling null values
final Class<?> firstArgumentType = getType(object);
for (int i = index; i < arguments.length; i++) {
final Object argument = arguments[i];
if (argument != null && !getType(argument).isAssignableFrom(firstArgumentType)) {
return false;
}
}
return true;
}
|
[
"static",
"boolean",
"areAllArgumentsOfSameType",
"(",
"Object",
"[",
"]",
"arguments",
")",
"{",
"if",
"(",
"arguments",
"==",
"null",
"||",
"arguments",
".",
"length",
"<=",
"1",
")",
"{",
"return",
"true",
";",
"}",
"// Handle null values",
"int",
"index",
"=",
"0",
";",
"Object",
"object",
"=",
"null",
";",
"while",
"(",
"object",
"==",
"null",
"&&",
"index",
"<",
"arguments",
".",
"length",
")",
"{",
"object",
"=",
"arguments",
"[",
"index",
"++",
"]",
";",
"}",
"if",
"(",
"object",
"==",
"null",
")",
"{",
"return",
"true",
";",
"}",
"// End of handling null values",
"final",
"Class",
"<",
"?",
">",
"firstArgumentType",
"=",
"getType",
"(",
"object",
")",
";",
"for",
"(",
"int",
"i",
"=",
"index",
";",
"i",
"<",
"arguments",
".",
"length",
";",
"i",
"++",
")",
"{",
"final",
"Object",
"argument",
"=",
"arguments",
"[",
"i",
"]",
";",
"if",
"(",
"argument",
"!=",
"null",
"&&",
"!",
"getType",
"(",
"argument",
")",
".",
"isAssignableFrom",
"(",
"firstArgumentType",
")",
")",
"{",
"return",
"false",
";",
"}",
"}",
"return",
"true",
";",
"}"
] |
Check if all arguments are of the same type.
@param arguments the arguments
@return true, if successful
|
[
"Check",
"if",
"all",
"arguments",
"are",
"of",
"the",
"same",
"type",
"."
] |
e8cd68026c284c6a7efe66959809eeebd8d1f9ad
|
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java#L1954-L1980
|
16,894
|
powermock/powermock
|
powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java
|
WhiteboxImpl.checkArgumentTypesMatchParameterTypes
|
static boolean checkArgumentTypesMatchParameterTypes(boolean isVarArgs, Class<?>[] parameterTypes,
Object[] arguments) {
if (parameterTypes == null) {
throw new IllegalArgumentException("parameter types cannot be null");
} else if (!isVarArgs && arguments.length != parameterTypes.length) {
return false;
}
for (int i = 0; i < arguments.length; i++) {
Object argument = arguments[i];
if (argument == null) {
final int index;
if (i >= parameterTypes.length) {
index = parameterTypes.length - 1;
} else {
index = i;
}
final Class<?> type = parameterTypes[index];
if (type.isPrimitive()) {
// Primitives cannot be null
return false;
} else {
continue;
}
} else if (i >= parameterTypes.length) {
if (isAssignableFrom(parameterTypes[parameterTypes.length - 1], getType(argument))) {
continue;
} else {
return false;
}
} else {
boolean assignableFrom = isAssignableFrom(parameterTypes[i], getType(argument));
final boolean isClass = parameterTypes[i].equals(Class.class) && isClass(argument);
if (!assignableFrom && !isClass) {
return false;
}
}
}
return true;
}
|
java
|
static boolean checkArgumentTypesMatchParameterTypes(boolean isVarArgs, Class<?>[] parameterTypes,
Object[] arguments) {
if (parameterTypes == null) {
throw new IllegalArgumentException("parameter types cannot be null");
} else if (!isVarArgs && arguments.length != parameterTypes.length) {
return false;
}
for (int i = 0; i < arguments.length; i++) {
Object argument = arguments[i];
if (argument == null) {
final int index;
if (i >= parameterTypes.length) {
index = parameterTypes.length - 1;
} else {
index = i;
}
final Class<?> type = parameterTypes[index];
if (type.isPrimitive()) {
// Primitives cannot be null
return false;
} else {
continue;
}
} else if (i >= parameterTypes.length) {
if (isAssignableFrom(parameterTypes[parameterTypes.length - 1], getType(argument))) {
continue;
} else {
return false;
}
} else {
boolean assignableFrom = isAssignableFrom(parameterTypes[i], getType(argument));
final boolean isClass = parameterTypes[i].equals(Class.class) && isClass(argument);
if (!assignableFrom && !isClass) {
return false;
}
}
}
return true;
}
|
[
"static",
"boolean",
"checkArgumentTypesMatchParameterTypes",
"(",
"boolean",
"isVarArgs",
",",
"Class",
"<",
"?",
">",
"[",
"]",
"parameterTypes",
",",
"Object",
"[",
"]",
"arguments",
")",
"{",
"if",
"(",
"parameterTypes",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"parameter types cannot be null\"",
")",
";",
"}",
"else",
"if",
"(",
"!",
"isVarArgs",
"&&",
"arguments",
".",
"length",
"!=",
"parameterTypes",
".",
"length",
")",
"{",
"return",
"false",
";",
"}",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"arguments",
".",
"length",
";",
"i",
"++",
")",
"{",
"Object",
"argument",
"=",
"arguments",
"[",
"i",
"]",
";",
"if",
"(",
"argument",
"==",
"null",
")",
"{",
"final",
"int",
"index",
";",
"if",
"(",
"i",
">=",
"parameterTypes",
".",
"length",
")",
"{",
"index",
"=",
"parameterTypes",
".",
"length",
"-",
"1",
";",
"}",
"else",
"{",
"index",
"=",
"i",
";",
"}",
"final",
"Class",
"<",
"?",
">",
"type",
"=",
"parameterTypes",
"[",
"index",
"]",
";",
"if",
"(",
"type",
".",
"isPrimitive",
"(",
")",
")",
"{",
"// Primitives cannot be null",
"return",
"false",
";",
"}",
"else",
"{",
"continue",
";",
"}",
"}",
"else",
"if",
"(",
"i",
">=",
"parameterTypes",
".",
"length",
")",
"{",
"if",
"(",
"isAssignableFrom",
"(",
"parameterTypes",
"[",
"parameterTypes",
".",
"length",
"-",
"1",
"]",
",",
"getType",
"(",
"argument",
")",
")",
")",
"{",
"continue",
";",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"}",
"else",
"{",
"boolean",
"assignableFrom",
"=",
"isAssignableFrom",
"(",
"parameterTypes",
"[",
"i",
"]",
",",
"getType",
"(",
"argument",
")",
")",
";",
"final",
"boolean",
"isClass",
"=",
"parameterTypes",
"[",
"i",
"]",
".",
"equals",
"(",
"Class",
".",
"class",
")",
"&&",
"isClass",
"(",
"argument",
")",
";",
"if",
"(",
"!",
"assignableFrom",
"&&",
"!",
"isClass",
")",
"{",
"return",
"false",
";",
"}",
"}",
"}",
"return",
"true",
";",
"}"
] |
Check argument types match parameter types.
@param isVarArgs If the last parameter is a var args.
@param parameterTypes the parameter types
@param arguments the arguments
@return if all actual parameter types are assignable from the expected
arguments, otherwise.
|
[
"Check",
"argument",
"types",
"match",
"parameter",
"types",
"."
] |
e8cd68026c284c6a7efe66959809eeebd8d1f9ad
|
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java#L1991-L2029
|
16,895
|
powermock/powermock
|
powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java
|
WhiteboxImpl.getInnerClassType
|
@SuppressWarnings("unchecked")
public static Class<Object> getInnerClassType(Class<?> declaringClass, String name) throws ClassNotFoundException {
return (Class<Object>) Class.forName(declaringClass.getName() + "$" + name);
}
|
java
|
@SuppressWarnings("unchecked")
public static Class<Object> getInnerClassType(Class<?> declaringClass, String name) throws ClassNotFoundException {
return (Class<Object>) Class.forName(declaringClass.getName() + "$" + name);
}
|
[
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"static",
"Class",
"<",
"Object",
">",
"getInnerClassType",
"(",
"Class",
"<",
"?",
">",
"declaringClass",
",",
"String",
"name",
")",
"throws",
"ClassNotFoundException",
"{",
"return",
"(",
"Class",
"<",
"Object",
">",
")",
"Class",
".",
"forName",
"(",
"declaringClass",
".",
"getName",
"(",
")",
"+",
"\"$\"",
"+",
"name",
")",
";",
"}"
] |
Get an inner class type.
@param declaringClass The class in which the inner class is declared.
@param name The unqualified name (simple name) of the inner class.
@return The type.
@throws ClassNotFoundException the class not found exception
|
[
"Get",
"an",
"inner",
"class",
"type",
"."
] |
e8cd68026c284c6a7efe66959809eeebd8d1f9ad
|
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java#L2093-L2096
|
16,896
|
powermock/powermock
|
powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java
|
WhiteboxImpl.getAllInstanceFields
|
public static Set<Field> getAllInstanceFields(Object object) {
return findAllFieldsUsingStrategy(new AllFieldsMatcherStrategy(), object, true, getUnproxyType(object));
}
|
java
|
public static Set<Field> getAllInstanceFields(Object object) {
return findAllFieldsUsingStrategy(new AllFieldsMatcherStrategy(), object, true, getUnproxyType(object));
}
|
[
"public",
"static",
"Set",
"<",
"Field",
">",
"getAllInstanceFields",
"(",
"Object",
"object",
")",
"{",
"return",
"findAllFieldsUsingStrategy",
"(",
"new",
"AllFieldsMatcherStrategy",
"(",
")",
",",
"object",
",",
"true",
",",
"getUnproxyType",
"(",
"object",
")",
")",
";",
"}"
] |
Get all instance fields for a particular object. It returns all fields
regardless of the field modifier and regardless of where in the class
hierarchy a field is located.
@param object The object whose instance fields to get.
@return All instance fields in the hierarchy. All fields are set to
accessible
|
[
"Get",
"all",
"instance",
"fields",
"for",
"a",
"particular",
"object",
".",
"It",
"returns",
"all",
"fields",
"regardless",
"of",
"the",
"field",
"modifier",
"and",
"regardless",
"of",
"where",
"in",
"the",
"class",
"hierarchy",
"a",
"field",
"is",
"located",
"."
] |
e8cd68026c284c6a7efe66959809eeebd8d1f9ad
|
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java#L2201-L2203
|
16,897
|
powermock/powermock
|
powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java
|
WhiteboxImpl.getAllStaticFields
|
public static Set<Field> getAllStaticFields(Class<?> type) {
final Set<Field> fields = new LinkedHashSet<Field>();
final Field[] declaredFields = type.getDeclaredFields();
for (Field field : declaredFields) {
if (Modifier.isStatic(field.getModifiers())) {
field.setAccessible(true);
fields.add(field);
}
}
return fields;
}
|
java
|
public static Set<Field> getAllStaticFields(Class<?> type) {
final Set<Field> fields = new LinkedHashSet<Field>();
final Field[] declaredFields = type.getDeclaredFields();
for (Field field : declaredFields) {
if (Modifier.isStatic(field.getModifiers())) {
field.setAccessible(true);
fields.add(field);
}
}
return fields;
}
|
[
"public",
"static",
"Set",
"<",
"Field",
">",
"getAllStaticFields",
"(",
"Class",
"<",
"?",
">",
"type",
")",
"{",
"final",
"Set",
"<",
"Field",
">",
"fields",
"=",
"new",
"LinkedHashSet",
"<",
"Field",
">",
"(",
")",
";",
"final",
"Field",
"[",
"]",
"declaredFields",
"=",
"type",
".",
"getDeclaredFields",
"(",
")",
";",
"for",
"(",
"Field",
"field",
":",
"declaredFields",
")",
"{",
"if",
"(",
"Modifier",
".",
"isStatic",
"(",
"field",
".",
"getModifiers",
"(",
")",
")",
")",
"{",
"field",
".",
"setAccessible",
"(",
"true",
")",
";",
"fields",
".",
"add",
"(",
"field",
")",
";",
"}",
"}",
"return",
"fields",
";",
"}"
] |
Get all static fields for a particular type.
@param type The class whose static fields to get.
@return All static fields in . All fields are set to accessible.
|
[
"Get",
"all",
"static",
"fields",
"for",
"a",
"particular",
"type",
"."
] |
e8cd68026c284c6a7efe66959809eeebd8d1f9ad
|
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java#L2211-L2221
|
16,898
|
powermock/powermock
|
powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java
|
WhiteboxImpl.checkIfParameterTypesAreSame
|
public static boolean checkIfParameterTypesAreSame(boolean isVarArgs, Class<?>[] expectedParameterTypes,
Class<?>[] actualParameterTypes) {
return new ParameterTypesMatcher(isVarArgs, expectedParameterTypes, actualParameterTypes).match();
}
|
java
|
public static boolean checkIfParameterTypesAreSame(boolean isVarArgs, Class<?>[] expectedParameterTypes,
Class<?>[] actualParameterTypes) {
return new ParameterTypesMatcher(isVarArgs, expectedParameterTypes, actualParameterTypes).match();
}
|
[
"public",
"static",
"boolean",
"checkIfParameterTypesAreSame",
"(",
"boolean",
"isVarArgs",
",",
"Class",
"<",
"?",
">",
"[",
"]",
"expectedParameterTypes",
",",
"Class",
"<",
"?",
">",
"[",
"]",
"actualParameterTypes",
")",
"{",
"return",
"new",
"ParameterTypesMatcher",
"(",
"isVarArgs",
",",
"expectedParameterTypes",
",",
"actualParameterTypes",
")",
".",
"match",
"(",
")",
";",
"}"
] |
Check if parameter types are same.
@param isVarArgs Whether or not the method or constructor contains var args.
@param expectedParameterTypes the expected parameter types
@param actualParameterTypes the actual parameter types
@return if all actual parameter types are assignable from the expected
parameter types, otherwise.
|
[
"Check",
"if",
"parameter",
"types",
"are",
"same",
"."
] |
e8cd68026c284c6a7efe66959809eeebd8d1f9ad
|
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java#L2242-L2245
|
16,899
|
powermock/powermock
|
powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java
|
WhiteboxImpl.findFieldOrThrowException
|
private static Field findFieldOrThrowException(Class<?> fieldType, Class<?> where) {
if (fieldType == null || where == null) {
throw new IllegalArgumentException("fieldType and where cannot be null");
}
Field field = null;
for (Field currentField : where.getDeclaredFields()) {
currentField.setAccessible(true);
if (currentField.getType().equals(fieldType)) {
field = currentField;
break;
}
}
if (field == null) {
throw new FieldNotFoundException("Cannot find a field of type " + fieldType + "in where.");
}
return field;
}
|
java
|
private static Field findFieldOrThrowException(Class<?> fieldType, Class<?> where) {
if (fieldType == null || where == null) {
throw new IllegalArgumentException("fieldType and where cannot be null");
}
Field field = null;
for (Field currentField : where.getDeclaredFields()) {
currentField.setAccessible(true);
if (currentField.getType().equals(fieldType)) {
field = currentField;
break;
}
}
if (field == null) {
throw new FieldNotFoundException("Cannot find a field of type " + fieldType + "in where.");
}
return field;
}
|
[
"private",
"static",
"Field",
"findFieldOrThrowException",
"(",
"Class",
"<",
"?",
">",
"fieldType",
",",
"Class",
"<",
"?",
">",
"where",
")",
"{",
"if",
"(",
"fieldType",
"==",
"null",
"||",
"where",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"fieldType and where cannot be null\"",
")",
";",
"}",
"Field",
"field",
"=",
"null",
";",
"for",
"(",
"Field",
"currentField",
":",
"where",
".",
"getDeclaredFields",
"(",
")",
")",
"{",
"currentField",
".",
"setAccessible",
"(",
"true",
")",
";",
"if",
"(",
"currentField",
".",
"getType",
"(",
")",
".",
"equals",
"(",
"fieldType",
")",
")",
"{",
"field",
"=",
"currentField",
";",
"break",
";",
"}",
"}",
"if",
"(",
"field",
"==",
"null",
")",
"{",
"throw",
"new",
"FieldNotFoundException",
"(",
"\"Cannot find a field of type \"",
"+",
"fieldType",
"+",
"\"in where.\"",
")",
";",
"}",
"return",
"field",
";",
"}"
] |
Find field or throw exception.
@param fieldType the field type
@param where the where
@return the field
|
[
"Find",
"field",
"or",
"throw",
"exception",
"."
] |
e8cd68026c284c6a7efe66959809eeebd8d1f9ad
|
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java#L2277-L2293
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.