repo stringlengths 7 58 | path stringlengths 12 218 | func_name stringlengths 3 140 | original_string stringlengths 73 34.1k | language stringclasses 1 value | code stringlengths 73 34.1k | code_tokens list | docstring stringlengths 3 16k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 105 339 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
thorntail/thorntail | core/container/src/main/java/org/wildfly/swarm/cli/CommandLine.java | CommandLine.parse | public static CommandLine parse(Options options, String... args) throws Exception {
return CommandLineParser.parse(options, args);
} | java | public static CommandLine parse(Options options, String... args) throws Exception {
return CommandLineParser.parse(options, args);
} | [
"public",
"static",
"CommandLine",
"parse",
"(",
"Options",
"options",
",",
"String",
"...",
"args",
")",
"throws",
"Exception",
"{",
"return",
"CommandLineParser",
".",
"parse",
"(",
"options",
",",
"args",
")",
";",
"}"
] | Parse an array of arguments using specific options.
@param options The options to use.
@param args The args to parse.
@return The parsed <code>CommandLine</code>. | [
"Parse",
"an",
"array",
"of",
"arguments",
"using",
"specific",
"options",
"."
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/core/container/src/main/java/org/wildfly/swarm/cli/CommandLine.java#L468-L470 | train |
thorntail/thorntail | core/bootstrap/src/main/java/org/jboss/modules/Environment.java | Environment.getModuleResourceLoader | public static ResourceLoader getModuleResourceLoader(final String rootPath, final String loaderPath, final String loaderName) {
if (Holder.JAR_FILE != null) {
return new JarFileResourceLoader(loaderName, Holder.JAR_FILE, Holder.FILE_SYSTEM.getPath(rootPath, loaderPath).toString());
}
return ResourceLoaders.createFileResourceLoader(loaderPath, new File(rootPath));
} | java | public static ResourceLoader getModuleResourceLoader(final String rootPath, final String loaderPath, final String loaderName) {
if (Holder.JAR_FILE != null) {
return new JarFileResourceLoader(loaderName, Holder.JAR_FILE, Holder.FILE_SYSTEM.getPath(rootPath, loaderPath).toString());
}
return ResourceLoaders.createFileResourceLoader(loaderPath, new File(rootPath));
} | [
"public",
"static",
"ResourceLoader",
"getModuleResourceLoader",
"(",
"final",
"String",
"rootPath",
",",
"final",
"String",
"loaderPath",
",",
"final",
"String",
"loaderName",
")",
"{",
"if",
"(",
"Holder",
".",
"JAR_FILE",
"!=",
"null",
")",
"{",
"return",
"new",
"JarFileResourceLoader",
"(",
"loaderName",
",",
"Holder",
".",
"JAR_FILE",
",",
"Holder",
".",
"FILE_SYSTEM",
".",
"getPath",
"(",
"rootPath",
",",
"loaderPath",
")",
".",
"toString",
"(",
")",
")",
";",
"}",
"return",
"ResourceLoaders",
".",
"createFileResourceLoader",
"(",
"loaderPath",
",",
"new",
"File",
"(",
"rootPath",
")",
")",
";",
"}"
] | Creates a new resource loader for the environment.
<p>
In an archive a {@link JarFileResourceLoader} is returned. Otherwise a file system based loader is returned.
</p>
@param rootPath the root path to the module
@param loaderPath the path to the module
@param loaderName the module name
@return a resource loader for the environment | [
"Creates",
"a",
"new",
"resource",
"loader",
"for",
"the",
"environment",
"."
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/core/bootstrap/src/main/java/org/jboss/modules/Environment.java#L65-L70 | train |
thorntail/thorntail | fractions/microprofile/microprofile-jwt/src/main/java/org/wildfly/swarm/microprofile/jwtauth/deployment/auth/JWTAuthMechanism.java | JWTAuthMechanism.authenticate | @Override
public AuthenticationMechanismOutcome authenticate(HttpServerExchange exchange, SecurityContext securityContext) {
List<String> authHeaders = exchange.getRequestHeaders().get(AUTHORIZATION);
if (authHeaders != null) {
String bearerToken = null;
for (String current : authHeaders) {
if (current.toLowerCase(Locale.ENGLISH).startsWith("bearer ")) {
bearerToken = current.substring(7);
if (UndertowLogger.SECURITY_LOGGER.isTraceEnabled()) {
UndertowLogger.SECURITY_LOGGER.tracef("Bearer token: %s", bearerToken);
}
try {
identityManager = securityContext.getIdentityManager();
JWTCredential credential = new JWTCredential(bearerToken, authContextInfo);
if (UndertowLogger.SECURITY_LOGGER.isTraceEnabled()) {
UndertowLogger.SECURITY_LOGGER.tracef("Bearer token: %s", bearerToken);
}
// Install the JWT principal as the caller
Account account = identityManager.verify(credential.getName(), credential);
if (account != null) {
JsonWebToken jwtPrincipal = (JsonWebToken) account.getPrincipal();
securityContext.authenticationComplete(account, "MP-JWT", false);
// Workaround authenticated JWTPrincipal not being installed as user principal
// https://issues.jboss.org/browse/WFLY-9212
org.jboss.security.SecurityContext jbSC = SecurityContextAssociation.getSecurityContext();
Subject subject = jbSC.getUtil().getSubject();
jbSC.getUtil().createSubjectInfo(jwtPrincipal, bearerToken, subject);
RoleGroup roles = extract(subject);
jbSC.getUtil().setRoles(roles);
UndertowLogger.SECURITY_LOGGER.debugf("Authenticated caller(%s) for path(%s) with roles: %s",
credential.getName(), exchange.getRequestPath(), account.getRoles());
return AuthenticationMechanismOutcome.AUTHENTICATED;
} else {
UndertowLogger.SECURITY_LOGGER.info("Failed to authenticate JWT bearer token");
return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
}
} catch (Exception e) {
UndertowLogger.SECURITY_LOGGER.infof(e, "Failed to validate JWT bearer token");
return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
}
}
}
}
// No suitable header has been found in this request,
return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
} | java | @Override
public AuthenticationMechanismOutcome authenticate(HttpServerExchange exchange, SecurityContext securityContext) {
List<String> authHeaders = exchange.getRequestHeaders().get(AUTHORIZATION);
if (authHeaders != null) {
String bearerToken = null;
for (String current : authHeaders) {
if (current.toLowerCase(Locale.ENGLISH).startsWith("bearer ")) {
bearerToken = current.substring(7);
if (UndertowLogger.SECURITY_LOGGER.isTraceEnabled()) {
UndertowLogger.SECURITY_LOGGER.tracef("Bearer token: %s", bearerToken);
}
try {
identityManager = securityContext.getIdentityManager();
JWTCredential credential = new JWTCredential(bearerToken, authContextInfo);
if (UndertowLogger.SECURITY_LOGGER.isTraceEnabled()) {
UndertowLogger.SECURITY_LOGGER.tracef("Bearer token: %s", bearerToken);
}
// Install the JWT principal as the caller
Account account = identityManager.verify(credential.getName(), credential);
if (account != null) {
JsonWebToken jwtPrincipal = (JsonWebToken) account.getPrincipal();
securityContext.authenticationComplete(account, "MP-JWT", false);
// Workaround authenticated JWTPrincipal not being installed as user principal
// https://issues.jboss.org/browse/WFLY-9212
org.jboss.security.SecurityContext jbSC = SecurityContextAssociation.getSecurityContext();
Subject subject = jbSC.getUtil().getSubject();
jbSC.getUtil().createSubjectInfo(jwtPrincipal, bearerToken, subject);
RoleGroup roles = extract(subject);
jbSC.getUtil().setRoles(roles);
UndertowLogger.SECURITY_LOGGER.debugf("Authenticated caller(%s) for path(%s) with roles: %s",
credential.getName(), exchange.getRequestPath(), account.getRoles());
return AuthenticationMechanismOutcome.AUTHENTICATED;
} else {
UndertowLogger.SECURITY_LOGGER.info("Failed to authenticate JWT bearer token");
return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
}
} catch (Exception e) {
UndertowLogger.SECURITY_LOGGER.infof(e, "Failed to validate JWT bearer token");
return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
}
}
}
}
// No suitable header has been found in this request,
return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
} | [
"@",
"Override",
"public",
"AuthenticationMechanismOutcome",
"authenticate",
"(",
"HttpServerExchange",
"exchange",
",",
"SecurityContext",
"securityContext",
")",
"{",
"List",
"<",
"String",
">",
"authHeaders",
"=",
"exchange",
".",
"getRequestHeaders",
"(",
")",
".",
"get",
"(",
"AUTHORIZATION",
")",
";",
"if",
"(",
"authHeaders",
"!=",
"null",
")",
"{",
"String",
"bearerToken",
"=",
"null",
";",
"for",
"(",
"String",
"current",
":",
"authHeaders",
")",
"{",
"if",
"(",
"current",
".",
"toLowerCase",
"(",
"Locale",
".",
"ENGLISH",
")",
".",
"startsWith",
"(",
"\"bearer \"",
")",
")",
"{",
"bearerToken",
"=",
"current",
".",
"substring",
"(",
"7",
")",
";",
"if",
"(",
"UndertowLogger",
".",
"SECURITY_LOGGER",
".",
"isTraceEnabled",
"(",
")",
")",
"{",
"UndertowLogger",
".",
"SECURITY_LOGGER",
".",
"tracef",
"(",
"\"Bearer token: %s\"",
",",
"bearerToken",
")",
";",
"}",
"try",
"{",
"identityManager",
"=",
"securityContext",
".",
"getIdentityManager",
"(",
")",
";",
"JWTCredential",
"credential",
"=",
"new",
"JWTCredential",
"(",
"bearerToken",
",",
"authContextInfo",
")",
";",
"if",
"(",
"UndertowLogger",
".",
"SECURITY_LOGGER",
".",
"isTraceEnabled",
"(",
")",
")",
"{",
"UndertowLogger",
".",
"SECURITY_LOGGER",
".",
"tracef",
"(",
"\"Bearer token: %s\"",
",",
"bearerToken",
")",
";",
"}",
"// Install the JWT principal as the caller",
"Account",
"account",
"=",
"identityManager",
".",
"verify",
"(",
"credential",
".",
"getName",
"(",
")",
",",
"credential",
")",
";",
"if",
"(",
"account",
"!=",
"null",
")",
"{",
"JsonWebToken",
"jwtPrincipal",
"=",
"(",
"JsonWebToken",
")",
"account",
".",
"getPrincipal",
"(",
")",
";",
"securityContext",
".",
"authenticationComplete",
"(",
"account",
",",
"\"MP-JWT\"",
",",
"false",
")",
";",
"// Workaround authenticated JWTPrincipal not being installed as user principal",
"// https://issues.jboss.org/browse/WFLY-9212",
"org",
".",
"jboss",
".",
"security",
".",
"SecurityContext",
"jbSC",
"=",
"SecurityContextAssociation",
".",
"getSecurityContext",
"(",
")",
";",
"Subject",
"subject",
"=",
"jbSC",
".",
"getUtil",
"(",
")",
".",
"getSubject",
"(",
")",
";",
"jbSC",
".",
"getUtil",
"(",
")",
".",
"createSubjectInfo",
"(",
"jwtPrincipal",
",",
"bearerToken",
",",
"subject",
")",
";",
"RoleGroup",
"roles",
"=",
"extract",
"(",
"subject",
")",
";",
"jbSC",
".",
"getUtil",
"(",
")",
".",
"setRoles",
"(",
"roles",
")",
";",
"UndertowLogger",
".",
"SECURITY_LOGGER",
".",
"debugf",
"(",
"\"Authenticated caller(%s) for path(%s) with roles: %s\"",
",",
"credential",
".",
"getName",
"(",
")",
",",
"exchange",
".",
"getRequestPath",
"(",
")",
",",
"account",
".",
"getRoles",
"(",
")",
")",
";",
"return",
"AuthenticationMechanismOutcome",
".",
"AUTHENTICATED",
";",
"}",
"else",
"{",
"UndertowLogger",
".",
"SECURITY_LOGGER",
".",
"info",
"(",
"\"Failed to authenticate JWT bearer token\"",
")",
";",
"return",
"AuthenticationMechanismOutcome",
".",
"NOT_AUTHENTICATED",
";",
"}",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"UndertowLogger",
".",
"SECURITY_LOGGER",
".",
"infof",
"(",
"e",
",",
"\"Failed to validate JWT bearer token\"",
")",
";",
"return",
"AuthenticationMechanismOutcome",
".",
"NOT_AUTHENTICATED",
";",
"}",
"}",
"}",
"}",
"// No suitable header has been found in this request,",
"return",
"AuthenticationMechanismOutcome",
".",
"NOT_ATTEMPTED",
";",
"}"
] | Extract the Authorization header and validate the bearer token if it exists. If it does, and is validated, this
builds the org.jboss.security.SecurityContext authenticated Subject that drives the container APIs as well as
the authorization layers.
@param exchange - the http request exchange object
@param securityContext - the current security context that
@return one of AUTHENTICATED, NOT_AUTHENTICATED or NOT_ATTEMPTED depending on the header and authentication outcome. | [
"Extract",
"the",
"Authorization",
"header",
"and",
"validate",
"the",
"bearer",
"token",
"if",
"it",
"exists",
".",
"If",
"it",
"does",
"and",
"is",
"validated",
"this",
"builds",
"the",
"org",
".",
"jboss",
".",
"security",
".",
"SecurityContext",
"authenticated",
"Subject",
"that",
"drives",
"the",
"container",
"APIs",
"as",
"well",
"as",
"the",
"authorization",
"layers",
"."
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/fractions/microprofile/microprofile-jwt/src/main/java/org/wildfly/swarm/microprofile/jwtauth/deployment/auth/JWTAuthMechanism.java#L67-L113 | train |
thorntail/thorntail | fractions/microprofile/microprofile-jwt/src/main/java/org/wildfly/swarm/microprofile/jwtauth/deployment/auth/JWTAuthMechanism.java | JWTAuthMechanism.extract | protected RoleGroup extract(Subject subject) {
Optional<Principal> match = subject.getPrincipals()
.stream()
.filter(g -> g.getName().equals(SecurityConstants.ROLES_IDENTIFIER))
.findFirst();
Group rolesGroup = (Group) match.get();
RoleGroup roles = new SimpleRoleGroup(rolesGroup);
return roles;
} | java | protected RoleGroup extract(Subject subject) {
Optional<Principal> match = subject.getPrincipals()
.stream()
.filter(g -> g.getName().equals(SecurityConstants.ROLES_IDENTIFIER))
.findFirst();
Group rolesGroup = (Group) match.get();
RoleGroup roles = new SimpleRoleGroup(rolesGroup);
return roles;
} | [
"protected",
"RoleGroup",
"extract",
"(",
"Subject",
"subject",
")",
"{",
"Optional",
"<",
"Principal",
">",
"match",
"=",
"subject",
".",
"getPrincipals",
"(",
")",
".",
"stream",
"(",
")",
".",
"filter",
"(",
"g",
"->",
"g",
".",
"getName",
"(",
")",
".",
"equals",
"(",
"SecurityConstants",
".",
"ROLES_IDENTIFIER",
")",
")",
".",
"findFirst",
"(",
")",
";",
"Group",
"rolesGroup",
"=",
"(",
"Group",
")",
"match",
".",
"get",
"(",
")",
";",
"RoleGroup",
"roles",
"=",
"new",
"SimpleRoleGroup",
"(",
"rolesGroup",
")",
";",
"return",
"roles",
";",
"}"
] | Extract the Roles group and return it as a RoleGroup
@param subject authenticated subject
@return RoleGroup from "Roles" | [
"Extract",
"the",
"Roles",
"group",
"and",
"return",
"it",
"as",
"a",
"RoleGroup"
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/fractions/microprofile/microprofile-jwt/src/main/java/org/wildfly/swarm/microprofile/jwtauth/deployment/auth/JWTAuthMechanism.java#L128-L136 | train |
thorntail/thorntail | core/container/src/main/java/org/wildfly/swarm/container/config/ConfigViewImpl.java | ConfigViewImpl.withProperties | public ConfigViewImpl withProperties(Properties properties) {
if (properties != null) {
this.properties = properties;
this.strategy.withProperties(properties);
}
return this;
} | java | public ConfigViewImpl withProperties(Properties properties) {
if (properties != null) {
this.properties = properties;
this.strategy.withProperties(properties);
}
return this;
} | [
"public",
"ConfigViewImpl",
"withProperties",
"(",
"Properties",
"properties",
")",
"{",
"if",
"(",
"properties",
"!=",
"null",
")",
"{",
"this",
".",
"properties",
"=",
"properties",
";",
"this",
".",
"strategy",
".",
"withProperties",
"(",
"properties",
")",
";",
"}",
"return",
"this",
";",
"}"
] | Supply explicit properties object for introspection and outrespection.
@param properties The properties.
@return This view. | [
"Supply",
"explicit",
"properties",
"object",
"for",
"introspection",
"and",
"outrespection",
"."
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/core/container/src/main/java/org/wildfly/swarm/container/config/ConfigViewImpl.java#L61-L67 | train |
thorntail/thorntail | fractions/swagger/src/main/java/org/wildfly/swarm/swagger/runtime/SwaggerArchivePreparer.java | SwaggerArchivePreparer.getPackagesForScanning | private Set<String> getPackagesForScanning(WARArchive deployment) {
final Set<String> packages = new TreeSet<>();
if (indexView != null) {
DotName dotName = DotName.createSimple(Api.class.getName());
Collection<AnnotationInstance> instances = indexView.getAnnotations(dotName);
instances.forEach(ai -> {
AnnotationTarget target = ai.target();
if (target.kind() == AnnotationTarget.Kind.CLASS) {
extractAndAddPackageInfo(target.asClass(), packages, indexView);
}
});
// Scan for all top level resources.
dotName = DotName.createSimple(Path.class.getName());
instances = indexView.getAnnotations(dotName);
instances.forEach(ai -> {
AnnotationTarget target = ai.target();
switch (target.kind()) {
case CLASS:
extractAndAddPackageInfo(target.asClass(), packages, indexView);
break;
case METHOD:
extractAndAddPackageInfo(target.asMethod().declaringClass(), packages, indexView);
break;
default:
// Do nothing. Probably log something here?
}
});
// Reduce the packages to just about what is required.
Set<String> tmp = new HashSet<>(packages);
Iterator<String> itr = packages.iterator();
while (itr.hasNext()) {
String current = itr.next();
boolean remove = false;
if (current.startsWith("org.wildfly.swarm")) {
remove = true;
} else {
// Search through the list to see if a parent package has already been included in the list.
for (String s : tmp) {
if (s.length() < current.length() && current.startsWith(s)) {
remove = true;
break;
}
}
}
if (remove) {
itr.remove();
}
}
} else {
//
// Existing default behavior.
//
String packageName = null;
for (Map.Entry<ArchivePath, Node> entry : deployment.getContent().entrySet()) {
final ArchivePath key = entry.getKey();
if (key.get().endsWith(".class")) {
String parentPath = key.getParent().get();
parentPath = parentPath.replaceFirst("/", "");
String parentPackage = parentPath.replaceFirst(".*/classes/", "");
parentPackage = parentPackage.replaceAll("/", ".");
if (parentPackage.startsWith("org.wildfly.swarm")) {
SwaggerMessages.MESSAGES.ignoringPackage(parentPackage);
} else {
packageName = parentPackage;
break;
}
}
}
packages.add(packageName);
}
return packages;
} | java | private Set<String> getPackagesForScanning(WARArchive deployment) {
final Set<String> packages = new TreeSet<>();
if (indexView != null) {
DotName dotName = DotName.createSimple(Api.class.getName());
Collection<AnnotationInstance> instances = indexView.getAnnotations(dotName);
instances.forEach(ai -> {
AnnotationTarget target = ai.target();
if (target.kind() == AnnotationTarget.Kind.CLASS) {
extractAndAddPackageInfo(target.asClass(), packages, indexView);
}
});
// Scan for all top level resources.
dotName = DotName.createSimple(Path.class.getName());
instances = indexView.getAnnotations(dotName);
instances.forEach(ai -> {
AnnotationTarget target = ai.target();
switch (target.kind()) {
case CLASS:
extractAndAddPackageInfo(target.asClass(), packages, indexView);
break;
case METHOD:
extractAndAddPackageInfo(target.asMethod().declaringClass(), packages, indexView);
break;
default:
// Do nothing. Probably log something here?
}
});
// Reduce the packages to just about what is required.
Set<String> tmp = new HashSet<>(packages);
Iterator<String> itr = packages.iterator();
while (itr.hasNext()) {
String current = itr.next();
boolean remove = false;
if (current.startsWith("org.wildfly.swarm")) {
remove = true;
} else {
// Search through the list to see if a parent package has already been included in the list.
for (String s : tmp) {
if (s.length() < current.length() && current.startsWith(s)) {
remove = true;
break;
}
}
}
if (remove) {
itr.remove();
}
}
} else {
//
// Existing default behavior.
//
String packageName = null;
for (Map.Entry<ArchivePath, Node> entry : deployment.getContent().entrySet()) {
final ArchivePath key = entry.getKey();
if (key.get().endsWith(".class")) {
String parentPath = key.getParent().get();
parentPath = parentPath.replaceFirst("/", "");
String parentPackage = parentPath.replaceFirst(".*/classes/", "");
parentPackage = parentPackage.replaceAll("/", ".");
if (parentPackage.startsWith("org.wildfly.swarm")) {
SwaggerMessages.MESSAGES.ignoringPackage(parentPackage);
} else {
packageName = parentPackage;
break;
}
}
}
packages.add(packageName);
}
return packages;
} | [
"private",
"Set",
"<",
"String",
">",
"getPackagesForScanning",
"(",
"WARArchive",
"deployment",
")",
"{",
"final",
"Set",
"<",
"String",
">",
"packages",
"=",
"new",
"TreeSet",
"<>",
"(",
")",
";",
"if",
"(",
"indexView",
"!=",
"null",
")",
"{",
"DotName",
"dotName",
"=",
"DotName",
".",
"createSimple",
"(",
"Api",
".",
"class",
".",
"getName",
"(",
")",
")",
";",
"Collection",
"<",
"AnnotationInstance",
">",
"instances",
"=",
"indexView",
".",
"getAnnotations",
"(",
"dotName",
")",
";",
"instances",
".",
"forEach",
"(",
"ai",
"->",
"{",
"AnnotationTarget",
"target",
"=",
"ai",
".",
"target",
"(",
")",
";",
"if",
"(",
"target",
".",
"kind",
"(",
")",
"==",
"AnnotationTarget",
".",
"Kind",
".",
"CLASS",
")",
"{",
"extractAndAddPackageInfo",
"(",
"target",
".",
"asClass",
"(",
")",
",",
"packages",
",",
"indexView",
")",
";",
"}",
"}",
")",
";",
"// Scan for all top level resources.",
"dotName",
"=",
"DotName",
".",
"createSimple",
"(",
"Path",
".",
"class",
".",
"getName",
"(",
")",
")",
";",
"instances",
"=",
"indexView",
".",
"getAnnotations",
"(",
"dotName",
")",
";",
"instances",
".",
"forEach",
"(",
"ai",
"->",
"{",
"AnnotationTarget",
"target",
"=",
"ai",
".",
"target",
"(",
")",
";",
"switch",
"(",
"target",
".",
"kind",
"(",
")",
")",
"{",
"case",
"CLASS",
":",
"extractAndAddPackageInfo",
"(",
"target",
".",
"asClass",
"(",
")",
",",
"packages",
",",
"indexView",
")",
";",
"break",
";",
"case",
"METHOD",
":",
"extractAndAddPackageInfo",
"(",
"target",
".",
"asMethod",
"(",
")",
".",
"declaringClass",
"(",
")",
",",
"packages",
",",
"indexView",
")",
";",
"break",
";",
"default",
":",
"// Do nothing. Probably log something here?",
"}",
"}",
")",
";",
"// Reduce the packages to just about what is required.",
"Set",
"<",
"String",
">",
"tmp",
"=",
"new",
"HashSet",
"<>",
"(",
"packages",
")",
";",
"Iterator",
"<",
"String",
">",
"itr",
"=",
"packages",
".",
"iterator",
"(",
")",
";",
"while",
"(",
"itr",
".",
"hasNext",
"(",
")",
")",
"{",
"String",
"current",
"=",
"itr",
".",
"next",
"(",
")",
";",
"boolean",
"remove",
"=",
"false",
";",
"if",
"(",
"current",
".",
"startsWith",
"(",
"\"org.wildfly.swarm\"",
")",
")",
"{",
"remove",
"=",
"true",
";",
"}",
"else",
"{",
"// Search through the list to see if a parent package has already been included in the list.",
"for",
"(",
"String",
"s",
":",
"tmp",
")",
"{",
"if",
"(",
"s",
".",
"length",
"(",
")",
"<",
"current",
".",
"length",
"(",
")",
"&&",
"current",
".",
"startsWith",
"(",
"s",
")",
")",
"{",
"remove",
"=",
"true",
";",
"break",
";",
"}",
"}",
"}",
"if",
"(",
"remove",
")",
"{",
"itr",
".",
"remove",
"(",
")",
";",
"}",
"}",
"}",
"else",
"{",
"//",
"// Existing default behavior.",
"//",
"String",
"packageName",
"=",
"null",
";",
"for",
"(",
"Map",
".",
"Entry",
"<",
"ArchivePath",
",",
"Node",
">",
"entry",
":",
"deployment",
".",
"getContent",
"(",
")",
".",
"entrySet",
"(",
")",
")",
"{",
"final",
"ArchivePath",
"key",
"=",
"entry",
".",
"getKey",
"(",
")",
";",
"if",
"(",
"key",
".",
"get",
"(",
")",
".",
"endsWith",
"(",
"\".class\"",
")",
")",
"{",
"String",
"parentPath",
"=",
"key",
".",
"getParent",
"(",
")",
".",
"get",
"(",
")",
";",
"parentPath",
"=",
"parentPath",
".",
"replaceFirst",
"(",
"\"/\"",
",",
"\"\"",
")",
";",
"String",
"parentPackage",
"=",
"parentPath",
".",
"replaceFirst",
"(",
"\".*/classes/\"",
",",
"\"\"",
")",
";",
"parentPackage",
"=",
"parentPackage",
".",
"replaceAll",
"(",
"\"/\"",
",",
"\".\"",
")",
";",
"if",
"(",
"parentPackage",
".",
"startsWith",
"(",
"\"org.wildfly.swarm\"",
")",
")",
"{",
"SwaggerMessages",
".",
"MESSAGES",
".",
"ignoringPackage",
"(",
"parentPackage",
")",
";",
"}",
"else",
"{",
"packageName",
"=",
"parentPackage",
";",
"break",
";",
"}",
"}",
"}",
"packages",
".",
"add",
"(",
"packageName",
")",
";",
"}",
"return",
"packages",
";",
"}"
] | Get the packages that should be scanned by Swagger. This method attempts to determine the root packages by leveraging
the IndexView of the deployment. If the IndexView is unavailable, then this method will fallback to the scanning the
classes manually.
@return the packages that should be scanned by Swagger. | [
"Get",
"the",
"packages",
"that",
"should",
"be",
"scanned",
"by",
"Swagger",
".",
"This",
"method",
"attempts",
"to",
"determine",
"the",
"root",
"packages",
"by",
"leveraging",
"the",
"IndexView",
"of",
"the",
"deployment",
".",
"If",
"the",
"IndexView",
"is",
"unavailable",
"then",
"this",
"method",
"will",
"fallback",
"to",
"the",
"scanning",
"the",
"classes",
"manually",
"."
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/fractions/swagger/src/main/java/org/wildfly/swarm/swagger/runtime/SwaggerArchivePreparer.java#L208-L283 | train |
thorntail/thorntail | core/container/src/main/java/org/wildfly/swarm/internal/wildfly/SelfContainedContainer.java | SelfContainedContainer.stop | public void stop() throws Exception {
final CountDownLatch latch = new CountDownLatch(1);
this.serviceContainer.addTerminateListener(info -> latch.countDown());
this.serviceContainer.shutdown();
latch.await();
executor.submit(new Runnable() {
@Override
public void run() {
TempFileManager.deleteRecursively(tmpDir);
}
});
executor.shutdown();
} | java | public void stop() throws Exception {
final CountDownLatch latch = new CountDownLatch(1);
this.serviceContainer.addTerminateListener(info -> latch.countDown());
this.serviceContainer.shutdown();
latch.await();
executor.submit(new Runnable() {
@Override
public void run() {
TempFileManager.deleteRecursively(tmpDir);
}
});
executor.shutdown();
} | [
"public",
"void",
"stop",
"(",
")",
"throws",
"Exception",
"{",
"final",
"CountDownLatch",
"latch",
"=",
"new",
"CountDownLatch",
"(",
"1",
")",
";",
"this",
".",
"serviceContainer",
".",
"addTerminateListener",
"(",
"info",
"->",
"latch",
".",
"countDown",
"(",
")",
")",
";",
"this",
".",
"serviceContainer",
".",
"shutdown",
"(",
")",
";",
"latch",
".",
"await",
"(",
")",
";",
"executor",
".",
"submit",
"(",
"new",
"Runnable",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"run",
"(",
")",
"{",
"TempFileManager",
".",
"deleteRecursively",
"(",
"tmpDir",
")",
";",
"}",
"}",
")",
";",
"executor",
".",
"shutdown",
"(",
")",
";",
"}"
] | Stops the service container and cleans up all file system resources.
@throws Exception | [
"Stops",
"the",
"service",
"container",
"and",
"cleans",
"up",
"all",
"file",
"system",
"resources",
"."
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/core/container/src/main/java/org/wildfly/swarm/internal/wildfly/SelfContainedContainer.java#L152-L167 | train |
thorntail/thorntail | fractions/microprofile/microprofile-health/src/main/java/org/wildfly/swarm/microprofile/health/deployment/HealthExtension.java | HealthExtension.beforeShutdown | public void beforeShutdown(@Observes final BeforeShutdown bs) {
monitor.unregisterHealthReporter();
monitor.unregisterContextClassLoader();
reporter = null;
reporterInstance.preDestroy().dispose();
reporterInstance = null;
} | java | public void beforeShutdown(@Observes final BeforeShutdown bs) {
monitor.unregisterHealthReporter();
monitor.unregisterContextClassLoader();
reporter = null;
reporterInstance.preDestroy().dispose();
reporterInstance = null;
} | [
"public",
"void",
"beforeShutdown",
"(",
"@",
"Observes",
"final",
"BeforeShutdown",
"bs",
")",
"{",
"monitor",
".",
"unregisterHealthReporter",
"(",
")",
";",
"monitor",
".",
"unregisterContextClassLoader",
"(",
")",
";",
"reporter",
"=",
"null",
";",
"reporterInstance",
".",
"preDestroy",
"(",
")",
".",
"dispose",
"(",
")",
";",
"reporterInstance",
"=",
"null",
";",
"}"
] | Called when the deployment is undeployed.
Remove the reporter instance of {@link SmallRyeHealthReporter} from the {@link Monitor}.
Handle manually their CDI destroy lifecycle. | [
"Called",
"when",
"the",
"deployment",
"is",
"undeployed",
"."
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/fractions/microprofile/microprofile-health/src/main/java/org/wildfly/swarm/microprofile/health/deployment/HealthExtension.java#L89-L95 | train |
thorntail/thorntail | arquillian/daemon/src/main/java/org/wildfly/swarm/arquillian/daemon/ContextManager.java | ContextManager.setup | void setup(final Map<String, Object> properties) {
final List<SetupAction> successfulActions = new ArrayList<SetupAction>();
for (final SetupAction action : setupActions) {
try {
action.setup(properties);
successfulActions.add(action);
} catch (final Throwable e) {
for (SetupAction s : successfulActions) {
try {
s.teardown(properties);
} catch (final Throwable t) {
// we ignore these, and just propagate the exception that caused the setup to fail
}
}
throw new RuntimeException(e);
}
}
} | java | void setup(final Map<String, Object> properties) {
final List<SetupAction> successfulActions = new ArrayList<SetupAction>();
for (final SetupAction action : setupActions) {
try {
action.setup(properties);
successfulActions.add(action);
} catch (final Throwable e) {
for (SetupAction s : successfulActions) {
try {
s.teardown(properties);
} catch (final Throwable t) {
// we ignore these, and just propagate the exception that caused the setup to fail
}
}
throw new RuntimeException(e);
}
}
} | [
"void",
"setup",
"(",
"final",
"Map",
"<",
"String",
",",
"Object",
">",
"properties",
")",
"{",
"final",
"List",
"<",
"SetupAction",
">",
"successfulActions",
"=",
"new",
"ArrayList",
"<",
"SetupAction",
">",
"(",
")",
";",
"for",
"(",
"final",
"SetupAction",
"action",
":",
"setupActions",
")",
"{",
"try",
"{",
"action",
".",
"setup",
"(",
"properties",
")",
";",
"successfulActions",
".",
"add",
"(",
"action",
")",
";",
"}",
"catch",
"(",
"final",
"Throwable",
"e",
")",
"{",
"for",
"(",
"SetupAction",
"s",
":",
"successfulActions",
")",
"{",
"try",
"{",
"s",
".",
"teardown",
"(",
"properties",
")",
";",
"}",
"catch",
"(",
"final",
"Throwable",
"t",
")",
"{",
"// we ignore these, and just propagate the exception that caused the setup to fail",
"}",
"}",
"throw",
"new",
"RuntimeException",
"(",
"e",
")",
";",
"}",
"}",
"}"
] | Sets up the contexts. If any of the setup actions fail then any setup contexts are torn down, and then the exception is
wrapped and thrown | [
"Sets",
"up",
"the",
"contexts",
".",
"If",
"any",
"of",
"the",
"setup",
"actions",
"fail",
"then",
"any",
"setup",
"contexts",
"are",
"torn",
"down",
"and",
"then",
"the",
"exception",
"is",
"wrapped",
"and",
"thrown"
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/arquillian/daemon/src/main/java/org/wildfly/swarm/arquillian/daemon/ContextManager.java#L52-L69 | train |
thorntail/thorntail | plugins/maven/src/main/java/org/wildfly/swarm/plugin/maven/MavenArtifactResolvingHelper.java | MavenArtifactResolvingHelper.resolveDependenciesInParallel | private void resolveDependenciesInParallel(List<DependencyNode> nodes) {
List<ArtifactRequest> artifactRequests = nodes.stream()
.map(node -> new ArtifactRequest(node.getArtifact(), this.remoteRepositories, null))
.collect(Collectors.toList());
try {
this.resolver.resolveArtifacts(this.session, artifactRequests);
} catch (ArtifactResolutionException e) {
// ignore, error will be printed by resolve(ArtifactSpec)
}
} | java | private void resolveDependenciesInParallel(List<DependencyNode> nodes) {
List<ArtifactRequest> artifactRequests = nodes.stream()
.map(node -> new ArtifactRequest(node.getArtifact(), this.remoteRepositories, null))
.collect(Collectors.toList());
try {
this.resolver.resolveArtifacts(this.session, artifactRequests);
} catch (ArtifactResolutionException e) {
// ignore, error will be printed by resolve(ArtifactSpec)
}
} | [
"private",
"void",
"resolveDependenciesInParallel",
"(",
"List",
"<",
"DependencyNode",
">",
"nodes",
")",
"{",
"List",
"<",
"ArtifactRequest",
">",
"artifactRequests",
"=",
"nodes",
".",
"stream",
"(",
")",
".",
"map",
"(",
"node",
"->",
"new",
"ArtifactRequest",
"(",
"node",
".",
"getArtifact",
"(",
")",
",",
"this",
".",
"remoteRepositories",
",",
"null",
")",
")",
".",
"collect",
"(",
"Collectors",
".",
"toList",
"(",
")",
")",
";",
"try",
"{",
"this",
".",
"resolver",
".",
"resolveArtifacts",
"(",
"this",
".",
"session",
",",
"artifactRequests",
")",
";",
"}",
"catch",
"(",
"ArtifactResolutionException",
"e",
")",
"{",
"// ignore, error will be printed by resolve(ArtifactSpec)",
"}",
"}"
] | This is needed to speed up things. | [
"This",
"is",
"needed",
"to",
"speed",
"up",
"things",
"."
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/plugins/maven/src/main/java/org/wildfly/swarm/plugin/maven/MavenArtifactResolvingHelper.java#L222-L232 | train |
thorntail/thorntail | core/container/src/main/java/org/wildfly/swarm/Swarm.java | Swarm.outboundSocketBinding | public Swarm outboundSocketBinding(String socketBindingGroup, OutboundSocketBinding binding) {
this.outboundSocketBindings.add(new OutboundSocketBindingRequest(socketBindingGroup, binding));
return this;
} | java | public Swarm outboundSocketBinding(String socketBindingGroup, OutboundSocketBinding binding) {
this.outboundSocketBindings.add(new OutboundSocketBindingRequest(socketBindingGroup, binding));
return this;
} | [
"public",
"Swarm",
"outboundSocketBinding",
"(",
"String",
"socketBindingGroup",
",",
"OutboundSocketBinding",
"binding",
")",
"{",
"this",
".",
"outboundSocketBindings",
".",
"add",
"(",
"new",
"OutboundSocketBindingRequest",
"(",
"socketBindingGroup",
",",
"binding",
")",
")",
";",
"return",
"this",
";",
"}"
] | Add an outbound socket-binding to the container.
<p>In the event the specified {@code socketBindingGroup} does not exist, the socket-binding
will be completely ignored.</p>
TODO fix the above-mentioned issue.
@param socketBindingGroup The name of the socket-binding group to attach a binding to.
@param binding The outbound socket-binding to add.
@return This container. | [
"Add",
"an",
"outbound",
"socket",
"-",
"binding",
"to",
"the",
"container",
"."
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/core/container/src/main/java/org/wildfly/swarm/Swarm.java#L351-L354 | train |
thorntail/thorntail | core/container/src/main/java/org/wildfly/swarm/Swarm.java | Swarm.socketBinding | public Swarm socketBinding(String socketBindingGroup, SocketBinding binding) {
this.socketBindings.add(new SocketBindingRequest(socketBindingGroup, binding));
return this;
} | java | public Swarm socketBinding(String socketBindingGroup, SocketBinding binding) {
this.socketBindings.add(new SocketBindingRequest(socketBindingGroup, binding));
return this;
} | [
"public",
"Swarm",
"socketBinding",
"(",
"String",
"socketBindingGroup",
",",
"SocketBinding",
"binding",
")",
"{",
"this",
".",
"socketBindings",
".",
"add",
"(",
"new",
"SocketBindingRequest",
"(",
"socketBindingGroup",
",",
"binding",
")",
")",
";",
"return",
"this",
";",
"}"
] | Add an inbound socket-binding to the container.
<p>In the even the specified {@code socketBindingGroup} does no exist, the socket-binding
will be completely ignored.</p>
TODO fix the above-mentioned issue.
@param socketBindingGroup The name of the socket-binding group to attach a binding to.
@param binding The inbound socket-binding to add.
@return This container. | [
"Add",
"an",
"inbound",
"socket",
"-",
"binding",
"to",
"the",
"container",
"."
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/core/container/src/main/java/org/wildfly/swarm/Swarm.java#L368-L371 | train |
thorntail/thorntail | core/container/src/main/java/org/wildfly/swarm/Swarm.java | Swarm.start | public Swarm start() throws Exception {
INSTANCE = this;
try (AutoCloseable handle = Performance.time("Thorntail.start()")) {
Module module = Module.getBootModuleLoader().loadModule(CONTAINER_MODULE_NAME);
Class<?> bootstrapClass = module.getClassLoader().loadClass("org.wildfly.swarm.container.runtime.ServerBootstrapImpl");
ServerBootstrap bootstrap = (ServerBootstrap) bootstrapClass.newInstance();
bootstrap
.withArguments(this.args)
.withBootstrapDebug(this.debugBootstrap)
.withExplicitlyInstalledFractions(this.explicitlyInstalledFractions)
.withSocketBindings(this.socketBindings)
.withOutboundSocketBindings(this.outboundSocketBindings)
.withUserComponents(this.userComponentClasses)
.withXmlConfig(this.xmlConfig)
.withConfigView(this.configView.get(true));
this.server = bootstrap.bootstrap();
return this;
}
} | java | public Swarm start() throws Exception {
INSTANCE = this;
try (AutoCloseable handle = Performance.time("Thorntail.start()")) {
Module module = Module.getBootModuleLoader().loadModule(CONTAINER_MODULE_NAME);
Class<?> bootstrapClass = module.getClassLoader().loadClass("org.wildfly.swarm.container.runtime.ServerBootstrapImpl");
ServerBootstrap bootstrap = (ServerBootstrap) bootstrapClass.newInstance();
bootstrap
.withArguments(this.args)
.withBootstrapDebug(this.debugBootstrap)
.withExplicitlyInstalledFractions(this.explicitlyInstalledFractions)
.withSocketBindings(this.socketBindings)
.withOutboundSocketBindings(this.outboundSocketBindings)
.withUserComponents(this.userComponentClasses)
.withXmlConfig(this.xmlConfig)
.withConfigView(this.configView.get(true));
this.server = bootstrap.bootstrap();
return this;
}
} | [
"public",
"Swarm",
"start",
"(",
")",
"throws",
"Exception",
"{",
"INSTANCE",
"=",
"this",
";",
"try",
"(",
"AutoCloseable",
"handle",
"=",
"Performance",
".",
"time",
"(",
"\"Thorntail.start()\"",
")",
")",
"{",
"Module",
"module",
"=",
"Module",
".",
"getBootModuleLoader",
"(",
")",
".",
"loadModule",
"(",
"CONTAINER_MODULE_NAME",
")",
";",
"Class",
"<",
"?",
">",
"bootstrapClass",
"=",
"module",
".",
"getClassLoader",
"(",
")",
".",
"loadClass",
"(",
"\"org.wildfly.swarm.container.runtime.ServerBootstrapImpl\"",
")",
";",
"ServerBootstrap",
"bootstrap",
"=",
"(",
"ServerBootstrap",
")",
"bootstrapClass",
".",
"newInstance",
"(",
")",
";",
"bootstrap",
".",
"withArguments",
"(",
"this",
".",
"args",
")",
".",
"withBootstrapDebug",
"(",
"this",
".",
"debugBootstrap",
")",
".",
"withExplicitlyInstalledFractions",
"(",
"this",
".",
"explicitlyInstalledFractions",
")",
".",
"withSocketBindings",
"(",
"this",
".",
"socketBindings",
")",
".",
"withOutboundSocketBindings",
"(",
"this",
".",
"outboundSocketBindings",
")",
".",
"withUserComponents",
"(",
"this",
".",
"userComponentClasses",
")",
".",
"withXmlConfig",
"(",
"this",
".",
"xmlConfig",
")",
".",
"withConfigView",
"(",
"this",
".",
"configView",
".",
"get",
"(",
"true",
")",
")",
";",
"this",
".",
"server",
"=",
"bootstrap",
".",
"bootstrap",
"(",
")",
";",
"return",
"this",
";",
"}",
"}"
] | Start the container.
<p>This is a blocking call, which guarateens that when it returns without error, the
container is fully started.</p>
@return The container.
@throws Exception if an error occurs. | [
"Start",
"the",
"container",
"."
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/core/container/src/main/java/org/wildfly/swarm/Swarm.java#L382-L405 | train |
thorntail/thorntail | core/container/src/main/java/org/wildfly/swarm/Swarm.java | Swarm.stop | public Swarm stop() throws Exception {
if (this.server == null) {
throw SwarmMessages.MESSAGES.containerNotStarted("stop()");
}
this.server.stop();
this.server = null;
Module module = Module.getBootModuleLoader().loadModule(CONTAINER_MODULE_NAME);
Class<?> shutdownClass = module.getClassLoader().loadClass("org.wildfly.swarm.container.runtime.WeldShutdownImpl");
WeldShutdown shutdown = (WeldShutdown) shutdownClass.newInstance();
shutdown.shutdown();
return this;
} | java | public Swarm stop() throws Exception {
if (this.server == null) {
throw SwarmMessages.MESSAGES.containerNotStarted("stop()");
}
this.server.stop();
this.server = null;
Module module = Module.getBootModuleLoader().loadModule(CONTAINER_MODULE_NAME);
Class<?> shutdownClass = module.getClassLoader().loadClass("org.wildfly.swarm.container.runtime.WeldShutdownImpl");
WeldShutdown shutdown = (WeldShutdown) shutdownClass.newInstance();
shutdown.shutdown();
return this;
} | [
"public",
"Swarm",
"stop",
"(",
")",
"throws",
"Exception",
"{",
"if",
"(",
"this",
".",
"server",
"==",
"null",
")",
"{",
"throw",
"SwarmMessages",
".",
"MESSAGES",
".",
"containerNotStarted",
"(",
"\"stop()\"",
")",
";",
"}",
"this",
".",
"server",
".",
"stop",
"(",
")",
";",
"this",
".",
"server",
"=",
"null",
";",
"Module",
"module",
"=",
"Module",
".",
"getBootModuleLoader",
"(",
")",
".",
"loadModule",
"(",
"CONTAINER_MODULE_NAME",
")",
";",
"Class",
"<",
"?",
">",
"shutdownClass",
"=",
"module",
".",
"getClassLoader",
"(",
")",
".",
"loadClass",
"(",
"\"org.wildfly.swarm.container.runtime.WeldShutdownImpl\"",
")",
";",
"WeldShutdown",
"shutdown",
"=",
"(",
"WeldShutdown",
")",
"shutdownClass",
".",
"newInstance",
"(",
")",
";",
"shutdown",
".",
"shutdown",
"(",
")",
";",
"return",
"this",
";",
"}"
] | Stop the container, first undeploying all deployments.
@return THe container.
@throws Exception If an error occurs. | [
"Stop",
"the",
"container",
"first",
"undeploying",
"all",
"deployments",
"."
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/core/container/src/main/java/org/wildfly/swarm/Swarm.java#L428-L444 | train |
thorntail/thorntail | core/container/src/main/java/org/wildfly/swarm/Swarm.java | Swarm.deploy | public Swarm deploy() throws IllegalStateException, DeploymentException {
if (this.server == null) {
throw SwarmMessages.MESSAGES.containerNotStarted("deploy()");
}
if (ApplicationEnvironment.get().isHollow()) {
this.server.deployer().deploy(
getCommandLine().extraArguments()
.stream()
.map(e -> Paths.get(e))
.collect(Collectors.toList())
);
} else {
this.server.deployer().deploy();
}
return this;
} | java | public Swarm deploy() throws IllegalStateException, DeploymentException {
if (this.server == null) {
throw SwarmMessages.MESSAGES.containerNotStarted("deploy()");
}
if (ApplicationEnvironment.get().isHollow()) {
this.server.deployer().deploy(
getCommandLine().extraArguments()
.stream()
.map(e -> Paths.get(e))
.collect(Collectors.toList())
);
} else {
this.server.deployer().deploy();
}
return this;
} | [
"public",
"Swarm",
"deploy",
"(",
")",
"throws",
"IllegalStateException",
",",
"DeploymentException",
"{",
"if",
"(",
"this",
".",
"server",
"==",
"null",
")",
"{",
"throw",
"SwarmMessages",
".",
"MESSAGES",
".",
"containerNotStarted",
"(",
"\"deploy()\"",
")",
";",
"}",
"if",
"(",
"ApplicationEnvironment",
".",
"get",
"(",
")",
".",
"isHollow",
"(",
")",
")",
"{",
"this",
".",
"server",
".",
"deployer",
"(",
")",
".",
"deploy",
"(",
"getCommandLine",
"(",
")",
".",
"extraArguments",
"(",
")",
".",
"stream",
"(",
")",
".",
"map",
"(",
"e",
"->",
"Paths",
".",
"get",
"(",
"e",
")",
")",
".",
"collect",
"(",
"Collectors",
".",
"toList",
"(",
")",
")",
")",
";",
"}",
"else",
"{",
"this",
".",
"server",
".",
"deployer",
"(",
")",
".",
"deploy",
"(",
")",
";",
"}",
"return",
"this",
";",
"}"
] | Perform a default deployment.
<p>For regular uberjars, it is effectively a short-cut for {@code deploy(swarm.createDefaultDeployment())},
deploying the baked-in deployment.</p>
<p>For hollow uberjars, it deploys whatever deployments were passed through the command-line, as
none are baked-in.</p>
@return The container.
@throws DeploymentException if an error occurs.
@throws IllegalStateException if the container has not already been started.
@see #Swarm(String...)
@see #setArgs(String...)
@see #deploy(Archive)
@see #createDefaultDeployment() | [
"Perform",
"a",
"default",
"deployment",
"."
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/core/container/src/main/java/org/wildfly/swarm/Swarm.java#L463-L479 | train |
thorntail/thorntail | core/container/src/main/java/org/wildfly/swarm/Swarm.java | Swarm.createDefaultDeployment | public Archive<?> createDefaultDeployment() throws Exception {
if (this.server == null) {
throw SwarmMessages.MESSAGES.containerNotStarted("createDefaultDeployment()");
}
return this.server.deployer().createDefaultDeployment();
} | java | public Archive<?> createDefaultDeployment() throws Exception {
if (this.server == null) {
throw SwarmMessages.MESSAGES.containerNotStarted("createDefaultDeployment()");
}
return this.server.deployer().createDefaultDeployment();
} | [
"public",
"Archive",
"<",
"?",
">",
"createDefaultDeployment",
"(",
")",
"throws",
"Exception",
"{",
"if",
"(",
"this",
".",
"server",
"==",
"null",
")",
"{",
"throw",
"SwarmMessages",
".",
"MESSAGES",
".",
"containerNotStarted",
"(",
"\"createDefaultDeployment()\"",
")",
";",
"}",
"return",
"this",
".",
"server",
".",
"deployer",
"(",
")",
".",
"createDefaultDeployment",
"(",
")",
";",
"}"
] | Retrieve the default ShrinkWrap deployment.
@return The default deployment, unmodified. | [
"Retrieve",
"the",
"default",
"ShrinkWrap",
"deployment",
"."
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/core/container/src/main/java/org/wildfly/swarm/Swarm.java#L502-L508 | train |
thorntail/thorntail | core/container/src/main/java/org/wildfly/swarm/Swarm.java | Swarm.artifact | public static JavaArchive artifact(String gav, String asName) throws Exception {
return artifactLookup().artifact(gav, asName);
} | java | public static JavaArchive artifact(String gav, String asName) throws Exception {
return artifactLookup().artifact(gav, asName);
} | [
"public",
"static",
"JavaArchive",
"artifact",
"(",
"String",
"gav",
",",
"String",
"asName",
")",
"throws",
"Exception",
"{",
"return",
"artifactLookup",
"(",
")",
".",
"artifact",
"(",
"gav",
",",
"asName",
")",
";",
"}"
] | Retrieve an artifact that was part of the original build using a
full or simplified Maven GAV specifier, returning an archive with a
specified name.
@param gav The Maven GAV.
@return The located artifact, as a {@code JavaArchive} with the specified name.
@throws Exception If the specified artifact is not locatable.
@see #artifact(String) | [
"Retrieve",
"an",
"artifact",
"that",
"was",
"part",
"of",
"the",
"original",
"build",
"using",
"a",
"full",
"or",
"simplified",
"Maven",
"GAV",
"specifier",
"returning",
"an",
"archive",
"with",
"a",
"specified",
"name",
"."
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/core/container/src/main/java/org/wildfly/swarm/Swarm.java#L840-L842 | train |
thorntail/thorntail | core/container/src/main/java/org/wildfly/swarm/Swarm.java | Swarm.installModuleMBeanServer | private void installModuleMBeanServer() {
try {
Method method = ModuleLoader.class.getDeclaredMethod("installMBeanServer");
method.setAccessible(true);
method.invoke(null);
} catch (Exception e) {
SwarmMessages.MESSAGES.moduleMBeanServerNotInstalled(e);
}
} | java | private void installModuleMBeanServer() {
try {
Method method = ModuleLoader.class.getDeclaredMethod("installMBeanServer");
method.setAccessible(true);
method.invoke(null);
} catch (Exception e) {
SwarmMessages.MESSAGES.moduleMBeanServerNotInstalled(e);
}
} | [
"private",
"void",
"installModuleMBeanServer",
"(",
")",
"{",
"try",
"{",
"Method",
"method",
"=",
"ModuleLoader",
".",
"class",
".",
"getDeclaredMethod",
"(",
"\"installMBeanServer\"",
")",
";",
"method",
".",
"setAccessible",
"(",
"true",
")",
";",
"method",
".",
"invoke",
"(",
"null",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"SwarmMessages",
".",
"MESSAGES",
".",
"moduleMBeanServerNotInstalled",
"(",
"e",
")",
";",
"}",
"}"
] | Installs the Module MBeanServer. | [
"Installs",
"the",
"Module",
"MBeanServer",
"."
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/core/container/src/main/java/org/wildfly/swarm/Swarm.java#L857-L865 | train |
thorntail/thorntail | core/bootstrap/src/main/java/org/wildfly/swarm/bootstrap/modules/GradleResolver.java | GradleResolver.downloadFromRemoteRepository | File downloadFromRemoteRepository(ArtifactCoordinates artifactCoordinates, String packaging, Path artifactDirectory) {
String artifactRelativeHttpPath = toGradleArtifactPath(artifactCoordinates);
String artifactRelativeMetadataHttpPath = artifactCoordinates.relativeMetadataPath('/');
for (String remoteRepos : remoteRepositories) {
String artifactAbsoluteHttpPath = remoteRepos + artifactRelativeHttpPath + ".";
File targetArtifactPomDirectory = artifactDirectory.resolve(computeGradleUUID(artifactCoordinates + ":pom")).toFile();
File targetArtifactDirectory = artifactDirectory.resolve(computeGradleUUID(artifactCoordinates + ":" + packaging)).toFile();
File artifactFile = doDownload(remoteRepos, artifactAbsoluteHttpPath, artifactRelativeHttpPath, artifactCoordinates, packaging, targetArtifactPomDirectory, targetArtifactDirectory);
if (artifactFile != null) {
return artifactFile; // Success
}
//Try to doDownload the snapshot version
if (artifactCoordinates.isSnapshot()) {
String remoteMetadataPath = remoteRepos + artifactRelativeMetadataHttpPath;
try {
String timestamp = MavenArtifactUtil.downloadTimestampVersion(artifactCoordinates + ":" + packaging, remoteMetadataPath);
String timestampedArtifactRelativePath = artifactCoordinates.relativeArtifactPath('/', timestamp);
String artifactTimestampedAbsoluteHttpPath = remoteRepos + timestampedArtifactRelativePath + ".";
File targetTimestampedArtifactPomDirectory = artifactDirectory.resolve(computeGradleUUID(artifactCoordinates + ":" + timestamp + ":pom")).toFile();
File targetTimestampedArtifactDirectory = artifactDirectory.resolve(computeGradleUUID(artifactCoordinates + ":" + packaging)).toFile();
File snapshotArtifactFile = doDownload(remoteRepos, artifactTimestampedAbsoluteHttpPath, timestampedArtifactRelativePath, artifactCoordinates, packaging, targetTimestampedArtifactPomDirectory, targetTimestampedArtifactDirectory);
if (snapshotArtifactFile != null) {
return snapshotArtifactFile; //Success
}
} catch (XPathExpressionException | IOException ex) {
Module.getModuleLogger().trace(ex, "Could not doDownload '%s' from '%s' repository", artifactRelativeHttpPath, remoteRepos);
// try next one
}
}
}
return null;
} | java | File downloadFromRemoteRepository(ArtifactCoordinates artifactCoordinates, String packaging, Path artifactDirectory) {
String artifactRelativeHttpPath = toGradleArtifactPath(artifactCoordinates);
String artifactRelativeMetadataHttpPath = artifactCoordinates.relativeMetadataPath('/');
for (String remoteRepos : remoteRepositories) {
String artifactAbsoluteHttpPath = remoteRepos + artifactRelativeHttpPath + ".";
File targetArtifactPomDirectory = artifactDirectory.resolve(computeGradleUUID(artifactCoordinates + ":pom")).toFile();
File targetArtifactDirectory = artifactDirectory.resolve(computeGradleUUID(artifactCoordinates + ":" + packaging)).toFile();
File artifactFile = doDownload(remoteRepos, artifactAbsoluteHttpPath, artifactRelativeHttpPath, artifactCoordinates, packaging, targetArtifactPomDirectory, targetArtifactDirectory);
if (artifactFile != null) {
return artifactFile; // Success
}
//Try to doDownload the snapshot version
if (artifactCoordinates.isSnapshot()) {
String remoteMetadataPath = remoteRepos + artifactRelativeMetadataHttpPath;
try {
String timestamp = MavenArtifactUtil.downloadTimestampVersion(artifactCoordinates + ":" + packaging, remoteMetadataPath);
String timestampedArtifactRelativePath = artifactCoordinates.relativeArtifactPath('/', timestamp);
String artifactTimestampedAbsoluteHttpPath = remoteRepos + timestampedArtifactRelativePath + ".";
File targetTimestampedArtifactPomDirectory = artifactDirectory.resolve(computeGradleUUID(artifactCoordinates + ":" + timestamp + ":pom")).toFile();
File targetTimestampedArtifactDirectory = artifactDirectory.resolve(computeGradleUUID(artifactCoordinates + ":" + packaging)).toFile();
File snapshotArtifactFile = doDownload(remoteRepos, artifactTimestampedAbsoluteHttpPath, timestampedArtifactRelativePath, artifactCoordinates, packaging, targetTimestampedArtifactPomDirectory, targetTimestampedArtifactDirectory);
if (snapshotArtifactFile != null) {
return snapshotArtifactFile; //Success
}
} catch (XPathExpressionException | IOException ex) {
Module.getModuleLogger().trace(ex, "Could not doDownload '%s' from '%s' repository", artifactRelativeHttpPath, remoteRepos);
// try next one
}
}
}
return null;
} | [
"File",
"downloadFromRemoteRepository",
"(",
"ArtifactCoordinates",
"artifactCoordinates",
",",
"String",
"packaging",
",",
"Path",
"artifactDirectory",
")",
"{",
"String",
"artifactRelativeHttpPath",
"=",
"toGradleArtifactPath",
"(",
"artifactCoordinates",
")",
";",
"String",
"artifactRelativeMetadataHttpPath",
"=",
"artifactCoordinates",
".",
"relativeMetadataPath",
"(",
"'",
"'",
")",
";",
"for",
"(",
"String",
"remoteRepos",
":",
"remoteRepositories",
")",
"{",
"String",
"artifactAbsoluteHttpPath",
"=",
"remoteRepos",
"+",
"artifactRelativeHttpPath",
"+",
"\".\"",
";",
"File",
"targetArtifactPomDirectory",
"=",
"artifactDirectory",
".",
"resolve",
"(",
"computeGradleUUID",
"(",
"artifactCoordinates",
"+",
"\":pom\"",
")",
")",
".",
"toFile",
"(",
")",
";",
"File",
"targetArtifactDirectory",
"=",
"artifactDirectory",
".",
"resolve",
"(",
"computeGradleUUID",
"(",
"artifactCoordinates",
"+",
"\":\"",
"+",
"packaging",
")",
")",
".",
"toFile",
"(",
")",
";",
"File",
"artifactFile",
"=",
"doDownload",
"(",
"remoteRepos",
",",
"artifactAbsoluteHttpPath",
",",
"artifactRelativeHttpPath",
",",
"artifactCoordinates",
",",
"packaging",
",",
"targetArtifactPomDirectory",
",",
"targetArtifactDirectory",
")",
";",
"if",
"(",
"artifactFile",
"!=",
"null",
")",
"{",
"return",
"artifactFile",
";",
"// Success",
"}",
"//Try to doDownload the snapshot version",
"if",
"(",
"artifactCoordinates",
".",
"isSnapshot",
"(",
")",
")",
"{",
"String",
"remoteMetadataPath",
"=",
"remoteRepos",
"+",
"artifactRelativeMetadataHttpPath",
";",
"try",
"{",
"String",
"timestamp",
"=",
"MavenArtifactUtil",
".",
"downloadTimestampVersion",
"(",
"artifactCoordinates",
"+",
"\":\"",
"+",
"packaging",
",",
"remoteMetadataPath",
")",
";",
"String",
"timestampedArtifactRelativePath",
"=",
"artifactCoordinates",
".",
"relativeArtifactPath",
"(",
"'",
"'",
",",
"timestamp",
")",
";",
"String",
"artifactTimestampedAbsoluteHttpPath",
"=",
"remoteRepos",
"+",
"timestampedArtifactRelativePath",
"+",
"\".\"",
";",
"File",
"targetTimestampedArtifactPomDirectory",
"=",
"artifactDirectory",
".",
"resolve",
"(",
"computeGradleUUID",
"(",
"artifactCoordinates",
"+",
"\":\"",
"+",
"timestamp",
"+",
"\":pom\"",
")",
")",
".",
"toFile",
"(",
")",
";",
"File",
"targetTimestampedArtifactDirectory",
"=",
"artifactDirectory",
".",
"resolve",
"(",
"computeGradleUUID",
"(",
"artifactCoordinates",
"+",
"\":\"",
"+",
"packaging",
")",
")",
".",
"toFile",
"(",
")",
";",
"File",
"snapshotArtifactFile",
"=",
"doDownload",
"(",
"remoteRepos",
",",
"artifactTimestampedAbsoluteHttpPath",
",",
"timestampedArtifactRelativePath",
",",
"artifactCoordinates",
",",
"packaging",
",",
"targetTimestampedArtifactPomDirectory",
",",
"targetTimestampedArtifactDirectory",
")",
";",
"if",
"(",
"snapshotArtifactFile",
"!=",
"null",
")",
"{",
"return",
"snapshotArtifactFile",
";",
"//Success",
"}",
"}",
"catch",
"(",
"XPathExpressionException",
"|",
"IOException",
"ex",
")",
"{",
"Module",
".",
"getModuleLogger",
"(",
")",
".",
"trace",
"(",
"ex",
",",
"\"Could not doDownload '%s' from '%s' repository\"",
",",
"artifactRelativeHttpPath",
",",
"remoteRepos",
")",
";",
"// try next one",
"}",
"}",
"}",
"return",
"null",
";",
"}"
] | Download artifact from remote repository.
@param artifactCoordinates
@param packaging
@param artifactDirectory
@return | [
"Download",
"artifact",
"from",
"remote",
"repository",
"."
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/core/bootstrap/src/main/java/org/wildfly/swarm/bootstrap/modules/GradleResolver.java#L99-L134 | train |
thorntail/thorntail | core/bootstrap/src/main/java/org/wildfly/swarm/bootstrap/modules/GradleResolver.java | GradleResolver.doDownload | File doDownload(String remoteRepos, String artifactAbsoluteHttpPath, String artifactRelativeHttpPath, ArtifactCoordinates artifactCoordinates, String packaging, File targetArtifactPomDirectory, File targetArtifactDirectory) {
//Download POM
File targetArtifactPomFile = new File(targetArtifactPomDirectory, toGradleArtifactFileName(artifactCoordinates, "pom"));
try {
MavenArtifactUtil.downloadFile(artifactCoordinates + ":pom", artifactAbsoluteHttpPath + "pom", targetArtifactPomFile);
} catch (IOException e) {
Module.getModuleLogger().trace(e, "Could not doDownload '%s' from '%s' repository", artifactRelativeHttpPath, remoteRepos);
// try next one
}
//Download Artifact
File targetArtifactFile = new File(targetArtifactDirectory, toGradleArtifactFileName(artifactCoordinates, packaging));
try {
MavenArtifactUtil.downloadFile(artifactCoordinates + ":" + packaging, artifactAbsoluteHttpPath + packaging, targetArtifactFile);
if (targetArtifactFile.exists()) {
return targetArtifactFile;
}
} catch (IOException e) {
Module.getModuleLogger().trace(e, "Could not doDownload '%s' from '%s' repository", artifactRelativeHttpPath, remoteRepos);
// try next one
}
return null;
} | java | File doDownload(String remoteRepos, String artifactAbsoluteHttpPath, String artifactRelativeHttpPath, ArtifactCoordinates artifactCoordinates, String packaging, File targetArtifactPomDirectory, File targetArtifactDirectory) {
//Download POM
File targetArtifactPomFile = new File(targetArtifactPomDirectory, toGradleArtifactFileName(artifactCoordinates, "pom"));
try {
MavenArtifactUtil.downloadFile(artifactCoordinates + ":pom", artifactAbsoluteHttpPath + "pom", targetArtifactPomFile);
} catch (IOException e) {
Module.getModuleLogger().trace(e, "Could not doDownload '%s' from '%s' repository", artifactRelativeHttpPath, remoteRepos);
// try next one
}
//Download Artifact
File targetArtifactFile = new File(targetArtifactDirectory, toGradleArtifactFileName(artifactCoordinates, packaging));
try {
MavenArtifactUtil.downloadFile(artifactCoordinates + ":" + packaging, artifactAbsoluteHttpPath + packaging, targetArtifactFile);
if (targetArtifactFile.exists()) {
return targetArtifactFile;
}
} catch (IOException e) {
Module.getModuleLogger().trace(e, "Could not doDownload '%s' from '%s' repository", artifactRelativeHttpPath, remoteRepos);
// try next one
}
return null;
} | [
"File",
"doDownload",
"(",
"String",
"remoteRepos",
",",
"String",
"artifactAbsoluteHttpPath",
",",
"String",
"artifactRelativeHttpPath",
",",
"ArtifactCoordinates",
"artifactCoordinates",
",",
"String",
"packaging",
",",
"File",
"targetArtifactPomDirectory",
",",
"File",
"targetArtifactDirectory",
")",
"{",
"//Download POM",
"File",
"targetArtifactPomFile",
"=",
"new",
"File",
"(",
"targetArtifactPomDirectory",
",",
"toGradleArtifactFileName",
"(",
"artifactCoordinates",
",",
"\"pom\"",
")",
")",
";",
"try",
"{",
"MavenArtifactUtil",
".",
"downloadFile",
"(",
"artifactCoordinates",
"+",
"\":pom\"",
",",
"artifactAbsoluteHttpPath",
"+",
"\"pom\"",
",",
"targetArtifactPomFile",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"Module",
".",
"getModuleLogger",
"(",
")",
".",
"trace",
"(",
"e",
",",
"\"Could not doDownload '%s' from '%s' repository\"",
",",
"artifactRelativeHttpPath",
",",
"remoteRepos",
")",
";",
"// try next one",
"}",
"//Download Artifact",
"File",
"targetArtifactFile",
"=",
"new",
"File",
"(",
"targetArtifactDirectory",
",",
"toGradleArtifactFileName",
"(",
"artifactCoordinates",
",",
"packaging",
")",
")",
";",
"try",
"{",
"MavenArtifactUtil",
".",
"downloadFile",
"(",
"artifactCoordinates",
"+",
"\":\"",
"+",
"packaging",
",",
"artifactAbsoluteHttpPath",
"+",
"packaging",
",",
"targetArtifactFile",
")",
";",
"if",
"(",
"targetArtifactFile",
".",
"exists",
"(",
")",
")",
"{",
"return",
"targetArtifactFile",
";",
"}",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"Module",
".",
"getModuleLogger",
"(",
")",
".",
"trace",
"(",
"e",
",",
"\"Could not doDownload '%s' from '%s' repository\"",
",",
"artifactRelativeHttpPath",
",",
"remoteRepos",
")",
";",
"// try next one",
"}",
"return",
"null",
";",
"}"
] | Download the POM and the artifact file and return it.
@param remoteRepos
@param artifactAbsoluteHttpPath
@param artifactRelativeHttpPath
@param artifactCoordinates
@param packaging
@param targetArtifactPomDirectory
@param targetArtifactDirectory
@return | [
"Download",
"the",
"POM",
"and",
"the",
"artifact",
"file",
"and",
"return",
"it",
"."
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/core/bootstrap/src/main/java/org/wildfly/swarm/bootstrap/modules/GradleResolver.java#L148-L170 | train |
thorntail/thorntail | core/bootstrap/src/main/java/org/wildfly/swarm/bootstrap/modules/GradleResolver.java | GradleResolver.toGradleArtifactFileName | String toGradleArtifactFileName(ArtifactCoordinates artifactCoordinates, String packaging) {
StringBuilder sbFileFilter = new StringBuilder();
sbFileFilter
.append(artifactCoordinates.getArtifactId())
.append("-")
.append(artifactCoordinates.getVersion());
if (artifactCoordinates.getClassifier() != null && artifactCoordinates.getClassifier().length() > 0) {
sbFileFilter
.append("-")
.append(artifactCoordinates.getClassifier());
}
sbFileFilter
.append(".")
.append(packaging);
return sbFileFilter.toString();
} | java | String toGradleArtifactFileName(ArtifactCoordinates artifactCoordinates, String packaging) {
StringBuilder sbFileFilter = new StringBuilder();
sbFileFilter
.append(artifactCoordinates.getArtifactId())
.append("-")
.append(artifactCoordinates.getVersion());
if (artifactCoordinates.getClassifier() != null && artifactCoordinates.getClassifier().length() > 0) {
sbFileFilter
.append("-")
.append(artifactCoordinates.getClassifier());
}
sbFileFilter
.append(".")
.append(packaging);
return sbFileFilter.toString();
} | [
"String",
"toGradleArtifactFileName",
"(",
"ArtifactCoordinates",
"artifactCoordinates",
",",
"String",
"packaging",
")",
"{",
"StringBuilder",
"sbFileFilter",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"sbFileFilter",
".",
"append",
"(",
"artifactCoordinates",
".",
"getArtifactId",
"(",
")",
")",
".",
"append",
"(",
"\"-\"",
")",
".",
"append",
"(",
"artifactCoordinates",
".",
"getVersion",
"(",
")",
")",
";",
"if",
"(",
"artifactCoordinates",
".",
"getClassifier",
"(",
")",
"!=",
"null",
"&&",
"artifactCoordinates",
".",
"getClassifier",
"(",
")",
".",
"length",
"(",
")",
">",
"0",
")",
"{",
"sbFileFilter",
".",
"append",
"(",
"\"-\"",
")",
".",
"append",
"(",
"artifactCoordinates",
".",
"getClassifier",
"(",
")",
")",
";",
"}",
"sbFileFilter",
".",
"append",
"(",
"\".\"",
")",
".",
"append",
"(",
"packaging",
")",
";",
"return",
"sbFileFilter",
".",
"toString",
"(",
")",
";",
"}"
] | Build file name for artifact.
@param artifactCoordinates
@param packaging
@return | [
"Build",
"file",
"name",
"for",
"artifact",
"."
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/core/bootstrap/src/main/java/org/wildfly/swarm/bootstrap/modules/GradleResolver.java#L179-L194 | train |
thorntail/thorntail | core/bootstrap/src/main/java/org/wildfly/swarm/bootstrap/modules/GradleResolver.java | GradleResolver.toGradleArtifactPath | String toGradleArtifactPath(ArtifactCoordinates artifactCoordinates) {
// e.g.: org/jboss/ws/cxf/jbossws-cxf-resources/5.1.5.Final/jbossws-cxf-resources-5.1.5.Final
String pathWithMissingClassifier = artifactCoordinates.relativeArtifactPath('/');
StringBuilder sb = new StringBuilder(pathWithMissingClassifier);
if (artifactCoordinates.getClassifier() != null && artifactCoordinates.getClassifier().length() > 0) {
// org/jboss/ws/cxf/jbossws-cxf-resources/5.1.5.Final/jbossws-cxf-resources-5.1.5.Final-wildfly1000
sb
.append("-")
.append(artifactCoordinates.getClassifier());
}
return sb.toString();
} | java | String toGradleArtifactPath(ArtifactCoordinates artifactCoordinates) {
// e.g.: org/jboss/ws/cxf/jbossws-cxf-resources/5.1.5.Final/jbossws-cxf-resources-5.1.5.Final
String pathWithMissingClassifier = artifactCoordinates.relativeArtifactPath('/');
StringBuilder sb = new StringBuilder(pathWithMissingClassifier);
if (artifactCoordinates.getClassifier() != null && artifactCoordinates.getClassifier().length() > 0) {
// org/jboss/ws/cxf/jbossws-cxf-resources/5.1.5.Final/jbossws-cxf-resources-5.1.5.Final-wildfly1000
sb
.append("-")
.append(artifactCoordinates.getClassifier());
}
return sb.toString();
} | [
"String",
"toGradleArtifactPath",
"(",
"ArtifactCoordinates",
"artifactCoordinates",
")",
"{",
"// e.g.: org/jboss/ws/cxf/jbossws-cxf-resources/5.1.5.Final/jbossws-cxf-resources-5.1.5.Final",
"String",
"pathWithMissingClassifier",
"=",
"artifactCoordinates",
".",
"relativeArtifactPath",
"(",
"'",
"'",
")",
";",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
"pathWithMissingClassifier",
")",
";",
"if",
"(",
"artifactCoordinates",
".",
"getClassifier",
"(",
")",
"!=",
"null",
"&&",
"artifactCoordinates",
".",
"getClassifier",
"(",
")",
".",
"length",
"(",
")",
">",
"0",
")",
"{",
"// org/jboss/ws/cxf/jbossws-cxf-resources/5.1.5.Final/jbossws-cxf-resources-5.1.5.Final-wildfly1000",
"sb",
".",
"append",
"(",
"\"-\"",
")",
".",
"append",
"(",
"artifactCoordinates",
".",
"getClassifier",
"(",
")",
")",
";",
"}",
"return",
"sb",
".",
"toString",
"(",
")",
";",
"}"
] | Build the artifact path including the classifier.
@param artifactCoordinates
@return | [
"Build",
"the",
"artifact",
"path",
"including",
"the",
"classifier",
"."
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/core/bootstrap/src/main/java/org/wildfly/swarm/bootstrap/modules/GradleResolver.java#L202-L215 | train |
thorntail/thorntail | core/bootstrap/src/main/java/org/wildfly/swarm/bootstrap/modules/GradleResolver.java | GradleResolver.computeGradleUUID | String computeGradleUUID(String content) {
try {
MessageDigest md = MessageDigest.getInstance(MD5_ALGORITHM);
md.reset();
byte[] bytes = content.trim().toLowerCase(Locale.US).getBytes("UTF-8");
md.update(bytes, 0, bytes.length);
return byteArrayToHexString(md.digest());
} catch (NoSuchAlgorithmException e) {
// Impossible
throw new IllegalArgumentException("unknown algorithm " + MD5_ALGORITHM, e);
} catch (UnsupportedEncodingException e) {
// Impossible except with IBM :)
throw new IllegalArgumentException("unknown charset UTF-8", e);
}
} | java | String computeGradleUUID(String content) {
try {
MessageDigest md = MessageDigest.getInstance(MD5_ALGORITHM);
md.reset();
byte[] bytes = content.trim().toLowerCase(Locale.US).getBytes("UTF-8");
md.update(bytes, 0, bytes.length);
return byteArrayToHexString(md.digest());
} catch (NoSuchAlgorithmException e) {
// Impossible
throw new IllegalArgumentException("unknown algorithm " + MD5_ALGORITHM, e);
} catch (UnsupportedEncodingException e) {
// Impossible except with IBM :)
throw new IllegalArgumentException("unknown charset UTF-8", e);
}
} | [
"String",
"computeGradleUUID",
"(",
"String",
"content",
")",
"{",
"try",
"{",
"MessageDigest",
"md",
"=",
"MessageDigest",
".",
"getInstance",
"(",
"MD5_ALGORITHM",
")",
";",
"md",
".",
"reset",
"(",
")",
";",
"byte",
"[",
"]",
"bytes",
"=",
"content",
".",
"trim",
"(",
")",
".",
"toLowerCase",
"(",
"Locale",
".",
"US",
")",
".",
"getBytes",
"(",
"\"UTF-8\"",
")",
";",
"md",
".",
"update",
"(",
"bytes",
",",
"0",
",",
"bytes",
".",
"length",
")",
";",
"return",
"byteArrayToHexString",
"(",
"md",
".",
"digest",
"(",
")",
")",
";",
"}",
"catch",
"(",
"NoSuchAlgorithmException",
"e",
")",
"{",
"// Impossible",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"unknown algorithm \"",
"+",
"MD5_ALGORITHM",
",",
"e",
")",
";",
"}",
"catch",
"(",
"UnsupportedEncodingException",
"e",
")",
"{",
"// Impossible except with IBM :)",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"unknown charset UTF-8\"",
",",
"e",
")",
";",
"}",
"}"
] | Compute gradle uuid for artifacts.
@param content
@return | [
"Compute",
"gradle",
"uuid",
"for",
"artifacts",
"."
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/core/bootstrap/src/main/java/org/wildfly/swarm/bootstrap/modules/GradleResolver.java#L223-L237 | train |
thorntail/thorntail | arquillian/gradle-adapter/src/main/java/org/wildfly/swarm/arquillian/adapter/gradle/GradleDependencyAdapter.java | GradleDependencyAdapter.getDependenciesViaIdeaModel | private DeclaredDependencies getDependenciesViaIdeaModel(ProjectConnection connection) {
DeclaredDependencies declaredDependencies = new DeclaredDependencies();
// 1. Get the IdeaProject model from the Gradle connection.
IdeaProject prj = connection.getModel(IdeaProject.class);
prj.getModules().forEach(this::computeProjectDependencies);
// 2. Find the IdeaModule that maps to the project that we are looking at.
Optional<? extends IdeaModule> prjModule = prj.getModules().stream()
.filter(m -> m.getGradleProject().getProjectDirectory().toPath().equals(rootPath))
.findFirst();
// We need to return the following collection of dependencies,
// 1. For the current project, return all artifacts that are marked as ["COMPILE", "TEST"]
// 2. From the upstream-projects, add all dependencies that are marked as ["COMPILE"]
// 3. For the current project, iterate through each dependencies marked as ["PROVIDED"] and do the following,
// a.) Check if they are already available from 1 & 2. If yes, then nothing to do here.
// b.) Check if this entry is defined as ["TEST"] in the upstream-projects. If yes, then include it.
// -- The reason for doing this is because of the optimization that Gradle does on the IdeaModule library set.
Set<ArtifactSpec> collectedDependencies = new HashSet<>();
prjModule.ifPresent(m -> {
Map<String, Set<ArtifactSpec>> currentPrjDeps = ARTIFACT_DEPS_OF_PRJ.get(m.getName());
Set<String> upstreamProjects = PRJ_DEPS_OF_PRJ.getOrDefault(m.getName(), emptySet());
collectedDependencies.addAll(currentPrjDeps.getOrDefault(DEP_SCOPE_COMPILE, emptySet()));
collectedDependencies.addAll(currentPrjDeps.getOrDefault(DEP_SCOPE_TEST, emptySet()));
upstreamProjects.forEach(moduleName -> {
Map<String, Set<ArtifactSpec>> moduleDeps = ARTIFACT_DEPS_OF_PRJ.getOrDefault(moduleName, emptyMap());
collectedDependencies.addAll(moduleDeps.getOrDefault(DEP_SCOPE_COMPILE, emptySet()));
});
Set<ArtifactSpec> providedScopeDeps = currentPrjDeps.getOrDefault(DEP_SCOPE_PROVIDED, emptySet());
providedScopeDeps.removeAll(collectedDependencies);
if (!providedScopeDeps.isEmpty()) {
List<ArtifactSpec> testScopedLibs = new ArrayList<>();
upstreamProjects.forEach(moduleName -> testScopedLibs.addAll(
ARTIFACT_DEPS_OF_PRJ.getOrDefault(moduleName, emptyMap())
.getOrDefault(DEP_SCOPE_TEST, emptySet())));
providedScopeDeps.stream().filter(testScopedLibs::contains).forEach(collectedDependencies::add);
}
});
collectedDependencies.forEach(declaredDependencies::add);
return declaredDependencies;
} | java | private DeclaredDependencies getDependenciesViaIdeaModel(ProjectConnection connection) {
DeclaredDependencies declaredDependencies = new DeclaredDependencies();
// 1. Get the IdeaProject model from the Gradle connection.
IdeaProject prj = connection.getModel(IdeaProject.class);
prj.getModules().forEach(this::computeProjectDependencies);
// 2. Find the IdeaModule that maps to the project that we are looking at.
Optional<? extends IdeaModule> prjModule = prj.getModules().stream()
.filter(m -> m.getGradleProject().getProjectDirectory().toPath().equals(rootPath))
.findFirst();
// We need to return the following collection of dependencies,
// 1. For the current project, return all artifacts that are marked as ["COMPILE", "TEST"]
// 2. From the upstream-projects, add all dependencies that are marked as ["COMPILE"]
// 3. For the current project, iterate through each dependencies marked as ["PROVIDED"] and do the following,
// a.) Check if they are already available from 1 & 2. If yes, then nothing to do here.
// b.) Check if this entry is defined as ["TEST"] in the upstream-projects. If yes, then include it.
// -- The reason for doing this is because of the optimization that Gradle does on the IdeaModule library set.
Set<ArtifactSpec> collectedDependencies = new HashSet<>();
prjModule.ifPresent(m -> {
Map<String, Set<ArtifactSpec>> currentPrjDeps = ARTIFACT_DEPS_OF_PRJ.get(m.getName());
Set<String> upstreamProjects = PRJ_DEPS_OF_PRJ.getOrDefault(m.getName(), emptySet());
collectedDependencies.addAll(currentPrjDeps.getOrDefault(DEP_SCOPE_COMPILE, emptySet()));
collectedDependencies.addAll(currentPrjDeps.getOrDefault(DEP_SCOPE_TEST, emptySet()));
upstreamProjects.forEach(moduleName -> {
Map<String, Set<ArtifactSpec>> moduleDeps = ARTIFACT_DEPS_OF_PRJ.getOrDefault(moduleName, emptyMap());
collectedDependencies.addAll(moduleDeps.getOrDefault(DEP_SCOPE_COMPILE, emptySet()));
});
Set<ArtifactSpec> providedScopeDeps = currentPrjDeps.getOrDefault(DEP_SCOPE_PROVIDED, emptySet());
providedScopeDeps.removeAll(collectedDependencies);
if (!providedScopeDeps.isEmpty()) {
List<ArtifactSpec> testScopedLibs = new ArrayList<>();
upstreamProjects.forEach(moduleName -> testScopedLibs.addAll(
ARTIFACT_DEPS_OF_PRJ.getOrDefault(moduleName, emptyMap())
.getOrDefault(DEP_SCOPE_TEST, emptySet())));
providedScopeDeps.stream().filter(testScopedLibs::contains).forEach(collectedDependencies::add);
}
});
collectedDependencies.forEach(declaredDependencies::add);
return declaredDependencies;
} | [
"private",
"DeclaredDependencies",
"getDependenciesViaIdeaModel",
"(",
"ProjectConnection",
"connection",
")",
"{",
"DeclaredDependencies",
"declaredDependencies",
"=",
"new",
"DeclaredDependencies",
"(",
")",
";",
"// 1. Get the IdeaProject model from the Gradle connection.",
"IdeaProject",
"prj",
"=",
"connection",
".",
"getModel",
"(",
"IdeaProject",
".",
"class",
")",
";",
"prj",
".",
"getModules",
"(",
")",
".",
"forEach",
"(",
"this",
"::",
"computeProjectDependencies",
")",
";",
"// 2. Find the IdeaModule that maps to the project that we are looking at.",
"Optional",
"<",
"?",
"extends",
"IdeaModule",
">",
"prjModule",
"=",
"prj",
".",
"getModules",
"(",
")",
".",
"stream",
"(",
")",
".",
"filter",
"(",
"m",
"->",
"m",
".",
"getGradleProject",
"(",
")",
".",
"getProjectDirectory",
"(",
")",
".",
"toPath",
"(",
")",
".",
"equals",
"(",
"rootPath",
")",
")",
".",
"findFirst",
"(",
")",
";",
"// We need to return the following collection of dependencies,",
"// 1. For the current project, return all artifacts that are marked as [\"COMPILE\", \"TEST\"]",
"// 2. From the upstream-projects, add all dependencies that are marked as [\"COMPILE\"]",
"// 3. For the current project, iterate through each dependencies marked as [\"PROVIDED\"] and do the following,",
"// a.) Check if they are already available from 1 & 2. If yes, then nothing to do here.",
"// b.) Check if this entry is defined as [\"TEST\"] in the upstream-projects. If yes, then include it.",
"// -- The reason for doing this is because of the optimization that Gradle does on the IdeaModule library set.",
"Set",
"<",
"ArtifactSpec",
">",
"collectedDependencies",
"=",
"new",
"HashSet",
"<>",
"(",
")",
";",
"prjModule",
".",
"ifPresent",
"(",
"m",
"->",
"{",
"Map",
"<",
"String",
",",
"Set",
"<",
"ArtifactSpec",
">",
">",
"currentPrjDeps",
"=",
"ARTIFACT_DEPS_OF_PRJ",
".",
"get",
"(",
"m",
".",
"getName",
"(",
")",
")",
";",
"Set",
"<",
"String",
">",
"upstreamProjects",
"=",
"PRJ_DEPS_OF_PRJ",
".",
"getOrDefault",
"(",
"m",
".",
"getName",
"(",
")",
",",
"emptySet",
"(",
")",
")",
";",
"collectedDependencies",
".",
"addAll",
"(",
"currentPrjDeps",
".",
"getOrDefault",
"(",
"DEP_SCOPE_COMPILE",
",",
"emptySet",
"(",
")",
")",
")",
";",
"collectedDependencies",
".",
"addAll",
"(",
"currentPrjDeps",
".",
"getOrDefault",
"(",
"DEP_SCOPE_TEST",
",",
"emptySet",
"(",
")",
")",
")",
";",
"upstreamProjects",
".",
"forEach",
"(",
"moduleName",
"->",
"{",
"Map",
"<",
"String",
",",
"Set",
"<",
"ArtifactSpec",
">",
">",
"moduleDeps",
"=",
"ARTIFACT_DEPS_OF_PRJ",
".",
"getOrDefault",
"(",
"moduleName",
",",
"emptyMap",
"(",
")",
")",
";",
"collectedDependencies",
".",
"addAll",
"(",
"moduleDeps",
".",
"getOrDefault",
"(",
"DEP_SCOPE_COMPILE",
",",
"emptySet",
"(",
")",
")",
")",
";",
"}",
")",
";",
"Set",
"<",
"ArtifactSpec",
">",
"providedScopeDeps",
"=",
"currentPrjDeps",
".",
"getOrDefault",
"(",
"DEP_SCOPE_PROVIDED",
",",
"emptySet",
"(",
")",
")",
";",
"providedScopeDeps",
".",
"removeAll",
"(",
"collectedDependencies",
")",
";",
"if",
"(",
"!",
"providedScopeDeps",
".",
"isEmpty",
"(",
")",
")",
"{",
"List",
"<",
"ArtifactSpec",
">",
"testScopedLibs",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"upstreamProjects",
".",
"forEach",
"(",
"moduleName",
"->",
"testScopedLibs",
".",
"addAll",
"(",
"ARTIFACT_DEPS_OF_PRJ",
".",
"getOrDefault",
"(",
"moduleName",
",",
"emptyMap",
"(",
")",
")",
".",
"getOrDefault",
"(",
"DEP_SCOPE_TEST",
",",
"emptySet",
"(",
")",
")",
")",
")",
";",
"providedScopeDeps",
".",
"stream",
"(",
")",
".",
"filter",
"(",
"testScopedLibs",
"::",
"contains",
")",
".",
"forEach",
"(",
"collectedDependencies",
"::",
"add",
")",
";",
"}",
"}",
")",
";",
"collectedDependencies",
".",
"forEach",
"(",
"declaredDependencies",
"::",
"add",
")",
";",
"return",
"declaredDependencies",
";",
"}"
] | Get the dependencies via the Gradle IDEA model.
@param connection the Gradle project connection.
@return the computed dependencies. | [
"Get",
"the",
"dependencies",
"via",
"the",
"Gradle",
"IDEA",
"model",
"."
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/arquillian/gradle-adapter/src/main/java/org/wildfly/swarm/arquillian/adapter/gradle/GradleDependencyAdapter.java#L90-L139 | train |
thorntail/thorntail | arquillian/gradle-adapter/src/main/java/org/wildfly/swarm/arquillian/adapter/gradle/GradleDependencyAdapter.java | GradleDependencyAdapter.toArtifactSpec | private static ArtifactSpec toArtifactSpec(DependencyDescriptor desc, String scope) {
return new ArtifactSpec(scope, desc.getGroup(), desc.getName(), desc.getVersion(), desc.getType(),
desc.getClassifier(), desc.getFile());
} | java | private static ArtifactSpec toArtifactSpec(DependencyDescriptor desc, String scope) {
return new ArtifactSpec(scope, desc.getGroup(), desc.getName(), desc.getVersion(), desc.getType(),
desc.getClassifier(), desc.getFile());
} | [
"private",
"static",
"ArtifactSpec",
"toArtifactSpec",
"(",
"DependencyDescriptor",
"desc",
",",
"String",
"scope",
")",
"{",
"return",
"new",
"ArtifactSpec",
"(",
"scope",
",",
"desc",
".",
"getGroup",
"(",
")",
",",
"desc",
".",
"getName",
"(",
")",
",",
"desc",
".",
"getVersion",
"(",
")",
",",
"desc",
".",
"getType",
"(",
")",
",",
"desc",
".",
"getClassifier",
"(",
")",
",",
"desc",
".",
"getFile",
"(",
")",
")",
";",
"}"
] | Translate the given dependency descriptor to the an artifact specification while overriding the scope as well.
@param desc the dependency descriptor reference.
@param scope the scope that needs to be set on the result.
@return an artifact sepcification. | [
"Translate",
"the",
"given",
"dependency",
"descriptor",
"to",
"the",
"an",
"artifact",
"specification",
"while",
"overriding",
"the",
"scope",
"as",
"well",
"."
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/arquillian/gradle-adapter/src/main/java/org/wildfly/swarm/arquillian/adapter/gradle/GradleDependencyAdapter.java#L197-L200 | train |
thorntail/thorntail | core/container/src/main/java/org/wildfly/swarm/container/config/ConfigResolutionStrategy.java | ConfigResolutionStrategy.activate | void activate() {
nodes().flatMap(e -> e.allKeysRecursively())
.distinct()
.forEach(key -> {
activate(key);
});
} | java | void activate() {
nodes().flatMap(e -> e.allKeysRecursively())
.distinct()
.forEach(key -> {
activate(key);
});
} | [
"void",
"activate",
"(",
")",
"{",
"nodes",
"(",
")",
".",
"flatMap",
"(",
"e",
"->",
"e",
".",
"allKeysRecursively",
"(",
")",
")",
".",
"distinct",
"(",
")",
".",
"forEach",
"(",
"key",
"->",
"{",
"activate",
"(",
"key",
")",
";",
"}",
")",
";",
"}"
] | Activate the strategy. | [
"Activate",
"the",
"strategy",
"."
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/core/container/src/main/java/org/wildfly/swarm/container/config/ConfigResolutionStrategy.java#L103-L109 | train |
thorntail/thorntail | core/bootstrap/src/main/java/org/jboss/modules/maven/MavenArtifactUtil.java | MavenArtifactUtil.createMavenArtifactLoader | public static ResourceLoader createMavenArtifactLoader(final MavenResolver mavenResolver, final String name) throws IOException {
return createMavenArtifactLoader(mavenResolver, ArtifactCoordinates.fromString(name), name);
} | java | public static ResourceLoader createMavenArtifactLoader(final MavenResolver mavenResolver, final String name) throws IOException {
return createMavenArtifactLoader(mavenResolver, ArtifactCoordinates.fromString(name), name);
} | [
"public",
"static",
"ResourceLoader",
"createMavenArtifactLoader",
"(",
"final",
"MavenResolver",
"mavenResolver",
",",
"final",
"String",
"name",
")",
"throws",
"IOException",
"{",
"return",
"createMavenArtifactLoader",
"(",
"mavenResolver",
",",
"ArtifactCoordinates",
".",
"fromString",
"(",
"name",
")",
",",
"name",
")",
";",
"}"
] | A utility method to create a Maven artifact resource loader for the given artifact name.
@param mavenResolver the Maven resolver to use (must not be {@code null})
@param name the artifact name
@return the resource loader
@throws IOException if the artifact could not be resolved | [
"A",
"utility",
"method",
"to",
"create",
"a",
"Maven",
"artifact",
"resource",
"loader",
"for",
"the",
"given",
"artifact",
"name",
"."
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/core/bootstrap/src/main/java/org/jboss/modules/maven/MavenArtifactUtil.java#L266-L268 | train |
thorntail/thorntail | core/bootstrap/src/main/java/org/jboss/modules/maven/MavenArtifactUtil.java | MavenArtifactUtil.createMavenArtifactLoader | public static ResourceLoader createMavenArtifactLoader(final MavenResolver mavenResolver, final ArtifactCoordinates coordinates, final String rootName) throws IOException {
File fp = mavenResolver.resolveJarArtifact(coordinates);
if (fp == null) return null;
JarFile jarFile = JDKSpecific.getJarFile(fp, true);
return ResourceLoaders.createJarResourceLoader(rootName, jarFile);
} | java | public static ResourceLoader createMavenArtifactLoader(final MavenResolver mavenResolver, final ArtifactCoordinates coordinates, final String rootName) throws IOException {
File fp = mavenResolver.resolveJarArtifact(coordinates);
if (fp == null) return null;
JarFile jarFile = JDKSpecific.getJarFile(fp, true);
return ResourceLoaders.createJarResourceLoader(rootName, jarFile);
} | [
"public",
"static",
"ResourceLoader",
"createMavenArtifactLoader",
"(",
"final",
"MavenResolver",
"mavenResolver",
",",
"final",
"ArtifactCoordinates",
"coordinates",
",",
"final",
"String",
"rootName",
")",
"throws",
"IOException",
"{",
"File",
"fp",
"=",
"mavenResolver",
".",
"resolveJarArtifact",
"(",
"coordinates",
")",
";",
"if",
"(",
"fp",
"==",
"null",
")",
"return",
"null",
";",
"JarFile",
"jarFile",
"=",
"JDKSpecific",
".",
"getJarFile",
"(",
"fp",
",",
"true",
")",
";",
"return",
"ResourceLoaders",
".",
"createJarResourceLoader",
"(",
"rootName",
",",
"jarFile",
")",
";",
"}"
] | A utility method to create a Maven artifact resource loader for the given artifact coordinates.
@param mavenResolver the Maven resolver to use (must not be {@code null})
@param coordinates the artifact coordinates to use (must not be {@code null})
@param rootName the resource root name to use (must not be {@code null})
@return the resource loader
@throws IOException if the artifact could not be resolved | [
"A",
"utility",
"method",
"to",
"create",
"a",
"Maven",
"artifact",
"resource",
"loader",
"for",
"the",
"given",
"artifact",
"coordinates",
"."
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/core/bootstrap/src/main/java/org/jboss/modules/maven/MavenArtifactUtil.java#L279-L284 | train |
thorntail/thorntail | fractions/microprofile/microprofile-jwt/src/main/java/org/wildfly/swarm/microprofile/jwtauth/deployment/auth/jaas/JWTLoginModule.java | JWTLoginModule.validate | protected JWTCallerPrincipal validate(JWTCredential jwtCredential) throws ParseException {
JWTCallerPrincipalFactory factory = JWTCallerPrincipalFactory.instance();
JWTCallerPrincipal callerPrincipal = factory.parse(jwtCredential.getBearerToken(), jwtCredential.getAuthContextInfo());
return callerPrincipal;
} | java | protected JWTCallerPrincipal validate(JWTCredential jwtCredential) throws ParseException {
JWTCallerPrincipalFactory factory = JWTCallerPrincipalFactory.instance();
JWTCallerPrincipal callerPrincipal = factory.parse(jwtCredential.getBearerToken(), jwtCredential.getAuthContextInfo());
return callerPrincipal;
} | [
"protected",
"JWTCallerPrincipal",
"validate",
"(",
"JWTCredential",
"jwtCredential",
")",
"throws",
"ParseException",
"{",
"JWTCallerPrincipalFactory",
"factory",
"=",
"JWTCallerPrincipalFactory",
".",
"instance",
"(",
")",
";",
"JWTCallerPrincipal",
"callerPrincipal",
"=",
"factory",
".",
"parse",
"(",
"jwtCredential",
".",
"getBearerToken",
"(",
")",
",",
"jwtCredential",
".",
"getAuthContextInfo",
"(",
")",
")",
";",
"return",
"callerPrincipal",
";",
"}"
] | Validate the bearer token passed in with the authorization header
@param jwtCredential - the input bearer token
@return return the validated JWTCallerPrincipal
@throws ParseException - thrown on token parse or validation failure | [
"Validate",
"the",
"bearer",
"token",
"passed",
"in",
"with",
"the",
"authorization",
"header"
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/fractions/microprofile/microprofile-jwt/src/main/java/org/wildfly/swarm/microprofile/jwtauth/deployment/auth/jaas/JWTLoginModule.java#L98-L102 | train |
thorntail/thorntail | fractions/monitor/src/main/java/org/wildfly/swarm/monitor/runtime/SecureHttpContexts.java | SecureHttpContexts.secureHandler | @SuppressWarnings("deprecation")
private HttpHandler secureHandler(final HttpHandler toWrap, SecurityRealm securityRealm) {
HttpHandler handler = toWrap;
handler = new AuthenticationCallHandler(handler);
handler = new AuthenticationConstraintHandler(handler);
RealmIdentityManager idm = new RealmIdentityManager(securityRealm);
Set<AuthMechanism> mechanisms = securityRealm.getSupportedAuthenticationMechanisms();
List<AuthenticationMechanism> undertowMechanisms = new ArrayList<AuthenticationMechanism>(mechanisms.size());
undertowMechanisms.add(wrap(new CachedAuthenticatedSessionMechanism(), null));
for (AuthMechanism current : mechanisms) {
switch (current) {
case DIGEST:
List<DigestAlgorithm> digestAlgorithms = Collections.singletonList(DigestAlgorithm.MD5);
List<DigestQop> digestQops = Collections.singletonList(DigestQop.AUTH);
undertowMechanisms.add(wrap(new DigestAuthenticationMechanism(digestAlgorithms, digestQops,
securityRealm.getName(), "Monitor", new SimpleNonceManager()), current));
break;
case PLAIN:
undertowMechanisms.add(wrap(new BasicAuthenticationMechanism(securityRealm.getName()), current));
break;
case LOCAL:
break;
default:
}
}
handler = new AuthenticationMechanismsHandler(handler, undertowMechanisms);
handler = new SecurityInitialHandler(AuthenticationMode.PRO_ACTIVE, idm, handler);
// the predicate handler takes care that all of the above
// will only be enacted on relevant web contexts
handler = new PredicateHandler(exchange -> {
if (!monitor.getSecurityRealm().isPresent()) {
return false;
}
if (Queries.isAggregatorEndpoint(monitor, exchange.getRelativePath())) {
return true;
}
if (Queries.isDirectAccessToHealthEndpoint(monitor, exchange.getRelativePath())) {
if (!hasTokenAuth(exchange)) {
return true;
}
return false;
}
if (HttpContexts.getDefaultContextNames().contains(exchange.getRelativePath())) {
return true;
}
return false;
}, handler, toWrap);
return handler;
} | java | @SuppressWarnings("deprecation")
private HttpHandler secureHandler(final HttpHandler toWrap, SecurityRealm securityRealm) {
HttpHandler handler = toWrap;
handler = new AuthenticationCallHandler(handler);
handler = new AuthenticationConstraintHandler(handler);
RealmIdentityManager idm = new RealmIdentityManager(securityRealm);
Set<AuthMechanism> mechanisms = securityRealm.getSupportedAuthenticationMechanisms();
List<AuthenticationMechanism> undertowMechanisms = new ArrayList<AuthenticationMechanism>(mechanisms.size());
undertowMechanisms.add(wrap(new CachedAuthenticatedSessionMechanism(), null));
for (AuthMechanism current : mechanisms) {
switch (current) {
case DIGEST:
List<DigestAlgorithm> digestAlgorithms = Collections.singletonList(DigestAlgorithm.MD5);
List<DigestQop> digestQops = Collections.singletonList(DigestQop.AUTH);
undertowMechanisms.add(wrap(new DigestAuthenticationMechanism(digestAlgorithms, digestQops,
securityRealm.getName(), "Monitor", new SimpleNonceManager()), current));
break;
case PLAIN:
undertowMechanisms.add(wrap(new BasicAuthenticationMechanism(securityRealm.getName()), current));
break;
case LOCAL:
break;
default:
}
}
handler = new AuthenticationMechanismsHandler(handler, undertowMechanisms);
handler = new SecurityInitialHandler(AuthenticationMode.PRO_ACTIVE, idm, handler);
// the predicate handler takes care that all of the above
// will only be enacted on relevant web contexts
handler = new PredicateHandler(exchange -> {
if (!monitor.getSecurityRealm().isPresent()) {
return false;
}
if (Queries.isAggregatorEndpoint(monitor, exchange.getRelativePath())) {
return true;
}
if (Queries.isDirectAccessToHealthEndpoint(monitor, exchange.getRelativePath())) {
if (!hasTokenAuth(exchange)) {
return true;
}
return false;
}
if (HttpContexts.getDefaultContextNames().contains(exchange.getRelativePath())) {
return true;
}
return false;
}, handler, toWrap);
return handler;
} | [
"@",
"SuppressWarnings",
"(",
"\"deprecation\"",
")",
"private",
"HttpHandler",
"secureHandler",
"(",
"final",
"HttpHandler",
"toWrap",
",",
"SecurityRealm",
"securityRealm",
")",
"{",
"HttpHandler",
"handler",
"=",
"toWrap",
";",
"handler",
"=",
"new",
"AuthenticationCallHandler",
"(",
"handler",
")",
";",
"handler",
"=",
"new",
"AuthenticationConstraintHandler",
"(",
"handler",
")",
";",
"RealmIdentityManager",
"idm",
"=",
"new",
"RealmIdentityManager",
"(",
"securityRealm",
")",
";",
"Set",
"<",
"AuthMechanism",
">",
"mechanisms",
"=",
"securityRealm",
".",
"getSupportedAuthenticationMechanisms",
"(",
")",
";",
"List",
"<",
"AuthenticationMechanism",
">",
"undertowMechanisms",
"=",
"new",
"ArrayList",
"<",
"AuthenticationMechanism",
">",
"(",
"mechanisms",
".",
"size",
"(",
")",
")",
";",
"undertowMechanisms",
".",
"add",
"(",
"wrap",
"(",
"new",
"CachedAuthenticatedSessionMechanism",
"(",
")",
",",
"null",
")",
")",
";",
"for",
"(",
"AuthMechanism",
"current",
":",
"mechanisms",
")",
"{",
"switch",
"(",
"current",
")",
"{",
"case",
"DIGEST",
":",
"List",
"<",
"DigestAlgorithm",
">",
"digestAlgorithms",
"=",
"Collections",
".",
"singletonList",
"(",
"DigestAlgorithm",
".",
"MD5",
")",
";",
"List",
"<",
"DigestQop",
">",
"digestQops",
"=",
"Collections",
".",
"singletonList",
"(",
"DigestQop",
".",
"AUTH",
")",
";",
"undertowMechanisms",
".",
"add",
"(",
"wrap",
"(",
"new",
"DigestAuthenticationMechanism",
"(",
"digestAlgorithms",
",",
"digestQops",
",",
"securityRealm",
".",
"getName",
"(",
")",
",",
"\"Monitor\"",
",",
"new",
"SimpleNonceManager",
"(",
")",
")",
",",
"current",
")",
")",
";",
"break",
";",
"case",
"PLAIN",
":",
"undertowMechanisms",
".",
"add",
"(",
"wrap",
"(",
"new",
"BasicAuthenticationMechanism",
"(",
"securityRealm",
".",
"getName",
"(",
")",
")",
",",
"current",
")",
")",
";",
"break",
";",
"case",
"LOCAL",
":",
"break",
";",
"default",
":",
"}",
"}",
"handler",
"=",
"new",
"AuthenticationMechanismsHandler",
"(",
"handler",
",",
"undertowMechanisms",
")",
";",
"handler",
"=",
"new",
"SecurityInitialHandler",
"(",
"AuthenticationMode",
".",
"PRO_ACTIVE",
",",
"idm",
",",
"handler",
")",
";",
"// the predicate handler takes care that all of the above",
"// will only be enacted on relevant web contexts",
"handler",
"=",
"new",
"PredicateHandler",
"(",
"exchange",
"->",
"{",
"if",
"(",
"!",
"monitor",
".",
"getSecurityRealm",
"(",
")",
".",
"isPresent",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"Queries",
".",
"isAggregatorEndpoint",
"(",
"monitor",
",",
"exchange",
".",
"getRelativePath",
"(",
")",
")",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"Queries",
".",
"isDirectAccessToHealthEndpoint",
"(",
"monitor",
",",
"exchange",
".",
"getRelativePath",
"(",
")",
")",
")",
"{",
"if",
"(",
"!",
"hasTokenAuth",
"(",
"exchange",
")",
")",
"{",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}",
"if",
"(",
"HttpContexts",
".",
"getDefaultContextNames",
"(",
")",
".",
"contains",
"(",
"exchange",
".",
"getRelativePath",
"(",
")",
")",
")",
"{",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}",
",",
"handler",
",",
"toWrap",
")",
";",
"return",
"handler",
";",
"}"
] | Wraps the target handler and makes it inheritSecurity.
Includes a predicate for relevant web contexts. | [
"Wraps",
"the",
"target",
"handler",
"and",
"makes",
"it",
"inheritSecurity",
".",
"Includes",
"a",
"predicate",
"for",
"relevant",
"web",
"contexts",
"."
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/fractions/monitor/src/main/java/org/wildfly/swarm/monitor/runtime/SecureHttpContexts.java#L88-L147 | train |
thorntail/thorntail | thorntail-runner/src/main/java/org/wildfly/swarm/runner/WarBuilder.java | WarBuilder.isWar | private boolean isWar(String path) {
String currentDir = Paths.get(".").toAbsolutePath().normalize().toString();
String classesDirPath = Paths.get(path).toAbsolutePath().normalize().toString();
return classesDirPath.startsWith(currentDir);
} | java | private boolean isWar(String path) {
String currentDir = Paths.get(".").toAbsolutePath().normalize().toString();
String classesDirPath = Paths.get(path).toAbsolutePath().normalize().toString();
return classesDirPath.startsWith(currentDir);
} | [
"private",
"boolean",
"isWar",
"(",
"String",
"path",
")",
"{",
"String",
"currentDir",
"=",
"Paths",
".",
"get",
"(",
"\".\"",
")",
".",
"toAbsolutePath",
"(",
")",
".",
"normalize",
"(",
")",
".",
"toString",
"(",
")",
";",
"String",
"classesDirPath",
"=",
"Paths",
".",
"get",
"(",
"path",
")",
".",
"toAbsolutePath",
"(",
")",
".",
"normalize",
"(",
")",
".",
"toString",
"(",
")",
";",
"return",
"classesDirPath",
".",
"startsWith",
"(",
"currentDir",
")",
";",
"}"
] | the assumption is that the Runner is invoked in the WAR module's directory | [
"the",
"assumption",
"is",
"that",
"the",
"Runner",
"is",
"invoked",
"in",
"the",
"WAR",
"module",
"s",
"directory"
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/thorntail-runner/src/main/java/org/wildfly/swarm/runner/WarBuilder.java#L89-L93 | train |
thorntail/thorntail | plugins/gradle/gradle-plugin/src/main/java/org/wildfly/swarm/plugin/gradle/GradleDependencyResolutionHelper.java | GradleDependencyResolutionHelper.determinePluginVersion | public static String determinePluginVersion() {
if (pluginVersion == null) {
final String fileName = "META-INF/gradle-plugins/thorntail.properties";
ClassLoader loader = Thread.currentThread().getContextClassLoader();
String version;
try (InputStream stream = loader.getResourceAsStream(fileName)) {
Properties props = new Properties();
props.load(stream);
version = props.getProperty("implementation-version");
} catch (IOException e) {
throw new IllegalStateException("Unable to locate file: " + fileName, e);
}
pluginVersion = version;
}
return pluginVersion;
} | java | public static String determinePluginVersion() {
if (pluginVersion == null) {
final String fileName = "META-INF/gradle-plugins/thorntail.properties";
ClassLoader loader = Thread.currentThread().getContextClassLoader();
String version;
try (InputStream stream = loader.getResourceAsStream(fileName)) {
Properties props = new Properties();
props.load(stream);
version = props.getProperty("implementation-version");
} catch (IOException e) {
throw new IllegalStateException("Unable to locate file: " + fileName, e);
}
pluginVersion = version;
}
return pluginVersion;
} | [
"public",
"static",
"String",
"determinePluginVersion",
"(",
")",
"{",
"if",
"(",
"pluginVersion",
"==",
"null",
")",
"{",
"final",
"String",
"fileName",
"=",
"\"META-INF/gradle-plugins/thorntail.properties\"",
";",
"ClassLoader",
"loader",
"=",
"Thread",
".",
"currentThread",
"(",
")",
".",
"getContextClassLoader",
"(",
")",
";",
"String",
"version",
";",
"try",
"(",
"InputStream",
"stream",
"=",
"loader",
".",
"getResourceAsStream",
"(",
"fileName",
")",
")",
"{",
"Properties",
"props",
"=",
"new",
"Properties",
"(",
")",
";",
"props",
".",
"load",
"(",
"stream",
")",
";",
"version",
"=",
"props",
".",
"getProperty",
"(",
"\"implementation-version\"",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"Unable to locate file: \"",
"+",
"fileName",
",",
"e",
")",
";",
"}",
"pluginVersion",
"=",
"version",
";",
"}",
"return",
"pluginVersion",
";",
"}"
] | Parse the plugin definition file and extract the version details from it. | [
"Parse",
"the",
"plugin",
"definition",
"file",
"and",
"extract",
"the",
"version",
"details",
"from",
"it",
"."
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/plugins/gradle/gradle-plugin/src/main/java/org/wildfly/swarm/plugin/gradle/GradleDependencyResolutionHelper.java#L67-L82 | train |
thorntail/thorntail | plugins/gradle/gradle-plugin/src/main/java/org/wildfly/swarm/plugin/gradle/GradleDependencyResolutionHelper.java | GradleDependencyResolutionHelper.isProject | public static boolean isProject(Project project, DependencyDescriptor descriptor) {
final String specGAV = String.format("%s:%s:%s", descriptor.getGroup(), descriptor.getName(), descriptor.getVersion());
return getAllProjects(project).containsKey(specGAV) || getIncludedProjectIdentifiers(project).contains(specGAV);
} | java | public static boolean isProject(Project project, DependencyDescriptor descriptor) {
final String specGAV = String.format("%s:%s:%s", descriptor.getGroup(), descriptor.getName(), descriptor.getVersion());
return getAllProjects(project).containsKey(specGAV) || getIncludedProjectIdentifiers(project).contains(specGAV);
} | [
"public",
"static",
"boolean",
"isProject",
"(",
"Project",
"project",
",",
"DependencyDescriptor",
"descriptor",
")",
"{",
"final",
"String",
"specGAV",
"=",
"String",
".",
"format",
"(",
"\"%s:%s:%s\"",
",",
"descriptor",
".",
"getGroup",
"(",
")",
",",
"descriptor",
".",
"getName",
"(",
")",
",",
"descriptor",
".",
"getVersion",
"(",
")",
")",
";",
"return",
"getAllProjects",
"(",
"project",
")",
".",
"containsKey",
"(",
"specGAV",
")",
"||",
"getIncludedProjectIdentifiers",
"(",
"project",
")",
".",
"contains",
"(",
"specGAV",
")",
";",
"}"
] | Convenience method to determine if the given dependency descriptor represents an internal Gradle project or not.
@param project the Gradle project reference.
@param descriptor the dependency descriptor.
@return true if the descriptor represents a Gradle project, false otherwise. | [
"Convenience",
"method",
"to",
"determine",
"if",
"the",
"given",
"dependency",
"descriptor",
"represents",
"an",
"internal",
"Gradle",
"project",
"or",
"not",
"."
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/plugins/gradle/gradle-plugin/src/main/java/org/wildfly/swarm/plugin/gradle/GradleDependencyResolutionHelper.java#L92-L95 | train |
thorntail/thorntail | plugins/gradle/gradle-plugin/src/main/java/org/wildfly/swarm/plugin/gradle/GradleDependencyResolutionHelper.java | GradleDependencyResolutionHelper.resolveArtifacts | public static Set<ArtifactSpec> resolveArtifacts(Project project, Collection<ArtifactSpec> specs, boolean transitive,
boolean excludeDefaults) {
if (project == null) {
throw new IllegalArgumentException("Gradle project reference cannot be null.");
}
if (specs == null) {
project.getLogger().warn("Artifact specification collection is null.");
return Collections.emptySet();
}
final Configuration config = project.getConfigurations().detachedConfiguration().setTransitive(transitive);
final DependencySet dependencySet = config.getDependencies();
final Map<String, Project> projectGAVCoordinates = getAllProjects(project);
final ProjectAccessListener listener = new DefaultProjectAccessListener();
Set<ArtifactSpec> result = new HashSet<>();
specs.forEach(s -> {
// 1. Do we need to resolve this entry?
final String specGAV = String.format("%s:%s:%s", s.groupId(), s.artifactId(), s.version());
boolean resolved = s.file != null;
boolean projectEntry = projectGAVCoordinates.containsKey(specGAV);
// 2. Should we skip this spec?
if (excludeDefaults && FractionDescriptor.THORNTAIL_GROUP_ID.equals(s.groupId()) && !projectEntry) {
return;
}
// 3. Should this entry be resolved?
if (!resolved || transitive) {
// a.) Does this entry represent a project dependency?
if (projectGAVCoordinates.containsKey(specGAV)) {
dependencySet.add(new DefaultProjectDependency((ProjectInternal) projectGAVCoordinates.get(specGAV), listener, false));
} else {
DefaultExternalModuleDependency d = new DefaultExternalModuleDependency(s.groupId(), s.artifactId(), s.version());
DefaultDependencyArtifact da = new DefaultDependencyArtifact(s.artifactId(), s.type(), s.type(), s.classifier(), null);
d.addArtifact(da);
dependencySet.add(d);
}
} else {
// 4. Nothing else to do, just add the spec to the result.
result.add(s);
}
});
// 5. Are there any specs that need resolution?
if (!dependencySet.isEmpty()) {
config.getResolvedConfiguration().getResolvedArtifacts().stream()
.map(ra -> asDescriptor("compile", ra).toArtifactSpec())
.forEach(result::add);
}
return result;
} | java | public static Set<ArtifactSpec> resolveArtifacts(Project project, Collection<ArtifactSpec> specs, boolean transitive,
boolean excludeDefaults) {
if (project == null) {
throw new IllegalArgumentException("Gradle project reference cannot be null.");
}
if (specs == null) {
project.getLogger().warn("Artifact specification collection is null.");
return Collections.emptySet();
}
final Configuration config = project.getConfigurations().detachedConfiguration().setTransitive(transitive);
final DependencySet dependencySet = config.getDependencies();
final Map<String, Project> projectGAVCoordinates = getAllProjects(project);
final ProjectAccessListener listener = new DefaultProjectAccessListener();
Set<ArtifactSpec> result = new HashSet<>();
specs.forEach(s -> {
// 1. Do we need to resolve this entry?
final String specGAV = String.format("%s:%s:%s", s.groupId(), s.artifactId(), s.version());
boolean resolved = s.file != null;
boolean projectEntry = projectGAVCoordinates.containsKey(specGAV);
// 2. Should we skip this spec?
if (excludeDefaults && FractionDescriptor.THORNTAIL_GROUP_ID.equals(s.groupId()) && !projectEntry) {
return;
}
// 3. Should this entry be resolved?
if (!resolved || transitive) {
// a.) Does this entry represent a project dependency?
if (projectGAVCoordinates.containsKey(specGAV)) {
dependencySet.add(new DefaultProjectDependency((ProjectInternal) projectGAVCoordinates.get(specGAV), listener, false));
} else {
DefaultExternalModuleDependency d = new DefaultExternalModuleDependency(s.groupId(), s.artifactId(), s.version());
DefaultDependencyArtifact da = new DefaultDependencyArtifact(s.artifactId(), s.type(), s.type(), s.classifier(), null);
d.addArtifact(da);
dependencySet.add(d);
}
} else {
// 4. Nothing else to do, just add the spec to the result.
result.add(s);
}
});
// 5. Are there any specs that need resolution?
if (!dependencySet.isEmpty()) {
config.getResolvedConfiguration().getResolvedArtifacts().stream()
.map(ra -> asDescriptor("compile", ra).toArtifactSpec())
.forEach(result::add);
}
return result;
} | [
"public",
"static",
"Set",
"<",
"ArtifactSpec",
">",
"resolveArtifacts",
"(",
"Project",
"project",
",",
"Collection",
"<",
"ArtifactSpec",
">",
"specs",
",",
"boolean",
"transitive",
",",
"boolean",
"excludeDefaults",
")",
"{",
"if",
"(",
"project",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Gradle project reference cannot be null.\"",
")",
";",
"}",
"if",
"(",
"specs",
"==",
"null",
")",
"{",
"project",
".",
"getLogger",
"(",
")",
".",
"warn",
"(",
"\"Artifact specification collection is null.\"",
")",
";",
"return",
"Collections",
".",
"emptySet",
"(",
")",
";",
"}",
"final",
"Configuration",
"config",
"=",
"project",
".",
"getConfigurations",
"(",
")",
".",
"detachedConfiguration",
"(",
")",
".",
"setTransitive",
"(",
"transitive",
")",
";",
"final",
"DependencySet",
"dependencySet",
"=",
"config",
".",
"getDependencies",
"(",
")",
";",
"final",
"Map",
"<",
"String",
",",
"Project",
">",
"projectGAVCoordinates",
"=",
"getAllProjects",
"(",
"project",
")",
";",
"final",
"ProjectAccessListener",
"listener",
"=",
"new",
"DefaultProjectAccessListener",
"(",
")",
";",
"Set",
"<",
"ArtifactSpec",
">",
"result",
"=",
"new",
"HashSet",
"<>",
"(",
")",
";",
"specs",
".",
"forEach",
"(",
"s",
"->",
"{",
"// 1. Do we need to resolve this entry?",
"final",
"String",
"specGAV",
"=",
"String",
".",
"format",
"(",
"\"%s:%s:%s\"",
",",
"s",
".",
"groupId",
"(",
")",
",",
"s",
".",
"artifactId",
"(",
")",
",",
"s",
".",
"version",
"(",
")",
")",
";",
"boolean",
"resolved",
"=",
"s",
".",
"file",
"!=",
"null",
";",
"boolean",
"projectEntry",
"=",
"projectGAVCoordinates",
".",
"containsKey",
"(",
"specGAV",
")",
";",
"// 2. Should we skip this spec?",
"if",
"(",
"excludeDefaults",
"&&",
"FractionDescriptor",
".",
"THORNTAIL_GROUP_ID",
".",
"equals",
"(",
"s",
".",
"groupId",
"(",
")",
")",
"&&",
"!",
"projectEntry",
")",
"{",
"return",
";",
"}",
"// 3. Should this entry be resolved?",
"if",
"(",
"!",
"resolved",
"||",
"transitive",
")",
"{",
"// a.) Does this entry represent a project dependency?",
"if",
"(",
"projectGAVCoordinates",
".",
"containsKey",
"(",
"specGAV",
")",
")",
"{",
"dependencySet",
".",
"add",
"(",
"new",
"DefaultProjectDependency",
"(",
"(",
"ProjectInternal",
")",
"projectGAVCoordinates",
".",
"get",
"(",
"specGAV",
")",
",",
"listener",
",",
"false",
")",
")",
";",
"}",
"else",
"{",
"DefaultExternalModuleDependency",
"d",
"=",
"new",
"DefaultExternalModuleDependency",
"(",
"s",
".",
"groupId",
"(",
")",
",",
"s",
".",
"artifactId",
"(",
")",
",",
"s",
".",
"version",
"(",
")",
")",
";",
"DefaultDependencyArtifact",
"da",
"=",
"new",
"DefaultDependencyArtifact",
"(",
"s",
".",
"artifactId",
"(",
")",
",",
"s",
".",
"type",
"(",
")",
",",
"s",
".",
"type",
"(",
")",
",",
"s",
".",
"classifier",
"(",
")",
",",
"null",
")",
";",
"d",
".",
"addArtifact",
"(",
"da",
")",
";",
"dependencySet",
".",
"add",
"(",
"d",
")",
";",
"}",
"}",
"else",
"{",
"// 4. Nothing else to do, just add the spec to the result.",
"result",
".",
"add",
"(",
"s",
")",
";",
"}",
"}",
")",
";",
"// 5. Are there any specs that need resolution?",
"if",
"(",
"!",
"dependencySet",
".",
"isEmpty",
"(",
")",
")",
"{",
"config",
".",
"getResolvedConfiguration",
"(",
")",
".",
"getResolvedArtifacts",
"(",
")",
".",
"stream",
"(",
")",
".",
"map",
"(",
"ra",
"->",
"asDescriptor",
"(",
"\"compile\"",
",",
"ra",
")",
".",
"toArtifactSpec",
"(",
")",
")",
".",
"forEach",
"(",
"result",
"::",
"add",
")",
";",
"}",
"return",
"result",
";",
"}"
] | Resolve the given artifact specifications.
@param project the Gradle project reference.
@param specs the specifications that need to be resolved.
@param transitive should the artifacts be resolved transitively?
@param excludeDefaults should we skip resolving artifacts that belong to the Thorntail group?
@return collection of resolved artifact specifications. | [
"Resolve",
"the",
"given",
"artifact",
"specifications",
"."
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/plugins/gradle/gradle-plugin/src/main/java/org/wildfly/swarm/plugin/gradle/GradleDependencyResolutionHelper.java#L106-L157 | train |
thorntail/thorntail | plugins/gradle/gradle-plugin/src/main/java/org/wildfly/swarm/plugin/gradle/GradleDependencyResolutionHelper.java | GradleDependencyResolutionHelper.determineProjectDependencies | public static Map<DependencyDescriptor, Set<DependencyDescriptor>>
determineProjectDependencies(Project project, String configuration, boolean resolveChildrenTransitively) {
if (project == null) {
throw new IllegalArgumentException("Gradle project reference cannot be null.");
}
project.getLogger().info("Requesting dependencies for configuration: {}", configuration);
Configuration requestedConfiguration = project.getConfigurations().findByName(configuration);
if (requestedConfiguration == null) {
project.getLogger().warn("Unable to locate dependency configuration with name: {}", configuration);
return Collections.emptyMap();
}
//
// Step 1
// ------
// Iterate through the hierarchy of the given configuration and determine the correct scope of all
// "top-level" dependencies.
//
Map<String, String> dependencyScopeMap = new HashMap<>();
// In case of custom configurations, we will assign the scope to what has been requested
String defaultScopeForUnknownConfigurations =
REMAPPED_SCOPES.computeIfAbsent(requestedConfiguration.getName(), cfgName -> {
throw new IllegalStateException("Unknown configuration name provided: " + cfgName);
});
requestedConfiguration.getHierarchy().forEach(cfg -> {
cfg.getDependencies().forEach(dep -> {
String key = String.format("%s:%s", dep.getGroup(), dep.getName());
dependencyScopeMap.put(key, REMAPPED_SCOPES.getOrDefault(cfg.getName(), defaultScopeForUnknownConfigurations));
});
});
//
// Step 2
// ------
// Assuming that the given configuration can be resolved, get the resolved artifacts and populate the return Map.
//
ResolvedConfiguration resolvedConfig = requestedConfiguration.getResolvedConfiguration();
Map<DependencyDescriptor, Set<DependencyDescriptor>> dependencyMap = new HashMap<>();
resolvedConfig.getFirstLevelModuleDependencies().forEach(resolvedDep -> {
String lookup = String.format("%s:%s", resolvedDep.getModuleGroup(), resolvedDep.getModuleName());
String scope = dependencyScopeMap.get(lookup);
if (scope == null) {
// Should never happen.
throw new IllegalStateException("Gradle dependency resolution logic is broken. Unable to get scope for dependency: " + lookup);
}
DependencyDescriptor key = asDescriptor(scope, resolvedDep);
Set<DependencyDescriptor> value;
if (resolveChildrenTransitively) {
value = getDependenciesTransitively(scope, resolvedDep);
} else {
value = resolvedDep.getChildren()
.stream()
.map(rd -> asDescriptor(scope, rd))
.collect(Collectors.toSet());
}
dependencyMap.put(key, value);
});
printDependencyMap(dependencyMap, project);
return dependencyMap;
} | java | public static Map<DependencyDescriptor, Set<DependencyDescriptor>>
determineProjectDependencies(Project project, String configuration, boolean resolveChildrenTransitively) {
if (project == null) {
throw new IllegalArgumentException("Gradle project reference cannot be null.");
}
project.getLogger().info("Requesting dependencies for configuration: {}", configuration);
Configuration requestedConfiguration = project.getConfigurations().findByName(configuration);
if (requestedConfiguration == null) {
project.getLogger().warn("Unable to locate dependency configuration with name: {}", configuration);
return Collections.emptyMap();
}
//
// Step 1
// ------
// Iterate through the hierarchy of the given configuration and determine the correct scope of all
// "top-level" dependencies.
//
Map<String, String> dependencyScopeMap = new HashMap<>();
// In case of custom configurations, we will assign the scope to what has been requested
String defaultScopeForUnknownConfigurations =
REMAPPED_SCOPES.computeIfAbsent(requestedConfiguration.getName(), cfgName -> {
throw new IllegalStateException("Unknown configuration name provided: " + cfgName);
});
requestedConfiguration.getHierarchy().forEach(cfg -> {
cfg.getDependencies().forEach(dep -> {
String key = String.format("%s:%s", dep.getGroup(), dep.getName());
dependencyScopeMap.put(key, REMAPPED_SCOPES.getOrDefault(cfg.getName(), defaultScopeForUnknownConfigurations));
});
});
//
// Step 2
// ------
// Assuming that the given configuration can be resolved, get the resolved artifacts and populate the return Map.
//
ResolvedConfiguration resolvedConfig = requestedConfiguration.getResolvedConfiguration();
Map<DependencyDescriptor, Set<DependencyDescriptor>> dependencyMap = new HashMap<>();
resolvedConfig.getFirstLevelModuleDependencies().forEach(resolvedDep -> {
String lookup = String.format("%s:%s", resolvedDep.getModuleGroup(), resolvedDep.getModuleName());
String scope = dependencyScopeMap.get(lookup);
if (scope == null) {
// Should never happen.
throw new IllegalStateException("Gradle dependency resolution logic is broken. Unable to get scope for dependency: " + lookup);
}
DependencyDescriptor key = asDescriptor(scope, resolvedDep);
Set<DependencyDescriptor> value;
if (resolveChildrenTransitively) {
value = getDependenciesTransitively(scope, resolvedDep);
} else {
value = resolvedDep.getChildren()
.stream()
.map(rd -> asDescriptor(scope, rd))
.collect(Collectors.toSet());
}
dependencyMap.put(key, value);
});
printDependencyMap(dependencyMap, project);
return dependencyMap;
} | [
"public",
"static",
"Map",
"<",
"DependencyDescriptor",
",",
"Set",
"<",
"DependencyDescriptor",
">",
">",
"determineProjectDependencies",
"(",
"Project",
"project",
",",
"String",
"configuration",
",",
"boolean",
"resolveChildrenTransitively",
")",
"{",
"if",
"(",
"project",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Gradle project reference cannot be null.\"",
")",
";",
"}",
"project",
".",
"getLogger",
"(",
")",
".",
"info",
"(",
"\"Requesting dependencies for configuration: {}\"",
",",
"configuration",
")",
";",
"Configuration",
"requestedConfiguration",
"=",
"project",
".",
"getConfigurations",
"(",
")",
".",
"findByName",
"(",
"configuration",
")",
";",
"if",
"(",
"requestedConfiguration",
"==",
"null",
")",
"{",
"project",
".",
"getLogger",
"(",
")",
".",
"warn",
"(",
"\"Unable to locate dependency configuration with name: {}\"",
",",
"configuration",
")",
";",
"return",
"Collections",
".",
"emptyMap",
"(",
")",
";",
"}",
"//",
"// Step 1",
"// ------",
"// Iterate through the hierarchy of the given configuration and determine the correct scope of all",
"// \"top-level\" dependencies.",
"//",
"Map",
"<",
"String",
",",
"String",
">",
"dependencyScopeMap",
"=",
"new",
"HashMap",
"<>",
"(",
")",
";",
"// In case of custom configurations, we will assign the scope to what has been requested",
"String",
"defaultScopeForUnknownConfigurations",
"=",
"REMAPPED_SCOPES",
".",
"computeIfAbsent",
"(",
"requestedConfiguration",
".",
"getName",
"(",
")",
",",
"cfgName",
"->",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"Unknown configuration name provided: \"",
"+",
"cfgName",
")",
";",
"}",
")",
";",
"requestedConfiguration",
".",
"getHierarchy",
"(",
")",
".",
"forEach",
"(",
"cfg",
"->",
"{",
"cfg",
".",
"getDependencies",
"(",
")",
".",
"forEach",
"(",
"dep",
"->",
"{",
"String",
"key",
"=",
"String",
".",
"format",
"(",
"\"%s:%s\"",
",",
"dep",
".",
"getGroup",
"(",
")",
",",
"dep",
".",
"getName",
"(",
")",
")",
";",
"dependencyScopeMap",
".",
"put",
"(",
"key",
",",
"REMAPPED_SCOPES",
".",
"getOrDefault",
"(",
"cfg",
".",
"getName",
"(",
")",
",",
"defaultScopeForUnknownConfigurations",
")",
")",
";",
"}",
")",
";",
"}",
")",
";",
"//",
"// Step 2",
"// ------",
"// Assuming that the given configuration can be resolved, get the resolved artifacts and populate the return Map.",
"//",
"ResolvedConfiguration",
"resolvedConfig",
"=",
"requestedConfiguration",
".",
"getResolvedConfiguration",
"(",
")",
";",
"Map",
"<",
"DependencyDescriptor",
",",
"Set",
"<",
"DependencyDescriptor",
">",
">",
"dependencyMap",
"=",
"new",
"HashMap",
"<>",
"(",
")",
";",
"resolvedConfig",
".",
"getFirstLevelModuleDependencies",
"(",
")",
".",
"forEach",
"(",
"resolvedDep",
"->",
"{",
"String",
"lookup",
"=",
"String",
".",
"format",
"(",
"\"%s:%s\"",
",",
"resolvedDep",
".",
"getModuleGroup",
"(",
")",
",",
"resolvedDep",
".",
"getModuleName",
"(",
")",
")",
";",
"String",
"scope",
"=",
"dependencyScopeMap",
".",
"get",
"(",
"lookup",
")",
";",
"if",
"(",
"scope",
"==",
"null",
")",
"{",
"// Should never happen.",
"throw",
"new",
"IllegalStateException",
"(",
"\"Gradle dependency resolution logic is broken. Unable to get scope for dependency: \"",
"+",
"lookup",
")",
";",
"}",
"DependencyDescriptor",
"key",
"=",
"asDescriptor",
"(",
"scope",
",",
"resolvedDep",
")",
";",
"Set",
"<",
"DependencyDescriptor",
">",
"value",
";",
"if",
"(",
"resolveChildrenTransitively",
")",
"{",
"value",
"=",
"getDependenciesTransitively",
"(",
"scope",
",",
"resolvedDep",
")",
";",
"}",
"else",
"{",
"value",
"=",
"resolvedDep",
".",
"getChildren",
"(",
")",
".",
"stream",
"(",
")",
".",
"map",
"(",
"rd",
"->",
"asDescriptor",
"(",
"scope",
",",
"rd",
")",
")",
".",
"collect",
"(",
"Collectors",
".",
"toSet",
"(",
")",
")",
";",
"}",
"dependencyMap",
".",
"put",
"(",
"key",
",",
"value",
")",
";",
"}",
")",
";",
"printDependencyMap",
"(",
"dependencyMap",
",",
"project",
")",
";",
"return",
"dependencyMap",
";",
"}"
] | Determine the dependencies associated with a Gradle project. This method returns a Map whose key represents a top level
dependency associated with this project and the value represents a collection of dependencies that the "key" requires.
@param project the Gradle project reference.
@param configuration the dependency configuration that needs to be resolved.
@param resolveChildrenTransitively if set to true, then upstream dependencies will be resolved transitively.
@return the dependencies associated with the Gradle project for the specified configuration. | [
"Determine",
"the",
"dependencies",
"associated",
"with",
"a",
"Gradle",
"project",
".",
"This",
"method",
"returns",
"a",
"Map",
"whose",
"key",
"represents",
"a",
"top",
"level",
"dependency",
"associated",
"with",
"this",
"project",
"and",
"the",
"value",
"represents",
"a",
"collection",
"of",
"dependencies",
"that",
"the",
"key",
"requires",
"."
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/plugins/gradle/gradle-plugin/src/main/java/org/wildfly/swarm/plugin/gradle/GradleDependencyResolutionHelper.java#L168-L229 | train |
thorntail/thorntail | plugins/gradle/gradle-plugin/src/main/java/org/wildfly/swarm/plugin/gradle/GradleDependencyResolutionHelper.java | GradleDependencyResolutionHelper.printDependencyMap | private static void printDependencyMap(Map<DependencyDescriptor, Set<DependencyDescriptor>> map, Project project) {
final String NEW_LINE = "\n";
if (project.getLogger().isEnabled(LogLevel.INFO)) {
StringBuilder builder = new StringBuilder(100);
builder.append("Resolved dependencies:").append(NEW_LINE);
map.forEach((k, v) -> {
builder.append(k).append(NEW_LINE);
v.forEach(e -> builder.append("\t").append(e).append(NEW_LINE));
builder.append(NEW_LINE);
});
project.getLogger().info(builder.toString());
}
} | java | private static void printDependencyMap(Map<DependencyDescriptor, Set<DependencyDescriptor>> map, Project project) {
final String NEW_LINE = "\n";
if (project.getLogger().isEnabled(LogLevel.INFO)) {
StringBuilder builder = new StringBuilder(100);
builder.append("Resolved dependencies:").append(NEW_LINE);
map.forEach((k, v) -> {
builder.append(k).append(NEW_LINE);
v.forEach(e -> builder.append("\t").append(e).append(NEW_LINE));
builder.append(NEW_LINE);
});
project.getLogger().info(builder.toString());
}
} | [
"private",
"static",
"void",
"printDependencyMap",
"(",
"Map",
"<",
"DependencyDescriptor",
",",
"Set",
"<",
"DependencyDescriptor",
">",
">",
"map",
",",
"Project",
"project",
")",
"{",
"final",
"String",
"NEW_LINE",
"=",
"\"\\n\"",
";",
"if",
"(",
"project",
".",
"getLogger",
"(",
")",
".",
"isEnabled",
"(",
"LogLevel",
".",
"INFO",
")",
")",
"{",
"StringBuilder",
"builder",
"=",
"new",
"StringBuilder",
"(",
"100",
")",
";",
"builder",
".",
"append",
"(",
"\"Resolved dependencies:\"",
")",
".",
"append",
"(",
"NEW_LINE",
")",
";",
"map",
".",
"forEach",
"(",
"(",
"k",
",",
"v",
")",
"->",
"{",
"builder",
".",
"append",
"(",
"k",
")",
".",
"append",
"(",
"NEW_LINE",
")",
";",
"v",
".",
"forEach",
"(",
"e",
"->",
"builder",
".",
"append",
"(",
"\"\\t\"",
")",
".",
"append",
"(",
"e",
")",
".",
"append",
"(",
"NEW_LINE",
")",
")",
";",
"builder",
".",
"append",
"(",
"NEW_LINE",
")",
";",
"}",
")",
";",
"project",
".",
"getLogger",
"(",
")",
".",
"info",
"(",
"builder",
".",
"toString",
"(",
")",
")",
";",
"}",
"}"
] | Temp method for printing out the dependency map. | [
"Temp",
"method",
"for",
"printing",
"out",
"the",
"dependency",
"map",
"."
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/plugins/gradle/gradle-plugin/src/main/java/org/wildfly/swarm/plugin/gradle/GradleDependencyResolutionHelper.java#L300-L312 | train |
thorntail/thorntail | plugins/gradle/gradle-plugin/src/main/java/org/wildfly/swarm/plugin/gradle/GradleDependencyResolutionHelper.java | GradleDependencyResolutionHelper.getAllProjects | private static Map<String, Project> getAllProjects(final Project project) {
return getCachedReference(project, "thorntail_project_gav_collection", () -> {
Map<String, Project> gavMap = new HashMap<>();
project.getRootProject().getAllprojects().forEach(p -> {
gavMap.put(p.getGroup() + ":" + p.getName() + ":" + p.getVersion(), p);
});
return gavMap;
});
} | java | private static Map<String, Project> getAllProjects(final Project project) {
return getCachedReference(project, "thorntail_project_gav_collection", () -> {
Map<String, Project> gavMap = new HashMap<>();
project.getRootProject().getAllprojects().forEach(p -> {
gavMap.put(p.getGroup() + ":" + p.getName() + ":" + p.getVersion(), p);
});
return gavMap;
});
} | [
"private",
"static",
"Map",
"<",
"String",
",",
"Project",
">",
"getAllProjects",
"(",
"final",
"Project",
"project",
")",
"{",
"return",
"getCachedReference",
"(",
"project",
",",
"\"thorntail_project_gav_collection\"",
",",
"(",
")",
"->",
"{",
"Map",
"<",
"String",
",",
"Project",
">",
"gavMap",
"=",
"new",
"HashMap",
"<>",
"(",
")",
";",
"project",
".",
"getRootProject",
"(",
")",
".",
"getAllprojects",
"(",
")",
".",
"forEach",
"(",
"p",
"->",
"{",
"gavMap",
".",
"put",
"(",
"p",
".",
"getGroup",
"(",
")",
"+",
"\":\"",
"+",
"p",
".",
"getName",
"(",
")",
"+",
"\":\"",
"+",
"p",
".",
"getVersion",
"(",
")",
",",
"p",
")",
";",
"}",
")",
";",
"return",
"gavMap",
";",
"}",
")",
";",
"}"
] | Get the collection of Gradle projects along with their GAV definitions. This collection is used for determining if an
artifact specification represents a Gradle project or not.
@param project the Gradle project that is being analyzed.
@return a map of GAV coordinates for each of the available projects (returned as keys). | [
"Get",
"the",
"collection",
"of",
"Gradle",
"projects",
"along",
"with",
"their",
"GAV",
"definitions",
".",
"This",
"collection",
"is",
"used",
"for",
"determining",
"if",
"an",
"artifact",
"specification",
"represents",
"a",
"Gradle",
"project",
"or",
"not",
"."
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/plugins/gradle/gradle-plugin/src/main/java/org/wildfly/swarm/plugin/gradle/GradleDependencyResolutionHelper.java#L321-L329 | train |
thorntail/thorntail | core/spi/src/main/java/org/wildfly/swarm/spi/api/Defaultable.java | Defaultable.ifPresent | public void ifPresent(Consumer<? super T> consumer) {
T value = get(false);
if (value != null) {
consumer.accept(value);
}
} | java | public void ifPresent(Consumer<? super T> consumer) {
T value = get(false);
if (value != null) {
consumer.accept(value);
}
} | [
"public",
"void",
"ifPresent",
"(",
"Consumer",
"<",
"?",
"super",
"T",
">",
"consumer",
")",
"{",
"T",
"value",
"=",
"get",
"(",
"false",
")",
";",
"if",
"(",
"value",
"!=",
"null",
")",
"{",
"consumer",
".",
"accept",
"(",
"value",
")",
";",
"}",
"}"
] | If a default or explicit value is present, invoke the supplied consumer with it.
@param consumer The consumer. | [
"If",
"a",
"default",
"or",
"explicit",
"value",
"is",
"present",
"invoke",
"the",
"supplied",
"consumer",
"with",
"it",
"."
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/core/spi/src/main/java/org/wildfly/swarm/spi/api/Defaultable.java#L195-L201 | train |
thorntail/thorntail | core/container/src/main/java/org/wildfly/swarm/internal/FileSystemLayout.java | FileSystemLayout.create | public static FileSystemLayout create() {
String userDir = System.getProperty(USER_DIR);
if (null == userDir) {
throw SwarmMessages.MESSAGES.systemPropertyNotFound(USER_DIR);
}
return create(userDir);
} | java | public static FileSystemLayout create() {
String userDir = System.getProperty(USER_DIR);
if (null == userDir) {
throw SwarmMessages.MESSAGES.systemPropertyNotFound(USER_DIR);
}
return create(userDir);
} | [
"public",
"static",
"FileSystemLayout",
"create",
"(",
")",
"{",
"String",
"userDir",
"=",
"System",
".",
"getProperty",
"(",
"USER_DIR",
")",
";",
"if",
"(",
"null",
"==",
"userDir",
")",
"{",
"throw",
"SwarmMessages",
".",
"MESSAGES",
".",
"systemPropertyNotFound",
"(",
"USER_DIR",
")",
";",
"}",
"return",
"create",
"(",
"userDir",
")",
";",
"}"
] | Derived form 'user.dir'
@return a FileSystemLayout instance | [
"Derived",
"form",
"user",
".",
"dir"
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/core/container/src/main/java/org/wildfly/swarm/internal/FileSystemLayout.java#L69-L77 | train |
thorntail/thorntail | core/container/src/main/java/org/wildfly/swarm/internal/FileSystemLayout.java | FileSystemLayout.create | public static FileSystemLayout create(String root) {
// THORN-2178: Check if a System property has been set to a specific implementation class.
String implClassName = System.getProperty(CUSTOM_LAYOUT_CLASS);
if (implClassName != null) {
implClassName = implClassName.trim();
if (!implClassName.isEmpty()) {
FileSystemLayout layout = null;
// Attempt to load the specified class implementation.
ClassLoader loader = Thread.currentThread().getContextClassLoader();
try {
Class<?> clazz = loader.loadClass(implClassName);
// Check if clazz is an implementation of FileSystemLayout or not.
if (FileSystemLayout.class.isAssignableFrom(clazz)) {
Class<? extends FileSystemLayout> implClazz = clazz.asSubclass(FileSystemLayout.class);
// Check if we have an appropriate constructor or not.
Constructor<? extends FileSystemLayout> ctor = implClazz.getDeclaredConstructor(String.class);
layout = ctor.newInstance(root);
} else {
String msg = String.format("%s does not subclass %s", implClassName, FileSystemLayout.class.getName());
LOG.warn(SwarmMessages.MESSAGES.invalidFileSystemLayoutProvided(msg));
}
} catch (ReflectiveOperationException e) {
Throwable cause = e.getCause();
String msg = String.format("Unable to instantiate layout class (%s) due to: %s", implClassName,
cause != null ? cause.getMessage() : e.getMessage());
LOG.warn(SwarmMessages.MESSAGES.invalidFileSystemLayoutProvided(msg));
LOG.debug(SwarmMessages.MESSAGES.invalidFileSystemLayoutProvided(msg), e);
throw SwarmMessages.MESSAGES.cannotIdentifyFileSystemLayout(msg);
}
if (layout != null) {
return layout;
}
} else {
LOG.warn(SwarmMessages.MESSAGES.invalidFileSystemLayoutProvided("Implementation class name is empty."));
}
}
String mavenBuildFile = resolveMavenBuildFileName();
if (Files.exists(Paths.get(root, mavenBuildFile))) {
return new MavenFileSystemLayout(root);
} else if (Files.exists(Paths.get(root, BUILD_GRADLE))) {
return new GradleFileSystemLayout(root);
}
throw SwarmMessages.MESSAGES.cannotIdentifyFileSystemLayout(root);
} | java | public static FileSystemLayout create(String root) {
// THORN-2178: Check if a System property has been set to a specific implementation class.
String implClassName = System.getProperty(CUSTOM_LAYOUT_CLASS);
if (implClassName != null) {
implClassName = implClassName.trim();
if (!implClassName.isEmpty()) {
FileSystemLayout layout = null;
// Attempt to load the specified class implementation.
ClassLoader loader = Thread.currentThread().getContextClassLoader();
try {
Class<?> clazz = loader.loadClass(implClassName);
// Check if clazz is an implementation of FileSystemLayout or not.
if (FileSystemLayout.class.isAssignableFrom(clazz)) {
Class<? extends FileSystemLayout> implClazz = clazz.asSubclass(FileSystemLayout.class);
// Check if we have an appropriate constructor or not.
Constructor<? extends FileSystemLayout> ctor = implClazz.getDeclaredConstructor(String.class);
layout = ctor.newInstance(root);
} else {
String msg = String.format("%s does not subclass %s", implClassName, FileSystemLayout.class.getName());
LOG.warn(SwarmMessages.MESSAGES.invalidFileSystemLayoutProvided(msg));
}
} catch (ReflectiveOperationException e) {
Throwable cause = e.getCause();
String msg = String.format("Unable to instantiate layout class (%s) due to: %s", implClassName,
cause != null ? cause.getMessage() : e.getMessage());
LOG.warn(SwarmMessages.MESSAGES.invalidFileSystemLayoutProvided(msg));
LOG.debug(SwarmMessages.MESSAGES.invalidFileSystemLayoutProvided(msg), e);
throw SwarmMessages.MESSAGES.cannotIdentifyFileSystemLayout(msg);
}
if (layout != null) {
return layout;
}
} else {
LOG.warn(SwarmMessages.MESSAGES.invalidFileSystemLayoutProvided("Implementation class name is empty."));
}
}
String mavenBuildFile = resolveMavenBuildFileName();
if (Files.exists(Paths.get(root, mavenBuildFile))) {
return new MavenFileSystemLayout(root);
} else if (Files.exists(Paths.get(root, BUILD_GRADLE))) {
return new GradleFileSystemLayout(root);
}
throw SwarmMessages.MESSAGES.cannotIdentifyFileSystemLayout(root);
} | [
"public",
"static",
"FileSystemLayout",
"create",
"(",
"String",
"root",
")",
"{",
"// THORN-2178: Check if a System property has been set to a specific implementation class.",
"String",
"implClassName",
"=",
"System",
".",
"getProperty",
"(",
"CUSTOM_LAYOUT_CLASS",
")",
";",
"if",
"(",
"implClassName",
"!=",
"null",
")",
"{",
"implClassName",
"=",
"implClassName",
".",
"trim",
"(",
")",
";",
"if",
"(",
"!",
"implClassName",
".",
"isEmpty",
"(",
")",
")",
"{",
"FileSystemLayout",
"layout",
"=",
"null",
";",
"// Attempt to load the specified class implementation.",
"ClassLoader",
"loader",
"=",
"Thread",
".",
"currentThread",
"(",
")",
".",
"getContextClassLoader",
"(",
")",
";",
"try",
"{",
"Class",
"<",
"?",
">",
"clazz",
"=",
"loader",
".",
"loadClass",
"(",
"implClassName",
")",
";",
"// Check if clazz is an implementation of FileSystemLayout or not.",
"if",
"(",
"FileSystemLayout",
".",
"class",
".",
"isAssignableFrom",
"(",
"clazz",
")",
")",
"{",
"Class",
"<",
"?",
"extends",
"FileSystemLayout",
">",
"implClazz",
"=",
"clazz",
".",
"asSubclass",
"(",
"FileSystemLayout",
".",
"class",
")",
";",
"// Check if we have an appropriate constructor or not.",
"Constructor",
"<",
"?",
"extends",
"FileSystemLayout",
">",
"ctor",
"=",
"implClazz",
".",
"getDeclaredConstructor",
"(",
"String",
".",
"class",
")",
";",
"layout",
"=",
"ctor",
".",
"newInstance",
"(",
"root",
")",
";",
"}",
"else",
"{",
"String",
"msg",
"=",
"String",
".",
"format",
"(",
"\"%s does not subclass %s\"",
",",
"implClassName",
",",
"FileSystemLayout",
".",
"class",
".",
"getName",
"(",
")",
")",
";",
"LOG",
".",
"warn",
"(",
"SwarmMessages",
".",
"MESSAGES",
".",
"invalidFileSystemLayoutProvided",
"(",
"msg",
")",
")",
";",
"}",
"}",
"catch",
"(",
"ReflectiveOperationException",
"e",
")",
"{",
"Throwable",
"cause",
"=",
"e",
".",
"getCause",
"(",
")",
";",
"String",
"msg",
"=",
"String",
".",
"format",
"(",
"\"Unable to instantiate layout class (%s) due to: %s\"",
",",
"implClassName",
",",
"cause",
"!=",
"null",
"?",
"cause",
".",
"getMessage",
"(",
")",
":",
"e",
".",
"getMessage",
"(",
")",
")",
";",
"LOG",
".",
"warn",
"(",
"SwarmMessages",
".",
"MESSAGES",
".",
"invalidFileSystemLayoutProvided",
"(",
"msg",
")",
")",
";",
"LOG",
".",
"debug",
"(",
"SwarmMessages",
".",
"MESSAGES",
".",
"invalidFileSystemLayoutProvided",
"(",
"msg",
")",
",",
"e",
")",
";",
"throw",
"SwarmMessages",
".",
"MESSAGES",
".",
"cannotIdentifyFileSystemLayout",
"(",
"msg",
")",
";",
"}",
"if",
"(",
"layout",
"!=",
"null",
")",
"{",
"return",
"layout",
";",
"}",
"}",
"else",
"{",
"LOG",
".",
"warn",
"(",
"SwarmMessages",
".",
"MESSAGES",
".",
"invalidFileSystemLayoutProvided",
"(",
"\"Implementation class name is empty.\"",
")",
")",
";",
"}",
"}",
"String",
"mavenBuildFile",
"=",
"resolveMavenBuildFileName",
"(",
")",
";",
"if",
"(",
"Files",
".",
"exists",
"(",
"Paths",
".",
"get",
"(",
"root",
",",
"mavenBuildFile",
")",
")",
")",
"{",
"return",
"new",
"MavenFileSystemLayout",
"(",
"root",
")",
";",
"}",
"else",
"if",
"(",
"Files",
".",
"exists",
"(",
"Paths",
".",
"get",
"(",
"root",
",",
"BUILD_GRADLE",
")",
")",
")",
"{",
"return",
"new",
"GradleFileSystemLayout",
"(",
"root",
")",
";",
"}",
"throw",
"SwarmMessages",
".",
"MESSAGES",
".",
"cannotIdentifyFileSystemLayout",
"(",
"root",
")",
";",
"}"
] | Derived from explicit path
@param root the fs entry point
@return a FileSystemLayout instance | [
"Derived",
"from",
"explicit",
"path"
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/core/container/src/main/java/org/wildfly/swarm/internal/FileSystemLayout.java#L85-L133 | train |
thorntail/thorntail | fractions/microprofile/microprofile-openapi/src/main/java/org/wildfly/swarm/microprofile/openapi/runtime/OpenApiDeploymentProcessor.java | OpenApiDeploymentProcessor.process | @Override
public void process() throws Exception {
// if the deployment is Implicit, we don't want to process it
if (deploymentContext != null && deploymentContext.isImplicit()) {
return;
}
try {
// First register OpenApiServletContextListener which triggers the final init
WARArchive warArchive = archive.as(WARArchive.class);
warArchive.findWebXmlAsset().addListener(LISTENER_CLASS);
} catch (Exception e) {
throw new RuntimeException("Failed to register OpenAPI listener", e);
}
OpenApiStaticFile staticFile = ArchiveUtil.archiveToStaticFile(archive);
// Set models from annotations and static file
OpenApiDocument openApiDocument = OpenApiDocument.INSTANCE;
openApiDocument.config(config);
openApiDocument.modelFromStaticFile(OpenApiProcessor.modelFromStaticFile(staticFile));
openApiDocument.modelFromAnnotations(OpenApiProcessor.modelFromAnnotations(config, index));
} | java | @Override
public void process() throws Exception {
// if the deployment is Implicit, we don't want to process it
if (deploymentContext != null && deploymentContext.isImplicit()) {
return;
}
try {
// First register OpenApiServletContextListener which triggers the final init
WARArchive warArchive = archive.as(WARArchive.class);
warArchive.findWebXmlAsset().addListener(LISTENER_CLASS);
} catch (Exception e) {
throw new RuntimeException("Failed to register OpenAPI listener", e);
}
OpenApiStaticFile staticFile = ArchiveUtil.archiveToStaticFile(archive);
// Set models from annotations and static file
OpenApiDocument openApiDocument = OpenApiDocument.INSTANCE;
openApiDocument.config(config);
openApiDocument.modelFromStaticFile(OpenApiProcessor.modelFromStaticFile(staticFile));
openApiDocument.modelFromAnnotations(OpenApiProcessor.modelFromAnnotations(config, index));
} | [
"@",
"Override",
"public",
"void",
"process",
"(",
")",
"throws",
"Exception",
"{",
"// if the deployment is Implicit, we don't want to process it",
"if",
"(",
"deploymentContext",
"!=",
"null",
"&&",
"deploymentContext",
".",
"isImplicit",
"(",
")",
")",
"{",
"return",
";",
"}",
"try",
"{",
"// First register OpenApiServletContextListener which triggers the final init",
"WARArchive",
"warArchive",
"=",
"archive",
".",
"as",
"(",
"WARArchive",
".",
"class",
")",
";",
"warArchive",
".",
"findWebXmlAsset",
"(",
")",
".",
"addListener",
"(",
"LISTENER_CLASS",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"Failed to register OpenAPI listener\"",
",",
"e",
")",
";",
"}",
"OpenApiStaticFile",
"staticFile",
"=",
"ArchiveUtil",
".",
"archiveToStaticFile",
"(",
"archive",
")",
";",
"// Set models from annotations and static file",
"OpenApiDocument",
"openApiDocument",
"=",
"OpenApiDocument",
".",
"INSTANCE",
";",
"openApiDocument",
".",
"config",
"(",
"config",
")",
";",
"openApiDocument",
".",
"modelFromStaticFile",
"(",
"OpenApiProcessor",
".",
"modelFromStaticFile",
"(",
"staticFile",
")",
")",
";",
"openApiDocument",
".",
"modelFromAnnotations",
"(",
"OpenApiProcessor",
".",
"modelFromAnnotations",
"(",
"config",
",",
"index",
")",
")",
";",
"}"
] | Process the deployment in order to produce an OpenAPI document.
@see org.wildfly.swarm.spi.api.DeploymentProcessor#process() | [
"Process",
"the",
"deployment",
"in",
"order",
"to",
"produce",
"an",
"OpenAPI",
"document",
"."
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/fractions/microprofile/microprofile-openapi/src/main/java/org/wildfly/swarm/microprofile/openapi/runtime/OpenApiDeploymentProcessor.java#L81-L102 | train |
thorntail/thorntail | core/container/src/main/java/org/wildfly/swarm/cli/Option.java | Option.toURL | public static URL toURL(String value) throws MalformedURLException {
try {
URL url = new URL(value);
return url;
} catch (MalformedURLException e) {
try {
return new File(value).toURI().toURL();
} catch (MalformedURLException e2) {
// throw the original
throw e;
}
}
} | java | public static URL toURL(String value) throws MalformedURLException {
try {
URL url = new URL(value);
return url;
} catch (MalformedURLException e) {
try {
return new File(value).toURI().toURL();
} catch (MalformedURLException e2) {
// throw the original
throw e;
}
}
} | [
"public",
"static",
"URL",
"toURL",
"(",
"String",
"value",
")",
"throws",
"MalformedURLException",
"{",
"try",
"{",
"URL",
"url",
"=",
"new",
"URL",
"(",
"value",
")",
";",
"return",
"url",
";",
"}",
"catch",
"(",
"MalformedURLException",
"e",
")",
"{",
"try",
"{",
"return",
"new",
"File",
"(",
"value",
")",
".",
"toURI",
"(",
")",
".",
"toURL",
"(",
")",
";",
"}",
"catch",
"(",
"MalformedURLException",
"e2",
")",
"{",
"// throw the original",
"throw",
"e",
";",
"}",
"}",
"}"
] | Helper to attempt forming a URL from a String in a sensible fashion.
@param value The input string.
@return The correct URL, if possible. | [
"Helper",
"to",
"attempt",
"forming",
"a",
"URL",
"from",
"a",
"String",
"in",
"a",
"sensible",
"fashion",
"."
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/core/container/src/main/java/org/wildfly/swarm/cli/Option.java#L342-L354 | train |
thorntail/thorntail | core/bootstrap/src/main/java/org/wildfly/swarm/bootstrap/util/BootstrapUtil.java | BootstrapUtil.explodeJar | public static void explodeJar(JarFile jarFile, String destDir) throws IOException {
Enumeration<java.util.jar.JarEntry> enu = jarFile.entries();
while (enu.hasMoreElements()) {
JarEntry je = enu.nextElement();
File fl = new File(destDir, je.getName());
if (!fl.exists()) {
fl.getParentFile().mkdirs();
fl = new File(destDir, je.getName());
}
if (je.isDirectory()) {
continue;
}
InputStream is = null;
try {
is = jarFile.getInputStream(je);
Files.copy(is, fl.toPath(), StandardCopyOption.REPLACE_EXISTING);
} finally {
if (is != null) {
is.close();
}
}
}
} | java | public static void explodeJar(JarFile jarFile, String destDir) throws IOException {
Enumeration<java.util.jar.JarEntry> enu = jarFile.entries();
while (enu.hasMoreElements()) {
JarEntry je = enu.nextElement();
File fl = new File(destDir, je.getName());
if (!fl.exists()) {
fl.getParentFile().mkdirs();
fl = new File(destDir, je.getName());
}
if (je.isDirectory()) {
continue;
}
InputStream is = null;
try {
is = jarFile.getInputStream(je);
Files.copy(is, fl.toPath(), StandardCopyOption.REPLACE_EXISTING);
} finally {
if (is != null) {
is.close();
}
}
}
} | [
"public",
"static",
"void",
"explodeJar",
"(",
"JarFile",
"jarFile",
",",
"String",
"destDir",
")",
"throws",
"IOException",
"{",
"Enumeration",
"<",
"java",
".",
"util",
".",
"jar",
".",
"JarEntry",
">",
"enu",
"=",
"jarFile",
".",
"entries",
"(",
")",
";",
"while",
"(",
"enu",
".",
"hasMoreElements",
"(",
")",
")",
"{",
"JarEntry",
"je",
"=",
"enu",
".",
"nextElement",
"(",
")",
";",
"File",
"fl",
"=",
"new",
"File",
"(",
"destDir",
",",
"je",
".",
"getName",
"(",
")",
")",
";",
"if",
"(",
"!",
"fl",
".",
"exists",
"(",
")",
")",
"{",
"fl",
".",
"getParentFile",
"(",
")",
".",
"mkdirs",
"(",
")",
";",
"fl",
"=",
"new",
"File",
"(",
"destDir",
",",
"je",
".",
"getName",
"(",
")",
")",
";",
"}",
"if",
"(",
"je",
".",
"isDirectory",
"(",
")",
")",
"{",
"continue",
";",
"}",
"InputStream",
"is",
"=",
"null",
";",
"try",
"{",
"is",
"=",
"jarFile",
".",
"getInputStream",
"(",
"je",
")",
";",
"Files",
".",
"copy",
"(",
"is",
",",
"fl",
".",
"toPath",
"(",
")",
",",
"StandardCopyOption",
".",
"REPLACE_EXISTING",
")",
";",
"}",
"finally",
"{",
"if",
"(",
"is",
"!=",
"null",
")",
"{",
"is",
".",
"close",
"(",
")",
";",
"}",
"}",
"}",
"}"
] | Extracts a jar file into a target destination directory
@param jarFile
@param destDir
@throws IOException | [
"Extracts",
"a",
"jar",
"file",
"into",
"a",
"target",
"destination",
"directory"
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/core/bootstrap/src/main/java/org/wildfly/swarm/bootstrap/util/BootstrapUtil.java#L43-L66 | train |
thorntail/thorntail | meta/fraction-metadata/src/main/java/org/wildfly/swarm/fractions/scanner/FilePresenceScanner.java | FilePresenceScanner.scan | public void scan(PathSource fileSource, Collection<FractionDetector<PathSource>> detectors, Consumer<File> handleFileAsZip) throws IOException {
detectors.stream()
.filter(d -> FileDetector.class.isAssignableFrom(d.getClass()))
.forEach(d -> d.detect(fileSource));
} | java | public void scan(PathSource fileSource, Collection<FractionDetector<PathSource>> detectors, Consumer<File> handleFileAsZip) throws IOException {
detectors.stream()
.filter(d -> FileDetector.class.isAssignableFrom(d.getClass()))
.forEach(d -> d.detect(fileSource));
} | [
"public",
"void",
"scan",
"(",
"PathSource",
"fileSource",
",",
"Collection",
"<",
"FractionDetector",
"<",
"PathSource",
">",
">",
"detectors",
",",
"Consumer",
"<",
"File",
">",
"handleFileAsZip",
")",
"throws",
"IOException",
"{",
"detectors",
".",
"stream",
"(",
")",
".",
"filter",
"(",
"d",
"->",
"FileDetector",
".",
"class",
".",
"isAssignableFrom",
"(",
"d",
".",
"getClass",
"(",
")",
")",
")",
".",
"forEach",
"(",
"d",
"->",
"d",
".",
"detect",
"(",
"fileSource",
")",
")",
";",
"}"
] | scans all xml files | [
"scans",
"all",
"xml",
"files"
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/meta/fraction-metadata/src/main/java/org/wildfly/swarm/fractions/scanner/FilePresenceScanner.java#L39-L43 | train |
thorntail/thorntail | fractions/microprofile/microprofile-jwt/src/main/java/org/wildfly/swarm/microprofile/jwtauth/deployment/auth/cdi/MPJWTExtension.java | MPJWTExtension.observesAfterBeanDiscovery | void observesAfterBeanDiscovery(@Observes final AfterBeanDiscovery event, final BeanManager beanManager) {
log.debugf("observesAfterBeanDiscovery, %s", claims);
installClaimValueProducerMethodsViaSyntheticBeans(event, beanManager);
} | java | void observesAfterBeanDiscovery(@Observes final AfterBeanDiscovery event, final BeanManager beanManager) {
log.debugf("observesAfterBeanDiscovery, %s", claims);
installClaimValueProducerMethodsViaSyntheticBeans(event, beanManager);
} | [
"void",
"observesAfterBeanDiscovery",
"(",
"@",
"Observes",
"final",
"AfterBeanDiscovery",
"event",
",",
"final",
"BeanManager",
"beanManager",
")",
"{",
"log",
".",
"debugf",
"(",
"\"observesAfterBeanDiscovery, %s\"",
",",
"claims",
")",
";",
"installClaimValueProducerMethodsViaSyntheticBeans",
"(",
"event",
",",
"beanManager",
")",
";",
"}"
] | Create producer methods for each ClaimValue injection site
@param event - AfterBeanDiscovery
@param beanManager - CDI bean manager | [
"Create",
"producer",
"methods",
"for",
"each",
"ClaimValue",
"injection",
"site"
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/fractions/microprofile/microprofile-jwt/src/main/java/org/wildfly/swarm/microprofile/jwtauth/deployment/auth/cdi/MPJWTExtension.java#L216-L219 | train |
thorntail/thorntail | tools/src/main/java/org/wildfly/swarm/tools/DeclaredDependencies.java | DeclaredDependencies.getDirectDependencies | public Collection<ArtifactSpec> getDirectDependencies(boolean includeUnsolved, boolean includePresolved) {
Set<ArtifactSpec> deps = new LinkedHashSet<>();
if (includeUnsolved) {
deps.addAll(getDirectDeps());
}
if (includePresolved) {
deps.addAll(presolvedDependencies.getDirectDeps());
}
return deps;
} | java | public Collection<ArtifactSpec> getDirectDependencies(boolean includeUnsolved, boolean includePresolved) {
Set<ArtifactSpec> deps = new LinkedHashSet<>();
if (includeUnsolved) {
deps.addAll(getDirectDeps());
}
if (includePresolved) {
deps.addAll(presolvedDependencies.getDirectDeps());
}
return deps;
} | [
"public",
"Collection",
"<",
"ArtifactSpec",
">",
"getDirectDependencies",
"(",
"boolean",
"includeUnsolved",
",",
"boolean",
"includePresolved",
")",
"{",
"Set",
"<",
"ArtifactSpec",
">",
"deps",
"=",
"new",
"LinkedHashSet",
"<>",
"(",
")",
";",
"if",
"(",
"includeUnsolved",
")",
"{",
"deps",
".",
"addAll",
"(",
"getDirectDeps",
"(",
")",
")",
";",
"}",
"if",
"(",
"includePresolved",
")",
"{",
"deps",
".",
"addAll",
"(",
"presolvedDependencies",
".",
"getDirectDeps",
"(",
")",
")",
";",
"}",
"return",
"deps",
";",
"}"
] | Get the collection of direct dependencies included in this instance.
@param includeUnsolved include dependencies that may need further
@param includePresolved include the dependencies that do not need further resolution.
@return the collection of direct dependencies included in this instance. | [
"Get",
"the",
"collection",
"of",
"direct",
"dependencies",
"included",
"in",
"this",
"instance",
"."
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/tools/src/main/java/org/wildfly/swarm/tools/DeclaredDependencies.java#L81-L90 | train |
thorntail/thorntail | tools/src/main/java/org/wildfly/swarm/tools/DeclaredDependencies.java | DeclaredDependencies.getTransientDependencies | public Set<ArtifactSpec> getTransientDependencies() {
if (null == allTransient) {
allTransient = getTransientDependencies(true, true);
}
return allTransient;
} | java | public Set<ArtifactSpec> getTransientDependencies() {
if (null == allTransient) {
allTransient = getTransientDependencies(true, true);
}
return allTransient;
} | [
"public",
"Set",
"<",
"ArtifactSpec",
">",
"getTransientDependencies",
"(",
")",
"{",
"if",
"(",
"null",
"==",
"allTransient",
")",
"{",
"allTransient",
"=",
"getTransientDependencies",
"(",
"true",
",",
"true",
")",
";",
"}",
"return",
"allTransient",
";",
"}"
] | Get the collection of all transient dependencies defined in this instance.
@return the collection of all transient dependencies defined in this instance. | [
"Get",
"the",
"collection",
"of",
"all",
"transient",
"dependencies",
"defined",
"in",
"this",
"instance",
"."
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/tools/src/main/java/org/wildfly/swarm/tools/DeclaredDependencies.java#L97-L102 | train |
thorntail/thorntail | tools/src/main/java/org/wildfly/swarm/tools/DeclaredDependencies.java | DeclaredDependencies.getTransientDependencies | public Set<ArtifactSpec> getTransientDependencies(boolean includeUnsolved, boolean includePresolved) {
Set<ArtifactSpec> deps = new HashSet<>();
List<DependencyTree<ArtifactSpec>> sources = new ArrayList<>();
if (includeUnsolved) {
sources.add(this);
}
if (includePresolved) {
sources.add(presolvedDependencies);
}
sources.forEach(s -> s.getDirectDeps().stream()
.filter(d -> !isThorntailRunner(d))
.forEach(d -> deps.addAll(s.getTransientDeps(d))));
return deps;
} | java | public Set<ArtifactSpec> getTransientDependencies(boolean includeUnsolved, boolean includePresolved) {
Set<ArtifactSpec> deps = new HashSet<>();
List<DependencyTree<ArtifactSpec>> sources = new ArrayList<>();
if (includeUnsolved) {
sources.add(this);
}
if (includePresolved) {
sources.add(presolvedDependencies);
}
sources.forEach(s -> s.getDirectDeps().stream()
.filter(d -> !isThorntailRunner(d))
.forEach(d -> deps.addAll(s.getTransientDeps(d))));
return deps;
} | [
"public",
"Set",
"<",
"ArtifactSpec",
">",
"getTransientDependencies",
"(",
"boolean",
"includeUnsolved",
",",
"boolean",
"includePresolved",
")",
"{",
"Set",
"<",
"ArtifactSpec",
">",
"deps",
"=",
"new",
"HashSet",
"<>",
"(",
")",
";",
"List",
"<",
"DependencyTree",
"<",
"ArtifactSpec",
">",
">",
"sources",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"if",
"(",
"includeUnsolved",
")",
"{",
"sources",
".",
"add",
"(",
"this",
")",
";",
"}",
"if",
"(",
"includePresolved",
")",
"{",
"sources",
".",
"add",
"(",
"presolvedDependencies",
")",
";",
"}",
"sources",
".",
"forEach",
"(",
"s",
"->",
"s",
".",
"getDirectDeps",
"(",
")",
".",
"stream",
"(",
")",
".",
"filter",
"(",
"d",
"->",
"!",
"isThorntailRunner",
"(",
"d",
")",
")",
".",
"forEach",
"(",
"d",
"->",
"deps",
".",
"addAll",
"(",
"s",
".",
"getTransientDeps",
"(",
"d",
")",
")",
")",
")",
";",
"return",
"deps",
";",
"}"
] | Get the collection of transient dependencies defined in this instance.
@param includeUnsolved include dependencies that may need further
@param includePresolved include the dependencies that do not need further resolution.
@return the collection of transient dependencies defined in this instance. | [
"Get",
"the",
"collection",
"of",
"transient",
"dependencies",
"defined",
"in",
"this",
"instance",
"."
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/tools/src/main/java/org/wildfly/swarm/tools/DeclaredDependencies.java#L111-L124 | train |
thorntail/thorntail | tools/src/main/java/org/wildfly/swarm/tools/DeclaredDependencies.java | DeclaredDependencies.getTransientDependencies | public Collection<ArtifactSpec> getTransientDependencies(ArtifactSpec artifact) {
Set<ArtifactSpec> deps = new HashSet<>();
if (this.isDirectDep(artifact)) {
deps.addAll(getTransientDeps(artifact));
}
if (presolvedDependencies.isDirectDep(artifact)) {
deps.addAll(presolvedDependencies.getTransientDeps(artifact));
}
return deps;
} | java | public Collection<ArtifactSpec> getTransientDependencies(ArtifactSpec artifact) {
Set<ArtifactSpec> deps = new HashSet<>();
if (this.isDirectDep(artifact)) {
deps.addAll(getTransientDeps(artifact));
}
if (presolvedDependencies.isDirectDep(artifact)) {
deps.addAll(presolvedDependencies.getTransientDeps(artifact));
}
return deps;
} | [
"public",
"Collection",
"<",
"ArtifactSpec",
">",
"getTransientDependencies",
"(",
"ArtifactSpec",
"artifact",
")",
"{",
"Set",
"<",
"ArtifactSpec",
">",
"deps",
"=",
"new",
"HashSet",
"<>",
"(",
")",
";",
"if",
"(",
"this",
".",
"isDirectDep",
"(",
"artifact",
")",
")",
"{",
"deps",
".",
"addAll",
"(",
"getTransientDeps",
"(",
"artifact",
")",
")",
";",
"}",
"if",
"(",
"presolvedDependencies",
".",
"isDirectDep",
"(",
"artifact",
")",
")",
"{",
"deps",
".",
"addAll",
"(",
"presolvedDependencies",
".",
"getTransientDeps",
"(",
"artifact",
")",
")",
";",
"}",
"return",
"deps",
";",
"}"
] | Get the transient dependencies defined for the given artifact specification.
@param artifact the artifact specification.
@return the transient dependencies defined for the given artifact specification. | [
"Get",
"the",
"transient",
"dependencies",
"defined",
"for",
"the",
"given",
"artifact",
"specification",
"."
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/tools/src/main/java/org/wildfly/swarm/tools/DeclaredDependencies.java#L152-L161 | train |
thorntail/thorntail | fractions/javaee/messaging/src/main/java/org/wildfly/swarm/messaging/EnhancedServer.java | EnhancedServer.remoteConnection | public EnhancedServer remoteConnection(String name) {
return remoteConnection(name, (config) -> {
});
}
/**
* Setup a named remote connection to a remote message broker.
*
* @param name The name of the connection.
* @param config The configuration.
* @return This server.
*/
public EnhancedServer remoteConnection(String name, RemoteConnection.Consumer config) {
return remoteConnection(() -> {
RemoteConnection connection = new RemoteConnection(name);
config.accept(connection);
return connection;
});
}
/**
* Setup a remote connection to a remote message broker.
*
* @param supplier The supplier of the configuration.
* @return This server.
*/
public EnhancedServer remoteConnection(RemoteConnection.Supplier supplier) {
RemoteConnection connection = supplier.get();
this.remoteConnections.add(connection);
return this;
}
public EnhancedServer enableRemote() {
enableHTTPConnections();
connectionFactory(new ConnectionFactory<>("RemoteConnectionFactory")
.connectors(Collections.singletonList("http-connector"))
.entries("java:/RemoteConnectionFactory", "java:jboss/exported/jms/RemoteConnectionFactory"));
return this;
}
private EnhancedServer enableHTTPConnections() {
if (this.subresources().acceptor(("http-acceptor")) != null) {
return this;
}
httpAcceptor(new HTTPAcceptor("http-acceptor")
.httpListener("default"));
httpAcceptor(new HTTPAcceptor("http-acceptor-throughput")
.httpListener("default")
.param("batch-delay", "50")
.param("direct-deliver", "false"));
httpConnector(new HTTPConnector(HTTP_CONNECTOR)
.socketBinding("http")
.endpoint("http-acceptor"));
httpConnector(new HTTPConnector("http-connector-throughput")
.socketBinding("http")
.endpoint("http-acceptor-throughput")
.param("batch-delay", "50"));
return this;
}
@SuppressWarnings("unchecked")
@Override
public EnhancedServer jmsQueue(String childKey, JMSQueueConsumer config) {
return super.jmsQueue(childKey, (q) -> {
if (config != null) {
config.accept(q);
}
if (q.entries() == null || q.entries().isEmpty()) {
q.entry("java:/jms/queue/" + childKey);
}
});
} | java | public EnhancedServer remoteConnection(String name) {
return remoteConnection(name, (config) -> {
});
}
/**
* Setup a named remote connection to a remote message broker.
*
* @param name The name of the connection.
* @param config The configuration.
* @return This server.
*/
public EnhancedServer remoteConnection(String name, RemoteConnection.Consumer config) {
return remoteConnection(() -> {
RemoteConnection connection = new RemoteConnection(name);
config.accept(connection);
return connection;
});
}
/**
* Setup a remote connection to a remote message broker.
*
* @param supplier The supplier of the configuration.
* @return This server.
*/
public EnhancedServer remoteConnection(RemoteConnection.Supplier supplier) {
RemoteConnection connection = supplier.get();
this.remoteConnections.add(connection);
return this;
}
public EnhancedServer enableRemote() {
enableHTTPConnections();
connectionFactory(new ConnectionFactory<>("RemoteConnectionFactory")
.connectors(Collections.singletonList("http-connector"))
.entries("java:/RemoteConnectionFactory", "java:jboss/exported/jms/RemoteConnectionFactory"));
return this;
}
private EnhancedServer enableHTTPConnections() {
if (this.subresources().acceptor(("http-acceptor")) != null) {
return this;
}
httpAcceptor(new HTTPAcceptor("http-acceptor")
.httpListener("default"));
httpAcceptor(new HTTPAcceptor("http-acceptor-throughput")
.httpListener("default")
.param("batch-delay", "50")
.param("direct-deliver", "false"));
httpConnector(new HTTPConnector(HTTP_CONNECTOR)
.socketBinding("http")
.endpoint("http-acceptor"));
httpConnector(new HTTPConnector("http-connector-throughput")
.socketBinding("http")
.endpoint("http-acceptor-throughput")
.param("batch-delay", "50"));
return this;
}
@SuppressWarnings("unchecked")
@Override
public EnhancedServer jmsQueue(String childKey, JMSQueueConsumer config) {
return super.jmsQueue(childKey, (q) -> {
if (config != null) {
config.accept(q);
}
if (q.entries() == null || q.entries().isEmpty()) {
q.entry("java:/jms/queue/" + childKey);
}
});
} | [
"public",
"EnhancedServer",
"remoteConnection",
"(",
"String",
"name",
")",
"{",
"return",
"remoteConnection",
"(",
"name",
",",
"(",
"config",
")",
"-",
">",
"{",
"}",
")",
";",
"}",
"/**\n * Setup a named remote connection to a remote message broker.\n *\n * @param name The name of the connection.\n * @param config The configuration.\n * @return This server.\n */",
"public",
"EnhancedServer",
"remoteConnection",
"(",
"String",
"name",
",",
"RemoteConnection",
".",
"Consumer",
"config",
")",
"{",
"return",
"remoteConnection",
"(",
"(",
")",
"->",
"{",
"RemoteConnection",
"connection",
"=",
"new",
"RemoteConnection",
"(",
"name",
")",
";",
"config",
".",
"accept",
"(",
"connection",
")",
";",
"return",
"connection",
";",
"}",
")",
";",
"}",
"/**\n * Setup a remote connection to a remote message broker.\n *\n * @param supplier The supplier of the configuration.\n * @return This server.\n */",
"public",
"EnhancedServer",
"remoteConnection",
"",
"(",
"RemoteConnection",
".",
"Supplier",
"supplier",
")",
"{",
"RemoteConnection",
"connection",
"=",
"supplier",
".",
"get",
"(",
")",
";",
"this",
".",
"remoteConnections",
".",
"add",
"(",
"connection",
")",
";",
"return",
"this",
";",
"}",
"public",
"EnhancedServer",
"enableRemote",
"",
"(",
")",
"{",
"enableHTTPConnections",
"(",
")",
";",
"connectionFactory",
"(",
"new",
"ConnectionFactory",
"<>",
"(",
"\"RemoteConnectionFactory\"",
")",
".",
"connectors",
"(",
"Collections",
".",
"singletonList",
"(",
"\"http-connector\"",
")",
")",
".",
"entries",
"(",
"\"java:/RemoteConnectionFactory\"",
",",
"\"java:jboss/exported/jms/RemoteConnectionFactory\"",
")",
")",
";",
"return",
"this",
";",
"}",
"private",
"EnhancedServer",
"enableHTTPConnections",
"",
"(",
")",
"{",
"if",
"(",
"this",
".",
"subresources",
"(",
")",
".",
"acceptor",
"(",
"(",
"\"http-acceptor\"",
")",
")",
"!=",
"null",
")",
"{",
"return",
"this",
";",
"}",
"httpAcceptor",
"(",
"new",
"HTTPAcceptor",
"(",
"\"http-acceptor\"",
")",
".",
"httpListener",
"(",
"\"default\"",
")",
")",
";",
"httpAcceptor",
"(",
"new",
"HTTPAcceptor",
"(",
"\"http-acceptor-throughput\"",
")",
".",
"httpListener",
"(",
"\"default\"",
")",
".",
"param",
"(",
"\"batch-delay\"",
",",
"\"50\"",
")",
".",
"param",
"(",
"\"direct-deliver\"",
",",
"\"false\"",
")",
")",
";",
"httpConnector",
"(",
"new",
"HTTPConnector",
"(",
"HTTP_CONNECTOR",
")",
".",
"socketBinding",
"(",
"\"http\"",
")",
".",
"endpoint",
"(",
"\"http-acceptor\"",
")",
")",
";",
"httpConnector",
"(",
"new",
"HTTPConnector",
"(",
"\"http-connector-throughput\"",
")",
".",
"socketBinding",
"(",
"\"http\"",
")",
".",
"endpoint",
"(",
"\"http-acceptor-throughput\"",
")",
".",
"param",
"(",
"\"batch-delay\"",
",",
"\"50\"",
")",
")",
";",
"return",
"this",
";",
"}",
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"@",
"Override",
"public",
"EnhancedServer",
"jmsQueue",
"",
"(",
"String",
"childKey",
",",
"JMSQueueConsumer",
"config",
")",
"{",
"return",
"super",
".",
"jmsQueue",
"(",
"childKey",
",",
"(",
"q",
")",
"-",
">",
"{",
"if",
"(",
"config",
"!=",
"null",
")",
"{",
"config",
".",
"accept",
"(",
"q",
")",
";",
"}",
"if",
"(",
"q",
".",
"entries",
"(",
")",
"==",
"null",
"||",
"q",
".",
"entries",
"(",
")",
".",
"isEmpty",
"(",
")",
")",
"{",
"q",
".",
"entry",
"(",
"\"java:/jms/queue/\"",
"+",
"childKey",
")",
";",
"}",
"}",
")",
";",
"}"
] | Setup a default named remote connection to a remote message broker.
<p>By default, it sets up a connection
connecting to <code>localhost</code> at port <code>61616</code>.
The connection factory is named <code>java:/jms/<b>name</b></code>.</p>
@return This server. | [
"Setup",
"a",
"default",
"named",
"remote",
"connection",
"to",
"a",
"remote",
"message",
"broker",
"."
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/fractions/javaee/messaging/src/main/java/org/wildfly/swarm/messaging/EnhancedServer.java#L142-L219 | train |
thorntail/thorntail | fractions/microprofile/microprofile-jwt/src/main/java/org/wildfly/swarm/microprofile/jwtauth/deployment/auth/cdi/CommonJwtProducer.java | CommonJwtProducer.generalJsonValueProducer | public JsonValue generalJsonValueProducer(InjectionPoint ip) {
String name = getName(ip);
Object value = getValue(name, false);
JsonValue jsonValue = wrapValue(value);
return jsonValue;
} | java | public JsonValue generalJsonValueProducer(InjectionPoint ip) {
String name = getName(ip);
Object value = getValue(name, false);
JsonValue jsonValue = wrapValue(value);
return jsonValue;
} | [
"public",
"JsonValue",
"generalJsonValueProducer",
"(",
"InjectionPoint",
"ip",
")",
"{",
"String",
"name",
"=",
"getName",
"(",
"ip",
")",
";",
"Object",
"value",
"=",
"getValue",
"(",
"name",
",",
"false",
")",
";",
"JsonValue",
"jsonValue",
"=",
"wrapValue",
"(",
"value",
")",
";",
"return",
"jsonValue",
";",
"}"
] | Return the indicated claim value as a JsonValue
@param ip - injection point of the claim
@return a JsonValue wrapper | [
"Return",
"the",
"indicated",
"claim",
"value",
"as",
"a",
"JsonValue"
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/fractions/microprofile/microprofile-jwt/src/main/java/org/wildfly/swarm/microprofile/jwtauth/deployment/auth/cdi/CommonJwtProducer.java#L78-L83 | train |
thorntail/thorntail | core/container/src/main/java/org/wildfly/swarm/container/runtime/RuntimeServer.java | RuntimeServer.cleanup | private void cleanup() throws IOException {
JarFileManager.INSTANCE.close();
TempFileManager.INSTANCE.close();
MavenResolvers.close();
} | java | private void cleanup() throws IOException {
JarFileManager.INSTANCE.close();
TempFileManager.INSTANCE.close();
MavenResolvers.close();
} | [
"private",
"void",
"cleanup",
"(",
")",
"throws",
"IOException",
"{",
"JarFileManager",
".",
"INSTANCE",
".",
"close",
"(",
")",
";",
"TempFileManager",
".",
"INSTANCE",
".",
"close",
"(",
")",
";",
"MavenResolvers",
".",
"close",
"(",
")",
";",
"}"
] | Clean up all open resources.
@throws IOException if the close operation fails. | [
"Clean",
"up",
"all",
"open",
"resources",
"."
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/core/container/src/main/java/org/wildfly/swarm/container/runtime/RuntimeServer.java#L321-L325 | train |
thorntail/thorntail | arquillian/daemon/src/main/java/org/wildfly/swarm/arquillian/daemon/container/DaemonDeployableContainerBase.java | DaemonDeployableContainerBase.closeRemoteResources | private void closeRemoteResources() {
if (reader != null) {
try {
reader.close();
} catch (final IOException ignore) {
}
reader = null;
}
if (writer != null) {
writer.close();
writer = null;
}
if (socketOutstream != null) {
try {
socketOutstream.close();
} catch (final IOException ignore) {
}
socketOutstream = null;
}
if (socketInstream != null) {
try {
socketInstream.close();
} catch (final IOException ignore) {
}
socketInstream = null;
}
if (socket != null) {
try {
socket.close();
} catch (final IOException ignore) {
}
socket = null;
}
} | java | private void closeRemoteResources() {
if (reader != null) {
try {
reader.close();
} catch (final IOException ignore) {
}
reader = null;
}
if (writer != null) {
writer.close();
writer = null;
}
if (socketOutstream != null) {
try {
socketOutstream.close();
} catch (final IOException ignore) {
}
socketOutstream = null;
}
if (socketInstream != null) {
try {
socketInstream.close();
} catch (final IOException ignore) {
}
socketInstream = null;
}
if (socket != null) {
try {
socket.close();
} catch (final IOException ignore) {
}
socket = null;
}
} | [
"private",
"void",
"closeRemoteResources",
"(",
")",
"{",
"if",
"(",
"reader",
"!=",
"null",
")",
"{",
"try",
"{",
"reader",
".",
"close",
"(",
")",
";",
"}",
"catch",
"(",
"final",
"IOException",
"ignore",
")",
"{",
"}",
"reader",
"=",
"null",
";",
"}",
"if",
"(",
"writer",
"!=",
"null",
")",
"{",
"writer",
".",
"close",
"(",
")",
";",
"writer",
"=",
"null",
";",
"}",
"if",
"(",
"socketOutstream",
"!=",
"null",
")",
"{",
"try",
"{",
"socketOutstream",
".",
"close",
"(",
")",
";",
"}",
"catch",
"(",
"final",
"IOException",
"ignore",
")",
"{",
"}",
"socketOutstream",
"=",
"null",
";",
"}",
"if",
"(",
"socketInstream",
"!=",
"null",
")",
"{",
"try",
"{",
"socketInstream",
".",
"close",
"(",
")",
";",
"}",
"catch",
"(",
"final",
"IOException",
"ignore",
")",
"{",
"}",
"socketInstream",
"=",
"null",
";",
"}",
"if",
"(",
"socket",
"!=",
"null",
")",
"{",
"try",
"{",
"socket",
".",
"close",
"(",
")",
";",
"}",
"catch",
"(",
"final",
"IOException",
"ignore",
")",
"{",
"}",
"socket",
"=",
"null",
";",
"}",
"}"
] | Safely close remote resources | [
"Safely",
"close",
"remote",
"resources"
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/arquillian/daemon/src/main/java/org/wildfly/swarm/arquillian/daemon/container/DaemonDeployableContainerBase.java#L205-L238 | train |
thorntail/thorntail | core/bootstrap/src/main/java/org/jboss/modules/maven/ArtifactCoordinates.java | ArtifactCoordinates.fromString | public static ArtifactCoordinates fromString(String string) {
final Matcher matcher = VALID_PATTERN.matcher(string);
if (matcher.matches()) {
if (matcher.group(4) != null) {
return new ArtifactCoordinates(matcher.group(1), matcher.group(2), matcher.group(3), matcher.group(4));
} else {
return new ArtifactCoordinates(matcher.group(1), matcher.group(2), matcher.group(3));
}
} else {
throw new IllegalArgumentException(string);
}
} | java | public static ArtifactCoordinates fromString(String string) {
final Matcher matcher = VALID_PATTERN.matcher(string);
if (matcher.matches()) {
if (matcher.group(4) != null) {
return new ArtifactCoordinates(matcher.group(1), matcher.group(2), matcher.group(3), matcher.group(4));
} else {
return new ArtifactCoordinates(matcher.group(1), matcher.group(2), matcher.group(3));
}
} else {
throw new IllegalArgumentException(string);
}
} | [
"public",
"static",
"ArtifactCoordinates",
"fromString",
"(",
"String",
"string",
")",
"{",
"final",
"Matcher",
"matcher",
"=",
"VALID_PATTERN",
".",
"matcher",
"(",
"string",
")",
";",
"if",
"(",
"matcher",
".",
"matches",
"(",
")",
")",
"{",
"if",
"(",
"matcher",
".",
"group",
"(",
"4",
")",
"!=",
"null",
")",
"{",
"return",
"new",
"ArtifactCoordinates",
"(",
"matcher",
".",
"group",
"(",
"1",
")",
",",
"matcher",
".",
"group",
"(",
"2",
")",
",",
"matcher",
".",
"group",
"(",
"3",
")",
",",
"matcher",
".",
"group",
"(",
"4",
")",
")",
";",
"}",
"else",
"{",
"return",
"new",
"ArtifactCoordinates",
"(",
"matcher",
".",
"group",
"(",
"1",
")",
",",
"matcher",
".",
"group",
"(",
"2",
")",
",",
"matcher",
".",
"group",
"(",
"3",
")",
")",
";",
"}",
"}",
"else",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"string",
")",
";",
"}",
"}"
] | Parse a string and produce artifact coordinates from it.
@param string the string to parse (must not be {@code null})
@return the artifact coordinates object (not {@code null}) | [
"Parse",
"a",
"string",
"and",
"produce",
"artifact",
"coordinates",
"from",
"it",
"."
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/core/bootstrap/src/main/java/org/jboss/modules/maven/ArtifactCoordinates.java#L72-L83 | train |
thorntail/thorntail | core/bootstrap/src/main/java/org/jboss/modules/maven/ArtifactCoordinates.java | ArtifactCoordinates.relativeArtifactPath | public String relativeArtifactPath(char separator) {
String artifactId1 = getArtifactId();
String version1 = getVersion();
StringBuilder builder = new StringBuilder(getGroupId().replace('.', separator));
builder.append(separator).append(artifactId1).append(separator);
String pathVersion;
final Matcher versionMatcher = snapshotPattern.matcher(version1);
if (versionMatcher.find()) {
// it's really a snapshot
pathVersion = version1.substring(0, versionMatcher.start()) + "-SNAPSHOT";
} else {
pathVersion = version1;
}
builder.append(pathVersion).append(separator).append(artifactId1).append('-').append(version1);
return builder.toString();
} | java | public String relativeArtifactPath(char separator) {
String artifactId1 = getArtifactId();
String version1 = getVersion();
StringBuilder builder = new StringBuilder(getGroupId().replace('.', separator));
builder.append(separator).append(artifactId1).append(separator);
String pathVersion;
final Matcher versionMatcher = snapshotPattern.matcher(version1);
if (versionMatcher.find()) {
// it's really a snapshot
pathVersion = version1.substring(0, versionMatcher.start()) + "-SNAPSHOT";
} else {
pathVersion = version1;
}
builder.append(pathVersion).append(separator).append(artifactId1).append('-').append(version1);
return builder.toString();
} | [
"public",
"String",
"relativeArtifactPath",
"(",
"char",
"separator",
")",
"{",
"String",
"artifactId1",
"=",
"getArtifactId",
"(",
")",
";",
"String",
"version1",
"=",
"getVersion",
"(",
")",
";",
"StringBuilder",
"builder",
"=",
"new",
"StringBuilder",
"(",
"getGroupId",
"(",
")",
".",
"replace",
"(",
"'",
"'",
",",
"separator",
")",
")",
";",
"builder",
".",
"append",
"(",
"separator",
")",
".",
"append",
"(",
"artifactId1",
")",
".",
"append",
"(",
"separator",
")",
";",
"String",
"pathVersion",
";",
"final",
"Matcher",
"versionMatcher",
"=",
"snapshotPattern",
".",
"matcher",
"(",
"version1",
")",
";",
"if",
"(",
"versionMatcher",
".",
"find",
"(",
")",
")",
"{",
"// it's really a snapshot",
"pathVersion",
"=",
"version1",
".",
"substring",
"(",
"0",
",",
"versionMatcher",
".",
"start",
"(",
")",
")",
"+",
"\"-SNAPSHOT\"",
";",
"}",
"else",
"{",
"pathVersion",
"=",
"version1",
";",
"}",
"builder",
".",
"append",
"(",
"pathVersion",
")",
".",
"append",
"(",
"separator",
")",
".",
"append",
"(",
"artifactId1",
")",
".",
"append",
"(",
"'",
"'",
")",
".",
"append",
"(",
"version1",
")",
";",
"return",
"builder",
".",
"toString",
"(",
")",
";",
"}"
] | Create a relative repository path for the given artifact coordinates.
@param separator the separator character to use (typically {@code '/'} or {@link File#separatorChar})
@return the path string | [
"Create",
"a",
"relative",
"repository",
"path",
"for",
"the",
"given",
"artifact",
"coordinates",
"."
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/core/bootstrap/src/main/java/org/jboss/modules/maven/ArtifactCoordinates.java#L140-L155 | train |
thorntail/thorntail | core/spi/src/main/java/org/wildfly/swarm/spi/api/Module.java | Module.withImportIncludePath | public Module withImportIncludePath(String path) {
checkList(this.imports, INCLUDE);
this.imports.get(INCLUDE).add(path);
return this;
} | java | public Module withImportIncludePath(String path) {
checkList(this.imports, INCLUDE);
this.imports.get(INCLUDE).add(path);
return this;
} | [
"public",
"Module",
"withImportIncludePath",
"(",
"String",
"path",
")",
"{",
"checkList",
"(",
"this",
".",
"imports",
",",
"INCLUDE",
")",
";",
"this",
".",
"imports",
".",
"get",
"(",
"INCLUDE",
")",
".",
"add",
"(",
"path",
")",
";",
"return",
"this",
";",
"}"
] | Add a path to import from this module.
@param path The path to add.
@return this module descriptor. | [
"Add",
"a",
"path",
"to",
"import",
"from",
"this",
"module",
"."
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/core/spi/src/main/java/org/wildfly/swarm/spi/api/Module.java#L179-L183 | train |
thorntail/thorntail | core/spi/src/main/java/org/wildfly/swarm/spi/api/Module.java | Module.withImportExcludePath | public Module withImportExcludePath(String path) {
checkList(this.imports, EXCLUDE);
this.imports.get(EXCLUDE).add(path);
return this;
} | java | public Module withImportExcludePath(String path) {
checkList(this.imports, EXCLUDE);
this.imports.get(EXCLUDE).add(path);
return this;
} | [
"public",
"Module",
"withImportExcludePath",
"(",
"String",
"path",
")",
"{",
"checkList",
"(",
"this",
".",
"imports",
",",
"EXCLUDE",
")",
";",
"this",
".",
"imports",
".",
"get",
"(",
"EXCLUDE",
")",
".",
"add",
"(",
"path",
")",
";",
"return",
"this",
";",
"}"
] | Add a path to exclude from importing from this module.
@param path The excluded path to add.
@return this module descriptor. | [
"Add",
"a",
"path",
"to",
"exclude",
"from",
"importing",
"from",
"this",
"module",
"."
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/core/spi/src/main/java/org/wildfly/swarm/spi/api/Module.java#L191-L195 | train |
thorntail/thorntail | core/spi/src/main/java/org/wildfly/swarm/spi/api/Module.java | Module.withExportIncludePath | public Module withExportIncludePath(String path) {
checkList(this.exports, INCLUDE);
this.exports.get(INCLUDE).add(path);
return this;
} | java | public Module withExportIncludePath(String path) {
checkList(this.exports, INCLUDE);
this.exports.get(INCLUDE).add(path);
return this;
} | [
"public",
"Module",
"withExportIncludePath",
"(",
"String",
"path",
")",
"{",
"checkList",
"(",
"this",
".",
"exports",
",",
"INCLUDE",
")",
";",
"this",
".",
"exports",
".",
"get",
"(",
"INCLUDE",
")",
".",
"add",
"(",
"path",
")",
";",
"return",
"this",
";",
"}"
] | Add a path to export from this module.
@param path The path to add.
@return this module descriptor. | [
"Add",
"a",
"path",
"to",
"export",
"from",
"this",
"module",
"."
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/core/spi/src/main/java/org/wildfly/swarm/spi/api/Module.java#L221-L225 | train |
thorntail/thorntail | core/spi/src/main/java/org/wildfly/swarm/spi/api/Module.java | Module.withExportExcludePath | public Module withExportExcludePath(String path) {
checkList(this.exports, EXCLUDE);
this.exports.get(EXCLUDE).add(path);
return this;
} | java | public Module withExportExcludePath(String path) {
checkList(this.exports, EXCLUDE);
this.exports.get(EXCLUDE).add(path);
return this;
} | [
"public",
"Module",
"withExportExcludePath",
"(",
"String",
"path",
")",
"{",
"checkList",
"(",
"this",
".",
"exports",
",",
"EXCLUDE",
")",
";",
"this",
".",
"exports",
".",
"get",
"(",
"EXCLUDE",
")",
".",
"add",
"(",
"path",
")",
";",
"return",
"this",
";",
"}"
] | Add a path to exclude from exporting from this module.
@param path The excluded path to add.
@return this module descriptor. | [
"Add",
"a",
"path",
"to",
"exclude",
"from",
"exporting",
"from",
"this",
"module",
"."
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/core/spi/src/main/java/org/wildfly/swarm/spi/api/Module.java#L233-L237 | train |
thorntail/thorntail | meta/meta-spi/src/main/java/org/wildfly/swarm/spi/meta/PathSource.java | PathSource.getRelativePath | public String getRelativePath() {
if (basePath == null) {
return source.toString();
}
return basePath.relativize(source).toString();
} | java | public String getRelativePath() {
if (basePath == null) {
return source.toString();
}
return basePath.relativize(source).toString();
} | [
"public",
"String",
"getRelativePath",
"(",
")",
"{",
"if",
"(",
"basePath",
"==",
"null",
")",
"{",
"return",
"source",
".",
"toString",
"(",
")",
";",
"}",
"return",
"basePath",
".",
"relativize",
"(",
"source",
")",
".",
"toString",
"(",
")",
";",
"}"
] | Gets the relative file path, instead of the absolute.
@return Relative path from this file, if basePath was provided. | [
"Gets",
"the",
"relative",
"file",
"path",
"instead",
"of",
"the",
"absolute",
"."
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/meta/meta-spi/src/main/java/org/wildfly/swarm/spi/meta/PathSource.java#L58-L64 | train |
thorntail/thorntail | fractions/jolokia/src/main/java/org/wildfly/swarm/jolokia/access/Section.java | Section.mbean | public Section mbean(String name, MBeanRule.Consumer config) {
MBeanRule rule = new MBeanRule(name);
config.accept(rule);
this.rules.add(rule);
return this;
} | java | public Section mbean(String name, MBeanRule.Consumer config) {
MBeanRule rule = new MBeanRule(name);
config.accept(rule);
this.rules.add(rule);
return this;
} | [
"public",
"Section",
"mbean",
"(",
"String",
"name",
",",
"MBeanRule",
".",
"Consumer",
"config",
")",
"{",
"MBeanRule",
"rule",
"=",
"new",
"MBeanRule",
"(",
"name",
")",
";",
"config",
".",
"accept",
"(",
"rule",
")",
";",
"this",
".",
"rules",
".",
"add",
"(",
"rule",
")",
";",
"return",
"this",
";",
"}"
] | Define a rule for a given MBean.
@param name The mbean name or pattern.
@param config Configuration.
@return This section. | [
"Define",
"a",
"rule",
"for",
"a",
"given",
"MBean",
"."
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/fractions/jolokia/src/main/java/org/wildfly/swarm/jolokia/access/Section.java#L41-L46 | train |
thorntail/thorntail | core/bootstrap/src/main/java/org/jboss/modules/maven/MavenSettings.java | MavenSettings.openConnection | public URLConnection openConnection(URL url) throws IOException {
Proxy proxy = getProxyFor(url);
URLConnection conn = null;
if (proxy != null) {
conn = url.openConnection(proxy.getProxy());
proxy.authenticate(conn);
} else {
conn = url.openConnection();
}
return conn;
} | java | public URLConnection openConnection(URL url) throws IOException {
Proxy proxy = getProxyFor(url);
URLConnection conn = null;
if (proxy != null) {
conn = url.openConnection(proxy.getProxy());
proxy.authenticate(conn);
} else {
conn = url.openConnection();
}
return conn;
} | [
"public",
"URLConnection",
"openConnection",
"(",
"URL",
"url",
")",
"throws",
"IOException",
"{",
"Proxy",
"proxy",
"=",
"getProxyFor",
"(",
"url",
")",
";",
"URLConnection",
"conn",
"=",
"null",
";",
"if",
"(",
"proxy",
"!=",
"null",
")",
"{",
"conn",
"=",
"url",
".",
"openConnection",
"(",
"proxy",
".",
"getProxy",
"(",
")",
")",
";",
"proxy",
".",
"authenticate",
"(",
"conn",
")",
";",
"}",
"else",
"{",
"conn",
"=",
"url",
".",
"openConnection",
"(",
")",
";",
"}",
"return",
"conn",
";",
"}"
] | Opens a connection with appropriate proxy and credentials, if required.
@param url The URL to open.
@return The opened connection.
@throws IOException If an error occurs establishing the connection. | [
"Opens",
"a",
"connection",
"with",
"appropriate",
"proxy",
"and",
"credentials",
"if",
"required",
"."
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/core/bootstrap/src/main/java/org/jboss/modules/maven/MavenSettings.java#L413-L425 | train |
thorntail/thorntail | fractions/jose/src/main/java/org/wildfly/swarm/jose/provider/JoseFactory.java | JoseFactory.instance | public static JoseFactory instance() {
if (instance == null) {
synchronized (JoseFactory.class) {
if (instance != null) {
return instance;
}
ClassLoader cl = AccessController.doPrivileged((PrivilegedAction<ClassLoader>) () -> Thread.currentThread().getContextClassLoader());
if (cl == null) {
cl = JoseFactory.class.getClassLoader();
}
JoseFactory newInstance = loadSpi(cl);
if (newInstance == null && cl != JoseFactory.class.getClassLoader()) {
cl = JoseFactory.class.getClassLoader();
newInstance = loadSpi(cl);
}
if (newInstance == null) {
newInstance = new DefaultJoseFactory();
}
instance = newInstance;
}
}
return instance;
} | java | public static JoseFactory instance() {
if (instance == null) {
synchronized (JoseFactory.class) {
if (instance != null) {
return instance;
}
ClassLoader cl = AccessController.doPrivileged((PrivilegedAction<ClassLoader>) () -> Thread.currentThread().getContextClassLoader());
if (cl == null) {
cl = JoseFactory.class.getClassLoader();
}
JoseFactory newInstance = loadSpi(cl);
if (newInstance == null && cl != JoseFactory.class.getClassLoader()) {
cl = JoseFactory.class.getClassLoader();
newInstance = loadSpi(cl);
}
if (newInstance == null) {
newInstance = new DefaultJoseFactory();
}
instance = newInstance;
}
}
return instance;
} | [
"public",
"static",
"JoseFactory",
"instance",
"(",
")",
"{",
"if",
"(",
"instance",
"==",
"null",
")",
"{",
"synchronized",
"(",
"JoseFactory",
".",
"class",
")",
"{",
"if",
"(",
"instance",
"!=",
"null",
")",
"{",
"return",
"instance",
";",
"}",
"ClassLoader",
"cl",
"=",
"AccessController",
".",
"doPrivileged",
"(",
"(",
"PrivilegedAction",
"<",
"ClassLoader",
">",
")",
"(",
")",
"->",
"Thread",
".",
"currentThread",
"(",
")",
".",
"getContextClassLoader",
"(",
")",
")",
";",
"if",
"(",
"cl",
"==",
"null",
")",
"{",
"cl",
"=",
"JoseFactory",
".",
"class",
".",
"getClassLoader",
"(",
")",
";",
"}",
"JoseFactory",
"newInstance",
"=",
"loadSpi",
"(",
"cl",
")",
";",
"if",
"(",
"newInstance",
"==",
"null",
"&&",
"cl",
"!=",
"JoseFactory",
".",
"class",
".",
"getClassLoader",
"(",
")",
")",
"{",
"cl",
"=",
"JoseFactory",
".",
"class",
".",
"getClassLoader",
"(",
")",
";",
"newInstance",
"=",
"loadSpi",
"(",
"cl",
")",
";",
"}",
"if",
"(",
"newInstance",
"==",
"null",
")",
"{",
"newInstance",
"=",
"new",
"DefaultJoseFactory",
"(",
")",
";",
"}",
"instance",
"=",
"newInstance",
";",
"}",
"}",
"return",
"instance",
";",
"}"
] | Obtain the JoseFactory using the ServiceLoader pattern.
@return the factory instance | [
"Obtain",
"the",
"JoseFactory",
"using",
"the",
"ServiceLoader",
"pattern",
"."
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/fractions/jose/src/main/java/org/wildfly/swarm/jose/provider/JoseFactory.java#L37-L64 | train |
thorntail/thorntail | fractions/jose/src/main/java/org/wildfly/swarm/jose/provider/JoseFactory.java | JoseFactory.loadSpi | private static JoseFactory loadSpi(ClassLoader cl) {
if (cl == null) {
return null;
}
// start from the root CL and go back down to the TCCL
JoseFactory instance = loadSpi(cl.getParent());
if (instance == null) {
ServiceLoader<JoseFactory> sl = ServiceLoader.load(JoseFactory.class, cl);
URL u = cl.getResource("/META-INF/services/org.wildfly.swarm.jose.provider.JoseFactory");
log.debugf("loadSpi, cl=%s, u=%s, sl=%s", cl, u, sl);
try {
for (Object spi : sl) {
if (spi instanceof JoseFactory) {
if (instance != null) {
log.warn("Multiple JoseFactory implementations found: "
+ spi.getClass().getName() + " and " + instance.getClass().getName());
break;
} else {
log.debugf("sl=%s, loaded=%s", sl, spi);
instance = (JoseFactory)spi;
}
}
}
} catch (Throwable e) {
log.warn("Failed to locate JoseFactory provider", e);
}
}
return instance;
} | java | private static JoseFactory loadSpi(ClassLoader cl) {
if (cl == null) {
return null;
}
// start from the root CL and go back down to the TCCL
JoseFactory instance = loadSpi(cl.getParent());
if (instance == null) {
ServiceLoader<JoseFactory> sl = ServiceLoader.load(JoseFactory.class, cl);
URL u = cl.getResource("/META-INF/services/org.wildfly.swarm.jose.provider.JoseFactory");
log.debugf("loadSpi, cl=%s, u=%s, sl=%s", cl, u, sl);
try {
for (Object spi : sl) {
if (spi instanceof JoseFactory) {
if (instance != null) {
log.warn("Multiple JoseFactory implementations found: "
+ spi.getClass().getName() + " and " + instance.getClass().getName());
break;
} else {
log.debugf("sl=%s, loaded=%s", sl, spi);
instance = (JoseFactory)spi;
}
}
}
} catch (Throwable e) {
log.warn("Failed to locate JoseFactory provider", e);
}
}
return instance;
} | [
"private",
"static",
"JoseFactory",
"loadSpi",
"(",
"ClassLoader",
"cl",
")",
"{",
"if",
"(",
"cl",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"// start from the root CL and go back down to the TCCL",
"JoseFactory",
"instance",
"=",
"loadSpi",
"(",
"cl",
".",
"getParent",
"(",
")",
")",
";",
"if",
"(",
"instance",
"==",
"null",
")",
"{",
"ServiceLoader",
"<",
"JoseFactory",
">",
"sl",
"=",
"ServiceLoader",
".",
"load",
"(",
"JoseFactory",
".",
"class",
",",
"cl",
")",
";",
"URL",
"u",
"=",
"cl",
".",
"getResource",
"(",
"\"/META-INF/services/org.wildfly.swarm.jose.provider.JoseFactory\"",
")",
";",
"log",
".",
"debugf",
"(",
"\"loadSpi, cl=%s, u=%s, sl=%s\"",
",",
"cl",
",",
"u",
",",
"sl",
")",
";",
"try",
"{",
"for",
"(",
"Object",
"spi",
":",
"sl",
")",
"{",
"if",
"(",
"spi",
"instanceof",
"JoseFactory",
")",
"{",
"if",
"(",
"instance",
"!=",
"null",
")",
"{",
"log",
".",
"warn",
"(",
"\"Multiple JoseFactory implementations found: \"",
"+",
"spi",
".",
"getClass",
"(",
")",
".",
"getName",
"(",
")",
"+",
"\" and \"",
"+",
"instance",
".",
"getClass",
"(",
")",
".",
"getName",
"(",
")",
")",
";",
"break",
";",
"}",
"else",
"{",
"log",
".",
"debugf",
"(",
"\"sl=%s, loaded=%s\"",
",",
"sl",
",",
"spi",
")",
";",
"instance",
"=",
"(",
"JoseFactory",
")",
"spi",
";",
"}",
"}",
"}",
"}",
"catch",
"(",
"Throwable",
"e",
")",
"{",
"log",
".",
"warn",
"(",
"\"Failed to locate JoseFactory provider\"",
",",
"e",
")",
";",
"}",
"}",
"return",
"instance",
";",
"}"
] | Look for a JoseFactory service implementation using the ServiceLoader.
@param cl - the ClassLoader to pass into the {@link ServiceLoader#load(Class, ClassLoader)} method.
@return the JoseFactory if found, null otherwise | [
"Look",
"for",
"a",
"JoseFactory",
"service",
"implementation",
"using",
"the",
"ServiceLoader",
"."
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/fractions/jose/src/main/java/org/wildfly/swarm/jose/provider/JoseFactory.java#L72-L102 | train |
thorntail/thorntail | core/container/src/main/java/org/wildfly/swarm/container/runtime/wildfly/SwarmContentRepository.java | SwarmContentRepository.addService | public static void addService(ServiceTarget serviceTarget, SwarmContentRepository repository) {
serviceTarget.addService(SERVICE_NAME, repository)
.setInitialMode(ServiceController.Mode.ACTIVE)
.install();
} | java | public static void addService(ServiceTarget serviceTarget, SwarmContentRepository repository) {
serviceTarget.addService(SERVICE_NAME, repository)
.setInitialMode(ServiceController.Mode.ACTIVE)
.install();
} | [
"public",
"static",
"void",
"addService",
"(",
"ServiceTarget",
"serviceTarget",
",",
"SwarmContentRepository",
"repository",
")",
"{",
"serviceTarget",
".",
"addService",
"(",
"SERVICE_NAME",
",",
"repository",
")",
".",
"setInitialMode",
"(",
"ServiceController",
".",
"Mode",
".",
"ACTIVE",
")",
".",
"install",
"(",
")",
";",
"}"
] | Install the service. | [
"Install",
"the",
"service",
"."
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/core/container/src/main/java/org/wildfly/swarm/container/runtime/wildfly/SwarmContentRepository.java#L86-L90 | train |
thorntail/thorntail | fractions/topology-webapp/src/main/java/org/wildfly/swarm/topology/webapp/TopologyWebAppFraction.java | TopologyWebAppFraction.proxyService | public void proxyService(String serviceName, String contextPath) {
if (proxiedServiceMappings().containsValue(contextPath)) {
throw new IllegalArgumentException("Cannot proxy multiple services under the same context path");
}
proxiedServiceMappings.put(serviceName, contextPath);
} | java | public void proxyService(String serviceName, String contextPath) {
if (proxiedServiceMappings().containsValue(contextPath)) {
throw new IllegalArgumentException("Cannot proxy multiple services under the same context path");
}
proxiedServiceMappings.put(serviceName, contextPath);
} | [
"public",
"void",
"proxyService",
"(",
"String",
"serviceName",
",",
"String",
"contextPath",
")",
"{",
"if",
"(",
"proxiedServiceMappings",
"(",
")",
".",
"containsValue",
"(",
"contextPath",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Cannot proxy multiple services under the same context path\"",
")",
";",
"}",
"proxiedServiceMappings",
".",
"put",
"(",
"serviceName",
",",
"contextPath",
")",
";",
"}"
] | Set up a load-balancing reverse proxy for the given service at the
given context path. Requests to this proxy will be load-balanced
among all instances of the service, as provided by our Topology.
@param serviceName the name of the service to proxy
@param contextPath the context path expose the proxy under | [
"Set",
"up",
"a",
"load",
"-",
"balancing",
"reverse",
"proxy",
"for",
"the",
"given",
"service",
"at",
"the",
"given",
"context",
"path",
".",
"Requests",
"to",
"this",
"proxy",
"will",
"be",
"load",
"-",
"balanced",
"among",
"all",
"instances",
"of",
"the",
"service",
"as",
"provided",
"by",
"our",
"Topology",
"."
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/fractions/topology-webapp/src/main/java/org/wildfly/swarm/topology/webapp/TopologyWebAppFraction.java#L55-L60 | train |
thorntail/thorntail | thorntail-runner/src/main/java/org/wildfly/swarm/runner/FatJarBuilder.java | FatJarBuilder.buildWar | private File buildWar(List<ArtifactOrFile> classPathEntries) {
try {
List<String> classesUrls = classPathEntries.stream()
.map(ArtifactOrFile::file)
.filter(this::isDirectory)
.filter(url -> url.contains("classes"))
.collect(Collectors.toList());
List<File> classpathJars = classPathEntries.stream()
.map(ArtifactOrFile::file)
.filter(file -> file.endsWith(".jar"))
.map(File::new)
.collect(Collectors.toList());
return WarBuilder.build(classesUrls, classpathJars);
} catch (IOException e) {
throw new RuntimeException("failed to build war", e);
}
} | java | private File buildWar(List<ArtifactOrFile> classPathEntries) {
try {
List<String> classesUrls = classPathEntries.stream()
.map(ArtifactOrFile::file)
.filter(this::isDirectory)
.filter(url -> url.contains("classes"))
.collect(Collectors.toList());
List<File> classpathJars = classPathEntries.stream()
.map(ArtifactOrFile::file)
.filter(file -> file.endsWith(".jar"))
.map(File::new)
.collect(Collectors.toList());
return WarBuilder.build(classesUrls, classpathJars);
} catch (IOException e) {
throw new RuntimeException("failed to build war", e);
}
} | [
"private",
"File",
"buildWar",
"(",
"List",
"<",
"ArtifactOrFile",
">",
"classPathEntries",
")",
"{",
"try",
"{",
"List",
"<",
"String",
">",
"classesUrls",
"=",
"classPathEntries",
".",
"stream",
"(",
")",
".",
"map",
"(",
"ArtifactOrFile",
"::",
"file",
")",
".",
"filter",
"(",
"this",
"::",
"isDirectory",
")",
".",
"filter",
"(",
"url",
"->",
"url",
".",
"contains",
"(",
"\"classes\"",
")",
")",
".",
"collect",
"(",
"Collectors",
".",
"toList",
"(",
")",
")",
";",
"List",
"<",
"File",
">",
"classpathJars",
"=",
"classPathEntries",
".",
"stream",
"(",
")",
".",
"map",
"(",
"ArtifactOrFile",
"::",
"file",
")",
".",
"filter",
"(",
"file",
"->",
"file",
".",
"endsWith",
"(",
"\".jar\"",
")",
")",
".",
"map",
"(",
"File",
"::",
"new",
")",
".",
"collect",
"(",
"Collectors",
".",
"toList",
"(",
")",
")",
";",
"return",
"WarBuilder",
".",
"build",
"(",
"classesUrls",
",",
"classpathJars",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"failed to build war\"",
",",
"e",
")",
";",
"}",
"}"
] | builds war with classes inside
@param classPathEntries class path entries as ArtifactSpec or URLs
@return the war file | [
"builds",
"war",
"with",
"classes",
"inside"
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/thorntail-runner/src/main/java/org/wildfly/swarm/runner/FatJarBuilder.java#L151-L169 | train |
thorntail/thorntail | arquillian/gradle-adapter/src/main/java/org/wildfly/swarm/arquillian/adapter/gradle/GradleDependencyDeclarationFactory.java | GradleDependencyDeclarationFactory.resolveDependencies | private static void resolveDependencies(Collection<ArtifactSpec> collection, ShrinkwrapArtifactResolvingHelper helper) {
// Identify the artifact specs that need resolution.
// Ideally, there should be none at this point.
collection.forEach(spec -> {
if (spec.file == null) {
// Resolve it.
ArtifactSpec resolved = helper.resolve(spec);
if (resolved != null) {
spec.file = resolved.file;
} else {
throw new IllegalStateException("Unable to resolve artifact: " + spec.toString());
}
}
});
} | java | private static void resolveDependencies(Collection<ArtifactSpec> collection, ShrinkwrapArtifactResolvingHelper helper) {
// Identify the artifact specs that need resolution.
// Ideally, there should be none at this point.
collection.forEach(spec -> {
if (spec.file == null) {
// Resolve it.
ArtifactSpec resolved = helper.resolve(spec);
if (resolved != null) {
spec.file = resolved.file;
} else {
throw new IllegalStateException("Unable to resolve artifact: " + spec.toString());
}
}
});
} | [
"private",
"static",
"void",
"resolveDependencies",
"(",
"Collection",
"<",
"ArtifactSpec",
">",
"collection",
",",
"ShrinkwrapArtifactResolvingHelper",
"helper",
")",
"{",
"// Identify the artifact specs that need resolution.",
"// Ideally, there should be none at this point.",
"collection",
".",
"forEach",
"(",
"spec",
"->",
"{",
"if",
"(",
"spec",
".",
"file",
"==",
"null",
")",
"{",
"// Resolve it.",
"ArtifactSpec",
"resolved",
"=",
"helper",
".",
"resolve",
"(",
"spec",
")",
";",
"if",
"(",
"resolved",
"!=",
"null",
")",
"{",
"spec",
".",
"file",
"=",
"resolved",
".",
"file",
";",
"}",
"else",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"Unable to resolve artifact: \"",
"+",
"spec",
".",
"toString",
"(",
")",
")",
";",
"}",
"}",
"}",
")",
";",
"}"
] | Resolve the given collection of ArtifactSpec references. This method attempts the resolution and ensures that the
references are updated to be as complete as possible.
@param collection the collection artifact specifications. | [
"Resolve",
"the",
"given",
"collection",
"of",
"ArtifactSpec",
"references",
".",
"This",
"method",
"attempts",
"the",
"resolution",
"and",
"ensures",
"that",
"the",
"references",
"are",
"updated",
"to",
"be",
"as",
"complete",
"as",
"possible",
"."
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/arquillian/gradle-adapter/src/main/java/org/wildfly/swarm/arquillian/adapter/gradle/GradleDependencyDeclarationFactory.java#L56-L70 | train |
thorntail/thorntail | core/spi/src/main/java/org/wildfly/swarm/spi/api/SocketBindingGroup.java | SocketBindingGroup.socketBinding | public SocketBinding socketBinding(String name) {
return this.socketBindings.stream().filter(e -> e.name().equals(name)).findFirst().orElse(null);
} | java | public SocketBinding socketBinding(String name) {
return this.socketBindings.stream().filter(e -> e.name().equals(name)).findFirst().orElse(null);
} | [
"public",
"SocketBinding",
"socketBinding",
"(",
"String",
"name",
")",
"{",
"return",
"this",
".",
"socketBindings",
".",
"stream",
"(",
")",
".",
"filter",
"(",
"e",
"->",
"e",
".",
"name",
"(",
")",
".",
"equals",
"(",
"name",
")",
")",
".",
"findFirst",
"(",
")",
".",
"orElse",
"(",
"null",
")",
";",
"}"
] | Retrieve a socket-binding by name.
@param name The socket-binding name.
@return The socket-binding if present, otherwise {@code null}. | [
"Retrieve",
"a",
"socket",
"-",
"binding",
"by",
"name",
"."
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/core/spi/src/main/java/org/wildfly/swarm/spi/api/SocketBindingGroup.java#L118-L120 | train |
thorntail/thorntail | fractions/microprofile/microprofile-jwt/src/main/java/org/wildfly/swarm/microprofile/jwtauth/deployment/auth/JWTAuthMethodExtension.java | JWTAuthMethodExtension.handleDeployment | @Override
public void handleDeployment(DeploymentInfo deploymentInfo, ServletContext servletContext) {
deploymentInfo.addAuthenticationMechanism("MP-JWT", new JWTAuthMechanismFactory());
deploymentInfo.addInnerHandlerChainWrapper(MpJwtPrincipalHandler::new);
} | java | @Override
public void handleDeployment(DeploymentInfo deploymentInfo, ServletContext servletContext) {
deploymentInfo.addAuthenticationMechanism("MP-JWT", new JWTAuthMechanismFactory());
deploymentInfo.addInnerHandlerChainWrapper(MpJwtPrincipalHandler::new);
} | [
"@",
"Override",
"public",
"void",
"handleDeployment",
"(",
"DeploymentInfo",
"deploymentInfo",
",",
"ServletContext",
"servletContext",
")",
"{",
"deploymentInfo",
".",
"addAuthenticationMechanism",
"(",
"\"MP-JWT\"",
",",
"new",
"JWTAuthMechanismFactory",
"(",
")",
")",
";",
"deploymentInfo",
".",
"addInnerHandlerChainWrapper",
"(",
"MpJwtPrincipalHandler",
"::",
"new",
")",
";",
"}"
] | This registers the JWTAuthMechanismFactory under the "MP-JWT" mechanism name
@param deploymentInfo - the deployment to augment
@param servletContext - the ServletContext for the deployment | [
"This",
"registers",
"the",
"JWTAuthMechanismFactory",
"under",
"the",
"MP",
"-",
"JWT",
"mechanism",
"name"
] | 4a391b68ffae98c6e66d30a3bfb99dadc9509f14 | https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/fractions/microprofile/microprofile-jwt/src/main/java/org/wildfly/swarm/microprofile/jwtauth/deployment/auth/JWTAuthMethodExtension.java#L35-L39 | train |
OpenHFT/Chronicle-Map | src/main/java/net/openhft/chronicle/hash/impl/stage/iter/IterationAlloc.java | IterationAlloc.alloc | @Override
public long alloc(int chunks, long prevPos, int prevChunks) {
long ret = s.allocReturnCode(chunks);
if (prevPos >= 0)
s.free(prevPos, prevChunks);
if (ret >= 0)
return ret;
while (true) {
s.nextTier();
ret = s.allocReturnCode(chunks);
if (ret >= 0)
return ret;
}
} | java | @Override
public long alloc(int chunks, long prevPos, int prevChunks) {
long ret = s.allocReturnCode(chunks);
if (prevPos >= 0)
s.free(prevPos, prevChunks);
if (ret >= 0)
return ret;
while (true) {
s.nextTier();
ret = s.allocReturnCode(chunks);
if (ret >= 0)
return ret;
}
} | [
"@",
"Override",
"public",
"long",
"alloc",
"(",
"int",
"chunks",
",",
"long",
"prevPos",
",",
"int",
"prevChunks",
")",
"{",
"long",
"ret",
"=",
"s",
".",
"allocReturnCode",
"(",
"chunks",
")",
";",
"if",
"(",
"prevPos",
">=",
"0",
")",
"s",
".",
"free",
"(",
"prevPos",
",",
"prevChunks",
")",
";",
"if",
"(",
"ret",
">=",
"0",
")",
"return",
"ret",
";",
"while",
"(",
"true",
")",
"{",
"s",
".",
"nextTier",
"(",
")",
";",
"ret",
"=",
"s",
".",
"allocReturnCode",
"(",
"chunks",
")",
";",
"if",
"(",
"ret",
">=",
"0",
")",
"return",
"ret",
";",
"}",
"}"
] | Move only to next tiers, to avoid double visiting of relocated entries during iteration | [
"Move",
"only",
"to",
"next",
"tiers",
"to",
"avoid",
"double",
"visiting",
"of",
"relocated",
"entries",
"during",
"iteration"
] | 0b09733cc96302f96be4394a261699eeb021fe37 | https://github.com/OpenHFT/Chronicle-Map/blob/0b09733cc96302f96be4394a261699eeb021fe37/src/main/java/net/openhft/chronicle/hash/impl/stage/iter/IterationAlloc.java#L33-L46 | train |
OpenHFT/Chronicle-Map | src/main/java/net/openhft/chronicle/hash/impl/util/BuildVersion.java | BuildVersion.getVersionFromPom | private static String getVersionFromPom() {
final String absolutePath = new File(BuildVersion.class.getResource(BuildVersion.class
.getSimpleName() + ".class").getPath())
.getParentFile().getParentFile().getParentFile().getParentFile().getParentFile()
.getParentFile().getParentFile().getAbsolutePath();
final File file = new File(absolutePath + "/pom.xml");
try (InputStreamReader reader = new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)) {
final MavenXpp3Reader xpp3Reader = new MavenXpp3Reader();
Model model = xpp3Reader.read(reader);
return model.getVersion();
} catch (NoClassDefFoundError e) {
// if you want to get the version possibly in development add in to your pom
// pax-url-aether.jar
return null;
} catch (Exception e) {
return null;
}
} | java | private static String getVersionFromPom() {
final String absolutePath = new File(BuildVersion.class.getResource(BuildVersion.class
.getSimpleName() + ".class").getPath())
.getParentFile().getParentFile().getParentFile().getParentFile().getParentFile()
.getParentFile().getParentFile().getAbsolutePath();
final File file = new File(absolutePath + "/pom.xml");
try (InputStreamReader reader = new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)) {
final MavenXpp3Reader xpp3Reader = new MavenXpp3Reader();
Model model = xpp3Reader.read(reader);
return model.getVersion();
} catch (NoClassDefFoundError e) {
// if you want to get the version possibly in development add in to your pom
// pax-url-aether.jar
return null;
} catch (Exception e) {
return null;
}
} | [
"private",
"static",
"String",
"getVersionFromPom",
"(",
")",
"{",
"final",
"String",
"absolutePath",
"=",
"new",
"File",
"(",
"BuildVersion",
".",
"class",
".",
"getResource",
"(",
"BuildVersion",
".",
"class",
".",
"getSimpleName",
"(",
")",
"+",
"\".class\"",
")",
".",
"getPath",
"(",
")",
")",
".",
"getParentFile",
"(",
")",
".",
"getParentFile",
"(",
")",
".",
"getParentFile",
"(",
")",
".",
"getParentFile",
"(",
")",
".",
"getParentFile",
"(",
")",
".",
"getParentFile",
"(",
")",
".",
"getParentFile",
"(",
")",
".",
"getAbsolutePath",
"(",
")",
";",
"final",
"File",
"file",
"=",
"new",
"File",
"(",
"absolutePath",
"+",
"\"/pom.xml\"",
")",
";",
"try",
"(",
"InputStreamReader",
"reader",
"=",
"new",
"InputStreamReader",
"(",
"new",
"FileInputStream",
"(",
"file",
")",
",",
"StandardCharsets",
".",
"UTF_8",
")",
")",
"{",
"final",
"MavenXpp3Reader",
"xpp3Reader",
"=",
"new",
"MavenXpp3Reader",
"(",
")",
";",
"Model",
"model",
"=",
"xpp3Reader",
".",
"read",
"(",
"reader",
")",
";",
"return",
"model",
".",
"getVersion",
"(",
")",
";",
"}",
"catch",
"(",
"NoClassDefFoundError",
"e",
")",
"{",
"// if you want to get the version possibly in development add in to your pom",
"// pax-url-aether.jar",
"return",
"null",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"return",
"null",
";",
"}",
"}"
] | reads the pom file to get this version, only to be used for development or within the IDE.
@return gets the version from the pom.xml | [
"reads",
"the",
"pom",
"file",
"to",
"get",
"this",
"version",
"only",
"to",
"be",
"used",
"for",
"development",
"or",
"within",
"the",
"IDE",
"."
] | 0b09733cc96302f96be4394a261699eeb021fe37 | https://github.com/OpenHFT/Chronicle-Map/blob/0b09733cc96302f96be4394a261699eeb021fe37/src/main/java/net/openhft/chronicle/hash/impl/util/BuildVersion.java#L91-L113 | train |
akexorcist/Android-RoundCornerProgressBar | library/src/main/java/com/akexorcist/roundcornerprogressbar/common/BaseRoundCornerProgressBar.java | BaseRoundCornerProgressBar.setupStyleable | public void setupStyleable(Context context, AttributeSet attrs) {
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.RoundCornerProgress);
radius = (int) typedArray.getDimension(R.styleable.RoundCornerProgress_rcRadius, dp2px(DEFAULT_PROGRESS_RADIUS));
padding = (int) typedArray.getDimension(R.styleable.RoundCornerProgress_rcBackgroundPadding, dp2px(DEFAULT_BACKGROUND_PADDING));
isReverse = typedArray.getBoolean(R.styleable.RoundCornerProgress_rcReverse, false);
max = typedArray.getFloat(R.styleable.RoundCornerProgress_rcMax, DEFAULT_MAX_PROGRESS);
progress = typedArray.getFloat(R.styleable.RoundCornerProgress_rcProgress, DEFAULT_PROGRESS);
secondaryProgress = typedArray.getFloat(R.styleable.RoundCornerProgress_rcSecondaryProgress, DEFAULT_SECONDARY_PROGRESS);
int colorBackgroundDefault = context.getResources().getColor(R.color.round_corner_progress_bar_background_default);
colorBackground = typedArray.getColor(R.styleable.RoundCornerProgress_rcBackgroundColor, colorBackgroundDefault);
int colorProgressDefault = context.getResources().getColor(R.color.round_corner_progress_bar_progress_default);
colorProgress = typedArray.getColor(R.styleable.RoundCornerProgress_rcProgressColor, colorProgressDefault);
int colorSecondaryProgressDefault = context.getResources().getColor(R.color.round_corner_progress_bar_secondary_progress_default);
colorSecondaryProgress = typedArray.getColor(R.styleable.RoundCornerProgress_rcSecondaryProgressColor, colorSecondaryProgressDefault);
typedArray.recycle();
initStyleable(context, attrs);
} | java | public void setupStyleable(Context context, AttributeSet attrs) {
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.RoundCornerProgress);
radius = (int) typedArray.getDimension(R.styleable.RoundCornerProgress_rcRadius, dp2px(DEFAULT_PROGRESS_RADIUS));
padding = (int) typedArray.getDimension(R.styleable.RoundCornerProgress_rcBackgroundPadding, dp2px(DEFAULT_BACKGROUND_PADDING));
isReverse = typedArray.getBoolean(R.styleable.RoundCornerProgress_rcReverse, false);
max = typedArray.getFloat(R.styleable.RoundCornerProgress_rcMax, DEFAULT_MAX_PROGRESS);
progress = typedArray.getFloat(R.styleable.RoundCornerProgress_rcProgress, DEFAULT_PROGRESS);
secondaryProgress = typedArray.getFloat(R.styleable.RoundCornerProgress_rcSecondaryProgress, DEFAULT_SECONDARY_PROGRESS);
int colorBackgroundDefault = context.getResources().getColor(R.color.round_corner_progress_bar_background_default);
colorBackground = typedArray.getColor(R.styleable.RoundCornerProgress_rcBackgroundColor, colorBackgroundDefault);
int colorProgressDefault = context.getResources().getColor(R.color.round_corner_progress_bar_progress_default);
colorProgress = typedArray.getColor(R.styleable.RoundCornerProgress_rcProgressColor, colorProgressDefault);
int colorSecondaryProgressDefault = context.getResources().getColor(R.color.round_corner_progress_bar_secondary_progress_default);
colorSecondaryProgress = typedArray.getColor(R.styleable.RoundCornerProgress_rcSecondaryProgressColor, colorSecondaryProgressDefault);
typedArray.recycle();
initStyleable(context, attrs);
} | [
"public",
"void",
"setupStyleable",
"(",
"Context",
"context",
",",
"AttributeSet",
"attrs",
")",
"{",
"TypedArray",
"typedArray",
"=",
"context",
".",
"obtainStyledAttributes",
"(",
"attrs",
",",
"R",
".",
"styleable",
".",
"RoundCornerProgress",
")",
";",
"radius",
"=",
"(",
"int",
")",
"typedArray",
".",
"getDimension",
"(",
"R",
".",
"styleable",
".",
"RoundCornerProgress_rcRadius",
",",
"dp2px",
"(",
"DEFAULT_PROGRESS_RADIUS",
")",
")",
";",
"padding",
"=",
"(",
"int",
")",
"typedArray",
".",
"getDimension",
"(",
"R",
".",
"styleable",
".",
"RoundCornerProgress_rcBackgroundPadding",
",",
"dp2px",
"(",
"DEFAULT_BACKGROUND_PADDING",
")",
")",
";",
"isReverse",
"=",
"typedArray",
".",
"getBoolean",
"(",
"R",
".",
"styleable",
".",
"RoundCornerProgress_rcReverse",
",",
"false",
")",
";",
"max",
"=",
"typedArray",
".",
"getFloat",
"(",
"R",
".",
"styleable",
".",
"RoundCornerProgress_rcMax",
",",
"DEFAULT_MAX_PROGRESS",
")",
";",
"progress",
"=",
"typedArray",
".",
"getFloat",
"(",
"R",
".",
"styleable",
".",
"RoundCornerProgress_rcProgress",
",",
"DEFAULT_PROGRESS",
")",
";",
"secondaryProgress",
"=",
"typedArray",
".",
"getFloat",
"(",
"R",
".",
"styleable",
".",
"RoundCornerProgress_rcSecondaryProgress",
",",
"DEFAULT_SECONDARY_PROGRESS",
")",
";",
"int",
"colorBackgroundDefault",
"=",
"context",
".",
"getResources",
"(",
")",
".",
"getColor",
"(",
"R",
".",
"color",
".",
"round_corner_progress_bar_background_default",
")",
";",
"colorBackground",
"=",
"typedArray",
".",
"getColor",
"(",
"R",
".",
"styleable",
".",
"RoundCornerProgress_rcBackgroundColor",
",",
"colorBackgroundDefault",
")",
";",
"int",
"colorProgressDefault",
"=",
"context",
".",
"getResources",
"(",
")",
".",
"getColor",
"(",
"R",
".",
"color",
".",
"round_corner_progress_bar_progress_default",
")",
";",
"colorProgress",
"=",
"typedArray",
".",
"getColor",
"(",
"R",
".",
"styleable",
".",
"RoundCornerProgress_rcProgressColor",
",",
"colorProgressDefault",
")",
";",
"int",
"colorSecondaryProgressDefault",
"=",
"context",
".",
"getResources",
"(",
")",
".",
"getColor",
"(",
"R",
".",
"color",
".",
"round_corner_progress_bar_secondary_progress_default",
")",
";",
"colorSecondaryProgress",
"=",
"typedArray",
".",
"getColor",
"(",
"R",
".",
"styleable",
".",
"RoundCornerProgress_rcSecondaryProgressColor",
",",
"colorSecondaryProgressDefault",
")",
";",
"typedArray",
".",
"recycle",
"(",
")",
";",
"initStyleable",
"(",
"context",
",",
"attrs",
")",
";",
"}"
] | Retrieve initial parameter from view attribute | [
"Retrieve",
"initial",
"parameter",
"from",
"view",
"attribute"
] | b3ba8c028671d3e9949b141931f3b985ceba9bfa | https://github.com/akexorcist/Android-RoundCornerProgressBar/blob/b3ba8c028671d3e9949b141931f3b985ceba9bfa/library/src/main/java/com/akexorcist/roundcornerprogressbar/common/BaseRoundCornerProgressBar.java#L135-L156 | train |
akexorcist/Android-RoundCornerProgressBar | library/src/main/java/com/akexorcist/roundcornerprogressbar/common/BaseRoundCornerProgressBar.java | BaseRoundCornerProgressBar.onSizeChanged | @Override
protected void onSizeChanged(int newWidth, int newHeight, int oldWidth, int oldHeight) {
super.onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
if(!isInEditMode()) {
totalWidth = newWidth;
drawAll();
postDelayed(new Runnable() {
@Override
public void run() {
drawPrimaryProgress();
drawSecondaryProgress();
}
}, 5);
}
} | java | @Override
protected void onSizeChanged(int newWidth, int newHeight, int oldWidth, int oldHeight) {
super.onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
if(!isInEditMode()) {
totalWidth = newWidth;
drawAll();
postDelayed(new Runnable() {
@Override
public void run() {
drawPrimaryProgress();
drawSecondaryProgress();
}
}, 5);
}
} | [
"@",
"Override",
"protected",
"void",
"onSizeChanged",
"(",
"int",
"newWidth",
",",
"int",
"newHeight",
",",
"int",
"oldWidth",
",",
"int",
"oldHeight",
")",
"{",
"super",
".",
"onSizeChanged",
"(",
"newWidth",
",",
"newHeight",
",",
"oldWidth",
",",
"oldHeight",
")",
";",
"if",
"(",
"!",
"isInEditMode",
"(",
")",
")",
"{",
"totalWidth",
"=",
"newWidth",
";",
"drawAll",
"(",
")",
";",
"postDelayed",
"(",
"new",
"Runnable",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"run",
"(",
")",
"{",
"drawPrimaryProgress",
"(",
")",
";",
"drawSecondaryProgress",
"(",
")",
";",
"}",
"}",
",",
"5",
")",
";",
"}",
"}"
] | Progress bar always refresh when view size has changed | [
"Progress",
"bar",
"always",
"refresh",
"when",
"view",
"size",
"has",
"changed"
] | b3ba8c028671d3e9949b141931f3b985ceba9bfa | https://github.com/akexorcist/Android-RoundCornerProgressBar/blob/b3ba8c028671d3e9949b141931f3b985ceba9bfa/library/src/main/java/com/akexorcist/roundcornerprogressbar/common/BaseRoundCornerProgressBar.java#L159-L173 | train |
akexorcist/Android-RoundCornerProgressBar | library/src/main/java/com/akexorcist/roundcornerprogressbar/common/BaseRoundCornerProgressBar.java | BaseRoundCornerProgressBar.drawBackgroundProgress | @SuppressWarnings("deprecation")
private void drawBackgroundProgress() {
GradientDrawable backgroundDrawable = createGradientDrawable(colorBackground);
int newRadius = radius - (padding / 2);
backgroundDrawable.setCornerRadii(new float[]{newRadius, newRadius, newRadius, newRadius, newRadius, newRadius, newRadius, newRadius});
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
layoutBackground.setBackground(backgroundDrawable);
} else {
layoutBackground.setBackgroundDrawable(backgroundDrawable);
}
} | java | @SuppressWarnings("deprecation")
private void drawBackgroundProgress() {
GradientDrawable backgroundDrawable = createGradientDrawable(colorBackground);
int newRadius = radius - (padding / 2);
backgroundDrawable.setCornerRadii(new float[]{newRadius, newRadius, newRadius, newRadius, newRadius, newRadius, newRadius, newRadius});
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
layoutBackground.setBackground(backgroundDrawable);
} else {
layoutBackground.setBackgroundDrawable(backgroundDrawable);
}
} | [
"@",
"SuppressWarnings",
"(",
"\"deprecation\"",
")",
"private",
"void",
"drawBackgroundProgress",
"(",
")",
"{",
"GradientDrawable",
"backgroundDrawable",
"=",
"createGradientDrawable",
"(",
"colorBackground",
")",
";",
"int",
"newRadius",
"=",
"radius",
"-",
"(",
"padding",
"/",
"2",
")",
";",
"backgroundDrawable",
".",
"setCornerRadii",
"(",
"new",
"float",
"[",
"]",
"{",
"newRadius",
",",
"newRadius",
",",
"newRadius",
",",
"newRadius",
",",
"newRadius",
",",
"newRadius",
",",
"newRadius",
",",
"newRadius",
"}",
")",
";",
"if",
"(",
"Build",
".",
"VERSION",
".",
"SDK_INT",
">=",
"Build",
".",
"VERSION_CODES",
".",
"JELLY_BEAN",
")",
"{",
"layoutBackground",
".",
"setBackground",
"(",
"backgroundDrawable",
")",
";",
"}",
"else",
"{",
"layoutBackground",
".",
"setBackgroundDrawable",
"(",
"backgroundDrawable",
")",
";",
"}",
"}"
] | Draw progress background | [
"Draw",
"progress",
"background"
] | b3ba8c028671d3e9949b141931f3b985ceba9bfa | https://github.com/akexorcist/Android-RoundCornerProgressBar/blob/b3ba8c028671d3e9949b141931f3b985ceba9bfa/library/src/main/java/com/akexorcist/roundcornerprogressbar/common/BaseRoundCornerProgressBar.java#L186-L196 | train |
akexorcist/Android-RoundCornerProgressBar | library/src/main/java/com/akexorcist/roundcornerprogressbar/common/BaseRoundCornerProgressBar.java | BaseRoundCornerProgressBar.createGradientDrawable | protected GradientDrawable createGradientDrawable(int color) {
GradientDrawable gradientDrawable = new GradientDrawable();
gradientDrawable.setShape(GradientDrawable.RECTANGLE);
gradientDrawable.setColor(color);
return gradientDrawable;
} | java | protected GradientDrawable createGradientDrawable(int color) {
GradientDrawable gradientDrawable = new GradientDrawable();
gradientDrawable.setShape(GradientDrawable.RECTANGLE);
gradientDrawable.setColor(color);
return gradientDrawable;
} | [
"protected",
"GradientDrawable",
"createGradientDrawable",
"(",
"int",
"color",
")",
"{",
"GradientDrawable",
"gradientDrawable",
"=",
"new",
"GradientDrawable",
"(",
")",
";",
"gradientDrawable",
".",
"setShape",
"(",
"GradientDrawable",
".",
"RECTANGLE",
")",
";",
"gradientDrawable",
".",
"setColor",
"(",
"color",
")",
";",
"return",
"gradientDrawable",
";",
"}"
] | Create an empty color rectangle gradient drawable | [
"Create",
"an",
"empty",
"color",
"rectangle",
"gradient",
"drawable"
] | b3ba8c028671d3e9949b141931f3b985ceba9bfa | https://github.com/akexorcist/Android-RoundCornerProgressBar/blob/b3ba8c028671d3e9949b141931f3b985ceba9bfa/library/src/main/java/com/akexorcist/roundcornerprogressbar/common/BaseRoundCornerProgressBar.java#L199-L204 | train |
akexorcist/Android-RoundCornerProgressBar | library/src/main/java/com/akexorcist/roundcornerprogressbar/common/BaseRoundCornerProgressBar.java | BaseRoundCornerProgressBar.setupReverse | private void setupReverse(LinearLayout layoutProgress) {
RelativeLayout.LayoutParams progressParams = (RelativeLayout.LayoutParams) layoutProgress.getLayoutParams();
removeLayoutParamsRule(progressParams);
if (isReverse) {
progressParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
// For support with RTL on API 17 or more
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1)
progressParams.addRule(RelativeLayout.ALIGN_PARENT_END);
} else {
progressParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
// For support with RTL on API 17 or more
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1)
progressParams.addRule(RelativeLayout.ALIGN_PARENT_START);
}
layoutProgress.setLayoutParams(progressParams);
} | java | private void setupReverse(LinearLayout layoutProgress) {
RelativeLayout.LayoutParams progressParams = (RelativeLayout.LayoutParams) layoutProgress.getLayoutParams();
removeLayoutParamsRule(progressParams);
if (isReverse) {
progressParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
// For support with RTL on API 17 or more
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1)
progressParams.addRule(RelativeLayout.ALIGN_PARENT_END);
} else {
progressParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
// For support with RTL on API 17 or more
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1)
progressParams.addRule(RelativeLayout.ALIGN_PARENT_START);
}
layoutProgress.setLayoutParams(progressParams);
} | [
"private",
"void",
"setupReverse",
"(",
"LinearLayout",
"layoutProgress",
")",
"{",
"RelativeLayout",
".",
"LayoutParams",
"progressParams",
"=",
"(",
"RelativeLayout",
".",
"LayoutParams",
")",
"layoutProgress",
".",
"getLayoutParams",
"(",
")",
";",
"removeLayoutParamsRule",
"(",
"progressParams",
")",
";",
"if",
"(",
"isReverse",
")",
"{",
"progressParams",
".",
"addRule",
"(",
"RelativeLayout",
".",
"ALIGN_PARENT_RIGHT",
")",
";",
"// For support with RTL on API 17 or more",
"if",
"(",
"Build",
".",
"VERSION",
".",
"SDK_INT",
">=",
"Build",
".",
"VERSION_CODES",
".",
"JELLY_BEAN_MR1",
")",
"progressParams",
".",
"addRule",
"(",
"RelativeLayout",
".",
"ALIGN_PARENT_END",
")",
";",
"}",
"else",
"{",
"progressParams",
".",
"addRule",
"(",
"RelativeLayout",
".",
"ALIGN_PARENT_LEFT",
")",
";",
"// For support with RTL on API 17 or more",
"if",
"(",
"Build",
".",
"VERSION",
".",
"SDK_INT",
">=",
"Build",
".",
"VERSION_CODES",
".",
"JELLY_BEAN_MR1",
")",
"progressParams",
".",
"addRule",
"(",
"RelativeLayout",
".",
"ALIGN_PARENT_START",
")",
";",
"}",
"layoutProgress",
".",
"setLayoutParams",
"(",
"progressParams",
")",
";",
"}"
] | Change progress position by depending on isReverse flag | [
"Change",
"progress",
"position",
"by",
"depending",
"on",
"isReverse",
"flag"
] | b3ba8c028671d3e9949b141931f3b985ceba9bfa | https://github.com/akexorcist/Android-RoundCornerProgressBar/blob/b3ba8c028671d3e9949b141931f3b985ceba9bfa/library/src/main/java/com/akexorcist/roundcornerprogressbar/common/BaseRoundCornerProgressBar.java#L220-L235 | train |
akexorcist/Android-RoundCornerProgressBar | library/src/main/java/com/akexorcist/roundcornerprogressbar/common/BaseRoundCornerProgressBar.java | BaseRoundCornerProgressBar.removeLayoutParamsRule | private void removeLayoutParamsRule(RelativeLayout.LayoutParams layoutParams) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
layoutParams.removeRule(RelativeLayout.ALIGN_PARENT_RIGHT);
layoutParams.removeRule(RelativeLayout.ALIGN_PARENT_END);
layoutParams.removeRule(RelativeLayout.ALIGN_PARENT_LEFT);
layoutParams.removeRule(RelativeLayout.ALIGN_PARENT_START);
} else {
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, 0);
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT, 0);
}
} | java | private void removeLayoutParamsRule(RelativeLayout.LayoutParams layoutParams) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
layoutParams.removeRule(RelativeLayout.ALIGN_PARENT_RIGHT);
layoutParams.removeRule(RelativeLayout.ALIGN_PARENT_END);
layoutParams.removeRule(RelativeLayout.ALIGN_PARENT_LEFT);
layoutParams.removeRule(RelativeLayout.ALIGN_PARENT_START);
} else {
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, 0);
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT, 0);
}
} | [
"private",
"void",
"removeLayoutParamsRule",
"(",
"RelativeLayout",
".",
"LayoutParams",
"layoutParams",
")",
"{",
"if",
"(",
"Build",
".",
"VERSION",
".",
"SDK_INT",
">=",
"Build",
".",
"VERSION_CODES",
".",
"JELLY_BEAN_MR1",
")",
"{",
"layoutParams",
".",
"removeRule",
"(",
"RelativeLayout",
".",
"ALIGN_PARENT_RIGHT",
")",
";",
"layoutParams",
".",
"removeRule",
"(",
"RelativeLayout",
".",
"ALIGN_PARENT_END",
")",
";",
"layoutParams",
".",
"removeRule",
"(",
"RelativeLayout",
".",
"ALIGN_PARENT_LEFT",
")",
";",
"layoutParams",
".",
"removeRule",
"(",
"RelativeLayout",
".",
"ALIGN_PARENT_START",
")",
";",
"}",
"else",
"{",
"layoutParams",
".",
"addRule",
"(",
"RelativeLayout",
".",
"ALIGN_PARENT_RIGHT",
",",
"0",
")",
";",
"layoutParams",
".",
"addRule",
"(",
"RelativeLayout",
".",
"ALIGN_PARENT_LEFT",
",",
"0",
")",
";",
"}",
"}"
] | Remove all of relative align rule | [
"Remove",
"all",
"of",
"relative",
"align",
"rule"
] | b3ba8c028671d3e9949b141931f3b985ceba9bfa | https://github.com/akexorcist/Android-RoundCornerProgressBar/blob/b3ba8c028671d3e9949b141931f3b985ceba9bfa/library/src/main/java/com/akexorcist/roundcornerprogressbar/common/BaseRoundCornerProgressBar.java#L242-L252 | train |
EsotericSoftware/kryonet | src/com/esotericsoftware/kryonet/Connection.java | Connection.sendTCP | public int sendTCP (Object object) {
if (object == null) throw new IllegalArgumentException("object cannot be null.");
try {
int length = tcp.send(this, object);
if (length == 0) {
if (TRACE) trace("kryonet", this + " TCP had nothing to send.");
} else if (DEBUG) {
String objectString = object == null ? "null" : object.getClass().getSimpleName();
if (!(object instanceof FrameworkMessage)) {
debug("kryonet", this + " sent TCP: " + objectString + " (" + length + ")");
} else if (TRACE) {
trace("kryonet", this + " sent TCP: " + objectString + " (" + length + ")");
}
}
return length;
} catch (IOException ex) {
if (DEBUG) debug("kryonet", "Unable to send TCP with connection: " + this, ex);
close();
return 0;
} catch (KryoNetException ex) {
if (ERROR) error("kryonet", "Unable to send TCP with connection: " + this, ex);
close();
return 0;
}
} | java | public int sendTCP (Object object) {
if (object == null) throw new IllegalArgumentException("object cannot be null.");
try {
int length = tcp.send(this, object);
if (length == 0) {
if (TRACE) trace("kryonet", this + " TCP had nothing to send.");
} else if (DEBUG) {
String objectString = object == null ? "null" : object.getClass().getSimpleName();
if (!(object instanceof FrameworkMessage)) {
debug("kryonet", this + " sent TCP: " + objectString + " (" + length + ")");
} else if (TRACE) {
trace("kryonet", this + " sent TCP: " + objectString + " (" + length + ")");
}
}
return length;
} catch (IOException ex) {
if (DEBUG) debug("kryonet", "Unable to send TCP with connection: " + this, ex);
close();
return 0;
} catch (KryoNetException ex) {
if (ERROR) error("kryonet", "Unable to send TCP with connection: " + this, ex);
close();
return 0;
}
} | [
"public",
"int",
"sendTCP",
"(",
"Object",
"object",
")",
"{",
"if",
"(",
"object",
"==",
"null",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"object cannot be null.\"",
")",
";",
"try",
"{",
"int",
"length",
"=",
"tcp",
".",
"send",
"(",
"this",
",",
"object",
")",
";",
"if",
"(",
"length",
"==",
"0",
")",
"{",
"if",
"(",
"TRACE",
")",
"trace",
"(",
"\"kryonet\"",
",",
"this",
"+",
"\" TCP had nothing to send.\"",
")",
";",
"}",
"else",
"if",
"(",
"DEBUG",
")",
"{",
"String",
"objectString",
"=",
"object",
"==",
"null",
"?",
"\"null\"",
":",
"object",
".",
"getClass",
"(",
")",
".",
"getSimpleName",
"(",
")",
";",
"if",
"(",
"!",
"(",
"object",
"instanceof",
"FrameworkMessage",
")",
")",
"{",
"debug",
"(",
"\"kryonet\"",
",",
"this",
"+",
"\" sent TCP: \"",
"+",
"objectString",
"+",
"\" (\"",
"+",
"length",
"+",
"\")\"",
")",
";",
"}",
"else",
"if",
"(",
"TRACE",
")",
"{",
"trace",
"(",
"\"kryonet\"",
",",
"this",
"+",
"\" sent TCP: \"",
"+",
"objectString",
"+",
"\" (\"",
"+",
"length",
"+",
"\")\"",
")",
";",
"}",
"}",
"return",
"length",
";",
"}",
"catch",
"(",
"IOException",
"ex",
")",
"{",
"if",
"(",
"DEBUG",
")",
"debug",
"(",
"\"kryonet\"",
",",
"\"Unable to send TCP with connection: \"",
"+",
"this",
",",
"ex",
")",
";",
"close",
"(",
")",
";",
"return",
"0",
";",
"}",
"catch",
"(",
"KryoNetException",
"ex",
")",
"{",
"if",
"(",
"ERROR",
")",
"error",
"(",
"\"kryonet\"",
",",
"\"Unable to send TCP with connection: \"",
"+",
"this",
",",
"ex",
")",
";",
"close",
"(",
")",
";",
"return",
"0",
";",
"}",
"}"
] | Sends the object over the network using TCP.
@return The number of bytes sent.
@see Kryo#register(Class, com.esotericsoftware.kryo.Serializer) | [
"Sends",
"the",
"object",
"over",
"the",
"network",
"using",
"TCP",
"."
] | 2ed19b4743667664d15e3778447e579855ba3a65 | https://github.com/EsotericSoftware/kryonet/blob/2ed19b4743667664d15e3778447e579855ba3a65/src/com/esotericsoftware/kryonet/Connection.java#L84-L108 | train |
EsotericSoftware/kryonet | src/com/esotericsoftware/kryonet/Connection.java | Connection.sendUDP | public int sendUDP (Object object) {
if (object == null) throw new IllegalArgumentException("object cannot be null.");
SocketAddress address = udpRemoteAddress;
if (address == null && udp != null) address = udp.connectedAddress;
if (address == null && isConnected) throw new IllegalStateException("Connection is not connected via UDP.");
try {
if (address == null) throw new SocketException("Connection is closed.");
int length = udp.send(this, object, address);
if (length == 0) {
if (TRACE) trace("kryonet", this + " UDP had nothing to send.");
} else if (DEBUG) {
if (length != -1) {
String objectString = object == null ? "null" : object.getClass().getSimpleName();
if (!(object instanceof FrameworkMessage)) {
debug("kryonet", this + " sent UDP: " + objectString + " (" + length + ")");
} else if (TRACE) {
trace("kryonet", this + " sent UDP: " + objectString + " (" + length + ")");
}
} else
debug("kryonet", this + " was unable to send, UDP socket buffer full.");
}
return length;
} catch (IOException ex) {
if (DEBUG) debug("kryonet", "Unable to send UDP with connection: " + this, ex);
close();
return 0;
} catch (KryoNetException ex) {
if (ERROR) error("kryonet", "Unable to send UDP with connection: " + this, ex);
close();
return 0;
}
} | java | public int sendUDP (Object object) {
if (object == null) throw new IllegalArgumentException("object cannot be null.");
SocketAddress address = udpRemoteAddress;
if (address == null && udp != null) address = udp.connectedAddress;
if (address == null && isConnected) throw new IllegalStateException("Connection is not connected via UDP.");
try {
if (address == null) throw new SocketException("Connection is closed.");
int length = udp.send(this, object, address);
if (length == 0) {
if (TRACE) trace("kryonet", this + " UDP had nothing to send.");
} else if (DEBUG) {
if (length != -1) {
String objectString = object == null ? "null" : object.getClass().getSimpleName();
if (!(object instanceof FrameworkMessage)) {
debug("kryonet", this + " sent UDP: " + objectString + " (" + length + ")");
} else if (TRACE) {
trace("kryonet", this + " sent UDP: " + objectString + " (" + length + ")");
}
} else
debug("kryonet", this + " was unable to send, UDP socket buffer full.");
}
return length;
} catch (IOException ex) {
if (DEBUG) debug("kryonet", "Unable to send UDP with connection: " + this, ex);
close();
return 0;
} catch (KryoNetException ex) {
if (ERROR) error("kryonet", "Unable to send UDP with connection: " + this, ex);
close();
return 0;
}
} | [
"public",
"int",
"sendUDP",
"(",
"Object",
"object",
")",
"{",
"if",
"(",
"object",
"==",
"null",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"object cannot be null.\"",
")",
";",
"SocketAddress",
"address",
"=",
"udpRemoteAddress",
";",
"if",
"(",
"address",
"==",
"null",
"&&",
"udp",
"!=",
"null",
")",
"address",
"=",
"udp",
".",
"connectedAddress",
";",
"if",
"(",
"address",
"==",
"null",
"&&",
"isConnected",
")",
"throw",
"new",
"IllegalStateException",
"(",
"\"Connection is not connected via UDP.\"",
")",
";",
"try",
"{",
"if",
"(",
"address",
"==",
"null",
")",
"throw",
"new",
"SocketException",
"(",
"\"Connection is closed.\"",
")",
";",
"int",
"length",
"=",
"udp",
".",
"send",
"(",
"this",
",",
"object",
",",
"address",
")",
";",
"if",
"(",
"length",
"==",
"0",
")",
"{",
"if",
"(",
"TRACE",
")",
"trace",
"(",
"\"kryonet\"",
",",
"this",
"+",
"\" UDP had nothing to send.\"",
")",
";",
"}",
"else",
"if",
"(",
"DEBUG",
")",
"{",
"if",
"(",
"length",
"!=",
"-",
"1",
")",
"{",
"String",
"objectString",
"=",
"object",
"==",
"null",
"?",
"\"null\"",
":",
"object",
".",
"getClass",
"(",
")",
".",
"getSimpleName",
"(",
")",
";",
"if",
"(",
"!",
"(",
"object",
"instanceof",
"FrameworkMessage",
")",
")",
"{",
"debug",
"(",
"\"kryonet\"",
",",
"this",
"+",
"\" sent UDP: \"",
"+",
"objectString",
"+",
"\" (\"",
"+",
"length",
"+",
"\")\"",
")",
";",
"}",
"else",
"if",
"(",
"TRACE",
")",
"{",
"trace",
"(",
"\"kryonet\"",
",",
"this",
"+",
"\" sent UDP: \"",
"+",
"objectString",
"+",
"\" (\"",
"+",
"length",
"+",
"\")\"",
")",
";",
"}",
"}",
"else",
"debug",
"(",
"\"kryonet\"",
",",
"this",
"+",
"\" was unable to send, UDP socket buffer full.\"",
")",
";",
"}",
"return",
"length",
";",
"}",
"catch",
"(",
"IOException",
"ex",
")",
"{",
"if",
"(",
"DEBUG",
")",
"debug",
"(",
"\"kryonet\"",
",",
"\"Unable to send UDP with connection: \"",
"+",
"this",
",",
"ex",
")",
";",
"close",
"(",
")",
";",
"return",
"0",
";",
"}",
"catch",
"(",
"KryoNetException",
"ex",
")",
"{",
"if",
"(",
"ERROR",
")",
"error",
"(",
"\"kryonet\"",
",",
"\"Unable to send UDP with connection: \"",
"+",
"this",
",",
"ex",
")",
";",
"close",
"(",
")",
";",
"return",
"0",
";",
"}",
"}"
] | Sends the object over the network using UDP.
@return The number of bytes sent.
@see Kryo#register(Class, com.esotericsoftware.kryo.Serializer)
@throws IllegalStateException if this connection was not opened with both TCP and UDP. | [
"Sends",
"the",
"object",
"over",
"the",
"network",
"using",
"UDP",
"."
] | 2ed19b4743667664d15e3778447e579855ba3a65 | https://github.com/EsotericSoftware/kryonet/blob/2ed19b4743667664d15e3778447e579855ba3a65/src/com/esotericsoftware/kryonet/Connection.java#L114-L147 | train |
EsotericSoftware/kryonet | src/com/esotericsoftware/kryonet/Connection.java | Connection.getRemoteAddressTCP | public InetSocketAddress getRemoteAddressTCP () {
SocketChannel socketChannel = tcp.socketChannel;
if (socketChannel != null) {
Socket socket = tcp.socketChannel.socket();
if (socket != null) {
return (InetSocketAddress)socket.getRemoteSocketAddress();
}
}
return null;
} | java | public InetSocketAddress getRemoteAddressTCP () {
SocketChannel socketChannel = tcp.socketChannel;
if (socketChannel != null) {
Socket socket = tcp.socketChannel.socket();
if (socket != null) {
return (InetSocketAddress)socket.getRemoteSocketAddress();
}
}
return null;
} | [
"public",
"InetSocketAddress",
"getRemoteAddressTCP",
"(",
")",
"{",
"SocketChannel",
"socketChannel",
"=",
"tcp",
".",
"socketChannel",
";",
"if",
"(",
"socketChannel",
"!=",
"null",
")",
"{",
"Socket",
"socket",
"=",
"tcp",
".",
"socketChannel",
".",
"socket",
"(",
")",
";",
"if",
"(",
"socket",
"!=",
"null",
")",
"{",
"return",
"(",
"InetSocketAddress",
")",
"socket",
".",
"getRemoteSocketAddress",
"(",
")",
";",
"}",
"}",
"return",
"null",
";",
"}"
] | Returns the IP address and port of the remote end of the TCP connection, or null if this connection is not connected. | [
"Returns",
"the",
"IP",
"address",
"and",
"port",
"of",
"the",
"remote",
"end",
"of",
"the",
"TCP",
"connection",
"or",
"null",
"if",
"this",
"connection",
"is",
"not",
"connected",
"."
] | 2ed19b4743667664d15e3778447e579855ba3a65 | https://github.com/EsotericSoftware/kryonet/blob/2ed19b4743667664d15e3778447e579855ba3a65/src/com/esotericsoftware/kryonet/Connection.java#L283-L292 | train |
EsotericSoftware/kryonet | src/com/esotericsoftware/kryonet/Connection.java | Connection.getRemoteAddressUDP | public InetSocketAddress getRemoteAddressUDP () {
InetSocketAddress connectedAddress = udp.connectedAddress;
if (connectedAddress != null) return connectedAddress;
return udpRemoteAddress;
} | java | public InetSocketAddress getRemoteAddressUDP () {
InetSocketAddress connectedAddress = udp.connectedAddress;
if (connectedAddress != null) return connectedAddress;
return udpRemoteAddress;
} | [
"public",
"InetSocketAddress",
"getRemoteAddressUDP",
"(",
")",
"{",
"InetSocketAddress",
"connectedAddress",
"=",
"udp",
".",
"connectedAddress",
";",
"if",
"(",
"connectedAddress",
"!=",
"null",
")",
"return",
"connectedAddress",
";",
"return",
"udpRemoteAddress",
";",
"}"
] | Returns the IP address and port of the remote end of the UDP connection, or null if this connection is not connected. | [
"Returns",
"the",
"IP",
"address",
"and",
"port",
"of",
"the",
"remote",
"end",
"of",
"the",
"UDP",
"connection",
"or",
"null",
"if",
"this",
"connection",
"is",
"not",
"connected",
"."
] | 2ed19b4743667664d15e3778447e579855ba3a65 | https://github.com/EsotericSoftware/kryonet/blob/2ed19b4743667664d15e3778447e579855ba3a65/src/com/esotericsoftware/kryonet/Connection.java#L295-L299 | train |
EsotericSoftware/kryonet | src/com/esotericsoftware/kryonet/rmi/ObjectSpace.java | ObjectSpace.close | public void close () {
Connection[] connections = this.connections;
for (int i = 0; i < connections.length; i++)
connections[i].removeListener(invokeListener);
synchronized (instancesLock) {
ArrayList<ObjectSpace> temp = new ArrayList(Arrays.asList(instances));
temp.remove(this);
instances = temp.toArray(new ObjectSpace[temp.size()]);
}
if (TRACE) trace("kryonet", "Closed ObjectSpace.");
} | java | public void close () {
Connection[] connections = this.connections;
for (int i = 0; i < connections.length; i++)
connections[i].removeListener(invokeListener);
synchronized (instancesLock) {
ArrayList<ObjectSpace> temp = new ArrayList(Arrays.asList(instances));
temp.remove(this);
instances = temp.toArray(new ObjectSpace[temp.size()]);
}
if (TRACE) trace("kryonet", "Closed ObjectSpace.");
} | [
"public",
"void",
"close",
"(",
")",
"{",
"Connection",
"[",
"]",
"connections",
"=",
"this",
".",
"connections",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"connections",
".",
"length",
";",
"i",
"++",
")",
"connections",
"[",
"i",
"]",
".",
"removeListener",
"(",
"invokeListener",
")",
";",
"synchronized",
"(",
"instancesLock",
")",
"{",
"ArrayList",
"<",
"ObjectSpace",
">",
"temp",
"=",
"new",
"ArrayList",
"(",
"Arrays",
".",
"asList",
"(",
"instances",
")",
")",
";",
"temp",
".",
"remove",
"(",
"this",
")",
";",
"instances",
"=",
"temp",
".",
"toArray",
"(",
"new",
"ObjectSpace",
"[",
"temp",
".",
"size",
"(",
")",
"]",
")",
";",
"}",
"if",
"(",
"TRACE",
")",
"trace",
"(",
"\"kryonet\"",
",",
"\"Closed ObjectSpace.\"",
")",
";",
"}"
] | Causes this ObjectSpace to stop listening to the connections for method invocation messages. | [
"Causes",
"this",
"ObjectSpace",
"to",
"stop",
"listening",
"to",
"the",
"connections",
"for",
"method",
"invocation",
"messages",
"."
] | 2ed19b4743667664d15e3778447e579855ba3a65 | https://github.com/EsotericSoftware/kryonet/blob/2ed19b4743667664d15e3778447e579855ba3a65/src/com/esotericsoftware/kryonet/rmi/ObjectSpace.java#L170-L182 | train |
EsotericSoftware/kryonet | src/com/esotericsoftware/kryonet/rmi/ObjectSpace.java | ObjectSpace.addConnection | public void addConnection (Connection connection) {
if (connection == null) throw new IllegalArgumentException("connection cannot be null.");
synchronized (connectionsLock) {
Connection[] newConnections = new Connection[connections.length + 1];
newConnections[0] = connection;
System.arraycopy(connections, 0, newConnections, 1, connections.length);
connections = newConnections;
}
connection.addListener(invokeListener);
if (TRACE) trace("kryonet", "Added connection to ObjectSpace: " + connection);
} | java | public void addConnection (Connection connection) {
if (connection == null) throw new IllegalArgumentException("connection cannot be null.");
synchronized (connectionsLock) {
Connection[] newConnections = new Connection[connections.length + 1];
newConnections[0] = connection;
System.arraycopy(connections, 0, newConnections, 1, connections.length);
connections = newConnections;
}
connection.addListener(invokeListener);
if (TRACE) trace("kryonet", "Added connection to ObjectSpace: " + connection);
} | [
"public",
"void",
"addConnection",
"(",
"Connection",
"connection",
")",
"{",
"if",
"(",
"connection",
"==",
"null",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"connection cannot be null.\"",
")",
";",
"synchronized",
"(",
"connectionsLock",
")",
"{",
"Connection",
"[",
"]",
"newConnections",
"=",
"new",
"Connection",
"[",
"connections",
".",
"length",
"+",
"1",
"]",
";",
"newConnections",
"[",
"0",
"]",
"=",
"connection",
";",
"System",
".",
"arraycopy",
"(",
"connections",
",",
"0",
",",
"newConnections",
",",
"1",
",",
"connections",
".",
"length",
")",
";",
"connections",
"=",
"newConnections",
";",
"}",
"connection",
".",
"addListener",
"(",
"invokeListener",
")",
";",
"if",
"(",
"TRACE",
")",
"trace",
"(",
"\"kryonet\"",
",",
"\"Added connection to ObjectSpace: \"",
"+",
"connection",
")",
";",
"}"
] | Allows the remote end of the specified connection to access objects registered in this ObjectSpace. | [
"Allows",
"the",
"remote",
"end",
"of",
"the",
"specified",
"connection",
"to",
"access",
"objects",
"registered",
"in",
"this",
"ObjectSpace",
"."
] | 2ed19b4743667664d15e3778447e579855ba3a65 | https://github.com/EsotericSoftware/kryonet/blob/2ed19b4743667664d15e3778447e579855ba3a65/src/com/esotericsoftware/kryonet/rmi/ObjectSpace.java#L185-L198 | train |
EsotericSoftware/kryonet | src/com/esotericsoftware/kryonet/rmi/ObjectSpace.java | ObjectSpace.removeConnection | public void removeConnection (Connection connection) {
if (connection == null) throw new IllegalArgumentException("connection cannot be null.");
connection.removeListener(invokeListener);
synchronized (connectionsLock) {
ArrayList<Connection> temp = new ArrayList(Arrays.asList(connections));
temp.remove(connection);
connections = temp.toArray(new Connection[temp.size()]);
}
if (TRACE) trace("kryonet", "Removed connection from ObjectSpace: " + connection);
} | java | public void removeConnection (Connection connection) {
if (connection == null) throw new IllegalArgumentException("connection cannot be null.");
connection.removeListener(invokeListener);
synchronized (connectionsLock) {
ArrayList<Connection> temp = new ArrayList(Arrays.asList(connections));
temp.remove(connection);
connections = temp.toArray(new Connection[temp.size()]);
}
if (TRACE) trace("kryonet", "Removed connection from ObjectSpace: " + connection);
} | [
"public",
"void",
"removeConnection",
"(",
"Connection",
"connection",
")",
"{",
"if",
"(",
"connection",
"==",
"null",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"connection cannot be null.\"",
")",
";",
"connection",
".",
"removeListener",
"(",
"invokeListener",
")",
";",
"synchronized",
"(",
"connectionsLock",
")",
"{",
"ArrayList",
"<",
"Connection",
">",
"temp",
"=",
"new",
"ArrayList",
"(",
"Arrays",
".",
"asList",
"(",
"connections",
")",
")",
";",
"temp",
".",
"remove",
"(",
"connection",
")",
";",
"connections",
"=",
"temp",
".",
"toArray",
"(",
"new",
"Connection",
"[",
"temp",
".",
"size",
"(",
")",
"]",
")",
";",
"}",
"if",
"(",
"TRACE",
")",
"trace",
"(",
"\"kryonet\"",
",",
"\"Removed connection from ObjectSpace: \"",
"+",
"connection",
")",
";",
"}"
] | Removes the specified connection, it will no longer be able to access objects registered in this ObjectSpace. | [
"Removes",
"the",
"specified",
"connection",
"it",
"will",
"no",
"longer",
"be",
"able",
"to",
"access",
"objects",
"registered",
"in",
"this",
"ObjectSpace",
"."
] | 2ed19b4743667664d15e3778447e579855ba3a65 | https://github.com/EsotericSoftware/kryonet/blob/2ed19b4743667664d15e3778447e579855ba3a65/src/com/esotericsoftware/kryonet/rmi/ObjectSpace.java#L201-L213 | train |
EsotericSoftware/kryonet | src/com/esotericsoftware/kryonet/rmi/ObjectSpace.java | ObjectSpace.getRegisteredObject | static Object getRegisteredObject (Connection connection, int objectID) {
ObjectSpace[] instances = ObjectSpace.instances;
for (int i = 0, n = instances.length; i < n; i++) {
ObjectSpace objectSpace = instances[i];
// Check if the connection is in this ObjectSpace.
Connection[] connections = objectSpace.connections;
for (int j = 0; j < connections.length; j++) {
if (connections[j] != connection) continue;
// Find an object with the objectID.
Object object = objectSpace.idToObject.get(objectID);
if (object != null) return object;
}
}
return null;
} | java | static Object getRegisteredObject (Connection connection, int objectID) {
ObjectSpace[] instances = ObjectSpace.instances;
for (int i = 0, n = instances.length; i < n; i++) {
ObjectSpace objectSpace = instances[i];
// Check if the connection is in this ObjectSpace.
Connection[] connections = objectSpace.connections;
for (int j = 0; j < connections.length; j++) {
if (connections[j] != connection) continue;
// Find an object with the objectID.
Object object = objectSpace.idToObject.get(objectID);
if (object != null) return object;
}
}
return null;
} | [
"static",
"Object",
"getRegisteredObject",
"(",
"Connection",
"connection",
",",
"int",
"objectID",
")",
"{",
"ObjectSpace",
"[",
"]",
"instances",
"=",
"ObjectSpace",
".",
"instances",
";",
"for",
"(",
"int",
"i",
"=",
"0",
",",
"n",
"=",
"instances",
".",
"length",
";",
"i",
"<",
"n",
";",
"i",
"++",
")",
"{",
"ObjectSpace",
"objectSpace",
"=",
"instances",
"[",
"i",
"]",
";",
"// Check if the connection is in this ObjectSpace.",
"Connection",
"[",
"]",
"connections",
"=",
"objectSpace",
".",
"connections",
";",
"for",
"(",
"int",
"j",
"=",
"0",
";",
"j",
"<",
"connections",
".",
"length",
";",
"j",
"++",
")",
"{",
"if",
"(",
"connections",
"[",
"j",
"]",
"!=",
"connection",
")",
"continue",
";",
"// Find an object with the objectID.",
"Object",
"object",
"=",
"objectSpace",
".",
"idToObject",
".",
"get",
"(",
"objectID",
")",
";",
"if",
"(",
"object",
"!=",
"null",
")",
"return",
"object",
";",
"}",
"}",
"return",
"null",
";",
"}"
] | Returns the first object registered with the specified ID in any of the ObjectSpaces the specified connection belongs
to. | [
"Returns",
"the",
"first",
"object",
"registered",
"with",
"the",
"specified",
"ID",
"in",
"any",
"of",
"the",
"ObjectSpaces",
"the",
"specified",
"connection",
"belongs",
"to",
"."
] | 2ed19b4743667664d15e3778447e579855ba3a65 | https://github.com/EsotericSoftware/kryonet/blob/2ed19b4743667664d15e3778447e579855ba3a65/src/com/esotericsoftware/kryonet/rmi/ObjectSpace.java#L651-L665 | train |
EsotericSoftware/kryonet | src/com/esotericsoftware/kryonet/rmi/ObjectSpace.java | ObjectSpace.getRegisteredID | static int getRegisteredID (Connection connection, Object object) {
ObjectSpace[] instances = ObjectSpace.instances;
for (int i = 0, n = instances.length; i < n; i++) {
ObjectSpace objectSpace = instances[i];
// Check if the connection is in this ObjectSpace.
Connection[] connections = objectSpace.connections;
for (int j = 0; j < connections.length; j++) {
if (connections[j] != connection) continue;
// Find an ID with the object.
int id = objectSpace.objectToID.get(object, Integer.MAX_VALUE);
if (id != Integer.MAX_VALUE) return id;
}
}
return Integer.MAX_VALUE;
} | java | static int getRegisteredID (Connection connection, Object object) {
ObjectSpace[] instances = ObjectSpace.instances;
for (int i = 0, n = instances.length; i < n; i++) {
ObjectSpace objectSpace = instances[i];
// Check if the connection is in this ObjectSpace.
Connection[] connections = objectSpace.connections;
for (int j = 0; j < connections.length; j++) {
if (connections[j] != connection) continue;
// Find an ID with the object.
int id = objectSpace.objectToID.get(object, Integer.MAX_VALUE);
if (id != Integer.MAX_VALUE) return id;
}
}
return Integer.MAX_VALUE;
} | [
"static",
"int",
"getRegisteredID",
"(",
"Connection",
"connection",
",",
"Object",
"object",
")",
"{",
"ObjectSpace",
"[",
"]",
"instances",
"=",
"ObjectSpace",
".",
"instances",
";",
"for",
"(",
"int",
"i",
"=",
"0",
",",
"n",
"=",
"instances",
".",
"length",
";",
"i",
"<",
"n",
";",
"i",
"++",
")",
"{",
"ObjectSpace",
"objectSpace",
"=",
"instances",
"[",
"i",
"]",
";",
"// Check if the connection is in this ObjectSpace.",
"Connection",
"[",
"]",
"connections",
"=",
"objectSpace",
".",
"connections",
";",
"for",
"(",
"int",
"j",
"=",
"0",
";",
"j",
"<",
"connections",
".",
"length",
";",
"j",
"++",
")",
"{",
"if",
"(",
"connections",
"[",
"j",
"]",
"!=",
"connection",
")",
"continue",
";",
"// Find an ID with the object.",
"int",
"id",
"=",
"objectSpace",
".",
"objectToID",
".",
"get",
"(",
"object",
",",
"Integer",
".",
"MAX_VALUE",
")",
";",
"if",
"(",
"id",
"!=",
"Integer",
".",
"MAX_VALUE",
")",
"return",
"id",
";",
"}",
"}",
"return",
"Integer",
".",
"MAX_VALUE",
";",
"}"
] | Returns the first ID registered for the specified object with any of the ObjectSpaces the specified connection belongs to,
or Integer.MAX_VALUE if not found. | [
"Returns",
"the",
"first",
"ID",
"registered",
"for",
"the",
"specified",
"object",
"with",
"any",
"of",
"the",
"ObjectSpaces",
"the",
"specified",
"connection",
"belongs",
"to",
"or",
"Integer",
".",
"MAX_VALUE",
"if",
"not",
"found",
"."
] | 2ed19b4743667664d15e3778447e579855ba3a65 | https://github.com/EsotericSoftware/kryonet/blob/2ed19b4743667664d15e3778447e579855ba3a65/src/com/esotericsoftware/kryonet/rmi/ObjectSpace.java#L669-L683 | train |
EsotericSoftware/kryonet | src/com/esotericsoftware/kryonet/rmi/ObjectSpace.java | ObjectSpace.registerClasses | static public void registerClasses (final Kryo kryo) {
kryo.register(Object[].class);
kryo.register(InvokeMethod.class);
FieldSerializer<InvokeMethodResult> resultSerializer = new FieldSerializer<InvokeMethodResult>(kryo,
InvokeMethodResult.class) {
public void write (Kryo kryo, Output output, InvokeMethodResult result) {
super.write(kryo, output, result);
output.writeInt(result.objectID, true);
}
public InvokeMethodResult read (Kryo kryo, Input input, Class<InvokeMethodResult> type) {
InvokeMethodResult result = super.read(kryo, input, type);
result.objectID = input.readInt(true);
return result;
}
};
resultSerializer.removeField("objectID");
kryo.register(InvokeMethodResult.class, resultSerializer);
kryo.register(InvocationHandler.class, new Serializer() {
public void write (Kryo kryo, Output output, Object object) {
RemoteInvocationHandler handler = (RemoteInvocationHandler)Proxy.getInvocationHandler(object);
output.writeInt(handler.objectID, true);
}
public Object read (Kryo kryo, Input input, Class type) {
int objectID = input.readInt(true);
Connection connection = (Connection)kryo.getContext().get("connection");
Object object = getRegisteredObject(connection, objectID);
if (WARN && object == null) warn("kryonet", "Unknown object ID " + objectID + " for connection: " + connection);
return object;
}
});
} | java | static public void registerClasses (final Kryo kryo) {
kryo.register(Object[].class);
kryo.register(InvokeMethod.class);
FieldSerializer<InvokeMethodResult> resultSerializer = new FieldSerializer<InvokeMethodResult>(kryo,
InvokeMethodResult.class) {
public void write (Kryo kryo, Output output, InvokeMethodResult result) {
super.write(kryo, output, result);
output.writeInt(result.objectID, true);
}
public InvokeMethodResult read (Kryo kryo, Input input, Class<InvokeMethodResult> type) {
InvokeMethodResult result = super.read(kryo, input, type);
result.objectID = input.readInt(true);
return result;
}
};
resultSerializer.removeField("objectID");
kryo.register(InvokeMethodResult.class, resultSerializer);
kryo.register(InvocationHandler.class, new Serializer() {
public void write (Kryo kryo, Output output, Object object) {
RemoteInvocationHandler handler = (RemoteInvocationHandler)Proxy.getInvocationHandler(object);
output.writeInt(handler.objectID, true);
}
public Object read (Kryo kryo, Input input, Class type) {
int objectID = input.readInt(true);
Connection connection = (Connection)kryo.getContext().get("connection");
Object object = getRegisteredObject(connection, objectID);
if (WARN && object == null) warn("kryonet", "Unknown object ID " + objectID + " for connection: " + connection);
return object;
}
});
} | [
"static",
"public",
"void",
"registerClasses",
"(",
"final",
"Kryo",
"kryo",
")",
"{",
"kryo",
".",
"register",
"(",
"Object",
"[",
"]",
".",
"class",
")",
";",
"kryo",
".",
"register",
"(",
"InvokeMethod",
".",
"class",
")",
";",
"FieldSerializer",
"<",
"InvokeMethodResult",
">",
"resultSerializer",
"=",
"new",
"FieldSerializer",
"<",
"InvokeMethodResult",
">",
"(",
"kryo",
",",
"InvokeMethodResult",
".",
"class",
")",
"{",
"public",
"void",
"write",
"(",
"Kryo",
"kryo",
",",
"Output",
"output",
",",
"InvokeMethodResult",
"result",
")",
"{",
"super",
".",
"write",
"(",
"kryo",
",",
"output",
",",
"result",
")",
";",
"output",
".",
"writeInt",
"(",
"result",
".",
"objectID",
",",
"true",
")",
";",
"}",
"public",
"InvokeMethodResult",
"read",
"(",
"Kryo",
"kryo",
",",
"Input",
"input",
",",
"Class",
"<",
"InvokeMethodResult",
">",
"type",
")",
"{",
"InvokeMethodResult",
"result",
"=",
"super",
".",
"read",
"(",
"kryo",
",",
"input",
",",
"type",
")",
";",
"result",
".",
"objectID",
"=",
"input",
".",
"readInt",
"(",
"true",
")",
";",
"return",
"result",
";",
"}",
"}",
";",
"resultSerializer",
".",
"removeField",
"(",
"\"objectID\"",
")",
";",
"kryo",
".",
"register",
"(",
"InvokeMethodResult",
".",
"class",
",",
"resultSerializer",
")",
";",
"kryo",
".",
"register",
"(",
"InvocationHandler",
".",
"class",
",",
"new",
"Serializer",
"(",
")",
"{",
"public",
"void",
"write",
"(",
"Kryo",
"kryo",
",",
"Output",
"output",
",",
"Object",
"object",
")",
"{",
"RemoteInvocationHandler",
"handler",
"=",
"(",
"RemoteInvocationHandler",
")",
"Proxy",
".",
"getInvocationHandler",
"(",
"object",
")",
";",
"output",
".",
"writeInt",
"(",
"handler",
".",
"objectID",
",",
"true",
")",
";",
"}",
"public",
"Object",
"read",
"(",
"Kryo",
"kryo",
",",
"Input",
"input",
",",
"Class",
"type",
")",
"{",
"int",
"objectID",
"=",
"input",
".",
"readInt",
"(",
"true",
")",
";",
"Connection",
"connection",
"=",
"(",
"Connection",
")",
"kryo",
".",
"getContext",
"(",
")",
".",
"get",
"(",
"\"connection\"",
")",
";",
"Object",
"object",
"=",
"getRegisteredObject",
"(",
"connection",
",",
"objectID",
")",
";",
"if",
"(",
"WARN",
"&&",
"object",
"==",
"null",
")",
"warn",
"(",
"\"kryonet\"",
",",
"\"Unknown object ID \"",
"+",
"objectID",
"+",
"\" for connection: \"",
"+",
"connection",
")",
";",
"return",
"object",
";",
"}",
"}",
")",
";",
"}"
] | Registers the classes needed to use ObjectSpaces. This should be called before any connections are opened.
@see Kryo#register(Class, Serializer) | [
"Registers",
"the",
"classes",
"needed",
"to",
"use",
"ObjectSpaces",
".",
"This",
"should",
"be",
"called",
"before",
"any",
"connections",
"are",
"opened",
"."
] | 2ed19b4743667664d15e3778447e579855ba3a65 | https://github.com/EsotericSoftware/kryonet/blob/2ed19b4743667664d15e3778447e579855ba3a65/src/com/esotericsoftware/kryonet/rmi/ObjectSpace.java#L687-L721 | train |
EsotericSoftware/kryonet | src/com/esotericsoftware/kryonet/util/ObjectIntMap.java | ObjectIntMap.ensureCapacity | public void ensureCapacity (int additionalCapacity) {
int sizeNeeded = size + additionalCapacity;
if (sizeNeeded >= threshold) resize(ObjectMap.nextPowerOfTwo((int)(sizeNeeded / loadFactor)));
} | java | public void ensureCapacity (int additionalCapacity) {
int sizeNeeded = size + additionalCapacity;
if (sizeNeeded >= threshold) resize(ObjectMap.nextPowerOfTwo((int)(sizeNeeded / loadFactor)));
} | [
"public",
"void",
"ensureCapacity",
"(",
"int",
"additionalCapacity",
")",
"{",
"int",
"sizeNeeded",
"=",
"size",
"+",
"additionalCapacity",
";",
"if",
"(",
"sizeNeeded",
">=",
"threshold",
")",
"resize",
"(",
"ObjectMap",
".",
"nextPowerOfTwo",
"(",
"(",
"int",
")",
"(",
"sizeNeeded",
"/",
"loadFactor",
")",
")",
")",
";",
"}"
] | Increases the size of the backing array to acommodate the specified number of additional items. Useful before adding many
items to avoid multiple backing array resizes. | [
"Increases",
"the",
"size",
"of",
"the",
"backing",
"array",
"to",
"acommodate",
"the",
"specified",
"number",
"of",
"additional",
"items",
".",
"Useful",
"before",
"adding",
"many",
"items",
"to",
"avoid",
"multiple",
"backing",
"array",
"resizes",
"."
] | 2ed19b4743667664d15e3778447e579855ba3a65 | https://github.com/EsotericSoftware/kryonet/blob/2ed19b4743667664d15e3778447e579855ba3a65/src/com/esotericsoftware/kryonet/util/ObjectIntMap.java#L443-L446 | train |
EsotericSoftware/kryonet | src/com/esotericsoftware/kryonet/Client.java | Client.discoverHost | public InetAddress discoverHost (int udpPort, int timeoutMillis) {
DatagramSocket socket = null;
try {
socket = new DatagramSocket();
broadcast(udpPort, socket);
socket.setSoTimeout(timeoutMillis);
DatagramPacket packet = discoveryHandler.onRequestNewDatagramPacket();
try {
socket.receive(packet);
} catch (SocketTimeoutException ex) {
if (INFO) info("kryonet", "Host discovery timed out.");
return null;
}
if (INFO) info("kryonet", "Discovered server: " + packet.getAddress());
discoveryHandler.onDiscoveredHost(packet, getKryo());
return packet.getAddress();
} catch (IOException ex) {
if (ERROR) error("kryonet", "Host discovery failed.", ex);
return null;
} finally {
if (socket != null) socket.close();
discoveryHandler.onFinally();
}
} | java | public InetAddress discoverHost (int udpPort, int timeoutMillis) {
DatagramSocket socket = null;
try {
socket = new DatagramSocket();
broadcast(udpPort, socket);
socket.setSoTimeout(timeoutMillis);
DatagramPacket packet = discoveryHandler.onRequestNewDatagramPacket();
try {
socket.receive(packet);
} catch (SocketTimeoutException ex) {
if (INFO) info("kryonet", "Host discovery timed out.");
return null;
}
if (INFO) info("kryonet", "Discovered server: " + packet.getAddress());
discoveryHandler.onDiscoveredHost(packet, getKryo());
return packet.getAddress();
} catch (IOException ex) {
if (ERROR) error("kryonet", "Host discovery failed.", ex);
return null;
} finally {
if (socket != null) socket.close();
discoveryHandler.onFinally();
}
} | [
"public",
"InetAddress",
"discoverHost",
"(",
"int",
"udpPort",
",",
"int",
"timeoutMillis",
")",
"{",
"DatagramSocket",
"socket",
"=",
"null",
";",
"try",
"{",
"socket",
"=",
"new",
"DatagramSocket",
"(",
")",
";",
"broadcast",
"(",
"udpPort",
",",
"socket",
")",
";",
"socket",
".",
"setSoTimeout",
"(",
"timeoutMillis",
")",
";",
"DatagramPacket",
"packet",
"=",
"discoveryHandler",
".",
"onRequestNewDatagramPacket",
"(",
")",
";",
"try",
"{",
"socket",
".",
"receive",
"(",
"packet",
")",
";",
"}",
"catch",
"(",
"SocketTimeoutException",
"ex",
")",
"{",
"if",
"(",
"INFO",
")",
"info",
"(",
"\"kryonet\"",
",",
"\"Host discovery timed out.\"",
")",
";",
"return",
"null",
";",
"}",
"if",
"(",
"INFO",
")",
"info",
"(",
"\"kryonet\"",
",",
"\"Discovered server: \"",
"+",
"packet",
".",
"getAddress",
"(",
")",
")",
";",
"discoveryHandler",
".",
"onDiscoveredHost",
"(",
"packet",
",",
"getKryo",
"(",
")",
")",
";",
"return",
"packet",
".",
"getAddress",
"(",
")",
";",
"}",
"catch",
"(",
"IOException",
"ex",
")",
"{",
"if",
"(",
"ERROR",
")",
"error",
"(",
"\"kryonet\"",
",",
"\"Host discovery failed.\"",
",",
"ex",
")",
";",
"return",
"null",
";",
"}",
"finally",
"{",
"if",
"(",
"socket",
"!=",
"null",
")",
"socket",
".",
"close",
"(",
")",
";",
"discoveryHandler",
".",
"onFinally",
"(",
")",
";",
"}",
"}"
] | Broadcasts a UDP message on the LAN to discover any running servers. The address of the first server to respond is
returned.
@param udpPort The UDP port of the server.
@param timeoutMillis The number of milliseconds to wait for a response.
@return the first server found, or null if no server responded. | [
"Broadcasts",
"a",
"UDP",
"message",
"on",
"the",
"LAN",
"to",
"discover",
"any",
"running",
"servers",
".",
"The",
"address",
"of",
"the",
"first",
"server",
"to",
"respond",
"is",
"returned",
"."
] | 2ed19b4743667664d15e3778447e579855ba3a65 | https://github.com/EsotericSoftware/kryonet/blob/2ed19b4743667664d15e3778447e579855ba3a65/src/com/esotericsoftware/kryonet/Client.java#L480-L503 | train |
EsotericSoftware/kryonet | src/com/esotericsoftware/kryonet/Client.java | Client.discoverHosts | public List<InetAddress> discoverHosts (int udpPort, int timeoutMillis) {
List<InetAddress> hosts = new ArrayList<InetAddress>();
DatagramSocket socket = null;
try {
socket = new DatagramSocket();
broadcast(udpPort, socket);
socket.setSoTimeout(timeoutMillis);
while (true) {
DatagramPacket packet = discoveryHandler.onRequestNewDatagramPacket();
try {
socket.receive(packet);
} catch (SocketTimeoutException ex) {
if (INFO) info("kryonet", "Host discovery timed out.");
return hosts;
}
if (INFO) info("kryonet", "Discovered server: " + packet.getAddress());
discoveryHandler.onDiscoveredHost(packet, getKryo());
hosts.add(packet.getAddress());
}
} catch (IOException ex) {
if (ERROR) error("kryonet", "Host discovery failed.", ex);
return hosts;
} finally {
if (socket != null) socket.close();
discoveryHandler.onFinally();
}
} | java | public List<InetAddress> discoverHosts (int udpPort, int timeoutMillis) {
List<InetAddress> hosts = new ArrayList<InetAddress>();
DatagramSocket socket = null;
try {
socket = new DatagramSocket();
broadcast(udpPort, socket);
socket.setSoTimeout(timeoutMillis);
while (true) {
DatagramPacket packet = discoveryHandler.onRequestNewDatagramPacket();
try {
socket.receive(packet);
} catch (SocketTimeoutException ex) {
if (INFO) info("kryonet", "Host discovery timed out.");
return hosts;
}
if (INFO) info("kryonet", "Discovered server: " + packet.getAddress());
discoveryHandler.onDiscoveredHost(packet, getKryo());
hosts.add(packet.getAddress());
}
} catch (IOException ex) {
if (ERROR) error("kryonet", "Host discovery failed.", ex);
return hosts;
} finally {
if (socket != null) socket.close();
discoveryHandler.onFinally();
}
} | [
"public",
"List",
"<",
"InetAddress",
">",
"discoverHosts",
"(",
"int",
"udpPort",
",",
"int",
"timeoutMillis",
")",
"{",
"List",
"<",
"InetAddress",
">",
"hosts",
"=",
"new",
"ArrayList",
"<",
"InetAddress",
">",
"(",
")",
";",
"DatagramSocket",
"socket",
"=",
"null",
";",
"try",
"{",
"socket",
"=",
"new",
"DatagramSocket",
"(",
")",
";",
"broadcast",
"(",
"udpPort",
",",
"socket",
")",
";",
"socket",
".",
"setSoTimeout",
"(",
"timeoutMillis",
")",
";",
"while",
"(",
"true",
")",
"{",
"DatagramPacket",
"packet",
"=",
"discoveryHandler",
".",
"onRequestNewDatagramPacket",
"(",
")",
";",
"try",
"{",
"socket",
".",
"receive",
"(",
"packet",
")",
";",
"}",
"catch",
"(",
"SocketTimeoutException",
"ex",
")",
"{",
"if",
"(",
"INFO",
")",
"info",
"(",
"\"kryonet\"",
",",
"\"Host discovery timed out.\"",
")",
";",
"return",
"hosts",
";",
"}",
"if",
"(",
"INFO",
")",
"info",
"(",
"\"kryonet\"",
",",
"\"Discovered server: \"",
"+",
"packet",
".",
"getAddress",
"(",
")",
")",
";",
"discoveryHandler",
".",
"onDiscoveredHost",
"(",
"packet",
",",
"getKryo",
"(",
")",
")",
";",
"hosts",
".",
"add",
"(",
"packet",
".",
"getAddress",
"(",
")",
")",
";",
"}",
"}",
"catch",
"(",
"IOException",
"ex",
")",
"{",
"if",
"(",
"ERROR",
")",
"error",
"(",
"\"kryonet\"",
",",
"\"Host discovery failed.\"",
",",
"ex",
")",
";",
"return",
"hosts",
";",
"}",
"finally",
"{",
"if",
"(",
"socket",
"!=",
"null",
")",
"socket",
".",
"close",
"(",
")",
";",
"discoveryHandler",
".",
"onFinally",
"(",
")",
";",
"}",
"}"
] | Broadcasts a UDP message on the LAN to discover any running servers.
@param udpPort The UDP port of the server.
@param timeoutMillis The number of milliseconds to wait for a response. | [
"Broadcasts",
"a",
"UDP",
"message",
"on",
"the",
"LAN",
"to",
"discover",
"any",
"running",
"servers",
"."
] | 2ed19b4743667664d15e3778447e579855ba3a65 | https://github.com/EsotericSoftware/kryonet/blob/2ed19b4743667664d15e3778447e579855ba3a65/src/com/esotericsoftware/kryonet/Client.java#L508-L534 | train |
EsotericSoftware/kryonet | src/com/esotericsoftware/kryonet/Server.java | Server.sendToAllTCP | public void sendToAllTCP (Object object) {
Connection[] connections = this.connections;
for (int i = 0, n = connections.length; i < n; i++) {
Connection connection = connections[i];
connection.sendTCP(object);
}
} | java | public void sendToAllTCP (Object object) {
Connection[] connections = this.connections;
for (int i = 0, n = connections.length; i < n; i++) {
Connection connection = connections[i];
connection.sendTCP(object);
}
} | [
"public",
"void",
"sendToAllTCP",
"(",
"Object",
"object",
")",
"{",
"Connection",
"[",
"]",
"connections",
"=",
"this",
".",
"connections",
";",
"for",
"(",
"int",
"i",
"=",
"0",
",",
"n",
"=",
"connections",
".",
"length",
";",
"i",
"<",
"n",
";",
"i",
"++",
")",
"{",
"Connection",
"connection",
"=",
"connections",
"[",
"i",
"]",
";",
"connection",
".",
"sendTCP",
"(",
"object",
")",
";",
"}",
"}"
] | BOZO - Provide mechanism for sending to multiple clients without serializing multiple times. | [
"BOZO",
"-",
"Provide",
"mechanism",
"for",
"sending",
"to",
"multiple",
"clients",
"without",
"serializing",
"multiple",
"times",
"."
] | 2ed19b4743667664d15e3778447e579855ba3a65 | https://github.com/EsotericSoftware/kryonet/blob/2ed19b4743667664d15e3778447e579855ba3a65/src/com/esotericsoftware/kryonet/Server.java#L465-L471 | train |
jmxtrans/jmxtrans | jmxtrans-output/jmxtrans-output-logback/src/main/java/com/googlecode/jmxtrans/model/output/NagiosWriter.java | NagiosWriter.internalWrite | @Override
public void internalWrite(Server server, Query query, ImmutableList<Result> results) throws Exception {
checkFile(query);
List<String> typeNames = getTypeNames();
for (Result result : results) {
String[] keyString = KeyUtils.getKeyString(server, query, result, typeNames, null).split("\\.");
if (isNumeric(result.getValue()) && filters.contains(keyString[2])) {
int thresholdPos = filters.indexOf(keyString[2]);
StringBuilder sb = new StringBuilder();
sb.append("[");
sb.append(result.getEpoch());
sb.append("] PROCESS_SERVICE_CHECK_RESULT;");
sb.append(nagiosHost);
sb.append(";");
if (prefix != null) {
sb.append(prefix);
}
sb.append(keyString[2]);
if (suffix != null) {
sb.append(suffix);
}
sb.append(";");
sb.append(nagiosCheckValue(result.getValue().toString(), thresholds.get(thresholdPos)));
sb.append(";");
//Missing the performance information
logger.info(sb.toString());
}
}
} | java | @Override
public void internalWrite(Server server, Query query, ImmutableList<Result> results) throws Exception {
checkFile(query);
List<String> typeNames = getTypeNames();
for (Result result : results) {
String[] keyString = KeyUtils.getKeyString(server, query, result, typeNames, null).split("\\.");
if (isNumeric(result.getValue()) && filters.contains(keyString[2])) {
int thresholdPos = filters.indexOf(keyString[2]);
StringBuilder sb = new StringBuilder();
sb.append("[");
sb.append(result.getEpoch());
sb.append("] PROCESS_SERVICE_CHECK_RESULT;");
sb.append(nagiosHost);
sb.append(";");
if (prefix != null) {
sb.append(prefix);
}
sb.append(keyString[2]);
if (suffix != null) {
sb.append(suffix);
}
sb.append(";");
sb.append(nagiosCheckValue(result.getValue().toString(), thresholds.get(thresholdPos)));
sb.append(";");
//Missing the performance information
logger.info(sb.toString());
}
}
} | [
"@",
"Override",
"public",
"void",
"internalWrite",
"(",
"Server",
"server",
",",
"Query",
"query",
",",
"ImmutableList",
"<",
"Result",
">",
"results",
")",
"throws",
"Exception",
"{",
"checkFile",
"(",
"query",
")",
";",
"List",
"<",
"String",
">",
"typeNames",
"=",
"getTypeNames",
"(",
")",
";",
"for",
"(",
"Result",
"result",
":",
"results",
")",
"{",
"String",
"[",
"]",
"keyString",
"=",
"KeyUtils",
".",
"getKeyString",
"(",
"server",
",",
"query",
",",
"result",
",",
"typeNames",
",",
"null",
")",
".",
"split",
"(",
"\"\\\\.\"",
")",
";",
"if",
"(",
"isNumeric",
"(",
"result",
".",
"getValue",
"(",
")",
")",
"&&",
"filters",
".",
"contains",
"(",
"keyString",
"[",
"2",
"]",
")",
")",
"{",
"int",
"thresholdPos",
"=",
"filters",
".",
"indexOf",
"(",
"keyString",
"[",
"2",
"]",
")",
";",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"sb",
".",
"append",
"(",
"\"[\"",
")",
";",
"sb",
".",
"append",
"(",
"result",
".",
"getEpoch",
"(",
")",
")",
";",
"sb",
".",
"append",
"(",
"\"] PROCESS_SERVICE_CHECK_RESULT;\"",
")",
";",
"sb",
".",
"append",
"(",
"nagiosHost",
")",
";",
"sb",
".",
"append",
"(",
"\";\"",
")",
";",
"if",
"(",
"prefix",
"!=",
"null",
")",
"{",
"sb",
".",
"append",
"(",
"prefix",
")",
";",
"}",
"sb",
".",
"append",
"(",
"keyString",
"[",
"2",
"]",
")",
";",
"if",
"(",
"suffix",
"!=",
"null",
")",
"{",
"sb",
".",
"append",
"(",
"suffix",
")",
";",
"}",
"sb",
".",
"append",
"(",
"\";\"",
")",
";",
"sb",
".",
"append",
"(",
"nagiosCheckValue",
"(",
"result",
".",
"getValue",
"(",
")",
".",
"toString",
"(",
")",
",",
"thresholds",
".",
"get",
"(",
"thresholdPos",
")",
")",
")",
";",
"sb",
".",
"append",
"(",
"\";\"",
")",
";",
"//Missing the performance information",
"logger",
".",
"info",
"(",
"sb",
".",
"toString",
"(",
")",
")",
";",
"}",
"}",
"}"
] | The meat of the output. Nagios format.. | [
"The",
"meat",
"of",
"the",
"output",
".",
"Nagios",
"format",
".."
] | 496f342de3bcf2c2226626374b7a16edf8f4ba2a | https://github.com/jmxtrans/jmxtrans/blob/496f342de3bcf2c2226626374b7a16edf8f4ba2a/jmxtrans-output/jmxtrans-output-logback/src/main/java/com/googlecode/jmxtrans/model/output/NagiosWriter.java#L167-L198 | train |
jmxtrans/jmxtrans | jmxtrans-output/jmxtrans-output-logback/src/main/java/com/googlecode/jmxtrans/model/output/NagiosWriter.java | NagiosWriter.nagiosCheckValue | protected String nagiosCheckValue(String value, String composeRange) {
List<String> simpleRange = Arrays.asList(composeRange.split(","));
double doubleValue = Double.parseDouble(value);
if (composeRange.isEmpty()) {
return "0";
}
if (simpleRange.size() == 1) {
if (composeRange.endsWith(",")) {
if (valueCheck(doubleValue, simpleRange.get(0))) {
return "1";
} else {
return "0";
}
} else if (valueCheck(doubleValue, simpleRange.get(0))) {
return "2";
} else {
return "0";
}
}
if (valueCheck(doubleValue, simpleRange.get(1))) {
return "2";
}
if (valueCheck(doubleValue, simpleRange.get(0))) {
return "1";
}
return "0";
} | java | protected String nagiosCheckValue(String value, String composeRange) {
List<String> simpleRange = Arrays.asList(composeRange.split(","));
double doubleValue = Double.parseDouble(value);
if (composeRange.isEmpty()) {
return "0";
}
if (simpleRange.size() == 1) {
if (composeRange.endsWith(",")) {
if (valueCheck(doubleValue, simpleRange.get(0))) {
return "1";
} else {
return "0";
}
} else if (valueCheck(doubleValue, simpleRange.get(0))) {
return "2";
} else {
return "0";
}
}
if (valueCheck(doubleValue, simpleRange.get(1))) {
return "2";
}
if (valueCheck(doubleValue, simpleRange.get(0))) {
return "1";
}
return "0";
} | [
"protected",
"String",
"nagiosCheckValue",
"(",
"String",
"value",
",",
"String",
"composeRange",
")",
"{",
"List",
"<",
"String",
">",
"simpleRange",
"=",
"Arrays",
".",
"asList",
"(",
"composeRange",
".",
"split",
"(",
"\",\"",
")",
")",
";",
"double",
"doubleValue",
"=",
"Double",
".",
"parseDouble",
"(",
"value",
")",
";",
"if",
"(",
"composeRange",
".",
"isEmpty",
"(",
")",
")",
"{",
"return",
"\"0\"",
";",
"}",
"if",
"(",
"simpleRange",
".",
"size",
"(",
")",
"==",
"1",
")",
"{",
"if",
"(",
"composeRange",
".",
"endsWith",
"(",
"\",\"",
")",
")",
"{",
"if",
"(",
"valueCheck",
"(",
"doubleValue",
",",
"simpleRange",
".",
"get",
"(",
"0",
")",
")",
")",
"{",
"return",
"\"1\"",
";",
"}",
"else",
"{",
"return",
"\"0\"",
";",
"}",
"}",
"else",
"if",
"(",
"valueCheck",
"(",
"doubleValue",
",",
"simpleRange",
".",
"get",
"(",
"0",
")",
")",
")",
"{",
"return",
"\"2\"",
";",
"}",
"else",
"{",
"return",
"\"0\"",
";",
"}",
"}",
"if",
"(",
"valueCheck",
"(",
"doubleValue",
",",
"simpleRange",
".",
"get",
"(",
"1",
")",
")",
")",
"{",
"return",
"\"2\"",
";",
"}",
"if",
"(",
"valueCheck",
"(",
"doubleValue",
",",
"simpleRange",
".",
"get",
"(",
"0",
")",
")",
")",
"{",
"return",
"\"1\"",
";",
"}",
"return",
"\"0\"",
";",
"}"
] | Define if a value is in a critical, warning or ok state. | [
"Define",
"if",
"a",
"value",
"is",
"in",
"a",
"critical",
"warning",
"or",
"ok",
"state",
"."
] | 496f342de3bcf2c2226626374b7a16edf8f4ba2a | https://github.com/jmxtrans/jmxtrans/blob/496f342de3bcf2c2226626374b7a16edf8f4ba2a/jmxtrans-output/jmxtrans-output-logback/src/main/java/com/googlecode/jmxtrans/model/output/NagiosWriter.java#L236-L268 | train |
jmxtrans/jmxtrans | jmxtrans-output/jmxtrans-output-core/src/main/java/com/googlecode/jmxtrans/model/output/TCollectorUDPWriter.java | TCollectorUDPWriter.prepareSender | @Override
public void prepareSender() throws LifecycleException {
if (host == null || port == null) {
throw new LifecycleException("Host and port for " + this.getClass().getSimpleName() + " output can't be null");
}
try {
this.dgSocket = new DatagramSocket();
this.address = new InetSocketAddress(host, port);
} catch (SocketException sockExc) {
log.error("Failed to create a datagram socket", sockExc);
throw new LifecycleException(sockExc);
}
} | java | @Override
public void prepareSender() throws LifecycleException {
if (host == null || port == null) {
throw new LifecycleException("Host and port for " + this.getClass().getSimpleName() + " output can't be null");
}
try {
this.dgSocket = new DatagramSocket();
this.address = new InetSocketAddress(host, port);
} catch (SocketException sockExc) {
log.error("Failed to create a datagram socket", sockExc);
throw new LifecycleException(sockExc);
}
} | [
"@",
"Override",
"public",
"void",
"prepareSender",
"(",
")",
"throws",
"LifecycleException",
"{",
"if",
"(",
"host",
"==",
"null",
"||",
"port",
"==",
"null",
")",
"{",
"throw",
"new",
"LifecycleException",
"(",
"\"Host and port for \"",
"+",
"this",
".",
"getClass",
"(",
")",
".",
"getSimpleName",
"(",
")",
"+",
"\" output can't be null\"",
")",
";",
"}",
"try",
"{",
"this",
".",
"dgSocket",
"=",
"new",
"DatagramSocket",
"(",
")",
";",
"this",
".",
"address",
"=",
"new",
"InetSocketAddress",
"(",
"host",
",",
"port",
")",
";",
"}",
"catch",
"(",
"SocketException",
"sockExc",
")",
"{",
"log",
".",
"error",
"(",
"\"Failed to create a datagram socket\"",
",",
"sockExc",
")",
";",
"throw",
"new",
"LifecycleException",
"(",
"sockExc",
")",
";",
"}",
"}"
] | Setup at start of the writer. | [
"Setup",
"at",
"start",
"of",
"the",
"writer",
"."
] | 496f342de3bcf2c2226626374b7a16edf8f4ba2a | https://github.com/jmxtrans/jmxtrans/blob/496f342de3bcf2c2226626374b7a16edf8f4ba2a/jmxtrans-output/jmxtrans-output-core/src/main/java/com/googlecode/jmxtrans/model/output/TCollectorUDPWriter.java#L106-L120 | train |
jmxtrans/jmxtrans | jmxtrans-output/jmxtrans-output-core/src/main/java/com/googlecode/jmxtrans/model/output/TCollectorUDPWriter.java | TCollectorUDPWriter.sendOutput | @Override
protected void sendOutput(String metricLine) throws IOException {
DatagramPacket packet;
byte[] data;
data = metricLine.getBytes("UTF-8");
packet = new DatagramPacket(data, 0, data.length, this.address);
this.dgSocket.send(packet);
} | java | @Override
protected void sendOutput(String metricLine) throws IOException {
DatagramPacket packet;
byte[] data;
data = metricLine.getBytes("UTF-8");
packet = new DatagramPacket(data, 0, data.length, this.address);
this.dgSocket.send(packet);
} | [
"@",
"Override",
"protected",
"void",
"sendOutput",
"(",
"String",
"metricLine",
")",
"throws",
"IOException",
"{",
"DatagramPacket",
"packet",
";",
"byte",
"[",
"]",
"data",
";",
"data",
"=",
"metricLine",
".",
"getBytes",
"(",
"\"UTF-8\"",
")",
";",
"packet",
"=",
"new",
"DatagramPacket",
"(",
"data",
",",
"0",
",",
"data",
".",
"length",
",",
"this",
".",
"address",
")",
";",
"this",
".",
"dgSocket",
".",
"send",
"(",
"packet",
")",
";",
"}"
] | Send a single metric to TCollector.
@param metricLine - the line containing the metric name, value, and tags for a single metric; excludes the
"put" keyword expected by OpenTSDB and the trailing newline character. | [
"Send",
"a",
"single",
"metric",
"to",
"TCollector",
"."
] | 496f342de3bcf2c2226626374b7a16edf8f4ba2a | https://github.com/jmxtrans/jmxtrans/blob/496f342de3bcf2c2226626374b7a16edf8f4ba2a/jmxtrans-output/jmxtrans-output-core/src/main/java/com/googlecode/jmxtrans/model/output/TCollectorUDPWriter.java#L128-L137 | train |
jmxtrans/jmxtrans | jmxtrans-utils/src/main/java/com/googlecode/jmxtrans/util/NumberUtils.java | NumberUtils.isNumeric | public static boolean isNumeric(Object value) {
if (value == null) return false;
if (value instanceof Number) return true;
if (value instanceof String) {
String stringValue = (String) value;
if (isNullOrEmpty(stringValue)) return true;
return isNumber(stringValue);
}
return false;
} | java | public static boolean isNumeric(Object value) {
if (value == null) return false;
if (value instanceof Number) return true;
if (value instanceof String) {
String stringValue = (String) value;
if (isNullOrEmpty(stringValue)) return true;
return isNumber(stringValue);
}
return false;
} | [
"public",
"static",
"boolean",
"isNumeric",
"(",
"Object",
"value",
")",
"{",
"if",
"(",
"value",
"==",
"null",
")",
"return",
"false",
";",
"if",
"(",
"value",
"instanceof",
"Number",
")",
"return",
"true",
";",
"if",
"(",
"value",
"instanceof",
"String",
")",
"{",
"String",
"stringValue",
"=",
"(",
"String",
")",
"value",
";",
"if",
"(",
"isNullOrEmpty",
"(",
"stringValue",
")",
")",
"return",
"true",
";",
"return",
"isNumber",
"(",
"stringValue",
")",
";",
"}",
"return",
"false",
";",
"}"
] | Useful for figuring out if an Object is a number. | [
"Useful",
"for",
"figuring",
"out",
"if",
"an",
"Object",
"is",
"a",
"number",
"."
] | 496f342de3bcf2c2226626374b7a16edf8f4ba2a | https://github.com/jmxtrans/jmxtrans/blob/496f342de3bcf2c2226626374b7a16edf8f4ba2a/jmxtrans-utils/src/main/java/com/googlecode/jmxtrans/util/NumberUtils.java#L35-L44 | train |
jmxtrans/jmxtrans | jmxtrans-output/jmxtrans-output-core/src/main/java/com/googlecode/jmxtrans/model/output/OpenTSDBGenericWriter.java | OpenTSDBGenericWriter.internalWrite | @Override
public void internalWrite(Server server, Query query, ImmutableList<Result> results) throws Exception {
this.startOutput();
for (String formattedResult : messageFormatter.formatResults(results, server)) {
log.debug("Sending result: {}", formattedResult);
this.sendOutput(formattedResult);
}
this.finishOutput();
} | java | @Override
public void internalWrite(Server server, Query query, ImmutableList<Result> results) throws Exception {
this.startOutput();
for (String formattedResult : messageFormatter.formatResults(results, server)) {
log.debug("Sending result: {}", formattedResult);
this.sendOutput(formattedResult);
}
this.finishOutput();
} | [
"@",
"Override",
"public",
"void",
"internalWrite",
"(",
"Server",
"server",
",",
"Query",
"query",
",",
"ImmutableList",
"<",
"Result",
">",
"results",
")",
"throws",
"Exception",
"{",
"this",
".",
"startOutput",
"(",
")",
";",
"for",
"(",
"String",
"formattedResult",
":",
"messageFormatter",
".",
"formatResults",
"(",
"results",
",",
"server",
")",
")",
"{",
"log",
".",
"debug",
"(",
"\"Sending result: {}\"",
",",
"formattedResult",
")",
";",
"this",
".",
"sendOutput",
"(",
"formattedResult",
")",
";",
"}",
"this",
".",
"finishOutput",
"(",
")",
";",
"}"
] | Write the results of the query.
@param server
@param query - the query and its results.
@param results | [
"Write",
"the",
"results",
"of",
"the",
"query",
"."
] | 496f342de3bcf2c2226626374b7a16edf8f4ba2a | https://github.com/jmxtrans/jmxtrans/blob/496f342de3bcf2c2226626374b7a16edf8f4ba2a/jmxtrans-output/jmxtrans-output-core/src/main/java/com/googlecode/jmxtrans/model/output/OpenTSDBGenericWriter.java#L144-L152 | train |
jmxtrans/jmxtrans | jmxtrans-core/src/main/java/com/googlecode/jmxtrans/model/naming/KeyUtils.java | KeyUtils.getKeyString | public static String getKeyString(Server server, Query query, Result result, List<String> typeNames, String rootPrefix) {
StringBuilder sb = new StringBuilder();
addRootPrefix(rootPrefix, sb);
addAlias(server, sb);
addSeparator(sb);
addMBeanIdentifier(query, result, sb);
addSeparator(sb);
addTypeName(query, result, typeNames, sb);
addKeyString(query, result, sb);
return sb.toString();
} | java | public static String getKeyString(Server server, Query query, Result result, List<String> typeNames, String rootPrefix) {
StringBuilder sb = new StringBuilder();
addRootPrefix(rootPrefix, sb);
addAlias(server, sb);
addSeparator(sb);
addMBeanIdentifier(query, result, sb);
addSeparator(sb);
addTypeName(query, result, typeNames, sb);
addKeyString(query, result, sb);
return sb.toString();
} | [
"public",
"static",
"String",
"getKeyString",
"(",
"Server",
"server",
",",
"Query",
"query",
",",
"Result",
"result",
",",
"List",
"<",
"String",
">",
"typeNames",
",",
"String",
"rootPrefix",
")",
"{",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"addRootPrefix",
"(",
"rootPrefix",
",",
"sb",
")",
";",
"addAlias",
"(",
"server",
",",
"sb",
")",
";",
"addSeparator",
"(",
"sb",
")",
";",
"addMBeanIdentifier",
"(",
"query",
",",
"result",
",",
"sb",
")",
";",
"addSeparator",
"(",
"sb",
")",
";",
"addTypeName",
"(",
"query",
",",
"result",
",",
"typeNames",
",",
"sb",
")",
";",
"addKeyString",
"(",
"query",
",",
"result",
",",
"sb",
")",
";",
"return",
"sb",
".",
"toString",
"(",
")",
";",
"}"
] | Gets the key string.
@param server
@param query the query
@param result the result
@param typeNames the type names
@param rootPrefix the root prefix
@return the key string | [
"Gets",
"the",
"key",
"string",
"."
] | 496f342de3bcf2c2226626374b7a16edf8f4ba2a | https://github.com/jmxtrans/jmxtrans/blob/496f342de3bcf2c2226626374b7a16edf8f4ba2a/jmxtrans-core/src/main/java/com/googlecode/jmxtrans/model/naming/KeyUtils.java#L46-L56 | train |
jmxtrans/jmxtrans | jmxtrans-core/src/main/java/com/googlecode/jmxtrans/model/naming/KeyUtils.java | KeyUtils.getKeyString | public static String getKeyString(Query query, Result result, List<String> typeNames) {
StringBuilder sb = new StringBuilder();
addMBeanIdentifier(query, result, sb);
addSeparator(sb);
addTypeName(query, result, typeNames, sb);
addKeyString(query, result, sb);
return sb.toString();
} | java | public static String getKeyString(Query query, Result result, List<String> typeNames) {
StringBuilder sb = new StringBuilder();
addMBeanIdentifier(query, result, sb);
addSeparator(sb);
addTypeName(query, result, typeNames, sb);
addKeyString(query, result, sb);
return sb.toString();
} | [
"public",
"static",
"String",
"getKeyString",
"(",
"Query",
"query",
",",
"Result",
"result",
",",
"List",
"<",
"String",
">",
"typeNames",
")",
"{",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"addMBeanIdentifier",
"(",
"query",
",",
"result",
",",
"sb",
")",
";",
"addSeparator",
"(",
"sb",
")",
";",
"addTypeName",
"(",
"query",
",",
"result",
",",
"typeNames",
",",
"sb",
")",
";",
"addKeyString",
"(",
"query",
",",
"result",
",",
"sb",
")",
";",
"return",
"sb",
".",
"toString",
"(",
")",
";",
"}"
] | Gets the key string, without rootPrefix nor Alias
@param query the query
@param result the result
@param typeNames the type names
@return the key string | [
"Gets",
"the",
"key",
"string",
"without",
"rootPrefix",
"nor",
"Alias"
] | 496f342de3bcf2c2226626374b7a16edf8f4ba2a | https://github.com/jmxtrans/jmxtrans/blob/496f342de3bcf2c2226626374b7a16edf8f4ba2a/jmxtrans-core/src/main/java/com/googlecode/jmxtrans/model/naming/KeyUtils.java#L66-L73 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.