id
int32
0
165k
repo
stringlengths
7
58
path
stringlengths
12
218
func_name
stringlengths
3
140
original_string
stringlengths
73
34.1k
language
stringclasses
1 value
code
stringlengths
73
34.1k
code_tokens
list
docstring
stringlengths
3
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
105
339
159,100
wildfly/wildfly-core
controller/src/main/java/org/jboss/as/controller/access/management/WritableAuthorizerConfiguration.java
WritableAuthorizerConfiguration.removeRoleMapping
public synchronized Object removeRoleMapping(final String roleName) { /* * Would not expect this to happen during boot so don't offer the 'immediate' optimisation. */ HashMap<String, RoleMappingImpl> newRoles = new HashMap<String, RoleMappingImpl>(roleMappings); if (newRoles.containsKey(roleName)) { RoleMappingImpl removed = newRoles.remove(roleName); Object removalKey = new Object(); removedRoles.put(removalKey, removed); roleMappings = Collections.unmodifiableMap(newRoles); return removalKey; } return null; }
java
public synchronized Object removeRoleMapping(final String roleName) { /* * Would not expect this to happen during boot so don't offer the 'immediate' optimisation. */ HashMap<String, RoleMappingImpl> newRoles = new HashMap<String, RoleMappingImpl>(roleMappings); if (newRoles.containsKey(roleName)) { RoleMappingImpl removed = newRoles.remove(roleName); Object removalKey = new Object(); removedRoles.put(removalKey, removed); roleMappings = Collections.unmodifiableMap(newRoles); return removalKey; } return null; }
[ "public", "synchronized", "Object", "removeRoleMapping", "(", "final", "String", "roleName", ")", "{", "/*\n * Would not expect this to happen during boot so don't offer the 'immediate' optimisation.\n */", "HashMap", "<", "String", ",", "RoleMappingImpl", ">", "newRoles", "=", "new", "HashMap", "<", "String", ",", "RoleMappingImpl", ">", "(", "roleMappings", ")", ";", "if", "(", "newRoles", ".", "containsKey", "(", "roleName", ")", ")", "{", "RoleMappingImpl", "removed", "=", "newRoles", ".", "remove", "(", "roleName", ")", ";", "Object", "removalKey", "=", "new", "Object", "(", ")", ";", "removedRoles", ".", "put", "(", "removalKey", ",", "removed", ")", ";", "roleMappings", "=", "Collections", ".", "unmodifiableMap", "(", "newRoles", ")", ";", "return", "removalKey", ";", "}", "return", "null", ";", "}" ]
Remove a role from the list of defined roles. @param roleName - The name of the role to be removed. @return A key that can be used to undo the removal.
[ "Remove", "a", "role", "from", "the", "list", "of", "defined", "roles", "." ]
cfaf0479dcbb2d320a44c5374b93b944ec39fade
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/access/management/WritableAuthorizerConfiguration.java#L190-L205
159,101
wildfly/wildfly-core
controller/src/main/java/org/jboss/as/controller/access/management/WritableAuthorizerConfiguration.java
WritableAuthorizerConfiguration.undoRoleMappingRemove
public synchronized boolean undoRoleMappingRemove(final Object removalKey) { HashMap<String, RoleMappingImpl> newRoles = new HashMap<String, RoleMappingImpl>(roleMappings); RoleMappingImpl toRestore = removedRoles.remove(removalKey); if (toRestore != null && newRoles.containsKey(toRestore.getName()) == false) { newRoles.put(toRestore.getName(), toRestore); roleMappings = Collections.unmodifiableMap(newRoles); return true; } return false; }
java
public synchronized boolean undoRoleMappingRemove(final Object removalKey) { HashMap<String, RoleMappingImpl> newRoles = new HashMap<String, RoleMappingImpl>(roleMappings); RoleMappingImpl toRestore = removedRoles.remove(removalKey); if (toRestore != null && newRoles.containsKey(toRestore.getName()) == false) { newRoles.put(toRestore.getName(), toRestore); roleMappings = Collections.unmodifiableMap(newRoles); return true; } return false; }
[ "public", "synchronized", "boolean", "undoRoleMappingRemove", "(", "final", "Object", "removalKey", ")", "{", "HashMap", "<", "String", ",", "RoleMappingImpl", ">", "newRoles", "=", "new", "HashMap", "<", "String", ",", "RoleMappingImpl", ">", "(", "roleMappings", ")", ";", "RoleMappingImpl", "toRestore", "=", "removedRoles", ".", "remove", "(", "removalKey", ")", ";", "if", "(", "toRestore", "!=", "null", "&&", "newRoles", ".", "containsKey", "(", "toRestore", ".", "getName", "(", ")", ")", "==", "false", ")", "{", "newRoles", ".", "put", "(", "toRestore", ".", "getName", "(", ")", ",", "toRestore", ")", ";", "roleMappings", "=", "Collections", ".", "unmodifiableMap", "(", "newRoles", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
Undo a prior removal using the supplied undo key. @param removalKey - The key returned from the call to removeRoleMapping. @return true if the undo was successful, false otherwise.
[ "Undo", "a", "prior", "removal", "using", "the", "supplied", "undo", "key", "." ]
cfaf0479dcbb2d320a44c5374b93b944ec39fade
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/access/management/WritableAuthorizerConfiguration.java#L213-L223
159,102
wildfly/wildfly-core
host-controller/src/main/java/org/jboss/as/domain/controller/operations/coordination/ServerOperationResolver.java
ServerOperationResolver.getDeploymentOverlayOperations
private Map<Set<ServerIdentity>, ModelNode> getDeploymentOverlayOperations(ModelNode operation, ModelNode host) { final PathAddress realAddress = PathAddress.pathAddress(operation.get(OP_ADDR)); if (realAddress.size() == 0 && COMPOSITE.equals(operation.get(OP).asString())) { //We have a composite operation resulting from a transformation to redeploy affected deployments //See redeploying deployments affected by an overlay. ModelNode serverOp = operation.clone(); Map<ServerIdentity, Operations.CompositeOperationBuilder> composite = new HashMap<>(); for (ModelNode step : serverOp.get(STEPS).asList()) { ModelNode newStep = step.clone(); String groupName = PathAddress.pathAddress(step.get(OP_ADDR)).getElement(0).getValue(); newStep.get(OP_ADDR).set(PathAddress.pathAddress(step.get(OP_ADDR)).subAddress(1).toModelNode()); Set<ServerIdentity> servers = getServersForGroup(groupName, host, localHostName, serverProxies); for(ServerIdentity server : servers) { if(!composite.containsKey(server)) { composite.put(server, Operations.CompositeOperationBuilder.create()); } composite.get(server).addStep(newStep); } if(!servers.isEmpty()) { newStep.get(OP_ADDR).set(PathAddress.pathAddress(step.get(OP_ADDR)).subAddress(1).toModelNode()); } } if(!composite.isEmpty()) { Map<Set<ServerIdentity>, ModelNode> result = new HashMap<>(); for(Entry<ServerIdentity, Operations.CompositeOperationBuilder> entry : composite.entrySet()) { result.put(Collections.singleton(entry.getKey()), entry.getValue().build().getOperation()); } return result; } return Collections.emptyMap(); } final Set<ServerIdentity> allServers = getAllRunningServers(host, localHostName, serverProxies); return Collections.singletonMap(allServers, operation.clone()); }
java
private Map<Set<ServerIdentity>, ModelNode> getDeploymentOverlayOperations(ModelNode operation, ModelNode host) { final PathAddress realAddress = PathAddress.pathAddress(operation.get(OP_ADDR)); if (realAddress.size() == 0 && COMPOSITE.equals(operation.get(OP).asString())) { //We have a composite operation resulting from a transformation to redeploy affected deployments //See redeploying deployments affected by an overlay. ModelNode serverOp = operation.clone(); Map<ServerIdentity, Operations.CompositeOperationBuilder> composite = new HashMap<>(); for (ModelNode step : serverOp.get(STEPS).asList()) { ModelNode newStep = step.clone(); String groupName = PathAddress.pathAddress(step.get(OP_ADDR)).getElement(0).getValue(); newStep.get(OP_ADDR).set(PathAddress.pathAddress(step.get(OP_ADDR)).subAddress(1).toModelNode()); Set<ServerIdentity> servers = getServersForGroup(groupName, host, localHostName, serverProxies); for(ServerIdentity server : servers) { if(!composite.containsKey(server)) { composite.put(server, Operations.CompositeOperationBuilder.create()); } composite.get(server).addStep(newStep); } if(!servers.isEmpty()) { newStep.get(OP_ADDR).set(PathAddress.pathAddress(step.get(OP_ADDR)).subAddress(1).toModelNode()); } } if(!composite.isEmpty()) { Map<Set<ServerIdentity>, ModelNode> result = new HashMap<>(); for(Entry<ServerIdentity, Operations.CompositeOperationBuilder> entry : composite.entrySet()) { result.put(Collections.singleton(entry.getKey()), entry.getValue().build().getOperation()); } return result; } return Collections.emptyMap(); } final Set<ServerIdentity> allServers = getAllRunningServers(host, localHostName, serverProxies); return Collections.singletonMap(allServers, operation.clone()); }
[ "private", "Map", "<", "Set", "<", "ServerIdentity", ">", ",", "ModelNode", ">", "getDeploymentOverlayOperations", "(", "ModelNode", "operation", ",", "ModelNode", "host", ")", "{", "final", "PathAddress", "realAddress", "=", "PathAddress", ".", "pathAddress", "(", "operation", ".", "get", "(", "OP_ADDR", ")", ")", ";", "if", "(", "realAddress", ".", "size", "(", ")", "==", "0", "&&", "COMPOSITE", ".", "equals", "(", "operation", ".", "get", "(", "OP", ")", ".", "asString", "(", ")", ")", ")", "{", "//We have a composite operation resulting from a transformation to redeploy affected deployments", "//See redeploying deployments affected by an overlay.", "ModelNode", "serverOp", "=", "operation", ".", "clone", "(", ")", ";", "Map", "<", "ServerIdentity", ",", "Operations", ".", "CompositeOperationBuilder", ">", "composite", "=", "new", "HashMap", "<>", "(", ")", ";", "for", "(", "ModelNode", "step", ":", "serverOp", ".", "get", "(", "STEPS", ")", ".", "asList", "(", ")", ")", "{", "ModelNode", "newStep", "=", "step", ".", "clone", "(", ")", ";", "String", "groupName", "=", "PathAddress", ".", "pathAddress", "(", "step", ".", "get", "(", "OP_ADDR", ")", ")", ".", "getElement", "(", "0", ")", ".", "getValue", "(", ")", ";", "newStep", ".", "get", "(", "OP_ADDR", ")", ".", "set", "(", "PathAddress", ".", "pathAddress", "(", "step", ".", "get", "(", "OP_ADDR", ")", ")", ".", "subAddress", "(", "1", ")", ".", "toModelNode", "(", ")", ")", ";", "Set", "<", "ServerIdentity", ">", "servers", "=", "getServersForGroup", "(", "groupName", ",", "host", ",", "localHostName", ",", "serverProxies", ")", ";", "for", "(", "ServerIdentity", "server", ":", "servers", ")", "{", "if", "(", "!", "composite", ".", "containsKey", "(", "server", ")", ")", "{", "composite", ".", "put", "(", "server", ",", "Operations", ".", "CompositeOperationBuilder", ".", "create", "(", ")", ")", ";", "}", "composite", ".", "get", "(", "server", ")", ".", "addStep", "(", "newStep", ")", ";", "}", "if", "(", "!", "servers", ".", "isEmpty", "(", ")", ")", "{", "newStep", ".", "get", "(", "OP_ADDR", ")", ".", "set", "(", "PathAddress", ".", "pathAddress", "(", "step", ".", "get", "(", "OP_ADDR", ")", ")", ".", "subAddress", "(", "1", ")", ".", "toModelNode", "(", ")", ")", ";", "}", "}", "if", "(", "!", "composite", ".", "isEmpty", "(", ")", ")", "{", "Map", "<", "Set", "<", "ServerIdentity", ">", ",", "ModelNode", ">", "result", "=", "new", "HashMap", "<>", "(", ")", ";", "for", "(", "Entry", "<", "ServerIdentity", ",", "Operations", ".", "CompositeOperationBuilder", ">", "entry", ":", "composite", ".", "entrySet", "(", ")", ")", "{", "result", ".", "put", "(", "Collections", ".", "singleton", "(", "entry", ".", "getKey", "(", ")", ")", ",", "entry", ".", "getValue", "(", ")", ".", "build", "(", ")", ".", "getOperation", "(", ")", ")", ";", "}", "return", "result", ";", "}", "return", "Collections", ".", "emptyMap", "(", ")", ";", "}", "final", "Set", "<", "ServerIdentity", ">", "allServers", "=", "getAllRunningServers", "(", "host", ",", "localHostName", ",", "serverProxies", ")", ";", "return", "Collections", ".", "singletonMap", "(", "allServers", ",", "operation", ".", "clone", "(", ")", ")", ";", "}" ]
Convert an operation for deployment overlays to be executed on local servers. Since this might be called in the case of redeployment of affected deployments, we need to take into account the composite op resulting from such a transformation @see AffectedDeploymentOverlay#redeployLinksAndTransformOperationForDomain @param operation @param host @return
[ "Convert", "an", "operation", "for", "deployment", "overlays", "to", "be", "executed", "on", "local", "servers", ".", "Since", "this", "might", "be", "called", "in", "the", "case", "of", "redeployment", "of", "affected", "deployments", "we", "need", "to", "take", "into", "account", "the", "composite", "op", "resulting", "from", "such", "a", "transformation" ]
cfaf0479dcbb2d320a44c5374b93b944ec39fade
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/host-controller/src/main/java/org/jboss/as/domain/controller/operations/coordination/ServerOperationResolver.java#L350-L384
159,103
wildfly/wildfly-core
cli/src/main/java/org/jboss/as/cli/gui/ServerLogsPanel.java
ServerLogsPanel.isLogDownloadAvailable
public static boolean isLogDownloadAvailable(CliGuiContext cliGuiCtx) { ModelNode readOps = null; try { readOps = cliGuiCtx.getExecutor().doCommand("/subsystem=logging:read-children-types"); } catch (CommandFormatException | IOException e) { return false; } if (!readOps.get("result").isDefined()) return false; for (ModelNode op: readOps.get("result").asList()) { if ("log-file".equals(op.asString())) return true; } return false; }
java
public static boolean isLogDownloadAvailable(CliGuiContext cliGuiCtx) { ModelNode readOps = null; try { readOps = cliGuiCtx.getExecutor().doCommand("/subsystem=logging:read-children-types"); } catch (CommandFormatException | IOException e) { return false; } if (!readOps.get("result").isDefined()) return false; for (ModelNode op: readOps.get("result").asList()) { if ("log-file".equals(op.asString())) return true; } return false; }
[ "public", "static", "boolean", "isLogDownloadAvailable", "(", "CliGuiContext", "cliGuiCtx", ")", "{", "ModelNode", "readOps", "=", "null", ";", "try", "{", "readOps", "=", "cliGuiCtx", ".", "getExecutor", "(", ")", ".", "doCommand", "(", "\"/subsystem=logging:read-children-types\"", ")", ";", "}", "catch", "(", "CommandFormatException", "|", "IOException", "e", ")", "{", "return", "false", ";", "}", "if", "(", "!", "readOps", ".", "get", "(", "\"result\"", ")", ".", "isDefined", "(", ")", ")", "return", "false", ";", "for", "(", "ModelNode", "op", ":", "readOps", ".", "get", "(", "\"result\"", ")", ".", "asList", "(", ")", ")", "{", "if", "(", "\"log-file\"", ".", "equals", "(", "op", ".", "asString", "(", ")", ")", ")", "return", "true", ";", "}", "return", "false", ";", "}" ]
Does the server support log downloads? @param cliGuiCtx The context. @return <code>true</code> if the server supports log downloads, <code>false</code> otherwise.
[ "Does", "the", "server", "support", "log", "downloads?" ]
cfaf0479dcbb2d320a44c5374b93b944ec39fade
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/cli/src/main/java/org/jboss/as/cli/gui/ServerLogsPanel.java#L80-L92
159,104
wildfly/wildfly-core
controller/src/main/java/org/jboss/as/controller/interfaces/InetAddressUtil.java
InetAddressUtil.getLocalHost
public static InetAddress getLocalHost() throws UnknownHostException { InetAddress addr; try { addr = InetAddress.getLocalHost(); } catch (ArrayIndexOutOfBoundsException e) { //this is workaround for mac osx bug see AS7-3223 and JGRP-1404 addr = InetAddress.getByName(null); } return addr; }
java
public static InetAddress getLocalHost() throws UnknownHostException { InetAddress addr; try { addr = InetAddress.getLocalHost(); } catch (ArrayIndexOutOfBoundsException e) { //this is workaround for mac osx bug see AS7-3223 and JGRP-1404 addr = InetAddress.getByName(null); } return addr; }
[ "public", "static", "InetAddress", "getLocalHost", "(", ")", "throws", "UnknownHostException", "{", "InetAddress", "addr", ";", "try", "{", "addr", "=", "InetAddress", ".", "getLocalHost", "(", ")", ";", "}", "catch", "(", "ArrayIndexOutOfBoundsException", "e", ")", "{", "//this is workaround for mac osx bug see AS7-3223 and JGRP-1404", "addr", "=", "InetAddress", ".", "getByName", "(", "null", ")", ";", "}", "return", "addr", ";", "}" ]
Methods returns InetAddress for localhost @return InetAddress of the localhost @throws UnknownHostException if localhost could not be resolved
[ "Methods", "returns", "InetAddress", "for", "localhost" ]
cfaf0479dcbb2d320a44c5374b93b944ec39fade
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/interfaces/InetAddressUtil.java#L44-L52
159,105
wildfly/wildfly-core
controller/src/main/java/org/jboss/as/controller/persistence/ConfigurationFile.java
ConfigurationFile.getBootFile
public File getBootFile() { if (bootFile == null) { synchronized (this) { if (bootFile == null) { if (bootFileReset) { //Reset the done bootup and the sequence, so that the old file we are reloading from // overwrites the main file on successful boot, and history is reset as when booting new doneBootup.set(false); sequence.set(0); } // If it's a reload with no new boot file name and we're persisting our config, we boot from mainFile, // as that's where we persist if (bootFileReset && !interactionPolicy.isReadOnly() && newReloadBootFileName == null) { // we boot from mainFile bootFile = mainFile; } else { // It's either first boot, or a reload where we're not persisting our config or with a new boot file. // So we need to figure out which file we're meant to boot from String bootFileName = this.bootFileName; if (newReloadBootFileName != null) { //A non-null new boot file on reload takes precedence over the reloadUsingLast functionality //A new boot file was specified. Use that and reset the new name to null bootFileName = newReloadBootFileName; newReloadBootFileName = null; } else if (interactionPolicy.isReadOnly() && reloadUsingLast) { //If we were reloaded, and it is not a persistent configuration we want to use the last from the history bootFileName = LAST; } boolean usingRawFile = bootFileName.equals(rawFileName); if (usingRawFile) { bootFile = mainFile; } else { bootFile = determineBootFile(configurationDir, bootFileName); try { bootFile = bootFile.getCanonicalFile(); } catch (IOException ioe) { throw ControllerLogger.ROOT_LOGGER.canonicalBootFileNotFound(ioe, bootFile); } } if (!bootFile.exists()) { if (!usingRawFile) { // TODO there's no reason usingRawFile should be an exception, // but the test infrastructure stuff is built around an assumption // that ConfigurationFile doesn't fail if test files are not // in the normal spot if (bootFileReset || interactionPolicy.isRequireExisting()) { throw ControllerLogger.ROOT_LOGGER.fileNotFound(bootFile.getAbsolutePath()); } } // Create it for the NEW and DISCARD cases if (!bootFileReset && !interactionPolicy.isRequireExisting()) { createBootFile(bootFile); } } else if (!bootFileReset) { if (interactionPolicy.isRejectExisting() && bootFile.length() > 0) { throw ControllerLogger.ROOT_LOGGER.rejectEmptyConfig(bootFile.getAbsolutePath()); } else if (interactionPolicy.isRemoveExisting() && bootFile.length() > 0) { if (!bootFile.delete()) { throw ControllerLogger.ROOT_LOGGER.cannotDelete(bootFile.getAbsoluteFile()); } createBootFile(bootFile); } } // else after first boot we want the file to exist } } } } return bootFile; }
java
public File getBootFile() { if (bootFile == null) { synchronized (this) { if (bootFile == null) { if (bootFileReset) { //Reset the done bootup and the sequence, so that the old file we are reloading from // overwrites the main file on successful boot, and history is reset as when booting new doneBootup.set(false); sequence.set(0); } // If it's a reload with no new boot file name and we're persisting our config, we boot from mainFile, // as that's where we persist if (bootFileReset && !interactionPolicy.isReadOnly() && newReloadBootFileName == null) { // we boot from mainFile bootFile = mainFile; } else { // It's either first boot, or a reload where we're not persisting our config or with a new boot file. // So we need to figure out which file we're meant to boot from String bootFileName = this.bootFileName; if (newReloadBootFileName != null) { //A non-null new boot file on reload takes precedence over the reloadUsingLast functionality //A new boot file was specified. Use that and reset the new name to null bootFileName = newReloadBootFileName; newReloadBootFileName = null; } else if (interactionPolicy.isReadOnly() && reloadUsingLast) { //If we were reloaded, and it is not a persistent configuration we want to use the last from the history bootFileName = LAST; } boolean usingRawFile = bootFileName.equals(rawFileName); if (usingRawFile) { bootFile = mainFile; } else { bootFile = determineBootFile(configurationDir, bootFileName); try { bootFile = bootFile.getCanonicalFile(); } catch (IOException ioe) { throw ControllerLogger.ROOT_LOGGER.canonicalBootFileNotFound(ioe, bootFile); } } if (!bootFile.exists()) { if (!usingRawFile) { // TODO there's no reason usingRawFile should be an exception, // but the test infrastructure stuff is built around an assumption // that ConfigurationFile doesn't fail if test files are not // in the normal spot if (bootFileReset || interactionPolicy.isRequireExisting()) { throw ControllerLogger.ROOT_LOGGER.fileNotFound(bootFile.getAbsolutePath()); } } // Create it for the NEW and DISCARD cases if (!bootFileReset && !interactionPolicy.isRequireExisting()) { createBootFile(bootFile); } } else if (!bootFileReset) { if (interactionPolicy.isRejectExisting() && bootFile.length() > 0) { throw ControllerLogger.ROOT_LOGGER.rejectEmptyConfig(bootFile.getAbsolutePath()); } else if (interactionPolicy.isRemoveExisting() && bootFile.length() > 0) { if (!bootFile.delete()) { throw ControllerLogger.ROOT_LOGGER.cannotDelete(bootFile.getAbsoluteFile()); } createBootFile(bootFile); } } // else after first boot we want the file to exist } } } } return bootFile; }
[ "public", "File", "getBootFile", "(", ")", "{", "if", "(", "bootFile", "==", "null", ")", "{", "synchronized", "(", "this", ")", "{", "if", "(", "bootFile", "==", "null", ")", "{", "if", "(", "bootFileReset", ")", "{", "//Reset the done bootup and the sequence, so that the old file we are reloading from", "// overwrites the main file on successful boot, and history is reset as when booting new", "doneBootup", ".", "set", "(", "false", ")", ";", "sequence", ".", "set", "(", "0", ")", ";", "}", "// If it's a reload with no new boot file name and we're persisting our config, we boot from mainFile,", "// as that's where we persist", "if", "(", "bootFileReset", "&&", "!", "interactionPolicy", ".", "isReadOnly", "(", ")", "&&", "newReloadBootFileName", "==", "null", ")", "{", "// we boot from mainFile", "bootFile", "=", "mainFile", ";", "}", "else", "{", "// It's either first boot, or a reload where we're not persisting our config or with a new boot file.", "// So we need to figure out which file we're meant to boot from", "String", "bootFileName", "=", "this", ".", "bootFileName", ";", "if", "(", "newReloadBootFileName", "!=", "null", ")", "{", "//A non-null new boot file on reload takes precedence over the reloadUsingLast functionality", "//A new boot file was specified. Use that and reset the new name to null", "bootFileName", "=", "newReloadBootFileName", ";", "newReloadBootFileName", "=", "null", ";", "}", "else", "if", "(", "interactionPolicy", ".", "isReadOnly", "(", ")", "&&", "reloadUsingLast", ")", "{", "//If we were reloaded, and it is not a persistent configuration we want to use the last from the history", "bootFileName", "=", "LAST", ";", "}", "boolean", "usingRawFile", "=", "bootFileName", ".", "equals", "(", "rawFileName", ")", ";", "if", "(", "usingRawFile", ")", "{", "bootFile", "=", "mainFile", ";", "}", "else", "{", "bootFile", "=", "determineBootFile", "(", "configurationDir", ",", "bootFileName", ")", ";", "try", "{", "bootFile", "=", "bootFile", ".", "getCanonicalFile", "(", ")", ";", "}", "catch", "(", "IOException", "ioe", ")", "{", "throw", "ControllerLogger", ".", "ROOT_LOGGER", ".", "canonicalBootFileNotFound", "(", "ioe", ",", "bootFile", ")", ";", "}", "}", "if", "(", "!", "bootFile", ".", "exists", "(", ")", ")", "{", "if", "(", "!", "usingRawFile", ")", "{", "// TODO there's no reason usingRawFile should be an exception,", "// but the test infrastructure stuff is built around an assumption", "// that ConfigurationFile doesn't fail if test files are not", "// in the normal spot", "if", "(", "bootFileReset", "||", "interactionPolicy", ".", "isRequireExisting", "(", ")", ")", "{", "throw", "ControllerLogger", ".", "ROOT_LOGGER", ".", "fileNotFound", "(", "bootFile", ".", "getAbsolutePath", "(", ")", ")", ";", "}", "}", "// Create it for the NEW and DISCARD cases", "if", "(", "!", "bootFileReset", "&&", "!", "interactionPolicy", ".", "isRequireExisting", "(", ")", ")", "{", "createBootFile", "(", "bootFile", ")", ";", "}", "}", "else", "if", "(", "!", "bootFileReset", ")", "{", "if", "(", "interactionPolicy", ".", "isRejectExisting", "(", ")", "&&", "bootFile", ".", "length", "(", ")", ">", "0", ")", "{", "throw", "ControllerLogger", ".", "ROOT_LOGGER", ".", "rejectEmptyConfig", "(", "bootFile", ".", "getAbsolutePath", "(", ")", ")", ";", "}", "else", "if", "(", "interactionPolicy", ".", "isRemoveExisting", "(", ")", "&&", "bootFile", ".", "length", "(", ")", ">", "0", ")", "{", "if", "(", "!", "bootFile", ".", "delete", "(", ")", ")", "{", "throw", "ControllerLogger", ".", "ROOT_LOGGER", ".", "cannotDelete", "(", "bootFile", ".", "getAbsoluteFile", "(", ")", ")", ";", "}", "createBootFile", "(", "bootFile", ")", ";", "}", "}", "// else after first boot we want the file to exist", "}", "}", "}", "}", "return", "bootFile", ";", "}" ]
Gets the file from which boot operations should be parsed. @return the file. Will not be {@code null}
[ "Gets", "the", "file", "from", "which", "boot", "operations", "should", "be", "parsed", "." ]
cfaf0479dcbb2d320a44c5374b93b944ec39fade
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/persistence/ConfigurationFile.java#L217-L287
159,106
wildfly/wildfly-core
controller/src/main/java/org/jboss/as/controller/persistence/ConfigurationFile.java
ConfigurationFile.successfulBoot
void successfulBoot() throws ConfigurationPersistenceException { synchronized (this) { if (doneBootup.get()) { return; } final File copySource; if (!interactionPolicy.isReadOnly()) { copySource = mainFile; } else { if ( FilePersistenceUtils.isParentFolderWritable(mainFile) ) { copySource = new File(mainFile.getParentFile(), mainFile.getName() + ".boot"); } else{ copySource = new File(configurationDir, mainFile.getName() + ".boot"); } FilePersistenceUtils.deleteFile(copySource); } try { if (!bootFile.equals(copySource)) { FilePersistenceUtils.copyFile(bootFile, copySource); } createHistoryDirectory(); final File historyBase = new File(historyRoot, mainFile.getName()); lastFile = addSuffixToFile(historyBase, LAST); final File boot = addSuffixToFile(historyBase, BOOT); final File initial = addSuffixToFile(historyBase, INITIAL); if (!initial.exists()) { FilePersistenceUtils.copyFile(copySource, initial); } FilePersistenceUtils.copyFile(copySource, lastFile); FilePersistenceUtils.copyFile(copySource, boot); } catch (IOException e) { throw ControllerLogger.ROOT_LOGGER.failedToCreateConfigurationBackup(e, bootFile); } finally { if (interactionPolicy.isReadOnly()) { //Delete the temporary file try { FilePersistenceUtils.deleteFile(copySource); } catch (Exception ignore) { } } } doneBootup.set(true); } }
java
void successfulBoot() throws ConfigurationPersistenceException { synchronized (this) { if (doneBootup.get()) { return; } final File copySource; if (!interactionPolicy.isReadOnly()) { copySource = mainFile; } else { if ( FilePersistenceUtils.isParentFolderWritable(mainFile) ) { copySource = new File(mainFile.getParentFile(), mainFile.getName() + ".boot"); } else{ copySource = new File(configurationDir, mainFile.getName() + ".boot"); } FilePersistenceUtils.deleteFile(copySource); } try { if (!bootFile.equals(copySource)) { FilePersistenceUtils.copyFile(bootFile, copySource); } createHistoryDirectory(); final File historyBase = new File(historyRoot, mainFile.getName()); lastFile = addSuffixToFile(historyBase, LAST); final File boot = addSuffixToFile(historyBase, BOOT); final File initial = addSuffixToFile(historyBase, INITIAL); if (!initial.exists()) { FilePersistenceUtils.copyFile(copySource, initial); } FilePersistenceUtils.copyFile(copySource, lastFile); FilePersistenceUtils.copyFile(copySource, boot); } catch (IOException e) { throw ControllerLogger.ROOT_LOGGER.failedToCreateConfigurationBackup(e, bootFile); } finally { if (interactionPolicy.isReadOnly()) { //Delete the temporary file try { FilePersistenceUtils.deleteFile(copySource); } catch (Exception ignore) { } } } doneBootup.set(true); } }
[ "void", "successfulBoot", "(", ")", "throws", "ConfigurationPersistenceException", "{", "synchronized", "(", "this", ")", "{", "if", "(", "doneBootup", ".", "get", "(", ")", ")", "{", "return", ";", "}", "final", "File", "copySource", ";", "if", "(", "!", "interactionPolicy", ".", "isReadOnly", "(", ")", ")", "{", "copySource", "=", "mainFile", ";", "}", "else", "{", "if", "(", "FilePersistenceUtils", ".", "isParentFolderWritable", "(", "mainFile", ")", ")", "{", "copySource", "=", "new", "File", "(", "mainFile", ".", "getParentFile", "(", ")", ",", "mainFile", ".", "getName", "(", ")", "+", "\".boot\"", ")", ";", "}", "else", "{", "copySource", "=", "new", "File", "(", "configurationDir", ",", "mainFile", ".", "getName", "(", ")", "+", "\".boot\"", ")", ";", "}", "FilePersistenceUtils", ".", "deleteFile", "(", "copySource", ")", ";", "}", "try", "{", "if", "(", "!", "bootFile", ".", "equals", "(", "copySource", ")", ")", "{", "FilePersistenceUtils", ".", "copyFile", "(", "bootFile", ",", "copySource", ")", ";", "}", "createHistoryDirectory", "(", ")", ";", "final", "File", "historyBase", "=", "new", "File", "(", "historyRoot", ",", "mainFile", ".", "getName", "(", ")", ")", ";", "lastFile", "=", "addSuffixToFile", "(", "historyBase", ",", "LAST", ")", ";", "final", "File", "boot", "=", "addSuffixToFile", "(", "historyBase", ",", "BOOT", ")", ";", "final", "File", "initial", "=", "addSuffixToFile", "(", "historyBase", ",", "INITIAL", ")", ";", "if", "(", "!", "initial", ".", "exists", "(", ")", ")", "{", "FilePersistenceUtils", ".", "copyFile", "(", "copySource", ",", "initial", ")", ";", "}", "FilePersistenceUtils", ".", "copyFile", "(", "copySource", ",", "lastFile", ")", ";", "FilePersistenceUtils", ".", "copyFile", "(", "copySource", ",", "boot", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "ControllerLogger", ".", "ROOT_LOGGER", ".", "failedToCreateConfigurationBackup", "(", "e", ",", "bootFile", ")", ";", "}", "finally", "{", "if", "(", "interactionPolicy", ".", "isReadOnly", "(", ")", ")", "{", "//Delete the temporary file", "try", "{", "FilePersistenceUtils", ".", "deleteFile", "(", "copySource", ")", ";", "}", "catch", "(", "Exception", "ignore", ")", "{", "}", "}", "}", "doneBootup", ".", "set", "(", "true", ")", ";", "}", "}" ]
Notification that boot has completed successfully and the configuration history should be updated
[ "Notification", "that", "boot", "has", "completed", "successfully", "and", "the", "configuration", "history", "should", "be", "updated" ]
cfaf0479dcbb2d320a44c5374b93b944ec39fade
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/persistence/ConfigurationFile.java#L483-L533
159,107
wildfly/wildfly-core
controller/src/main/java/org/jboss/as/controller/persistence/ConfigurationFile.java
ConfigurationFile.backup
void backup() throws ConfigurationPersistenceException { if (!doneBootup.get()) { return; } try { if (!interactionPolicy.isReadOnly()) { //Move the main file to the versioned history moveFile(mainFile, getVersionedFile(mainFile)); } else { //Copy the Last file to the versioned history moveFile(lastFile, getVersionedFile(mainFile)); } int seq = sequence.get(); // delete unwanted backup files int currentHistoryLength = getInteger(CURRENT_HISTORY_LENGTH_PROPERTY, CURRENT_HISTORY_LENGTH, 0); if (seq > currentHistoryLength) { for (int k = seq - currentHistoryLength; k > 0; k--) { File delete = getVersionedFile(mainFile, k); if (! delete.exists()) { break; } delete.delete(); } } } catch (IOException e) { throw ControllerLogger.ROOT_LOGGER.failedToBackup(e, mainFile); } }
java
void backup() throws ConfigurationPersistenceException { if (!doneBootup.get()) { return; } try { if (!interactionPolicy.isReadOnly()) { //Move the main file to the versioned history moveFile(mainFile, getVersionedFile(mainFile)); } else { //Copy the Last file to the versioned history moveFile(lastFile, getVersionedFile(mainFile)); } int seq = sequence.get(); // delete unwanted backup files int currentHistoryLength = getInteger(CURRENT_HISTORY_LENGTH_PROPERTY, CURRENT_HISTORY_LENGTH, 0); if (seq > currentHistoryLength) { for (int k = seq - currentHistoryLength; k > 0; k--) { File delete = getVersionedFile(mainFile, k); if (! delete.exists()) { break; } delete.delete(); } } } catch (IOException e) { throw ControllerLogger.ROOT_LOGGER.failedToBackup(e, mainFile); } }
[ "void", "backup", "(", ")", "throws", "ConfigurationPersistenceException", "{", "if", "(", "!", "doneBootup", ".", "get", "(", ")", ")", "{", "return", ";", "}", "try", "{", "if", "(", "!", "interactionPolicy", ".", "isReadOnly", "(", ")", ")", "{", "//Move the main file to the versioned history", "moveFile", "(", "mainFile", ",", "getVersionedFile", "(", "mainFile", ")", ")", ";", "}", "else", "{", "//Copy the Last file to the versioned history", "moveFile", "(", "lastFile", ",", "getVersionedFile", "(", "mainFile", ")", ")", ";", "}", "int", "seq", "=", "sequence", ".", "get", "(", ")", ";", "// delete unwanted backup files", "int", "currentHistoryLength", "=", "getInteger", "(", "CURRENT_HISTORY_LENGTH_PROPERTY", ",", "CURRENT_HISTORY_LENGTH", ",", "0", ")", ";", "if", "(", "seq", ">", "currentHistoryLength", ")", "{", "for", "(", "int", "k", "=", "seq", "-", "currentHistoryLength", ";", "k", ">", "0", ";", "k", "--", ")", "{", "File", "delete", "=", "getVersionedFile", "(", "mainFile", ",", "k", ")", ";", "if", "(", "!", "delete", ".", "exists", "(", ")", ")", "{", "break", ";", "}", "delete", ".", "delete", "(", ")", ";", "}", "}", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "ControllerLogger", ".", "ROOT_LOGGER", ".", "failedToBackup", "(", "e", ",", "mainFile", ")", ";", "}", "}" ]
Backup the current version of the configuration to the versioned configuration history
[ "Backup", "the", "current", "version", "of", "the", "configuration", "to", "the", "versioned", "configuration", "history" ]
cfaf0479dcbb2d320a44c5374b93b944ec39fade
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/persistence/ConfigurationFile.java#L537-L564
159,108
wildfly/wildfly-core
controller/src/main/java/org/jboss/as/controller/persistence/ConfigurationFile.java
ConfigurationFile.commitTempFile
void commitTempFile(File temp) throws ConfigurationPersistenceException { if (!doneBootup.get()) { return; } if (!interactionPolicy.isReadOnly()) { FilePersistenceUtils.moveTempFileToMain(temp, mainFile); } else { FilePersistenceUtils.moveTempFileToMain(temp, lastFile); } }
java
void commitTempFile(File temp) throws ConfigurationPersistenceException { if (!doneBootup.get()) { return; } if (!interactionPolicy.isReadOnly()) { FilePersistenceUtils.moveTempFileToMain(temp, mainFile); } else { FilePersistenceUtils.moveTempFileToMain(temp, lastFile); } }
[ "void", "commitTempFile", "(", "File", "temp", ")", "throws", "ConfigurationPersistenceException", "{", "if", "(", "!", "doneBootup", ".", "get", "(", ")", ")", "{", "return", ";", "}", "if", "(", "!", "interactionPolicy", ".", "isReadOnly", "(", ")", ")", "{", "FilePersistenceUtils", ".", "moveTempFileToMain", "(", "temp", ",", "mainFile", ")", ";", "}", "else", "{", "FilePersistenceUtils", ".", "moveTempFileToMain", "(", "temp", ",", "lastFile", ")", ";", "}", "}" ]
Commit the contents of the given temp file to either the main file, or, if we are not persisting to the main file, to the .last file in the configuration history @param temp temp file containing the latest configuration. Will not be {@code null} @throws ConfigurationPersistenceException
[ "Commit", "the", "contents", "of", "the", "given", "temp", "file", "to", "either", "the", "main", "file", "or", "if", "we", "are", "not", "persisting", "to", "the", "main", "file", "to", "the", ".", "last", "file", "in", "the", "configuration", "history" ]
cfaf0479dcbb2d320a44c5374b93b944ec39fade
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/persistence/ConfigurationFile.java#L572-L581
159,109
wildfly/wildfly-core
controller/src/main/java/org/jboss/as/controller/persistence/ConfigurationFile.java
ConfigurationFile.fileWritten
void fileWritten() throws ConfigurationPersistenceException { if (!doneBootup.get() || interactionPolicy.isReadOnly()) { return; } try { FilePersistenceUtils.copyFile(mainFile, lastFile); } catch (IOException e) { throw ControllerLogger.ROOT_LOGGER.failedToBackup(e, mainFile); } }
java
void fileWritten() throws ConfigurationPersistenceException { if (!doneBootup.get() || interactionPolicy.isReadOnly()) { return; } try { FilePersistenceUtils.copyFile(mainFile, lastFile); } catch (IOException e) { throw ControllerLogger.ROOT_LOGGER.failedToBackup(e, mainFile); } }
[ "void", "fileWritten", "(", ")", "throws", "ConfigurationPersistenceException", "{", "if", "(", "!", "doneBootup", ".", "get", "(", ")", "||", "interactionPolicy", ".", "isReadOnly", "(", ")", ")", "{", "return", ";", "}", "try", "{", "FilePersistenceUtils", ".", "copyFile", "(", "mainFile", ",", "lastFile", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "ControllerLogger", ".", "ROOT_LOGGER", ".", "failedToBackup", "(", "e", ",", "mainFile", ")", ";", "}", "}" ]
Notification that the configuration has been written, and its current content should be stored to the .last file
[ "Notification", "that", "the", "configuration", "has", "been", "written", "and", "its", "current", "content", "should", "be", "stored", "to", "the", ".", "last", "file" ]
cfaf0479dcbb2d320a44c5374b93b944ec39fade
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/persistence/ConfigurationFile.java#L584-L593
159,110
wildfly/wildfly-core
controller/src/main/java/org/jboss/as/controller/persistence/ConfigurationFile.java
ConfigurationFile.deleteRecursive
private void deleteRecursive(final File file) { if (file.isDirectory()) { final String[] files = file.list(); if (files != null) { for (String name : files) { deleteRecursive(new File(file, name)); } } } if (!file.delete()) { ControllerLogger.ROOT_LOGGER.cannotDeleteFileOrDirectory(file); } }
java
private void deleteRecursive(final File file) { if (file.isDirectory()) { final String[] files = file.list(); if (files != null) { for (String name : files) { deleteRecursive(new File(file, name)); } } } if (!file.delete()) { ControllerLogger.ROOT_LOGGER.cannotDeleteFileOrDirectory(file); } }
[ "private", "void", "deleteRecursive", "(", "final", "File", "file", ")", "{", "if", "(", "file", ".", "isDirectory", "(", ")", ")", "{", "final", "String", "[", "]", "files", "=", "file", ".", "list", "(", ")", ";", "if", "(", "files", "!=", "null", ")", "{", "for", "(", "String", "name", ":", "files", ")", "{", "deleteRecursive", "(", "new", "File", "(", "file", ",", "name", ")", ")", ";", "}", "}", "}", "if", "(", "!", "file", ".", "delete", "(", ")", ")", "{", "ControllerLogger", ".", "ROOT_LOGGER", ".", "cannotDeleteFileOrDirectory", "(", "file", ")", ";", "}", "}" ]
note, this just logs an error and doesn't throw as its only used to remove old configuration files, and shouldn't stop boot
[ "note", "this", "just", "logs", "an", "error", "and", "doesn", "t", "throw", "as", "its", "only", "used", "to", "remove", "old", "configuration", "files", "and", "shouldn", "t", "stop", "boot" ]
cfaf0479dcbb2d320a44c5374b93b944ec39fade
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/persistence/ConfigurationFile.java#L714-L727
159,111
wildfly/wildfly-core
controller/src/main/java/org/jboss/as/controller/RestartParentResourceRemoveHandler.java
RestartParentResourceRemoveHandler.updateModel
protected void updateModel(final OperationContext context, final ModelNode operation) throws OperationFailedException { // verify that the resource exist before removing it context.readResource(PathAddress.EMPTY_ADDRESS, false); Resource resource = context.removeResource(PathAddress.EMPTY_ADDRESS); recordCapabilitiesAndRequirements(context, operation, resource); }
java
protected void updateModel(final OperationContext context, final ModelNode operation) throws OperationFailedException { // verify that the resource exist before removing it context.readResource(PathAddress.EMPTY_ADDRESS, false); Resource resource = context.removeResource(PathAddress.EMPTY_ADDRESS); recordCapabilitiesAndRequirements(context, operation, resource); }
[ "protected", "void", "updateModel", "(", "final", "OperationContext", "context", ",", "final", "ModelNode", "operation", ")", "throws", "OperationFailedException", "{", "// verify that the resource exist before removing it", "context", ".", "readResource", "(", "PathAddress", ".", "EMPTY_ADDRESS", ",", "false", ")", ";", "Resource", "resource", "=", "context", ".", "removeResource", "(", "PathAddress", ".", "EMPTY_ADDRESS", ")", ";", "recordCapabilitiesAndRequirements", "(", "context", ",", "operation", ",", "resource", ")", ";", "}" ]
Performs the update to the persistent configuration model. This default implementation simply removes the targeted resource. @param context the operation context @param operation the operation @throws OperationFailedException if there is a problem updating the model
[ "Performs", "the", "update", "to", "the", "persistent", "configuration", "model", ".", "This", "default", "implementation", "simply", "removes", "the", "targeted", "resource", "." ]
cfaf0479dcbb2d320a44c5374b93b944ec39fade
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/RestartParentResourceRemoveHandler.java#L62-L67
159,112
wildfly/wildfly-core
controller/src/main/java/org/jboss/as/controller/AbstractOperationContext.java
AbstractOperationContext.executeOperation
ResultAction executeOperation() { assert isControllingThread(); try { /** Execution has begun */ executing = true; processStages(); if (resultAction == ResultAction.KEEP) { report(MessageSeverity.INFO, ControllerLogger.ROOT_LOGGER.operationSucceeded()); } else { report(MessageSeverity.INFO, ControllerLogger.ROOT_LOGGER.operationRollingBack()); } } catch (RuntimeException e) { handleUncaughtException(e); ControllerLogger.MGMT_OP_LOGGER.unexpectedOperationExecutionException(e, controllerOperations); } finally { // On failure close any attached response streams if (resultAction != ResultAction.KEEP && !isBooting()) { synchronized (this) { if (responseStreams != null) { int i = 0; for (OperationResponse.StreamEntry is : responseStreams.values()) { try { is.getStream().close(); } catch (Exception e) { ControllerLogger.MGMT_OP_LOGGER.debugf(e, "Failed closing stream at index %d", i); } i++; } responseStreams.clear(); } } } } return resultAction; }
java
ResultAction executeOperation() { assert isControllingThread(); try { /** Execution has begun */ executing = true; processStages(); if (resultAction == ResultAction.KEEP) { report(MessageSeverity.INFO, ControllerLogger.ROOT_LOGGER.operationSucceeded()); } else { report(MessageSeverity.INFO, ControllerLogger.ROOT_LOGGER.operationRollingBack()); } } catch (RuntimeException e) { handleUncaughtException(e); ControllerLogger.MGMT_OP_LOGGER.unexpectedOperationExecutionException(e, controllerOperations); } finally { // On failure close any attached response streams if (resultAction != ResultAction.KEEP && !isBooting()) { synchronized (this) { if (responseStreams != null) { int i = 0; for (OperationResponse.StreamEntry is : responseStreams.values()) { try { is.getStream().close(); } catch (Exception e) { ControllerLogger.MGMT_OP_LOGGER.debugf(e, "Failed closing stream at index %d", i); } i++; } responseStreams.clear(); } } } } return resultAction; }
[ "ResultAction", "executeOperation", "(", ")", "{", "assert", "isControllingThread", "(", ")", ";", "try", "{", "/** Execution has begun */", "executing", "=", "true", ";", "processStages", "(", ")", ";", "if", "(", "resultAction", "==", "ResultAction", ".", "KEEP", ")", "{", "report", "(", "MessageSeverity", ".", "INFO", ",", "ControllerLogger", ".", "ROOT_LOGGER", ".", "operationSucceeded", "(", ")", ")", ";", "}", "else", "{", "report", "(", "MessageSeverity", ".", "INFO", ",", "ControllerLogger", ".", "ROOT_LOGGER", ".", "operationRollingBack", "(", ")", ")", ";", "}", "}", "catch", "(", "RuntimeException", "e", ")", "{", "handleUncaughtException", "(", "e", ")", ";", "ControllerLogger", ".", "MGMT_OP_LOGGER", ".", "unexpectedOperationExecutionException", "(", "e", ",", "controllerOperations", ")", ";", "}", "finally", "{", "// On failure close any attached response streams", "if", "(", "resultAction", "!=", "ResultAction", ".", "KEEP", "&&", "!", "isBooting", "(", ")", ")", "{", "synchronized", "(", "this", ")", "{", "if", "(", "responseStreams", "!=", "null", ")", "{", "int", "i", "=", "0", ";", "for", "(", "OperationResponse", ".", "StreamEntry", "is", ":", "responseStreams", ".", "values", "(", ")", ")", "{", "try", "{", "is", ".", "getStream", "(", ")", ".", "close", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "ControllerLogger", ".", "MGMT_OP_LOGGER", ".", "debugf", "(", "e", ",", "\"Failed closing stream at index %d\"", ",", "i", ")", ";", "}", "i", "++", ";", "}", "responseStreams", ".", "clear", "(", ")", ";", "}", "}", "}", "}", "return", "resultAction", ";", "}" ]
Package-protected method used to initiate operation execution. @return the result action
[ "Package", "-", "protected", "method", "used", "to", "initiate", "operation", "execution", "." ]
cfaf0479dcbb2d320a44c5374b93b944ec39fade
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/AbstractOperationContext.java#L460-L499
159,113
wildfly/wildfly-core
controller/src/main/java/org/jboss/as/controller/AbstractOperationContext.java
AbstractOperationContext.logAuditRecord
void logAuditRecord() { trackConfigurationChange(); if (!auditLogged) { try { AccessAuditContext accessContext = SecurityActions.currentAccessAuditContext(); Caller caller = getCaller(); auditLogger.log( isReadOnly(), resultAction, caller == null ? null : caller.getName(), accessContext == null ? null : accessContext.getDomainUuid(), accessContext == null ? null : accessContext.getAccessMechanism(), accessContext == null ? null : accessContext.getRemoteAddress(), getModel(), controllerOperations); auditLogged = true; } catch (Exception e) { ControllerLogger.MGMT_OP_LOGGER.failedToUpdateAuditLog(e); } } }
java
void logAuditRecord() { trackConfigurationChange(); if (!auditLogged) { try { AccessAuditContext accessContext = SecurityActions.currentAccessAuditContext(); Caller caller = getCaller(); auditLogger.log( isReadOnly(), resultAction, caller == null ? null : caller.getName(), accessContext == null ? null : accessContext.getDomainUuid(), accessContext == null ? null : accessContext.getAccessMechanism(), accessContext == null ? null : accessContext.getRemoteAddress(), getModel(), controllerOperations); auditLogged = true; } catch (Exception e) { ControllerLogger.MGMT_OP_LOGGER.failedToUpdateAuditLog(e); } } }
[ "void", "logAuditRecord", "(", ")", "{", "trackConfigurationChange", "(", ")", ";", "if", "(", "!", "auditLogged", ")", "{", "try", "{", "AccessAuditContext", "accessContext", "=", "SecurityActions", ".", "currentAccessAuditContext", "(", ")", ";", "Caller", "caller", "=", "getCaller", "(", ")", ";", "auditLogger", ".", "log", "(", "isReadOnly", "(", ")", ",", "resultAction", ",", "caller", "==", "null", "?", "null", ":", "caller", ".", "getName", "(", ")", ",", "accessContext", "==", "null", "?", "null", ":", "accessContext", ".", "getDomainUuid", "(", ")", ",", "accessContext", "==", "null", "?", "null", ":", "accessContext", ".", "getAccessMechanism", "(", ")", ",", "accessContext", "==", "null", "?", "null", ":", "accessContext", ".", "getRemoteAddress", "(", ")", ",", "getModel", "(", ")", ",", "controllerOperations", ")", ";", "auditLogged", "=", "true", ";", "}", "catch", "(", "Exception", "e", ")", "{", "ControllerLogger", ".", "MGMT_OP_LOGGER", ".", "failedToUpdateAuditLog", "(", "e", ")", ";", "}", "}", "}" ]
Log an audit record of this operation.
[ "Log", "an", "audit", "record", "of", "this", "operation", "." ]
cfaf0479dcbb2d320a44c5374b93b944ec39fade
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/AbstractOperationContext.java#L621-L641
159,114
wildfly/wildfly-core
controller/src/main/java/org/jboss/as/controller/AbstractOperationContext.java
AbstractOperationContext.processStages
private void processStages() { // Locate the next step to execute. ModelNode primaryResponse = null; Step step; do { step = steps.get(currentStage).pollFirst(); if (step == null) { if (currentStage == Stage.MODEL && addModelValidationSteps()) { continue; } // No steps remain in this stage; give subclasses a chance to check status // and approve moving to the next stage if (!tryStageCompleted(currentStage)) { // Can't continue resultAction = ResultAction.ROLLBACK; executeResultHandlerPhase(null); return; } // Proceed to the next stage if (currentStage.hasNext()) { currentStage = currentStage.next(); if (currentStage == Stage.VERIFY) { // a change was made to the runtime. Thus, we must wait // for stability before resuming in to verify. try { awaitServiceContainerStability(); } catch (InterruptedException e) { cancelled = true; handleContainerStabilityFailure(primaryResponse, e); executeResultHandlerPhase(null); return; } catch (TimeoutException te) { // The service container is in an unknown state; but we don't require restart // because rollback may allow the container to stabilize. We force require-restart // in the rollback handling if the container cannot stabilize (see OperationContextImpl.releaseStepLocks) //processState.setRestartRequired(); // don't use our restartRequired() method as this is not reversible in rollback handleContainerStabilityFailure(primaryResponse, te); executeResultHandlerPhase(null); return; } } } } else { // The response to the first step is what goes to the outside caller if (primaryResponse == null) { primaryResponse = step.response; } // Execute the step, but make sure we always finalize any steps Throwable toThrow = null; // Whether to return after try/finally boolean exit = false; try { CapabilityRegistry.RuntimeStatus stepStatus = getStepExecutionStatus(step); if (stepStatus == RuntimeCapabilityRegistry.RuntimeStatus.NORMAL) { executeStep(step); } else { String header = stepStatus == RuntimeCapabilityRegistry.RuntimeStatus.RESTART_REQUIRED ? OPERATION_REQUIRES_RESTART : OPERATION_REQUIRES_RELOAD; step.response.get(RESPONSE_HEADERS, header).set(true); } } catch (RuntimeException | Error re) { resultAction = ResultAction.ROLLBACK; toThrow = re; } finally { // See if executeStep put us in a state where we shouldn't do any more if (toThrow != null || !canContinueProcessing()) { // We're done. executeResultHandlerPhase(toThrow); exit = true; // we're on the return path } } if (exit) { return; } } } while (currentStage != Stage.DONE); assert primaryResponse != null; // else ModelControllerImpl executed an op with no steps // All steps ran and canContinueProcessing returned true for the last one, so... executeDoneStage(primaryResponse); }
java
private void processStages() { // Locate the next step to execute. ModelNode primaryResponse = null; Step step; do { step = steps.get(currentStage).pollFirst(); if (step == null) { if (currentStage == Stage.MODEL && addModelValidationSteps()) { continue; } // No steps remain in this stage; give subclasses a chance to check status // and approve moving to the next stage if (!tryStageCompleted(currentStage)) { // Can't continue resultAction = ResultAction.ROLLBACK; executeResultHandlerPhase(null); return; } // Proceed to the next stage if (currentStage.hasNext()) { currentStage = currentStage.next(); if (currentStage == Stage.VERIFY) { // a change was made to the runtime. Thus, we must wait // for stability before resuming in to verify. try { awaitServiceContainerStability(); } catch (InterruptedException e) { cancelled = true; handleContainerStabilityFailure(primaryResponse, e); executeResultHandlerPhase(null); return; } catch (TimeoutException te) { // The service container is in an unknown state; but we don't require restart // because rollback may allow the container to stabilize. We force require-restart // in the rollback handling if the container cannot stabilize (see OperationContextImpl.releaseStepLocks) //processState.setRestartRequired(); // don't use our restartRequired() method as this is not reversible in rollback handleContainerStabilityFailure(primaryResponse, te); executeResultHandlerPhase(null); return; } } } } else { // The response to the first step is what goes to the outside caller if (primaryResponse == null) { primaryResponse = step.response; } // Execute the step, but make sure we always finalize any steps Throwable toThrow = null; // Whether to return after try/finally boolean exit = false; try { CapabilityRegistry.RuntimeStatus stepStatus = getStepExecutionStatus(step); if (stepStatus == RuntimeCapabilityRegistry.RuntimeStatus.NORMAL) { executeStep(step); } else { String header = stepStatus == RuntimeCapabilityRegistry.RuntimeStatus.RESTART_REQUIRED ? OPERATION_REQUIRES_RESTART : OPERATION_REQUIRES_RELOAD; step.response.get(RESPONSE_HEADERS, header).set(true); } } catch (RuntimeException | Error re) { resultAction = ResultAction.ROLLBACK; toThrow = re; } finally { // See if executeStep put us in a state where we shouldn't do any more if (toThrow != null || !canContinueProcessing()) { // We're done. executeResultHandlerPhase(toThrow); exit = true; // we're on the return path } } if (exit) { return; } } } while (currentStage != Stage.DONE); assert primaryResponse != null; // else ModelControllerImpl executed an op with no steps // All steps ran and canContinueProcessing returned true for the last one, so... executeDoneStage(primaryResponse); }
[ "private", "void", "processStages", "(", ")", "{", "// Locate the next step to execute.", "ModelNode", "primaryResponse", "=", "null", ";", "Step", "step", ";", "do", "{", "step", "=", "steps", ".", "get", "(", "currentStage", ")", ".", "pollFirst", "(", ")", ";", "if", "(", "step", "==", "null", ")", "{", "if", "(", "currentStage", "==", "Stage", ".", "MODEL", "&&", "addModelValidationSteps", "(", ")", ")", "{", "continue", ";", "}", "// No steps remain in this stage; give subclasses a chance to check status", "// and approve moving to the next stage", "if", "(", "!", "tryStageCompleted", "(", "currentStage", ")", ")", "{", "// Can't continue", "resultAction", "=", "ResultAction", ".", "ROLLBACK", ";", "executeResultHandlerPhase", "(", "null", ")", ";", "return", ";", "}", "// Proceed to the next stage", "if", "(", "currentStage", ".", "hasNext", "(", ")", ")", "{", "currentStage", "=", "currentStage", ".", "next", "(", ")", ";", "if", "(", "currentStage", "==", "Stage", ".", "VERIFY", ")", "{", "// a change was made to the runtime. Thus, we must wait", "// for stability before resuming in to verify.", "try", "{", "awaitServiceContainerStability", "(", ")", ";", "}", "catch", "(", "InterruptedException", "e", ")", "{", "cancelled", "=", "true", ";", "handleContainerStabilityFailure", "(", "primaryResponse", ",", "e", ")", ";", "executeResultHandlerPhase", "(", "null", ")", ";", "return", ";", "}", "catch", "(", "TimeoutException", "te", ")", "{", "// The service container is in an unknown state; but we don't require restart", "// because rollback may allow the container to stabilize. We force require-restart", "// in the rollback handling if the container cannot stabilize (see OperationContextImpl.releaseStepLocks)", "//processState.setRestartRequired(); // don't use our restartRequired() method as this is not reversible in rollback", "handleContainerStabilityFailure", "(", "primaryResponse", ",", "te", ")", ";", "executeResultHandlerPhase", "(", "null", ")", ";", "return", ";", "}", "}", "}", "}", "else", "{", "// The response to the first step is what goes to the outside caller", "if", "(", "primaryResponse", "==", "null", ")", "{", "primaryResponse", "=", "step", ".", "response", ";", "}", "// Execute the step, but make sure we always finalize any steps", "Throwable", "toThrow", "=", "null", ";", "// Whether to return after try/finally", "boolean", "exit", "=", "false", ";", "try", "{", "CapabilityRegistry", ".", "RuntimeStatus", "stepStatus", "=", "getStepExecutionStatus", "(", "step", ")", ";", "if", "(", "stepStatus", "==", "RuntimeCapabilityRegistry", ".", "RuntimeStatus", ".", "NORMAL", ")", "{", "executeStep", "(", "step", ")", ";", "}", "else", "{", "String", "header", "=", "stepStatus", "==", "RuntimeCapabilityRegistry", ".", "RuntimeStatus", ".", "RESTART_REQUIRED", "?", "OPERATION_REQUIRES_RESTART", ":", "OPERATION_REQUIRES_RELOAD", ";", "step", ".", "response", ".", "get", "(", "RESPONSE_HEADERS", ",", "header", ")", ".", "set", "(", "true", ")", ";", "}", "}", "catch", "(", "RuntimeException", "|", "Error", "re", ")", "{", "resultAction", "=", "ResultAction", ".", "ROLLBACK", ";", "toThrow", "=", "re", ";", "}", "finally", "{", "// See if executeStep put us in a state where we shouldn't do any more", "if", "(", "toThrow", "!=", "null", "||", "!", "canContinueProcessing", "(", ")", ")", "{", "// We're done.", "executeResultHandlerPhase", "(", "toThrow", ")", ";", "exit", "=", "true", ";", "// we're on the return path", "}", "}", "if", "(", "exit", ")", "{", "return", ";", "}", "}", "}", "while", "(", "currentStage", "!=", "Stage", ".", "DONE", ")", ";", "assert", "primaryResponse", "!=", "null", ";", "// else ModelControllerImpl executed an op with no steps", "// All steps ran and canContinueProcessing returned true for the last one, so...", "executeDoneStage", "(", "primaryResponse", ")", ";", "}" ]
Perform the work of processing the various OperationContext.Stage queues, and then the DONE stage.
[ "Perform", "the", "work", "of", "processing", "the", "various", "OperationContext", ".", "Stage", "queues", "and", "then", "the", "DONE", "stage", "." ]
cfaf0479dcbb2d320a44c5374b93b944ec39fade
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/AbstractOperationContext.java#L687-L770
159,115
wildfly/wildfly-core
controller/src/main/java/org/jboss/as/controller/AbstractOperationContext.java
AbstractOperationContext.checkUndefinedNotification
private void checkUndefinedNotification(Notification notification) { String type = notification.getType(); PathAddress source = notification.getSource(); Map<String, NotificationEntry> descriptions = getRootResourceRegistration().getNotificationDescriptions(source, true); if (!descriptions.keySet().contains(type)) { missingNotificationDescriptionWarnings.add(ControllerLogger.ROOT_LOGGER.notificationIsNotDescribed(type, source)); } }
java
private void checkUndefinedNotification(Notification notification) { String type = notification.getType(); PathAddress source = notification.getSource(); Map<String, NotificationEntry> descriptions = getRootResourceRegistration().getNotificationDescriptions(source, true); if (!descriptions.keySet().contains(type)) { missingNotificationDescriptionWarnings.add(ControllerLogger.ROOT_LOGGER.notificationIsNotDescribed(type, source)); } }
[ "private", "void", "checkUndefinedNotification", "(", "Notification", "notification", ")", "{", "String", "type", "=", "notification", ".", "getType", "(", ")", ";", "PathAddress", "source", "=", "notification", ".", "getSource", "(", ")", ";", "Map", "<", "String", ",", "NotificationEntry", ">", "descriptions", "=", "getRootResourceRegistration", "(", ")", ".", "getNotificationDescriptions", "(", "source", ",", "true", ")", ";", "if", "(", "!", "descriptions", ".", "keySet", "(", ")", ".", "contains", "(", "type", ")", ")", "{", "missingNotificationDescriptionWarnings", ".", "add", "(", "ControllerLogger", ".", "ROOT_LOGGER", ".", "notificationIsNotDescribed", "(", "type", ",", "source", ")", ")", ";", "}", "}" ]
Check that each emitted notification is properly described by its source.
[ "Check", "that", "each", "emitted", "notification", "is", "properly", "described", "by", "its", "source", "." ]
cfaf0479dcbb2d320a44c5374b93b944ec39fade
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/AbstractOperationContext.java#L939-L946
159,116
wildfly/wildfly-core
controller/src/main/java/org/jboss/as/controller/AbstractOperationContext.java
AbstractOperationContext.getFailedResultAction
private ResultAction getFailedResultAction(Throwable cause) { if (currentStage == Stage.MODEL || cancelled || isRollbackOnRuntimeFailure() || isRollbackOnly() || (cause != null && !(cause instanceof OperationFailedException))) { return ResultAction.ROLLBACK; } return ResultAction.KEEP; }
java
private ResultAction getFailedResultAction(Throwable cause) { if (currentStage == Stage.MODEL || cancelled || isRollbackOnRuntimeFailure() || isRollbackOnly() || (cause != null && !(cause instanceof OperationFailedException))) { return ResultAction.ROLLBACK; } return ResultAction.KEEP; }
[ "private", "ResultAction", "getFailedResultAction", "(", "Throwable", "cause", ")", "{", "if", "(", "currentStage", "==", "Stage", ".", "MODEL", "||", "cancelled", "||", "isRollbackOnRuntimeFailure", "(", ")", "||", "isRollbackOnly", "(", ")", "||", "(", "cause", "!=", "null", "&&", "!", "(", "cause", "instanceof", "OperationFailedException", ")", ")", ")", "{", "return", "ResultAction", ".", "ROLLBACK", ";", "}", "return", "ResultAction", ".", "KEEP", ";", "}" ]
Decide whether failure should trigger a rollback. @param cause the cause of the failure, or {@code null} if failure is not the result of catching a throwable @return the result action
[ "Decide", "whether", "failure", "should", "trigger", "a", "rollback", "." ]
cfaf0479dcbb2d320a44c5374b93b944ec39fade
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/AbstractOperationContext.java#L1117-L1123
159,117
wildfly/wildfly-core
host-controller/src/main/java/org/jboss/as/domain/controller/plan/ServerUpdatePolicy.java
ServerUpdatePolicy.canUpdateServer
public boolean canUpdateServer(ServerIdentity server) { if (!serverGroupName.equals(server.getServerGroupName()) || !servers.contains(server)) { throw DomainControllerLogger.HOST_CONTROLLER_LOGGER.unknownServer(server); } if (!parent.canChildProceed()) return false; synchronized (this) { return failureCount <= maxFailed; } }
java
public boolean canUpdateServer(ServerIdentity server) { if (!serverGroupName.equals(server.getServerGroupName()) || !servers.contains(server)) { throw DomainControllerLogger.HOST_CONTROLLER_LOGGER.unknownServer(server); } if (!parent.canChildProceed()) return false; synchronized (this) { return failureCount <= maxFailed; } }
[ "public", "boolean", "canUpdateServer", "(", "ServerIdentity", "server", ")", "{", "if", "(", "!", "serverGroupName", ".", "equals", "(", "server", ".", "getServerGroupName", "(", ")", ")", "||", "!", "servers", ".", "contains", "(", "server", ")", ")", "{", "throw", "DomainControllerLogger", ".", "HOST_CONTROLLER_LOGGER", ".", "unknownServer", "(", "server", ")", ";", "}", "if", "(", "!", "parent", ".", "canChildProceed", "(", ")", ")", "return", "false", ";", "synchronized", "(", "this", ")", "{", "return", "failureCount", "<=", "maxFailed", ";", "}", "}" ]
Gets whether the given server can be updated. @param server the id of the server. Cannot be <code>null</code> @return <code>true</code> if the server can be updated; <code>false</code> if the update should be cancelled @throws IllegalStateException if this policy is not expecting a request to update the given server
[ "Gets", "whether", "the", "given", "server", "can", "be", "updated", "." ]
cfaf0479dcbb2d320a44c5374b93b944ec39fade
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/host-controller/src/main/java/org/jboss/as/domain/controller/plan/ServerUpdatePolicy.java#L111-L122
159,118
wildfly/wildfly-core
host-controller/src/main/java/org/jboss/as/domain/controller/plan/ServerUpdatePolicy.java
ServerUpdatePolicy.recordServerResult
public void recordServerResult(ServerIdentity server, ModelNode response) { if (!serverGroupName.equals(server.getServerGroupName()) || !servers.contains(server)) { throw DomainControllerLogger.HOST_CONTROLLER_LOGGER.unknownServer(server); } boolean serverFailed = response.has(FAILURE_DESCRIPTION); DomainControllerLogger.HOST_CONTROLLER_LOGGER.tracef("Recording server result for '%s': failed = %s", server, server); synchronized (this) { int previousFailed = failureCount; if (serverFailed) { failureCount++; } else { successCount++; } if (previousFailed <= maxFailed) { if (!serverFailed && (successCount + failureCount) == servers.size()) { // All results are in; notify parent of success parent.recordServerGroupResult(serverGroupName, false); } else if (serverFailed && failureCount > maxFailed) { parent.recordServerGroupResult(serverGroupName, true); } } } }
java
public void recordServerResult(ServerIdentity server, ModelNode response) { if (!serverGroupName.equals(server.getServerGroupName()) || !servers.contains(server)) { throw DomainControllerLogger.HOST_CONTROLLER_LOGGER.unknownServer(server); } boolean serverFailed = response.has(FAILURE_DESCRIPTION); DomainControllerLogger.HOST_CONTROLLER_LOGGER.tracef("Recording server result for '%s': failed = %s", server, server); synchronized (this) { int previousFailed = failureCount; if (serverFailed) { failureCount++; } else { successCount++; } if (previousFailed <= maxFailed) { if (!serverFailed && (successCount + failureCount) == servers.size()) { // All results are in; notify parent of success parent.recordServerGroupResult(serverGroupName, false); } else if (serverFailed && failureCount > maxFailed) { parent.recordServerGroupResult(serverGroupName, true); } } } }
[ "public", "void", "recordServerResult", "(", "ServerIdentity", "server", ",", "ModelNode", "response", ")", "{", "if", "(", "!", "serverGroupName", ".", "equals", "(", "server", ".", "getServerGroupName", "(", ")", ")", "||", "!", "servers", ".", "contains", "(", "server", ")", ")", "{", "throw", "DomainControllerLogger", ".", "HOST_CONTROLLER_LOGGER", ".", "unknownServer", "(", "server", ")", ";", "}", "boolean", "serverFailed", "=", "response", ".", "has", "(", "FAILURE_DESCRIPTION", ")", ";", "DomainControllerLogger", ".", "HOST_CONTROLLER_LOGGER", ".", "tracef", "(", "\"Recording server result for '%s': failed = %s\"", ",", "server", ",", "server", ")", ";", "synchronized", "(", "this", ")", "{", "int", "previousFailed", "=", "failureCount", ";", "if", "(", "serverFailed", ")", "{", "failureCount", "++", ";", "}", "else", "{", "successCount", "++", ";", "}", "if", "(", "previousFailed", "<=", "maxFailed", ")", "{", "if", "(", "!", "serverFailed", "&&", "(", "successCount", "+", "failureCount", ")", "==", "servers", ".", "size", "(", ")", ")", "{", "// All results are in; notify parent of success", "parent", ".", "recordServerGroupResult", "(", "serverGroupName", ",", "false", ")", ";", "}", "else", "if", "(", "serverFailed", "&&", "failureCount", ">", "maxFailed", ")", "{", "parent", ".", "recordServerGroupResult", "(", "serverGroupName", ",", "true", ")", ";", "}", "}", "}", "}" ]
Records the result of updating a server. @param server the id of the server. Cannot be <code>null</code> @param response the result of the updates
[ "Records", "the", "result", "of", "updating", "a", "server", "." ]
cfaf0479dcbb2d320a44c5374b93b944ec39fade
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/host-controller/src/main/java/org/jboss/as/domain/controller/plan/ServerUpdatePolicy.java#L130-L160
159,119
wildfly/wildfly-core
launcher/src/main/java/org/wildfly/core/launcher/Arguments.java
Arguments.set
public void set(final Argument argument) { if (argument != null) { map.put(argument.getKey(), Collections.singleton(argument)); } }
java
public void set(final Argument argument) { if (argument != null) { map.put(argument.getKey(), Collections.singleton(argument)); } }
[ "public", "void", "set", "(", "final", "Argument", "argument", ")", "{", "if", "(", "argument", "!=", "null", ")", "{", "map", ".", "put", "(", "argument", ".", "getKey", "(", ")", ",", "Collections", ".", "singleton", "(", "argument", ")", ")", ";", "}", "}" ]
Sets an argument to the collection of arguments. This guarantees only one value will be assigned to the argument key. @param argument the argument to add
[ "Sets", "an", "argument", "to", "the", "collection", "of", "arguments", ".", "This", "guarantees", "only", "one", "value", "will", "be", "assigned", "to", "the", "argument", "key", "." ]
cfaf0479dcbb2d320a44c5374b93b944ec39fade
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/launcher/src/main/java/org/wildfly/core/launcher/Arguments.java#L126-L130
159,120
wildfly/wildfly-core
launcher/src/main/java/org/wildfly/core/launcher/Arguments.java
Arguments.get
public String get(final String key) { final Collection<Argument> args = map.get(key); if (args != null) { return args.iterator().hasNext() ? args.iterator().next().getValue() : null; } return null; }
java
public String get(final String key) { final Collection<Argument> args = map.get(key); if (args != null) { return args.iterator().hasNext() ? args.iterator().next().getValue() : null; } return null; }
[ "public", "String", "get", "(", "final", "String", "key", ")", "{", "final", "Collection", "<", "Argument", ">", "args", "=", "map", ".", "get", "(", "key", ")", ";", "if", "(", "args", "!=", "null", ")", "{", "return", "args", ".", "iterator", "(", ")", ".", "hasNext", "(", ")", "?", "args", ".", "iterator", "(", ")", ".", "next", "(", ")", ".", "getValue", "(", ")", ":", "null", ";", "}", "return", "null", ";", "}" ]
Gets the first value for the key. @param key the key to check for the value @return the value or {@code null} if the key is not found or the value was {@code null}
[ "Gets", "the", "first", "value", "for", "the", "key", "." ]
cfaf0479dcbb2d320a44c5374b93b944ec39fade
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/launcher/src/main/java/org/wildfly/core/launcher/Arguments.java#L154-L160
159,121
wildfly/wildfly-core
launcher/src/main/java/org/wildfly/core/launcher/Arguments.java
Arguments.getArguments
public Collection<Argument> getArguments(final String key) { final Collection<Argument> args = map.get(key); if (args != null) { return new ArrayList<>(args); } return Collections.emptyList(); }
java
public Collection<Argument> getArguments(final String key) { final Collection<Argument> args = map.get(key); if (args != null) { return new ArrayList<>(args); } return Collections.emptyList(); }
[ "public", "Collection", "<", "Argument", ">", "getArguments", "(", "final", "String", "key", ")", "{", "final", "Collection", "<", "Argument", ">", "args", "=", "map", ".", "get", "(", "key", ")", ";", "if", "(", "args", "!=", "null", ")", "{", "return", "new", "ArrayList", "<>", "(", "args", ")", ";", "}", "return", "Collections", ".", "emptyList", "(", ")", ";", "}" ]
Gets the value for the key. @param key the key to check for the value @return the value or an empty collection if no values were set
[ "Gets", "the", "value", "for", "the", "key", "." ]
cfaf0479dcbb2d320a44c5374b93b944ec39fade
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/launcher/src/main/java/org/wildfly/core/launcher/Arguments.java#L169-L175
159,122
wildfly/wildfly-core
launcher/src/main/java/org/wildfly/core/launcher/Arguments.java
Arguments.asList
public List<String> asList() { final List<String> result = new ArrayList<>(); for (Collection<Argument> args : map.values()) { for (Argument arg : args) { result.add(arg.asCommandLineArgument()); } } return result; }
java
public List<String> asList() { final List<String> result = new ArrayList<>(); for (Collection<Argument> args : map.values()) { for (Argument arg : args) { result.add(arg.asCommandLineArgument()); } } return result; }
[ "public", "List", "<", "String", ">", "asList", "(", ")", "{", "final", "List", "<", "String", ">", "result", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "Collection", "<", "Argument", ">", "args", ":", "map", ".", "values", "(", ")", ")", "{", "for", "(", "Argument", "arg", ":", "args", ")", "{", "result", ".", "add", "(", "arg", ".", "asCommandLineArgument", "(", ")", ")", ";", "}", "}", "return", "result", ";", "}" ]
Returns the arguments as a list in their command line form. @return the arguments for the command line
[ "Returns", "the", "arguments", "as", "a", "list", "in", "their", "command", "line", "form", "." ]
cfaf0479dcbb2d320a44c5374b93b944ec39fade
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/launcher/src/main/java/org/wildfly/core/launcher/Arguments.java#L193-L201
159,123
wildfly/wildfly-core
domain-management/src/main/java/org/jboss/as/domain/management/parsing/ManagementXml_Legacy.java
ManagementXml_Legacy.parseLdapAuthorization_1_5
private void parseLdapAuthorization_1_5(final XMLExtendedStreamReader reader, final ModelNode realmAddress, final List<ModelNode> list) throws XMLStreamException { ModelNode addr = realmAddress.clone().add(AUTHORIZATION, LDAP); ModelNode ldapAuthorization = Util.getEmptyOperation(ADD, addr); list.add(ldapAuthorization); Set<Attribute> required = EnumSet.of(Attribute.CONNECTION); final int count = reader.getAttributeCount(); for (int i = 0; i < count; i++) { final String value = reader.getAttributeValue(i); if (!isNoNamespaceAttribute(reader, i)) { throw unexpectedAttribute(reader, i); } else { final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i)); required.remove(attribute); switch (attribute) { case CONNECTION: { LdapAuthorizationResourceDefinition.CONNECTION.parseAndSetParameter(value, ldapAuthorization, reader); break; } default: { throw unexpectedAttribute(reader, i); } } } } if (required.isEmpty() == false) { throw missingRequired(reader, required); } Set<Element> foundElements = new HashSet<Element>(); while (reader.hasNext() && reader.nextTag() != END_ELEMENT) { requireNamespace(reader, namespace); final Element element = Element.forName(reader.getLocalName()); if (foundElements.add(element) == false) { throw unexpectedElement(reader); // Only one of each allowed. } switch (element) { case USERNAME_TO_DN: { switch (namespace.getMajorVersion()) { case 1: // 1.5 up to but not including 2.0 parseUsernameToDn_1_5(reader, addr, list); break; default: // 2.0 and onwards parseUsernameToDn_2_0(reader, addr, list); break; } break; } case GROUP_SEARCH: { switch (namespace) { case DOMAIN_1_5: case DOMAIN_1_6: parseGroupSearch_1_5(reader, addr, list); break; default: parseGroupSearch_1_7_and_2_0(reader, addr, list); break; } break; } default: { throw unexpectedElement(reader); } } } }
java
private void parseLdapAuthorization_1_5(final XMLExtendedStreamReader reader, final ModelNode realmAddress, final List<ModelNode> list) throws XMLStreamException { ModelNode addr = realmAddress.clone().add(AUTHORIZATION, LDAP); ModelNode ldapAuthorization = Util.getEmptyOperation(ADD, addr); list.add(ldapAuthorization); Set<Attribute> required = EnumSet.of(Attribute.CONNECTION); final int count = reader.getAttributeCount(); for (int i = 0; i < count; i++) { final String value = reader.getAttributeValue(i); if (!isNoNamespaceAttribute(reader, i)) { throw unexpectedAttribute(reader, i); } else { final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i)); required.remove(attribute); switch (attribute) { case CONNECTION: { LdapAuthorizationResourceDefinition.CONNECTION.parseAndSetParameter(value, ldapAuthorization, reader); break; } default: { throw unexpectedAttribute(reader, i); } } } } if (required.isEmpty() == false) { throw missingRequired(reader, required); } Set<Element> foundElements = new HashSet<Element>(); while (reader.hasNext() && reader.nextTag() != END_ELEMENT) { requireNamespace(reader, namespace); final Element element = Element.forName(reader.getLocalName()); if (foundElements.add(element) == false) { throw unexpectedElement(reader); // Only one of each allowed. } switch (element) { case USERNAME_TO_DN: { switch (namespace.getMajorVersion()) { case 1: // 1.5 up to but not including 2.0 parseUsernameToDn_1_5(reader, addr, list); break; default: // 2.0 and onwards parseUsernameToDn_2_0(reader, addr, list); break; } break; } case GROUP_SEARCH: { switch (namespace) { case DOMAIN_1_5: case DOMAIN_1_6: parseGroupSearch_1_5(reader, addr, list); break; default: parseGroupSearch_1_7_and_2_0(reader, addr, list); break; } break; } default: { throw unexpectedElement(reader); } } } }
[ "private", "void", "parseLdapAuthorization_1_5", "(", "final", "XMLExtendedStreamReader", "reader", ",", "final", "ModelNode", "realmAddress", ",", "final", "List", "<", "ModelNode", ">", "list", ")", "throws", "XMLStreamException", "{", "ModelNode", "addr", "=", "realmAddress", ".", "clone", "(", ")", ".", "add", "(", "AUTHORIZATION", ",", "LDAP", ")", ";", "ModelNode", "ldapAuthorization", "=", "Util", ".", "getEmptyOperation", "(", "ADD", ",", "addr", ")", ";", "list", ".", "add", "(", "ldapAuthorization", ")", ";", "Set", "<", "Attribute", ">", "required", "=", "EnumSet", ".", "of", "(", "Attribute", ".", "CONNECTION", ")", ";", "final", "int", "count", "=", "reader", ".", "getAttributeCount", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "count", ";", "i", "++", ")", "{", "final", "String", "value", "=", "reader", ".", "getAttributeValue", "(", "i", ")", ";", "if", "(", "!", "isNoNamespaceAttribute", "(", "reader", ",", "i", ")", ")", "{", "throw", "unexpectedAttribute", "(", "reader", ",", "i", ")", ";", "}", "else", "{", "final", "Attribute", "attribute", "=", "Attribute", ".", "forName", "(", "reader", ".", "getAttributeLocalName", "(", "i", ")", ")", ";", "required", ".", "remove", "(", "attribute", ")", ";", "switch", "(", "attribute", ")", "{", "case", "CONNECTION", ":", "{", "LdapAuthorizationResourceDefinition", ".", "CONNECTION", ".", "parseAndSetParameter", "(", "value", ",", "ldapAuthorization", ",", "reader", ")", ";", "break", ";", "}", "default", ":", "{", "throw", "unexpectedAttribute", "(", "reader", ",", "i", ")", ";", "}", "}", "}", "}", "if", "(", "required", ".", "isEmpty", "(", ")", "==", "false", ")", "{", "throw", "missingRequired", "(", "reader", ",", "required", ")", ";", "}", "Set", "<", "Element", ">", "foundElements", "=", "new", "HashSet", "<", "Element", ">", "(", ")", ";", "while", "(", "reader", ".", "hasNext", "(", ")", "&&", "reader", ".", "nextTag", "(", ")", "!=", "END_ELEMENT", ")", "{", "requireNamespace", "(", "reader", ",", "namespace", ")", ";", "final", "Element", "element", "=", "Element", ".", "forName", "(", "reader", ".", "getLocalName", "(", ")", ")", ";", "if", "(", "foundElements", ".", "add", "(", "element", ")", "==", "false", ")", "{", "throw", "unexpectedElement", "(", "reader", ")", ";", "// Only one of each allowed.", "}", "switch", "(", "element", ")", "{", "case", "USERNAME_TO_DN", ":", "{", "switch", "(", "namespace", ".", "getMajorVersion", "(", ")", ")", "{", "case", "1", ":", "// 1.5 up to but not including 2.0", "parseUsernameToDn_1_5", "(", "reader", ",", "addr", ",", "list", ")", ";", "break", ";", "default", ":", "// 2.0 and onwards", "parseUsernameToDn_2_0", "(", "reader", ",", "addr", ",", "list", ")", ";", "break", ";", "}", "break", ";", "}", "case", "GROUP_SEARCH", ":", "{", "switch", "(", "namespace", ")", "{", "case", "DOMAIN_1_5", ":", "case", "DOMAIN_1_6", ":", "parseGroupSearch_1_5", "(", "reader", ",", "addr", ",", "list", ")", ";", "break", ";", "default", ":", "parseGroupSearch_1_7_and_2_0", "(", "reader", ",", "addr", ",", "list", ")", ";", "break", ";", "}", "break", ";", "}", "default", ":", "{", "throw", "unexpectedElement", "(", "reader", ")", ";", "}", "}", "}", "}" ]
1.5 and on, 2.0 and on, 3.0 and on.
[ "1", ".", "5", "and", "on", "2", ".", "0", "and", "on", "3", ".", "0", "and", "on", "." ]
cfaf0479dcbb2d320a44c5374b93b944ec39fade
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/domain-management/src/main/java/org/jboss/as/domain/management/parsing/ManagementXml_Legacy.java#L2443-L2512
159,124
wildfly/wildfly-core
server/src/main/java/org/jboss/as/server/deployment/module/ResourceRoot.java
ResourceRoot.merge
public void merge(final ResourceRoot additionalResourceRoot) { if(!additionalResourceRoot.getRoot().equals(root)) { throw ServerLogger.ROOT_LOGGER.cannotMergeResourceRoot(root, additionalResourceRoot.getRoot()); } usePhysicalCodeSource = additionalResourceRoot.usePhysicalCodeSource; if(additionalResourceRoot.getExportFilters().isEmpty()) { //new root has no filters, so we don't want our existing filters to break anything //see WFLY-1527 this.exportFilters.clear(); } else { this.exportFilters.addAll(additionalResourceRoot.getExportFilters()); } }
java
public void merge(final ResourceRoot additionalResourceRoot) { if(!additionalResourceRoot.getRoot().equals(root)) { throw ServerLogger.ROOT_LOGGER.cannotMergeResourceRoot(root, additionalResourceRoot.getRoot()); } usePhysicalCodeSource = additionalResourceRoot.usePhysicalCodeSource; if(additionalResourceRoot.getExportFilters().isEmpty()) { //new root has no filters, so we don't want our existing filters to break anything //see WFLY-1527 this.exportFilters.clear(); } else { this.exportFilters.addAll(additionalResourceRoot.getExportFilters()); } }
[ "public", "void", "merge", "(", "final", "ResourceRoot", "additionalResourceRoot", ")", "{", "if", "(", "!", "additionalResourceRoot", ".", "getRoot", "(", ")", ".", "equals", "(", "root", ")", ")", "{", "throw", "ServerLogger", ".", "ROOT_LOGGER", ".", "cannotMergeResourceRoot", "(", "root", ",", "additionalResourceRoot", ".", "getRoot", "(", ")", ")", ";", "}", "usePhysicalCodeSource", "=", "additionalResourceRoot", ".", "usePhysicalCodeSource", ";", "if", "(", "additionalResourceRoot", ".", "getExportFilters", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "//new root has no filters, so we don't want our existing filters to break anything", "//see WFLY-1527", "this", ".", "exportFilters", ".", "clear", "(", ")", ";", "}", "else", "{", "this", ".", "exportFilters", ".", "addAll", "(", "additionalResourceRoot", ".", "getExportFilters", "(", ")", ")", ";", "}", "}" ]
Merges information from the resource root into this resource root @param additionalResourceRoot The root to merge
[ "Merges", "information", "from", "the", "resource", "root", "into", "this", "resource", "root" ]
cfaf0479dcbb2d320a44c5374b93b944ec39fade
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/server/src/main/java/org/jboss/as/server/deployment/module/ResourceRoot.java#L94-L106
159,125
wildfly/wildfly-core
security-manager/src/main/java/org/wildfly/extension/security/manager/SecurityManagerExtensionTransformerRegistration.java
SecurityManagerExtensionTransformerRegistration.registerTransformers
@Override public void registerTransformers(SubsystemTransformerRegistration subsystemRegistration) { ResourceTransformationDescriptionBuilder builder = ResourceTransformationDescriptionBuilder.Factory.createSubsystemInstance(); builder.addChildResource(DeploymentPermissionsResourceDefinition.DEPLOYMENT_PERMISSIONS_PATH). getAttributeBuilder().addRejectCheck(new RejectAttributeChecker.DefaultRejectAttributeChecker() { @Override protected boolean rejectAttribute(PathAddress address, String attributeName, ModelNode value, TransformationContext context) { // reject the maximum set if it is defined and empty as that would result in complete incompatible policies // being used in nodes running earlier versions of the subsystem. if (value.isDefined() && value.asList().isEmpty()) { return true; } return false; } @Override public String getRejectionLogMessage(Map<String, ModelNode> attributes) { return SecurityManagerLogger.ROOT_LOGGER.rejectedEmptyMaximumSet(); } }, DeploymentPermissionsResourceDefinition.MAXIMUM_PERMISSIONS); TransformationDescription.Tools.register(builder.build(), subsystemRegistration, EAP_7_0_0_MODEL_VERSION); }
java
@Override public void registerTransformers(SubsystemTransformerRegistration subsystemRegistration) { ResourceTransformationDescriptionBuilder builder = ResourceTransformationDescriptionBuilder.Factory.createSubsystemInstance(); builder.addChildResource(DeploymentPermissionsResourceDefinition.DEPLOYMENT_PERMISSIONS_PATH). getAttributeBuilder().addRejectCheck(new RejectAttributeChecker.DefaultRejectAttributeChecker() { @Override protected boolean rejectAttribute(PathAddress address, String attributeName, ModelNode value, TransformationContext context) { // reject the maximum set if it is defined and empty as that would result in complete incompatible policies // being used in nodes running earlier versions of the subsystem. if (value.isDefined() && value.asList().isEmpty()) { return true; } return false; } @Override public String getRejectionLogMessage(Map<String, ModelNode> attributes) { return SecurityManagerLogger.ROOT_LOGGER.rejectedEmptyMaximumSet(); } }, DeploymentPermissionsResourceDefinition.MAXIMUM_PERMISSIONS); TransformationDescription.Tools.register(builder.build(), subsystemRegistration, EAP_7_0_0_MODEL_VERSION); }
[ "@", "Override", "public", "void", "registerTransformers", "(", "SubsystemTransformerRegistration", "subsystemRegistration", ")", "{", "ResourceTransformationDescriptionBuilder", "builder", "=", "ResourceTransformationDescriptionBuilder", ".", "Factory", ".", "createSubsystemInstance", "(", ")", ";", "builder", ".", "addChildResource", "(", "DeploymentPermissionsResourceDefinition", ".", "DEPLOYMENT_PERMISSIONS_PATH", ")", ".", "getAttributeBuilder", "(", ")", ".", "addRejectCheck", "(", "new", "RejectAttributeChecker", ".", "DefaultRejectAttributeChecker", "(", ")", "{", "@", "Override", "protected", "boolean", "rejectAttribute", "(", "PathAddress", "address", ",", "String", "attributeName", ",", "ModelNode", "value", ",", "TransformationContext", "context", ")", "{", "// reject the maximum set if it is defined and empty as that would result in complete incompatible policies", "// being used in nodes running earlier versions of the subsystem.", "if", "(", "value", ".", "isDefined", "(", ")", "&&", "value", ".", "asList", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}", "@", "Override", "public", "String", "getRejectionLogMessage", "(", "Map", "<", "String", ",", "ModelNode", ">", "attributes", ")", "{", "return", "SecurityManagerLogger", ".", "ROOT_LOGGER", ".", "rejectedEmptyMaximumSet", "(", ")", ";", "}", "}", ",", "DeploymentPermissionsResourceDefinition", ".", "MAXIMUM_PERMISSIONS", ")", ";", "TransformationDescription", ".", "Tools", ".", "register", "(", "builder", ".", "build", "(", ")", ",", "subsystemRegistration", ",", "EAP_7_0_0_MODEL_VERSION", ")", ";", "}" ]
Registers the transformers for JBoss EAP 7.0.0. @param subsystemRegistration contains data about the subsystem registration
[ "Registers", "the", "transformers", "for", "JBoss", "EAP", "7", ".", "0", ".", "0", "." ]
cfaf0479dcbb2d320a44c5374b93b944ec39fade
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/security-manager/src/main/java/org/wildfly/extension/security/manager/SecurityManagerExtensionTransformerRegistration.java#L50-L70
159,126
wildfly/wildfly-core
controller/src/main/java/org/jboss/as/controller/operations/global/FilteredData.java
FilteredData.toModelNode
ModelNode toModelNode() { ModelNode result = null; if (map != null) { result = new ModelNode(); for (Map.Entry<PathAddress, ResourceData> entry : map.entrySet()) { ModelNode item = new ModelNode(); PathAddress pa = entry.getKey(); item.get(ABSOLUTE_ADDRESS).set(pa.toModelNode()); ResourceData rd = entry.getValue(); item.get(RELATIVE_ADDRESS).set(pa.subAddress(baseAddressLength).toModelNode()); ModelNode attrs = new ModelNode().setEmptyList(); if (rd.attributes != null) { for (String attr : rd.attributes) { attrs.add(attr); } } if (attrs.asInt() > 0) { item.get(FILTERED_ATTRIBUTES).set(attrs); } ModelNode children = new ModelNode().setEmptyList(); if (rd.children != null) { for (PathElement pe : rd.children) { children.add(new Property(pe.getKey(), new ModelNode(pe.getValue()))); } } if (children.asInt() > 0) { item.get(UNREADABLE_CHILDREN).set(children); } ModelNode childTypes = new ModelNode().setEmptyList(); if (rd.childTypes != null) { Set<String> added = new HashSet<String>(); for (PathElement pe : rd.childTypes) { if (added.add(pe.getKey())) { childTypes.add(pe.getKey()); } } } if (childTypes.asInt() > 0) { item.get(FILTERED_CHILDREN_TYPES).set(childTypes); } result.add(item); } } return result; }
java
ModelNode toModelNode() { ModelNode result = null; if (map != null) { result = new ModelNode(); for (Map.Entry<PathAddress, ResourceData> entry : map.entrySet()) { ModelNode item = new ModelNode(); PathAddress pa = entry.getKey(); item.get(ABSOLUTE_ADDRESS).set(pa.toModelNode()); ResourceData rd = entry.getValue(); item.get(RELATIVE_ADDRESS).set(pa.subAddress(baseAddressLength).toModelNode()); ModelNode attrs = new ModelNode().setEmptyList(); if (rd.attributes != null) { for (String attr : rd.attributes) { attrs.add(attr); } } if (attrs.asInt() > 0) { item.get(FILTERED_ATTRIBUTES).set(attrs); } ModelNode children = new ModelNode().setEmptyList(); if (rd.children != null) { for (PathElement pe : rd.children) { children.add(new Property(pe.getKey(), new ModelNode(pe.getValue()))); } } if (children.asInt() > 0) { item.get(UNREADABLE_CHILDREN).set(children); } ModelNode childTypes = new ModelNode().setEmptyList(); if (rd.childTypes != null) { Set<String> added = new HashSet<String>(); for (PathElement pe : rd.childTypes) { if (added.add(pe.getKey())) { childTypes.add(pe.getKey()); } } } if (childTypes.asInt() > 0) { item.get(FILTERED_CHILDREN_TYPES).set(childTypes); } result.add(item); } } return result; }
[ "ModelNode", "toModelNode", "(", ")", "{", "ModelNode", "result", "=", "null", ";", "if", "(", "map", "!=", "null", ")", "{", "result", "=", "new", "ModelNode", "(", ")", ";", "for", "(", "Map", ".", "Entry", "<", "PathAddress", ",", "ResourceData", ">", "entry", ":", "map", ".", "entrySet", "(", ")", ")", "{", "ModelNode", "item", "=", "new", "ModelNode", "(", ")", ";", "PathAddress", "pa", "=", "entry", ".", "getKey", "(", ")", ";", "item", ".", "get", "(", "ABSOLUTE_ADDRESS", ")", ".", "set", "(", "pa", ".", "toModelNode", "(", ")", ")", ";", "ResourceData", "rd", "=", "entry", ".", "getValue", "(", ")", ";", "item", ".", "get", "(", "RELATIVE_ADDRESS", ")", ".", "set", "(", "pa", ".", "subAddress", "(", "baseAddressLength", ")", ".", "toModelNode", "(", ")", ")", ";", "ModelNode", "attrs", "=", "new", "ModelNode", "(", ")", ".", "setEmptyList", "(", ")", ";", "if", "(", "rd", ".", "attributes", "!=", "null", ")", "{", "for", "(", "String", "attr", ":", "rd", ".", "attributes", ")", "{", "attrs", ".", "add", "(", "attr", ")", ";", "}", "}", "if", "(", "attrs", ".", "asInt", "(", ")", ">", "0", ")", "{", "item", ".", "get", "(", "FILTERED_ATTRIBUTES", ")", ".", "set", "(", "attrs", ")", ";", "}", "ModelNode", "children", "=", "new", "ModelNode", "(", ")", ".", "setEmptyList", "(", ")", ";", "if", "(", "rd", ".", "children", "!=", "null", ")", "{", "for", "(", "PathElement", "pe", ":", "rd", ".", "children", ")", "{", "children", ".", "add", "(", "new", "Property", "(", "pe", ".", "getKey", "(", ")", ",", "new", "ModelNode", "(", "pe", ".", "getValue", "(", ")", ")", ")", ")", ";", "}", "}", "if", "(", "children", ".", "asInt", "(", ")", ">", "0", ")", "{", "item", ".", "get", "(", "UNREADABLE_CHILDREN", ")", ".", "set", "(", "children", ")", ";", "}", "ModelNode", "childTypes", "=", "new", "ModelNode", "(", ")", ".", "setEmptyList", "(", ")", ";", "if", "(", "rd", ".", "childTypes", "!=", "null", ")", "{", "Set", "<", "String", ">", "added", "=", "new", "HashSet", "<", "String", ">", "(", ")", ";", "for", "(", "PathElement", "pe", ":", "rd", ".", "childTypes", ")", "{", "if", "(", "added", ".", "add", "(", "pe", ".", "getKey", "(", ")", ")", ")", "{", "childTypes", ".", "add", "(", "pe", ".", "getKey", "(", ")", ")", ";", "}", "}", "}", "if", "(", "childTypes", ".", "asInt", "(", ")", ">", "0", ")", "{", "item", ".", "get", "(", "FILTERED_CHILDREN_TYPES", ")", ".", "set", "(", "childTypes", ")", ";", "}", "result", ".", "add", "(", "item", ")", ";", "}", "}", "return", "result", ";", "}" ]
Report on the filtered data in DMR .
[ "Report", "on", "the", "filtered", "data", "in", "DMR", "." ]
cfaf0479dcbb2d320a44c5374b93b944ec39fade
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/operations/global/FilteredData.java#L107-L151
159,127
wildfly/wildfly-core
patching/src/main/java/org/jboss/as/patching/runner/IdentityPatchRunner.java
IdentityPatchRunner.rollbackLast
public PatchingResult rollbackLast(final ContentVerificationPolicy contentPolicy, final boolean resetConfiguration, InstallationManager.InstallationModification modification) throws PatchingException { // Determine the patch id to rollback String patchId; final List<String> oneOffs = modification.getPatchIDs(); if (oneOffs.isEmpty()) { patchId = modification.getCumulativePatchID(); if (patchId == null || Constants.NOT_PATCHED.equals(patchId)) { throw PatchLogger.ROOT_LOGGER.noPatchesApplied(); } } else { patchId = oneOffs.get(0);//oneOffs.get(oneOffs.size() - 1); } return rollbackPatch(patchId, contentPolicy, false, resetConfiguration, modification); }
java
public PatchingResult rollbackLast(final ContentVerificationPolicy contentPolicy, final boolean resetConfiguration, InstallationManager.InstallationModification modification) throws PatchingException { // Determine the patch id to rollback String patchId; final List<String> oneOffs = modification.getPatchIDs(); if (oneOffs.isEmpty()) { patchId = modification.getCumulativePatchID(); if (patchId == null || Constants.NOT_PATCHED.equals(patchId)) { throw PatchLogger.ROOT_LOGGER.noPatchesApplied(); } } else { patchId = oneOffs.get(0);//oneOffs.get(oneOffs.size() - 1); } return rollbackPatch(patchId, contentPolicy, false, resetConfiguration, modification); }
[ "public", "PatchingResult", "rollbackLast", "(", "final", "ContentVerificationPolicy", "contentPolicy", ",", "final", "boolean", "resetConfiguration", ",", "InstallationManager", ".", "InstallationModification", "modification", ")", "throws", "PatchingException", "{", "// Determine the patch id to rollback", "String", "patchId", ";", "final", "List", "<", "String", ">", "oneOffs", "=", "modification", ".", "getPatchIDs", "(", ")", ";", "if", "(", "oneOffs", ".", "isEmpty", "(", ")", ")", "{", "patchId", "=", "modification", ".", "getCumulativePatchID", "(", ")", ";", "if", "(", "patchId", "==", "null", "||", "Constants", ".", "NOT_PATCHED", ".", "equals", "(", "patchId", ")", ")", "{", "throw", "PatchLogger", ".", "ROOT_LOGGER", ".", "noPatchesApplied", "(", ")", ";", "}", "}", "else", "{", "patchId", "=", "oneOffs", ".", "get", "(", "0", ")", ";", "//oneOffs.get(oneOffs.size() - 1);", "}", "return", "rollbackPatch", "(", "patchId", ",", "contentPolicy", ",", "false", ",", "resetConfiguration", ",", "modification", ")", ";", "}" ]
Rollback the last applied patch. @param contentPolicy the content policy @param resetConfiguration whether to reset the configuration @param modification the installation modification @return the patching result @throws PatchingException
[ "Rollback", "the", "last", "applied", "patch", "." ]
cfaf0479dcbb2d320a44c5374b93b944ec39fade
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/patching/src/main/java/org/jboss/as/patching/runner/IdentityPatchRunner.java#L284-L298
159,128
wildfly/wildfly-core
patching/src/main/java/org/jboss/as/patching/runner/IdentityPatchRunner.java
IdentityPatchRunner.restoreFromHistory
static void restoreFromHistory(final InstallationManager.MutablePatchingTarget target, final String rollbackPatchId, final Patch.PatchType patchType, final PatchableTarget.TargetInfo history) throws PatchingException { if (patchType == Patch.PatchType.CUMULATIVE) { assert history.getCumulativePatchID().equals(rollbackPatchId); target.apply(rollbackPatchId, patchType); // Restore one off state final List<String> oneOffs = new ArrayList<String>(history.getPatchIDs()); Collections.reverse(oneOffs); for (final String oneOff : oneOffs) { target.apply(oneOff, Patch.PatchType.ONE_OFF); } } checkState(history, history); // Just check for tests, that rollback should restore the old state }
java
static void restoreFromHistory(final InstallationManager.MutablePatchingTarget target, final String rollbackPatchId, final Patch.PatchType patchType, final PatchableTarget.TargetInfo history) throws PatchingException { if (patchType == Patch.PatchType.CUMULATIVE) { assert history.getCumulativePatchID().equals(rollbackPatchId); target.apply(rollbackPatchId, patchType); // Restore one off state final List<String> oneOffs = new ArrayList<String>(history.getPatchIDs()); Collections.reverse(oneOffs); for (final String oneOff : oneOffs) { target.apply(oneOff, Patch.PatchType.ONE_OFF); } } checkState(history, history); // Just check for tests, that rollback should restore the old state }
[ "static", "void", "restoreFromHistory", "(", "final", "InstallationManager", ".", "MutablePatchingTarget", "target", ",", "final", "String", "rollbackPatchId", ",", "final", "Patch", ".", "PatchType", "patchType", ",", "final", "PatchableTarget", ".", "TargetInfo", "history", ")", "throws", "PatchingException", "{", "if", "(", "patchType", "==", "Patch", ".", "PatchType", ".", "CUMULATIVE", ")", "{", "assert", "history", ".", "getCumulativePatchID", "(", ")", ".", "equals", "(", "rollbackPatchId", ")", ";", "target", ".", "apply", "(", "rollbackPatchId", ",", "patchType", ")", ";", "// Restore one off state", "final", "List", "<", "String", ">", "oneOffs", "=", "new", "ArrayList", "<", "String", ">", "(", "history", ".", "getPatchIDs", "(", ")", ")", ";", "Collections", ".", "reverse", "(", "oneOffs", ")", ";", "for", "(", "final", "String", "oneOff", ":", "oneOffs", ")", "{", "target", ".", "apply", "(", "oneOff", ",", "Patch", ".", "PatchType", ".", "ONE_OFF", ")", ";", "}", "}", "checkState", "(", "history", ",", "history", ")", ";", "// Just check for tests, that rollback should restore the old state", "}" ]
Restore the recorded state from the rollback xml. @param target the patchable target @param rollbackPatchId the rollback patch id @param patchType the the current patch type @param history the recorded history @throws PatchingException
[ "Restore", "the", "recorded", "state", "from", "the", "rollback", "xml", "." ]
cfaf0479dcbb2d320a44c5374b93b944ec39fade
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/patching/src/main/java/org/jboss/as/patching/runner/IdentityPatchRunner.java#L425-L438
159,129
wildfly/wildfly-core
patching/src/main/java/org/jboss/as/patching/runner/IdentityPatchRunner.java
IdentityPatchRunner.portForward
void portForward(final Patch patch, IdentityPatchContext context) throws PatchingException, IOException, XMLStreamException { assert patch.getIdentity().getPatchType() == Patch.PatchType.CUMULATIVE; final PatchingHistory history = context.getHistory(); for (final PatchElement element : patch.getElements()) { final PatchElementProvider provider = element.getProvider(); final String name = provider.getName(); final boolean addOn = provider.isAddOn(); final IdentityPatchContext.PatchEntry target = context.resolveForElement(element); final String cumulativePatchID = target.getCumulativePatchID(); if (Constants.BASE.equals(cumulativePatchID)) { reenableRolledBackInBase(target); continue; } boolean found = false; final PatchingHistory.Iterator iterator = history.iterator(); while (iterator.hasNextCP()) { final PatchingHistory.Entry entry = iterator.nextCP(); final String patchId = addOn ? entry.getAddOnPatches().get(name) : entry.getLayerPatches().get(name); if (patchId != null && patchId.equals(cumulativePatchID)) { final Patch original = loadPatchInformation(entry.getPatchId(), installedImage); for (final PatchElement originalElement : original.getElements()) { if (name.equals(originalElement.getProvider().getName()) && addOn == originalElement.getProvider().isAddOn()) { PatchingTasks.addMissingModifications(target, originalElement.getModifications(), ContentItemFilter.ALL_BUT_MISC); } } // Record a loader to have access to the current modules final DirectoryStructure structure = target.getDirectoryStructure(); final File modulesRoot = structure.getModulePatchDirectory(patchId); final File bundlesRoot = structure.getBundlesPatchDirectory(patchId); final PatchContentLoader loader = PatchContentLoader.create(null, bundlesRoot, modulesRoot); context.recordContentLoader(patchId, loader); found = true; break; } } if (!found) { throw PatchLogger.ROOT_LOGGER.patchNotFoundInHistory(cumulativePatchID); } reenableRolledBackInBase(target); } }
java
void portForward(final Patch patch, IdentityPatchContext context) throws PatchingException, IOException, XMLStreamException { assert patch.getIdentity().getPatchType() == Patch.PatchType.CUMULATIVE; final PatchingHistory history = context.getHistory(); for (final PatchElement element : patch.getElements()) { final PatchElementProvider provider = element.getProvider(); final String name = provider.getName(); final boolean addOn = provider.isAddOn(); final IdentityPatchContext.PatchEntry target = context.resolveForElement(element); final String cumulativePatchID = target.getCumulativePatchID(); if (Constants.BASE.equals(cumulativePatchID)) { reenableRolledBackInBase(target); continue; } boolean found = false; final PatchingHistory.Iterator iterator = history.iterator(); while (iterator.hasNextCP()) { final PatchingHistory.Entry entry = iterator.nextCP(); final String patchId = addOn ? entry.getAddOnPatches().get(name) : entry.getLayerPatches().get(name); if (patchId != null && patchId.equals(cumulativePatchID)) { final Patch original = loadPatchInformation(entry.getPatchId(), installedImage); for (final PatchElement originalElement : original.getElements()) { if (name.equals(originalElement.getProvider().getName()) && addOn == originalElement.getProvider().isAddOn()) { PatchingTasks.addMissingModifications(target, originalElement.getModifications(), ContentItemFilter.ALL_BUT_MISC); } } // Record a loader to have access to the current modules final DirectoryStructure structure = target.getDirectoryStructure(); final File modulesRoot = structure.getModulePatchDirectory(patchId); final File bundlesRoot = structure.getBundlesPatchDirectory(patchId); final PatchContentLoader loader = PatchContentLoader.create(null, bundlesRoot, modulesRoot); context.recordContentLoader(patchId, loader); found = true; break; } } if (!found) { throw PatchLogger.ROOT_LOGGER.patchNotFoundInHistory(cumulativePatchID); } reenableRolledBackInBase(target); } }
[ "void", "portForward", "(", "final", "Patch", "patch", ",", "IdentityPatchContext", "context", ")", "throws", "PatchingException", ",", "IOException", ",", "XMLStreamException", "{", "assert", "patch", ".", "getIdentity", "(", ")", ".", "getPatchType", "(", ")", "==", "Patch", ".", "PatchType", ".", "CUMULATIVE", ";", "final", "PatchingHistory", "history", "=", "context", ".", "getHistory", "(", ")", ";", "for", "(", "final", "PatchElement", "element", ":", "patch", ".", "getElements", "(", ")", ")", "{", "final", "PatchElementProvider", "provider", "=", "element", ".", "getProvider", "(", ")", ";", "final", "String", "name", "=", "provider", ".", "getName", "(", ")", ";", "final", "boolean", "addOn", "=", "provider", ".", "isAddOn", "(", ")", ";", "final", "IdentityPatchContext", ".", "PatchEntry", "target", "=", "context", ".", "resolveForElement", "(", "element", ")", ";", "final", "String", "cumulativePatchID", "=", "target", ".", "getCumulativePatchID", "(", ")", ";", "if", "(", "Constants", ".", "BASE", ".", "equals", "(", "cumulativePatchID", ")", ")", "{", "reenableRolledBackInBase", "(", "target", ")", ";", "continue", ";", "}", "boolean", "found", "=", "false", ";", "final", "PatchingHistory", ".", "Iterator", "iterator", "=", "history", ".", "iterator", "(", ")", ";", "while", "(", "iterator", ".", "hasNextCP", "(", ")", ")", "{", "final", "PatchingHistory", ".", "Entry", "entry", "=", "iterator", ".", "nextCP", "(", ")", ";", "final", "String", "patchId", "=", "addOn", "?", "entry", ".", "getAddOnPatches", "(", ")", ".", "get", "(", "name", ")", ":", "entry", ".", "getLayerPatches", "(", ")", ".", "get", "(", "name", ")", ";", "if", "(", "patchId", "!=", "null", "&&", "patchId", ".", "equals", "(", "cumulativePatchID", ")", ")", "{", "final", "Patch", "original", "=", "loadPatchInformation", "(", "entry", ".", "getPatchId", "(", ")", ",", "installedImage", ")", ";", "for", "(", "final", "PatchElement", "originalElement", ":", "original", ".", "getElements", "(", ")", ")", "{", "if", "(", "name", ".", "equals", "(", "originalElement", ".", "getProvider", "(", ")", ".", "getName", "(", ")", ")", "&&", "addOn", "==", "originalElement", ".", "getProvider", "(", ")", ".", "isAddOn", "(", ")", ")", "{", "PatchingTasks", ".", "addMissingModifications", "(", "target", ",", "originalElement", ".", "getModifications", "(", ")", ",", "ContentItemFilter", ".", "ALL_BUT_MISC", ")", ";", "}", "}", "// Record a loader to have access to the current modules", "final", "DirectoryStructure", "structure", "=", "target", ".", "getDirectoryStructure", "(", ")", ";", "final", "File", "modulesRoot", "=", "structure", ".", "getModulePatchDirectory", "(", "patchId", ")", ";", "final", "File", "bundlesRoot", "=", "structure", ".", "getBundlesPatchDirectory", "(", "patchId", ")", ";", "final", "PatchContentLoader", "loader", "=", "PatchContentLoader", ".", "create", "(", "null", ",", "bundlesRoot", ",", "modulesRoot", ")", ";", "context", ".", "recordContentLoader", "(", "patchId", ",", "loader", ")", ";", "found", "=", "true", ";", "break", ";", "}", "}", "if", "(", "!", "found", ")", "{", "throw", "PatchLogger", ".", "ROOT_LOGGER", ".", "patchNotFoundInHistory", "(", "cumulativePatchID", ")", ";", "}", "reenableRolledBackInBase", "(", "target", ")", ";", "}", "}" ]
Port forward missing module changes for each layer. @param patch the current patch @param context the patch context @throws PatchingException @throws IOException @throws XMLStreamException
[ "Port", "forward", "missing", "module", "changes", "for", "each", "layer", "." ]
cfaf0479dcbb2d320a44c5374b93b944ec39fade
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/patching/src/main/java/org/jboss/as/patching/runner/IdentityPatchRunner.java#L563-L610
159,130
wildfly/wildfly-core
patching/src/main/java/org/jboss/as/patching/runner/IdentityPatchRunner.java
IdentityPatchRunner.executeTasks
static PatchingResult executeTasks(final IdentityPatchContext context, final IdentityPatchContext.FinalizeCallback callback) throws Exception { final List<PreparedTask> tasks = new ArrayList<PreparedTask>(); final List<ContentItem> conflicts = new ArrayList<ContentItem>(); // Identity prepareTasks(context.getIdentityEntry(), context, tasks, conflicts); // Layers for (final IdentityPatchContext.PatchEntry layer : context.getLayers()) { prepareTasks(layer, context, tasks, conflicts); } // AddOns for (final IdentityPatchContext.PatchEntry addOn : context.getAddOns()) { prepareTasks(addOn, context, tasks, conflicts); } // If there were problems report them if (!conflicts.isEmpty()) { throw PatchLogger.ROOT_LOGGER.conflictsDetected(conflicts); } // Execute the tasks for (final PreparedTask task : tasks) { // Unless it's excluded by the user final ContentItem item = task.getContentItem(); if (item != null && context.isExcluded(item)) { continue; } // Run the task task.execute(); } return context.finalize(callback); }
java
static PatchingResult executeTasks(final IdentityPatchContext context, final IdentityPatchContext.FinalizeCallback callback) throws Exception { final List<PreparedTask> tasks = new ArrayList<PreparedTask>(); final List<ContentItem> conflicts = new ArrayList<ContentItem>(); // Identity prepareTasks(context.getIdentityEntry(), context, tasks, conflicts); // Layers for (final IdentityPatchContext.PatchEntry layer : context.getLayers()) { prepareTasks(layer, context, tasks, conflicts); } // AddOns for (final IdentityPatchContext.PatchEntry addOn : context.getAddOns()) { prepareTasks(addOn, context, tasks, conflicts); } // If there were problems report them if (!conflicts.isEmpty()) { throw PatchLogger.ROOT_LOGGER.conflictsDetected(conflicts); } // Execute the tasks for (final PreparedTask task : tasks) { // Unless it's excluded by the user final ContentItem item = task.getContentItem(); if (item != null && context.isExcluded(item)) { continue; } // Run the task task.execute(); } return context.finalize(callback); }
[ "static", "PatchingResult", "executeTasks", "(", "final", "IdentityPatchContext", "context", ",", "final", "IdentityPatchContext", ".", "FinalizeCallback", "callback", ")", "throws", "Exception", "{", "final", "List", "<", "PreparedTask", ">", "tasks", "=", "new", "ArrayList", "<", "PreparedTask", ">", "(", ")", ";", "final", "List", "<", "ContentItem", ">", "conflicts", "=", "new", "ArrayList", "<", "ContentItem", ">", "(", ")", ";", "// Identity", "prepareTasks", "(", "context", ".", "getIdentityEntry", "(", ")", ",", "context", ",", "tasks", ",", "conflicts", ")", ";", "// Layers", "for", "(", "final", "IdentityPatchContext", ".", "PatchEntry", "layer", ":", "context", ".", "getLayers", "(", ")", ")", "{", "prepareTasks", "(", "layer", ",", "context", ",", "tasks", ",", "conflicts", ")", ";", "}", "// AddOns", "for", "(", "final", "IdentityPatchContext", ".", "PatchEntry", "addOn", ":", "context", ".", "getAddOns", "(", ")", ")", "{", "prepareTasks", "(", "addOn", ",", "context", ",", "tasks", ",", "conflicts", ")", ";", "}", "// If there were problems report them", "if", "(", "!", "conflicts", ".", "isEmpty", "(", ")", ")", "{", "throw", "PatchLogger", ".", "ROOT_LOGGER", ".", "conflictsDetected", "(", "conflicts", ")", ";", "}", "// Execute the tasks", "for", "(", "final", "PreparedTask", "task", ":", "tasks", ")", "{", "// Unless it's excluded by the user", "final", "ContentItem", "item", "=", "task", ".", "getContentItem", "(", ")", ";", "if", "(", "item", "!=", "null", "&&", "context", ".", "isExcluded", "(", "item", ")", ")", "{", "continue", ";", "}", "// Run the task", "task", ".", "execute", "(", ")", ";", "}", "return", "context", ".", "finalize", "(", "callback", ")", ";", "}" ]
Execute all recorded tasks. @param context the patch context @param callback the finalization callback @throws Exception
[ "Execute", "all", "recorded", "tasks", "." ]
cfaf0479dcbb2d320a44c5374b93b944ec39fade
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/patching/src/main/java/org/jboss/as/patching/runner/IdentityPatchRunner.java#L630-L658
159,131
wildfly/wildfly-core
patching/src/main/java/org/jboss/as/patching/runner/IdentityPatchRunner.java
IdentityPatchRunner.prepareTasks
static void prepareTasks(final IdentityPatchContext.PatchEntry entry, final IdentityPatchContext context, final List<PreparedTask> tasks, final List<ContentItem> conflicts) throws PatchingException { for (final PatchingTasks.ContentTaskDefinition definition : entry.getTaskDefinitions()) { final PatchingTask task = createTask(definition, context, entry); if(!task.isRelevant(entry)) { continue; } try { // backup and validate content if (!task.prepare(entry) || definition.hasConflicts()) { // Unless it a content item was manually ignored (or excluded) final ContentItem item = task.getContentItem(); if (!context.isIgnored(item)) { conflicts.add(item); } } tasks.add(new PreparedTask(task, entry)); } catch (IOException e) { throw new PatchingException(e); } } }
java
static void prepareTasks(final IdentityPatchContext.PatchEntry entry, final IdentityPatchContext context, final List<PreparedTask> tasks, final List<ContentItem> conflicts) throws PatchingException { for (final PatchingTasks.ContentTaskDefinition definition : entry.getTaskDefinitions()) { final PatchingTask task = createTask(definition, context, entry); if(!task.isRelevant(entry)) { continue; } try { // backup and validate content if (!task.prepare(entry) || definition.hasConflicts()) { // Unless it a content item was manually ignored (or excluded) final ContentItem item = task.getContentItem(); if (!context.isIgnored(item)) { conflicts.add(item); } } tasks.add(new PreparedTask(task, entry)); } catch (IOException e) { throw new PatchingException(e); } } }
[ "static", "void", "prepareTasks", "(", "final", "IdentityPatchContext", ".", "PatchEntry", "entry", ",", "final", "IdentityPatchContext", "context", ",", "final", "List", "<", "PreparedTask", ">", "tasks", ",", "final", "List", "<", "ContentItem", ">", "conflicts", ")", "throws", "PatchingException", "{", "for", "(", "final", "PatchingTasks", ".", "ContentTaskDefinition", "definition", ":", "entry", ".", "getTaskDefinitions", "(", ")", ")", "{", "final", "PatchingTask", "task", "=", "createTask", "(", "definition", ",", "context", ",", "entry", ")", ";", "if", "(", "!", "task", ".", "isRelevant", "(", "entry", ")", ")", "{", "continue", ";", "}", "try", "{", "// backup and validate content", "if", "(", "!", "task", ".", "prepare", "(", "entry", ")", "||", "definition", ".", "hasConflicts", "(", ")", ")", "{", "// Unless it a content item was manually ignored (or excluded)", "final", "ContentItem", "item", "=", "task", ".", "getContentItem", "(", ")", ";", "if", "(", "!", "context", ".", "isIgnored", "(", "item", ")", ")", "{", "conflicts", ".", "add", "(", "item", ")", ";", "}", "}", "tasks", ".", "add", "(", "new", "PreparedTask", "(", "task", ",", "entry", ")", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "PatchingException", "(", "e", ")", ";", "}", "}", "}" ]
Prepare all tasks. @param entry the patch entry @param context the patch context @param tasks a list for prepared tasks @param conflicts a list for conflicting content items @throws PatchingException
[ "Prepare", "all", "tasks", "." ]
cfaf0479dcbb2d320a44c5374b93b944ec39fade
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/patching/src/main/java/org/jboss/as/patching/runner/IdentityPatchRunner.java#L669-L689
159,132
wildfly/wildfly-core
patching/src/main/java/org/jboss/as/patching/runner/IdentityPatchRunner.java
IdentityPatchRunner.createTask
static PatchingTask createTask(final PatchingTasks.ContentTaskDefinition definition, final PatchContentProvider provider, final IdentityPatchContext.PatchEntry context) { final PatchContentLoader contentLoader = provider.getLoader(definition.getTarget().getPatchId()); final PatchingTaskDescription description = PatchingTaskDescription.create(definition, contentLoader); return PatchingTask.Factory.create(description, context); }
java
static PatchingTask createTask(final PatchingTasks.ContentTaskDefinition definition, final PatchContentProvider provider, final IdentityPatchContext.PatchEntry context) { final PatchContentLoader contentLoader = provider.getLoader(definition.getTarget().getPatchId()); final PatchingTaskDescription description = PatchingTaskDescription.create(definition, contentLoader); return PatchingTask.Factory.create(description, context); }
[ "static", "PatchingTask", "createTask", "(", "final", "PatchingTasks", ".", "ContentTaskDefinition", "definition", ",", "final", "PatchContentProvider", "provider", ",", "final", "IdentityPatchContext", ".", "PatchEntry", "context", ")", "{", "final", "PatchContentLoader", "contentLoader", "=", "provider", ".", "getLoader", "(", "definition", ".", "getTarget", "(", ")", ".", "getPatchId", "(", ")", ")", ";", "final", "PatchingTaskDescription", "description", "=", "PatchingTaskDescription", ".", "create", "(", "definition", ",", "contentLoader", ")", ";", "return", "PatchingTask", ".", "Factory", ".", "create", "(", "description", ",", "context", ")", ";", "}" ]
Create the patching task based on the definition. @param definition the task description @param provider the content provider @param context the task context @return the created task
[ "Create", "the", "patching", "task", "based", "on", "the", "definition", "." ]
cfaf0479dcbb2d320a44c5374b93b944ec39fade
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/patching/src/main/java/org/jboss/as/patching/runner/IdentityPatchRunner.java#L699-L703
159,133
wildfly/wildfly-core
patching/src/main/java/org/jboss/as/patching/runner/IdentityPatchRunner.java
IdentityPatchRunner.checkUpgradeConditions
static void checkUpgradeConditions(final UpgradeCondition condition, final InstallationManager.MutablePatchingTarget target) throws PatchingException { // See if the prerequisites are met for (final String required : condition.getRequires()) { if (!target.isApplied(required)) { throw PatchLogger.ROOT_LOGGER.requiresPatch(required); } } // Check for incompatibilities for (final String incompatible : condition.getIncompatibleWith()) { if (target.isApplied(incompatible)) { throw PatchLogger.ROOT_LOGGER.incompatiblePatch(incompatible); } } }
java
static void checkUpgradeConditions(final UpgradeCondition condition, final InstallationManager.MutablePatchingTarget target) throws PatchingException { // See if the prerequisites are met for (final String required : condition.getRequires()) { if (!target.isApplied(required)) { throw PatchLogger.ROOT_LOGGER.requiresPatch(required); } } // Check for incompatibilities for (final String incompatible : condition.getIncompatibleWith()) { if (target.isApplied(incompatible)) { throw PatchLogger.ROOT_LOGGER.incompatiblePatch(incompatible); } } }
[ "static", "void", "checkUpgradeConditions", "(", "final", "UpgradeCondition", "condition", ",", "final", "InstallationManager", ".", "MutablePatchingTarget", "target", ")", "throws", "PatchingException", "{", "// See if the prerequisites are met", "for", "(", "final", "String", "required", ":", "condition", ".", "getRequires", "(", ")", ")", "{", "if", "(", "!", "target", ".", "isApplied", "(", "required", ")", ")", "{", "throw", "PatchLogger", ".", "ROOT_LOGGER", ".", "requiresPatch", "(", "required", ")", ";", "}", "}", "// Check for incompatibilities", "for", "(", "final", "String", "incompatible", ":", "condition", ".", "getIncompatibleWith", "(", ")", ")", "{", "if", "(", "target", ".", "isApplied", "(", "incompatible", ")", ")", "{", "throw", "PatchLogger", ".", "ROOT_LOGGER", ".", "incompatiblePatch", "(", "incompatible", ")", ";", "}", "}", "}" ]
Check whether the patch can be applied to a given target. @param condition the conditions @param target the target @throws PatchingException
[ "Check", "whether", "the", "patch", "can", "be", "applied", "to", "a", "given", "target", "." ]
cfaf0479dcbb2d320a44c5374b93b944ec39fade
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/patching/src/main/java/org/jboss/as/patching/runner/IdentityPatchRunner.java#L769-L782
159,134
wildfly/wildfly-core
host-controller/src/main/java/org/jboss/as/host/controller/discovery/S3Util.java
S3Util.domainControllerDataFromByteBuffer
public static List<DomainControllerData> domainControllerDataFromByteBuffer(byte[] buffer) throws Exception { List<DomainControllerData> retval = new ArrayList<DomainControllerData>(); if (buffer == null) { return retval; } ByteArrayInputStream in_stream = new ByteArrayInputStream(buffer); DataInputStream in = new DataInputStream(in_stream); String content = SEPARATOR; while (SEPARATOR.equals(content)) { DomainControllerData data = new DomainControllerData(); data.readFrom(in); retval.add(data); try { content = readString(in); } catch (EOFException ex) { content = null; } } in.close(); return retval; }
java
public static List<DomainControllerData> domainControllerDataFromByteBuffer(byte[] buffer) throws Exception { List<DomainControllerData> retval = new ArrayList<DomainControllerData>(); if (buffer == null) { return retval; } ByteArrayInputStream in_stream = new ByteArrayInputStream(buffer); DataInputStream in = new DataInputStream(in_stream); String content = SEPARATOR; while (SEPARATOR.equals(content)) { DomainControllerData data = new DomainControllerData(); data.readFrom(in); retval.add(data); try { content = readString(in); } catch (EOFException ex) { content = null; } } in.close(); return retval; }
[ "public", "static", "List", "<", "DomainControllerData", ">", "domainControllerDataFromByteBuffer", "(", "byte", "[", "]", "buffer", ")", "throws", "Exception", "{", "List", "<", "DomainControllerData", ">", "retval", "=", "new", "ArrayList", "<", "DomainControllerData", ">", "(", ")", ";", "if", "(", "buffer", "==", "null", ")", "{", "return", "retval", ";", "}", "ByteArrayInputStream", "in_stream", "=", "new", "ByteArrayInputStream", "(", "buffer", ")", ";", "DataInputStream", "in", "=", "new", "DataInputStream", "(", "in_stream", ")", ";", "String", "content", "=", "SEPARATOR", ";", "while", "(", "SEPARATOR", ".", "equals", "(", "content", ")", ")", "{", "DomainControllerData", "data", "=", "new", "DomainControllerData", "(", ")", ";", "data", ".", "readFrom", "(", "in", ")", ";", "retval", ".", "add", "(", "data", ")", ";", "try", "{", "content", "=", "readString", "(", "in", ")", ";", "}", "catch", "(", "EOFException", "ex", ")", "{", "content", "=", "null", ";", "}", "}", "in", ".", "close", "(", ")", ";", "return", "retval", ";", "}" ]
Get the domain controller data from the given byte buffer. @param buffer the byte buffer @return the domain controller data @throws Exception
[ "Get", "the", "domain", "controller", "data", "from", "the", "given", "byte", "buffer", "." ]
cfaf0479dcbb2d320a44c5374b93b944ec39fade
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/host-controller/src/main/java/org/jboss/as/host/controller/discovery/S3Util.java#L83-L103
159,135
wildfly/wildfly-core
host-controller/src/main/java/org/jboss/as/host/controller/discovery/S3Util.java
S3Util.domainControllerDataToByteBuffer
public static byte[] domainControllerDataToByteBuffer(List<DomainControllerData> data) throws Exception { final ByteArrayOutputStream out_stream = new ByteArrayOutputStream(512); byte[] result; try (DataOutputStream out = new DataOutputStream(out_stream)) { Iterator<DomainControllerData> iter = data.iterator(); while (iter.hasNext()) { DomainControllerData dcData = iter.next(); dcData.writeTo(out); if (iter.hasNext()) { S3Util.writeString(SEPARATOR, out); } } result = out_stream.toByteArray(); } return result; }
java
public static byte[] domainControllerDataToByteBuffer(List<DomainControllerData> data) throws Exception { final ByteArrayOutputStream out_stream = new ByteArrayOutputStream(512); byte[] result; try (DataOutputStream out = new DataOutputStream(out_stream)) { Iterator<DomainControllerData> iter = data.iterator(); while (iter.hasNext()) { DomainControllerData dcData = iter.next(); dcData.writeTo(out); if (iter.hasNext()) { S3Util.writeString(SEPARATOR, out); } } result = out_stream.toByteArray(); } return result; }
[ "public", "static", "byte", "[", "]", "domainControllerDataToByteBuffer", "(", "List", "<", "DomainControllerData", ">", "data", ")", "throws", "Exception", "{", "final", "ByteArrayOutputStream", "out_stream", "=", "new", "ByteArrayOutputStream", "(", "512", ")", ";", "byte", "[", "]", "result", ";", "try", "(", "DataOutputStream", "out", "=", "new", "DataOutputStream", "(", "out_stream", ")", ")", "{", "Iterator", "<", "DomainControllerData", ">", "iter", "=", "data", ".", "iterator", "(", ")", ";", "while", "(", "iter", ".", "hasNext", "(", ")", ")", "{", "DomainControllerData", "dcData", "=", "iter", ".", "next", "(", ")", ";", "dcData", ".", "writeTo", "(", "out", ")", ";", "if", "(", "iter", ".", "hasNext", "(", ")", ")", "{", "S3Util", ".", "writeString", "(", "SEPARATOR", ",", "out", ")", ";", "}", "}", "result", "=", "out_stream", ".", "toByteArray", "(", ")", ";", "}", "return", "result", ";", "}" ]
Write the domain controller data to a byte buffer. @param data the domain controller data @return the byte buffer @throws Exception
[ "Write", "the", "domain", "controller", "data", "to", "a", "byte", "buffer", "." ]
cfaf0479dcbb2d320a44c5374b93b944ec39fade
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/host-controller/src/main/java/org/jboss/as/host/controller/discovery/S3Util.java#L112-L127
159,136
wildfly/wildfly-core
host-controller/src/main/java/org/jboss/as/domain/controller/plan/ConcurrentGroupServerUpdatePolicy.java
ConcurrentGroupServerUpdatePolicy.canSuccessorProceed
private boolean canSuccessorProceed() { if (predecessor != null && !predecessor.canSuccessorProceed()) { return false; } synchronized (this) { while (responseCount < groups.size()) { try { wait(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return false; } } return !failed; } }
java
private boolean canSuccessorProceed() { if (predecessor != null && !predecessor.canSuccessorProceed()) { return false; } synchronized (this) { while (responseCount < groups.size()) { try { wait(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return false; } } return !failed; } }
[ "private", "boolean", "canSuccessorProceed", "(", ")", "{", "if", "(", "predecessor", "!=", "null", "&&", "!", "predecessor", ".", "canSuccessorProceed", "(", ")", ")", "{", "return", "false", ";", "}", "synchronized", "(", "this", ")", "{", "while", "(", "responseCount", "<", "groups", ".", "size", "(", ")", ")", "{", "try", "{", "wait", "(", ")", ";", "}", "catch", "(", "InterruptedException", "e", ")", "{", "Thread", ".", "currentThread", "(", ")", ".", "interrupt", "(", ")", ";", "return", "false", ";", "}", "}", "return", "!", "failed", ";", "}", "}" ]
Check from another ConcurrentGroupServerUpdatePolicy whose plans are meant to execute once this policy's plans are successfully completed. @return <code>true</code> if the successor can proceed
[ "Check", "from", "another", "ConcurrentGroupServerUpdatePolicy", "whose", "plans", "are", "meant", "to", "execute", "once", "this", "policy", "s", "plans", "are", "successfully", "completed", "." ]
cfaf0479dcbb2d320a44c5374b93b944ec39fade
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/host-controller/src/main/java/org/jboss/as/domain/controller/plan/ConcurrentGroupServerUpdatePolicy.java#L64-L81
159,137
wildfly/wildfly-core
host-controller/src/main/java/org/jboss/as/domain/controller/plan/ConcurrentGroupServerUpdatePolicy.java
ConcurrentGroupServerUpdatePolicy.recordServerGroupResult
public void recordServerGroupResult(final String serverGroup, final boolean failed) { synchronized (this) { if (groups.contains(serverGroup)) { responseCount++; if (failed) { this.failed = true; } DomainControllerLogger.HOST_CONTROLLER_LOGGER.tracef("Recorded group result for '%s': failed = %s", serverGroup, failed); notifyAll(); } else { throw DomainControllerLogger.HOST_CONTROLLER_LOGGER.unknownServerGroup(serverGroup); } } }
java
public void recordServerGroupResult(final String serverGroup, final boolean failed) { synchronized (this) { if (groups.contains(serverGroup)) { responseCount++; if (failed) { this.failed = true; } DomainControllerLogger.HOST_CONTROLLER_LOGGER.tracef("Recorded group result for '%s': failed = %s", serverGroup, failed); notifyAll(); } else { throw DomainControllerLogger.HOST_CONTROLLER_LOGGER.unknownServerGroup(serverGroup); } } }
[ "public", "void", "recordServerGroupResult", "(", "final", "String", "serverGroup", ",", "final", "boolean", "failed", ")", "{", "synchronized", "(", "this", ")", "{", "if", "(", "groups", ".", "contains", "(", "serverGroup", ")", ")", "{", "responseCount", "++", ";", "if", "(", "failed", ")", "{", "this", ".", "failed", "=", "true", ";", "}", "DomainControllerLogger", ".", "HOST_CONTROLLER_LOGGER", ".", "tracef", "(", "\"Recorded group result for '%s': failed = %s\"", ",", "serverGroup", ",", "failed", ")", ";", "notifyAll", "(", ")", ";", "}", "else", "{", "throw", "DomainControllerLogger", ".", "HOST_CONTROLLER_LOGGER", ".", "unknownServerGroup", "(", "serverGroup", ")", ";", "}", "}", "}" ]
Records the result of updating a server group. @param serverGroup the server group's name. Cannot be <code>null</code> @param failed <code>true</code> if the server group update failed; <code>false</code> if it succeeded
[ "Records", "the", "result", "of", "updating", "a", "server", "group", "." ]
cfaf0479dcbb2d320a44c5374b93b944ec39fade
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/host-controller/src/main/java/org/jboss/as/domain/controller/plan/ConcurrentGroupServerUpdatePolicy.java#L100-L116
159,138
wildfly/wildfly-core
controller/src/main/java/org/jboss/as/controller/ModelControllerImpl.java
ModelControllerImpl.executeReadOnlyOperation
@SuppressWarnings("deprecation") protected ModelNode executeReadOnlyOperation(final ModelNode operation, final OperationMessageHandler handler, final OperationTransactionControl control, final OperationStepHandler prepareStep, final int operationId) { final AbstractOperationContext delegateContext = getDelegateContext(operationId); CurrentOperationIdHolder.setCurrentOperationID(operationId); try { return executeReadOnlyOperation(operation, delegateContext.getManagementModel(), control, prepareStep, delegateContext); } finally { CurrentOperationIdHolder.setCurrentOperationID(null); } }
java
@SuppressWarnings("deprecation") protected ModelNode executeReadOnlyOperation(final ModelNode operation, final OperationMessageHandler handler, final OperationTransactionControl control, final OperationStepHandler prepareStep, final int operationId) { final AbstractOperationContext delegateContext = getDelegateContext(operationId); CurrentOperationIdHolder.setCurrentOperationID(operationId); try { return executeReadOnlyOperation(operation, delegateContext.getManagementModel(), control, prepareStep, delegateContext); } finally { CurrentOperationIdHolder.setCurrentOperationID(null); } }
[ "@", "SuppressWarnings", "(", "\"deprecation\"", ")", "protected", "ModelNode", "executeReadOnlyOperation", "(", "final", "ModelNode", "operation", ",", "final", "OperationMessageHandler", "handler", ",", "final", "OperationTransactionControl", "control", ",", "final", "OperationStepHandler", "prepareStep", ",", "final", "int", "operationId", ")", "{", "final", "AbstractOperationContext", "delegateContext", "=", "getDelegateContext", "(", "operationId", ")", ";", "CurrentOperationIdHolder", ".", "setCurrentOperationID", "(", "operationId", ")", ";", "try", "{", "return", "executeReadOnlyOperation", "(", "operation", ",", "delegateContext", ".", "getManagementModel", "(", ")", ",", "control", ",", "prepareStep", ",", "delegateContext", ")", ";", "}", "finally", "{", "CurrentOperationIdHolder", ".", "setCurrentOperationID", "(", "null", ")", ";", "}", "}" ]
Executes an operation on the controller latching onto an existing transaction @param operation the operation @param handler the handler @param control the transaction control @param prepareStep the prepare step to be executed before any other steps @param operationId the id of the current transaction @return the result of the operation
[ "Executes", "an", "operation", "on", "the", "controller", "latching", "onto", "an", "existing", "transaction" ]
cfaf0479dcbb2d320a44c5374b93b944ec39fade
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/ModelControllerImpl.java#L271-L280
159,139
wildfly/wildfly-core
domain-http/interface/src/main/java/org/jboss/as/domain/http/server/ManagementHttpRequestProcessor.java
ManagementHttpRequestProcessor.addShutdownListener
public synchronized void addShutdownListener(ShutdownListener listener) { if (state == CLOSED) { listener.handleCompleted(); } else { listeners.add(listener); } }
java
public synchronized void addShutdownListener(ShutdownListener listener) { if (state == CLOSED) { listener.handleCompleted(); } else { listeners.add(listener); } }
[ "public", "synchronized", "void", "addShutdownListener", "(", "ShutdownListener", "listener", ")", "{", "if", "(", "state", "==", "CLOSED", ")", "{", "listener", ".", "handleCompleted", "(", ")", ";", "}", "else", "{", "listeners", ".", "add", "(", "listener", ")", ";", "}", "}" ]
Add a shutdown listener, which gets called when all requests completed on shutdown. @param listener the shutdown listener
[ "Add", "a", "shutdown", "listener", "which", "gets", "called", "when", "all", "requests", "completed", "on", "shutdown", "." ]
cfaf0479dcbb2d320a44c5374b93b944ec39fade
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/domain-http/interface/src/main/java/org/jboss/as/domain/http/server/ManagementHttpRequestProcessor.java#L93-L99
159,140
wildfly/wildfly-core
domain-http/interface/src/main/java/org/jboss/as/domain/http/server/ManagementHttpRequestProcessor.java
ManagementHttpRequestProcessor.handleCompleted
protected synchronized void handleCompleted() { latch.countDown(); for (final ShutdownListener listener : listeners) { listener.handleCompleted(); } listeners.clear(); }
java
protected synchronized void handleCompleted() { latch.countDown(); for (final ShutdownListener listener : listeners) { listener.handleCompleted(); } listeners.clear(); }
[ "protected", "synchronized", "void", "handleCompleted", "(", ")", "{", "latch", ".", "countDown", "(", ")", ";", "for", "(", "final", "ShutdownListener", "listener", ":", "listeners", ")", "{", "listener", ".", "handleCompleted", "(", ")", ";", "}", "listeners", ".", "clear", "(", ")", ";", "}" ]
Notify all shutdown listeners that the shutdown completed.
[ "Notify", "all", "shutdown", "listeners", "that", "the", "shutdown", "completed", "." ]
cfaf0479dcbb2d320a44c5374b93b944ec39fade
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/domain-http/interface/src/main/java/org/jboss/as/domain/http/server/ManagementHttpRequestProcessor.java#L104-L110
159,141
wildfly/wildfly-core
server/src/main/java/org/jboss/as/server/deployment/DeploymentResourceSupport.java
DeploymentResourceSupport.hasDeploymentSubsystemModel
public boolean hasDeploymentSubsystemModel(final String subsystemName) { final Resource root = deploymentUnit.getAttachment(DEPLOYMENT_RESOURCE); final PathElement subsystem = PathElement.pathElement(SUBSYSTEM, subsystemName); return root.hasChild(subsystem); }
java
public boolean hasDeploymentSubsystemModel(final String subsystemName) { final Resource root = deploymentUnit.getAttachment(DEPLOYMENT_RESOURCE); final PathElement subsystem = PathElement.pathElement(SUBSYSTEM, subsystemName); return root.hasChild(subsystem); }
[ "public", "boolean", "hasDeploymentSubsystemModel", "(", "final", "String", "subsystemName", ")", "{", "final", "Resource", "root", "=", "deploymentUnit", ".", "getAttachment", "(", "DEPLOYMENT_RESOURCE", ")", ";", "final", "PathElement", "subsystem", "=", "PathElement", ".", "pathElement", "(", "SUBSYSTEM", ",", "subsystemName", ")", ";", "return", "root", ".", "hasChild", "(", "subsystem", ")", ";", "}" ]
Checks to see if a subsystem resource has already been registered for the deployment. @param subsystemName the name of the subsystem @return {@code true} if the subsystem exists on the deployment otherwise {@code false}
[ "Checks", "to", "see", "if", "a", "subsystem", "resource", "has", "already", "been", "registered", "for", "the", "deployment", "." ]
cfaf0479dcbb2d320a44c5374b93b944ec39fade
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/server/src/main/java/org/jboss/as/server/deployment/DeploymentResourceSupport.java#L59-L63
159,142
wildfly/wildfly-core
server/src/main/java/org/jboss/as/server/deployment/DeploymentResourceSupport.java
DeploymentResourceSupport.getDeploymentSubsystemModel
public ModelNode getDeploymentSubsystemModel(final String subsystemName) { assert subsystemName != null : "The subsystemName cannot be null"; return getDeploymentSubModel(subsystemName, PathAddress.EMPTY_ADDRESS, null, deploymentUnit); }
java
public ModelNode getDeploymentSubsystemModel(final String subsystemName) { assert subsystemName != null : "The subsystemName cannot be null"; return getDeploymentSubModel(subsystemName, PathAddress.EMPTY_ADDRESS, null, deploymentUnit); }
[ "public", "ModelNode", "getDeploymentSubsystemModel", "(", "final", "String", "subsystemName", ")", "{", "assert", "subsystemName", "!=", "null", ":", "\"The subsystemName cannot be null\"", ";", "return", "getDeploymentSubModel", "(", "subsystemName", ",", "PathAddress", ".", "EMPTY_ADDRESS", ",", "null", ",", "deploymentUnit", ")", ";", "}" ]
Get the subsystem deployment model root. <p> If the subsystem resource does not exist one will be created. </p> @param subsystemName the subsystem name. @return the model
[ "Get", "the", "subsystem", "deployment", "model", "root", "." ]
cfaf0479dcbb2d320a44c5374b93b944ec39fade
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/server/src/main/java/org/jboss/as/server/deployment/DeploymentResourceSupport.java#L76-L79
159,143
wildfly/wildfly-core
server/src/main/java/org/jboss/as/server/deployment/DeploymentResourceSupport.java
DeploymentResourceSupport.registerDeploymentSubsystemResource
public ModelNode registerDeploymentSubsystemResource(final String subsystemName, final Resource resource) { assert subsystemName != null : "The subsystemName cannot be null"; assert resource != null : "The resource cannot be null"; return registerDeploymentSubResource(subsystemName, PathAddress.EMPTY_ADDRESS, resource); }
java
public ModelNode registerDeploymentSubsystemResource(final String subsystemName, final Resource resource) { assert subsystemName != null : "The subsystemName cannot be null"; assert resource != null : "The resource cannot be null"; return registerDeploymentSubResource(subsystemName, PathAddress.EMPTY_ADDRESS, resource); }
[ "public", "ModelNode", "registerDeploymentSubsystemResource", "(", "final", "String", "subsystemName", ",", "final", "Resource", "resource", ")", "{", "assert", "subsystemName", "!=", "null", ":", "\"The subsystemName cannot be null\"", ";", "assert", "resource", "!=", "null", ":", "\"The resource cannot be null\"", ";", "return", "registerDeploymentSubResource", "(", "subsystemName", ",", "PathAddress", ".", "EMPTY_ADDRESS", ",", "resource", ")", ";", "}" ]
Registers the resource to the parent deployment resource. The model returned is that of the resource parameter. @param subsystemName the subsystem name @param resource the resource to be used for the subsystem on the deployment @return the model @throws java.lang.IllegalStateException if the subsystem resource already exists
[ "Registers", "the", "resource", "to", "the", "parent", "deployment", "resource", ".", "The", "model", "returned", "is", "that", "of", "the", "resource", "parameter", "." ]
cfaf0479dcbb2d320a44c5374b93b944ec39fade
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/server/src/main/java/org/jboss/as/server/deployment/DeploymentResourceSupport.java#L91-L95
159,144
wildfly/wildfly-core
server/src/main/java/org/jboss/as/server/deployment/DeploymentResourceSupport.java
DeploymentResourceSupport.getOrCreateSubDeployment
static Resource getOrCreateSubDeployment(final String deploymentName, final DeploymentUnit parent) { final Resource root = parent.getAttachment(DEPLOYMENT_RESOURCE); return getOrCreate(root, PathElement.pathElement(SUBDEPLOYMENT, deploymentName)); }
java
static Resource getOrCreateSubDeployment(final String deploymentName, final DeploymentUnit parent) { final Resource root = parent.getAttachment(DEPLOYMENT_RESOURCE); return getOrCreate(root, PathElement.pathElement(SUBDEPLOYMENT, deploymentName)); }
[ "static", "Resource", "getOrCreateSubDeployment", "(", "final", "String", "deploymentName", ",", "final", "DeploymentUnit", "parent", ")", "{", "final", "Resource", "root", "=", "parent", ".", "getAttachment", "(", "DEPLOYMENT_RESOURCE", ")", ";", "return", "getOrCreate", "(", "root", ",", "PathElement", ".", "pathElement", "(", "SUBDEPLOYMENT", ",", "deploymentName", ")", ")", ";", "}" ]
Gets or creates the a resource for the sub-deployment on the parent deployments resource. @param deploymentName the name of the deployment @param parent the parent deployment used to find the parent resource @return the already registered resource or a newly created resource
[ "Gets", "or", "creates", "the", "a", "resource", "for", "the", "sub", "-", "deployment", "on", "the", "parent", "deployments", "resource", "." ]
cfaf0479dcbb2d320a44c5374b93b944ec39fade
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/server/src/main/java/org/jboss/as/server/deployment/DeploymentResourceSupport.java#L231-L234
159,145
wildfly/wildfly-core
server/src/main/java/org/jboss/as/server/deployment/DeploymentResourceSupport.java
DeploymentResourceSupport.cleanup
static void cleanup(final Resource resource) { synchronized (resource) { for (final Resource.ResourceEntry entry : resource.getChildren(SUBSYSTEM)) { resource.removeChild(entry.getPathElement()); } for (final Resource.ResourceEntry entry : resource.getChildren(SUBDEPLOYMENT)) { resource.removeChild(entry.getPathElement()); } } }
java
static void cleanup(final Resource resource) { synchronized (resource) { for (final Resource.ResourceEntry entry : resource.getChildren(SUBSYSTEM)) { resource.removeChild(entry.getPathElement()); } for (final Resource.ResourceEntry entry : resource.getChildren(SUBDEPLOYMENT)) { resource.removeChild(entry.getPathElement()); } } }
[ "static", "void", "cleanup", "(", "final", "Resource", "resource", ")", "{", "synchronized", "(", "resource", ")", "{", "for", "(", "final", "Resource", ".", "ResourceEntry", "entry", ":", "resource", ".", "getChildren", "(", "SUBSYSTEM", ")", ")", "{", "resource", ".", "removeChild", "(", "entry", ".", "getPathElement", "(", ")", ")", ";", "}", "for", "(", "final", "Resource", ".", "ResourceEntry", "entry", ":", "resource", ".", "getChildren", "(", "SUBDEPLOYMENT", ")", ")", "{", "resource", ".", "removeChild", "(", "entry", ".", "getPathElement", "(", ")", ")", ";", "}", "}", "}" ]
Cleans up the subsystem children for the deployment and each sub-deployment resource. @param resource the subsystem resource to clean up
[ "Cleans", "up", "the", "subsystem", "children", "for", "the", "deployment", "and", "each", "sub", "-", "deployment", "resource", "." ]
cfaf0479dcbb2d320a44c5374b93b944ec39fade
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/server/src/main/java/org/jboss/as/server/deployment/DeploymentResourceSupport.java#L241-L250
159,146
wildfly/wildfly-core
embedded/src/main/java/org/wildfly/core/embedded/SystemPropertyContext.java
SystemPropertyContext.resolveBaseDir
Path resolveBaseDir(final String name, final String dirName) { final String currentDir = SecurityActions.getPropertyPrivileged(name); if (currentDir == null) { return jbossHomeDir.resolve(dirName); } return Paths.get(currentDir); }
java
Path resolveBaseDir(final String name, final String dirName) { final String currentDir = SecurityActions.getPropertyPrivileged(name); if (currentDir == null) { return jbossHomeDir.resolve(dirName); } return Paths.get(currentDir); }
[ "Path", "resolveBaseDir", "(", "final", "String", "name", ",", "final", "String", "dirName", ")", "{", "final", "String", "currentDir", "=", "SecurityActions", ".", "getPropertyPrivileged", "(", "name", ")", ";", "if", "(", "currentDir", "==", "null", ")", "{", "return", "jbossHomeDir", ".", "resolve", "(", "dirName", ")", ";", "}", "return", "Paths", ".", "get", "(", "currentDir", ")", ";", "}" ]
Resolves the base directory. If the system property is set that value will be used. Otherwise the path is resolved from the home directory. @param name the system property name @param dirName the directory name relative to the base directory @return the resolved base directory
[ "Resolves", "the", "base", "directory", ".", "If", "the", "system", "property", "is", "set", "that", "value", "will", "be", "used", ".", "Otherwise", "the", "path", "is", "resolved", "from", "the", "home", "directory", "." ]
cfaf0479dcbb2d320a44c5374b93b944ec39fade
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/embedded/src/main/java/org/wildfly/core/embedded/SystemPropertyContext.java#L151-L157
159,147
wildfly/wildfly-core
embedded/src/main/java/org/wildfly/core/embedded/SystemPropertyContext.java
SystemPropertyContext.resolvePath
static Path resolvePath(final Path base, final String... paths) { return Paths.get(base.toString(), paths); }
java
static Path resolvePath(final Path base, final String... paths) { return Paths.get(base.toString(), paths); }
[ "static", "Path", "resolvePath", "(", "final", "Path", "base", ",", "final", "String", "...", "paths", ")", "{", "return", "Paths", ".", "get", "(", "base", ".", "toString", "(", ")", ",", "paths", ")", ";", "}" ]
Resolves a path relative to the base path. @param base the base path @param paths paths relative to the base directory @return the resolved path
[ "Resolves", "a", "path", "relative", "to", "the", "base", "path", "." ]
cfaf0479dcbb2d320a44c5374b93b944ec39fade
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/embedded/src/main/java/org/wildfly/core/embedded/SystemPropertyContext.java#L167-L169
159,148
wildfly/wildfly-core
controller/src/main/java/org/jboss/as/controller/operations/global/GlobalOperationHandlers.java
GlobalOperationHandlers.getChildAddresses
static Map<String, Set<String>> getChildAddresses(final OperationContext context, final PathAddress addr, final ImmutableManagementResourceRegistration registry, Resource resource, final String validChildType) { Map<String, Set<String>> result = new HashMap<>(); Predicate<String> validChildTypeFilter = childType -> (validChildType == null) || validChildType.equals(childType); if (resource != null) { for (String childType : registry.getChildNames(PathAddress.EMPTY_ADDRESS)) { if (validChildTypeFilter.test(childType)) { List<String> list = new ArrayList<>(); for (String child : resource.getChildrenNames(childType)) { if (registry.getSubModel(PathAddress.pathAddress(PathElement.pathElement(childType, child))) != null) { list.add(child); } } result.put(childType, new LinkedHashSet<>(list)); } } } Set<PathElement> paths = registry.getChildAddresses(PathAddress.EMPTY_ADDRESS); for (PathElement path : paths) { String childType = path.getKey(); if (validChildTypeFilter.test(childType)) { Set<String> children = result.get(childType); if (children == null) { // WFLY-3306 Ensure we have an entry for any valid child type children = new LinkedHashSet<>(); result.put(childType, children); } ImmutableManagementResourceRegistration childRegistration = registry.getSubModel(PathAddress.pathAddress(path)); if (childRegistration != null) { AliasEntry aliasEntry = childRegistration.getAliasEntry(); if (aliasEntry != null) { PathAddress childAddr = addr.append(path); PathAddress target = aliasEntry.convertToTargetAddress(childAddr, AliasContext.create(childAddr, context)); assert !childAddr.equals(target) : "Alias was not translated"; PathAddress targetParent = target.getParent(); Resource parentResource = context.readResourceFromRoot(targetParent, false); if (parentResource != null) { PathElement targetElement = target.getLastElement(); if (targetElement.isWildcard()) { children.addAll(parentResource.getChildrenNames(targetElement.getKey())); } else if (parentResource.hasChild(targetElement)) { children.add(path.getValue()); } } } if (!path.isWildcard() && childRegistration.isRemote()) { children.add(path.getValue()); } } } } return result; }
java
static Map<String, Set<String>> getChildAddresses(final OperationContext context, final PathAddress addr, final ImmutableManagementResourceRegistration registry, Resource resource, final String validChildType) { Map<String, Set<String>> result = new HashMap<>(); Predicate<String> validChildTypeFilter = childType -> (validChildType == null) || validChildType.equals(childType); if (resource != null) { for (String childType : registry.getChildNames(PathAddress.EMPTY_ADDRESS)) { if (validChildTypeFilter.test(childType)) { List<String> list = new ArrayList<>(); for (String child : resource.getChildrenNames(childType)) { if (registry.getSubModel(PathAddress.pathAddress(PathElement.pathElement(childType, child))) != null) { list.add(child); } } result.put(childType, new LinkedHashSet<>(list)); } } } Set<PathElement> paths = registry.getChildAddresses(PathAddress.EMPTY_ADDRESS); for (PathElement path : paths) { String childType = path.getKey(); if (validChildTypeFilter.test(childType)) { Set<String> children = result.get(childType); if (children == null) { // WFLY-3306 Ensure we have an entry for any valid child type children = new LinkedHashSet<>(); result.put(childType, children); } ImmutableManagementResourceRegistration childRegistration = registry.getSubModel(PathAddress.pathAddress(path)); if (childRegistration != null) { AliasEntry aliasEntry = childRegistration.getAliasEntry(); if (aliasEntry != null) { PathAddress childAddr = addr.append(path); PathAddress target = aliasEntry.convertToTargetAddress(childAddr, AliasContext.create(childAddr, context)); assert !childAddr.equals(target) : "Alias was not translated"; PathAddress targetParent = target.getParent(); Resource parentResource = context.readResourceFromRoot(targetParent, false); if (parentResource != null) { PathElement targetElement = target.getLastElement(); if (targetElement.isWildcard()) { children.addAll(parentResource.getChildrenNames(targetElement.getKey())); } else if (parentResource.hasChild(targetElement)) { children.add(path.getValue()); } } } if (!path.isWildcard() && childRegistration.isRemote()) { children.add(path.getValue()); } } } } return result; }
[ "static", "Map", "<", "String", ",", "Set", "<", "String", ">", ">", "getChildAddresses", "(", "final", "OperationContext", "context", ",", "final", "PathAddress", "addr", ",", "final", "ImmutableManagementResourceRegistration", "registry", ",", "Resource", "resource", ",", "final", "String", "validChildType", ")", "{", "Map", "<", "String", ",", "Set", "<", "String", ">", ">", "result", "=", "new", "HashMap", "<>", "(", ")", ";", "Predicate", "<", "String", ">", "validChildTypeFilter", "=", "childType", "->", "(", "validChildType", "==", "null", ")", "||", "validChildType", ".", "equals", "(", "childType", ")", ";", "if", "(", "resource", "!=", "null", ")", "{", "for", "(", "String", "childType", ":", "registry", ".", "getChildNames", "(", "PathAddress", ".", "EMPTY_ADDRESS", ")", ")", "{", "if", "(", "validChildTypeFilter", ".", "test", "(", "childType", ")", ")", "{", "List", "<", "String", ">", "list", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "String", "child", ":", "resource", ".", "getChildrenNames", "(", "childType", ")", ")", "{", "if", "(", "registry", ".", "getSubModel", "(", "PathAddress", ".", "pathAddress", "(", "PathElement", ".", "pathElement", "(", "childType", ",", "child", ")", ")", ")", "!=", "null", ")", "{", "list", ".", "add", "(", "child", ")", ";", "}", "}", "result", ".", "put", "(", "childType", ",", "new", "LinkedHashSet", "<>", "(", "list", ")", ")", ";", "}", "}", "}", "Set", "<", "PathElement", ">", "paths", "=", "registry", ".", "getChildAddresses", "(", "PathAddress", ".", "EMPTY_ADDRESS", ")", ";", "for", "(", "PathElement", "path", ":", "paths", ")", "{", "String", "childType", "=", "path", ".", "getKey", "(", ")", ";", "if", "(", "validChildTypeFilter", ".", "test", "(", "childType", ")", ")", "{", "Set", "<", "String", ">", "children", "=", "result", ".", "get", "(", "childType", ")", ";", "if", "(", "children", "==", "null", ")", "{", "// WFLY-3306 Ensure we have an entry for any valid child type", "children", "=", "new", "LinkedHashSet", "<>", "(", ")", ";", "result", ".", "put", "(", "childType", ",", "children", ")", ";", "}", "ImmutableManagementResourceRegistration", "childRegistration", "=", "registry", ".", "getSubModel", "(", "PathAddress", ".", "pathAddress", "(", "path", ")", ")", ";", "if", "(", "childRegistration", "!=", "null", ")", "{", "AliasEntry", "aliasEntry", "=", "childRegistration", ".", "getAliasEntry", "(", ")", ";", "if", "(", "aliasEntry", "!=", "null", ")", "{", "PathAddress", "childAddr", "=", "addr", ".", "append", "(", "path", ")", ";", "PathAddress", "target", "=", "aliasEntry", ".", "convertToTargetAddress", "(", "childAddr", ",", "AliasContext", ".", "create", "(", "childAddr", ",", "context", ")", ")", ";", "assert", "!", "childAddr", ".", "equals", "(", "target", ")", ":", "\"Alias was not translated\"", ";", "PathAddress", "targetParent", "=", "target", ".", "getParent", "(", ")", ";", "Resource", "parentResource", "=", "context", ".", "readResourceFromRoot", "(", "targetParent", ",", "false", ")", ";", "if", "(", "parentResource", "!=", "null", ")", "{", "PathElement", "targetElement", "=", "target", ".", "getLastElement", "(", ")", ";", "if", "(", "targetElement", ".", "isWildcard", "(", ")", ")", "{", "children", ".", "addAll", "(", "parentResource", ".", "getChildrenNames", "(", "targetElement", ".", "getKey", "(", ")", ")", ")", ";", "}", "else", "if", "(", "parentResource", ".", "hasChild", "(", "targetElement", ")", ")", "{", "children", ".", "add", "(", "path", ".", "getValue", "(", ")", ")", ";", "}", "}", "}", "if", "(", "!", "path", ".", "isWildcard", "(", ")", "&&", "childRegistration", ".", "isRemote", "(", ")", ")", "{", "children", ".", "add", "(", "path", ".", "getValue", "(", ")", ")", ";", "}", "}", "}", "}", "return", "result", ";", "}" ]
Gets the addresses of the child resources under the given resource. @param context the operation context @param registry registry entry representing the resource @param resource the current resource @param validChildType a single child type to which the results should be limited. If {@code null} the result should include all child types @return map where the keys are the child types and the values are a set of child names associated with a type
[ "Gets", "the", "addresses", "of", "the", "child", "resources", "under", "the", "given", "resource", "." ]
cfaf0479dcbb2d320a44c5374b93b944ec39fade
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/operations/global/GlobalOperationHandlers.java#L1009-L1064
159,149
Comcast/jrugged
jrugged-core/src/main/java/org/fishwife/jrugged/interval/DiscreteInterval.java
DiscreteInterval.plus
public DiscreteInterval plus(DiscreteInterval other) { return new DiscreteInterval(this.min + other.min, this.max + other.max); }
java
public DiscreteInterval plus(DiscreteInterval other) { return new DiscreteInterval(this.min + other.min, this.max + other.max); }
[ "public", "DiscreteInterval", "plus", "(", "DiscreteInterval", "other", ")", "{", "return", "new", "DiscreteInterval", "(", "this", ".", "min", "+", "other", ".", "min", ",", "this", ".", "max", "+", "other", ".", "max", ")", ";", "}" ]
Returns an interval representing the addition of the given interval with this one. @param other interval to add to this one @return interval sum
[ "Returns", "an", "interval", "representing", "the", "addition", "of", "the", "given", "interval", "with", "this", "one", "." ]
b6a5147c68ee733faf5616d49800abcbba67afe9
https://github.com/Comcast/jrugged/blob/b6a5147c68ee733faf5616d49800abcbba67afe9/jrugged-core/src/main/java/org/fishwife/jrugged/interval/DiscreteInterval.java#L74-L76
159,150
Comcast/jrugged
jrugged-core/src/main/java/org/fishwife/jrugged/interval/DiscreteInterval.java
DiscreteInterval.minus
public DiscreteInterval minus(DiscreteInterval other) { return new DiscreteInterval(this.min - other.max, this.max - other.min); }
java
public DiscreteInterval minus(DiscreteInterval other) { return new DiscreteInterval(this.min - other.max, this.max - other.min); }
[ "public", "DiscreteInterval", "minus", "(", "DiscreteInterval", "other", ")", "{", "return", "new", "DiscreteInterval", "(", "this", ".", "min", "-", "other", ".", "max", ",", "this", ".", "max", "-", "other", ".", "min", ")", ";", "}" ]
Returns an interval representing the subtraction of the given interval from this one. @param other interval to subtract from this one @return result of subtraction
[ "Returns", "an", "interval", "representing", "the", "subtraction", "of", "the", "given", "interval", "from", "this", "one", "." ]
b6a5147c68ee733faf5616d49800abcbba67afe9
https://github.com/Comcast/jrugged/blob/b6a5147c68ee733faf5616d49800abcbba67afe9/jrugged-core/src/main/java/org/fishwife/jrugged/interval/DiscreteInterval.java#L91-L93
159,151
Comcast/jrugged
jrugged-spring/src/main/java/org/fishwife/jrugged/spring/AnnotatedMethodScanner.java
AnnotatedMethodScanner.findAnnotatedMethods
public Set<Method> findAnnotatedMethods(String scanBase, Class<? extends Annotation> annotationClass) { Set<BeanDefinition> filteredComponents = findCandidateBeans(scanBase, annotationClass); return extractAnnotatedMethods(filteredComponents, annotationClass); }
java
public Set<Method> findAnnotatedMethods(String scanBase, Class<? extends Annotation> annotationClass) { Set<BeanDefinition> filteredComponents = findCandidateBeans(scanBase, annotationClass); return extractAnnotatedMethods(filteredComponents, annotationClass); }
[ "public", "Set", "<", "Method", ">", "findAnnotatedMethods", "(", "String", "scanBase", ",", "Class", "<", "?", "extends", "Annotation", ">", "annotationClass", ")", "{", "Set", "<", "BeanDefinition", ">", "filteredComponents", "=", "findCandidateBeans", "(", "scanBase", ",", "annotationClass", ")", ";", "return", "extractAnnotatedMethods", "(", "filteredComponents", ",", "annotationClass", ")", ";", "}" ]
Find all methods on classes under scanBase that are annotated with annotationClass. @param scanBase Package to scan recursively, in dot notation (ie: org.jrugged...) @param annotationClass Class of the annotation to search for @return Set&lt;Method&gt; The set of all @{java.lang.reflect.Method}s having the annotation
[ "Find", "all", "methods", "on", "classes", "under", "scanBase", "that", "are", "annotated", "with", "annotationClass", "." ]
b6a5147c68ee733faf5616d49800abcbba67afe9
https://github.com/Comcast/jrugged/blob/b6a5147c68ee733faf5616d49800abcbba67afe9/jrugged-spring/src/main/java/org/fishwife/jrugged/spring/AnnotatedMethodScanner.java#L48-L51
159,152
Comcast/jrugged
jrugged-core/src/main/java/org/fishwife/jrugged/CircuitBreaker.java
CircuitBreaker.reset
public void reset() { state = BreakerState.CLOSED; isHardTrip = false; byPass = false; isAttemptLive = false; notifyBreakerStateChange(getStatus()); }
java
public void reset() { state = BreakerState.CLOSED; isHardTrip = false; byPass = false; isAttemptLive = false; notifyBreakerStateChange(getStatus()); }
[ "public", "void", "reset", "(", ")", "{", "state", "=", "BreakerState", ".", "CLOSED", ";", "isHardTrip", "=", "false", ";", "byPass", "=", "false", ";", "isAttemptLive", "=", "false", ";", "notifyBreakerStateChange", "(", "getStatus", "(", ")", ")", ";", "}" ]
Manually set the breaker to be reset and ready for use. This is only useful after a manual trip otherwise the breaker will trip automatically again if the service is still unavailable. Just like a real breaker. WOOT!!!
[ "Manually", "set", "the", "breaker", "to", "be", "reset", "and", "ready", "for", "use", ".", "This", "is", "only", "useful", "after", "a", "manual", "trip", "otherwise", "the", "breaker", "will", "trip", "automatically", "again", "if", "the", "service", "is", "still", "unavailable", ".", "Just", "like", "a", "real", "breaker", ".", "WOOT!!!" ]
b6a5147c68ee733faf5616d49800abcbba67afe9
https://github.com/Comcast/jrugged/blob/b6a5147c68ee733faf5616d49800abcbba67afe9/jrugged-core/src/main/java/org/fishwife/jrugged/CircuitBreaker.java#L403-L410
159,153
Comcast/jrugged
jrugged-spring/src/main/java/org/fishwife/jrugged/spring/jmx/WebMBeanServerAdapter.java
WebMBeanServerAdapter.createWebMBeanAdapter
public WebMBeanAdapter createWebMBeanAdapter(String mBeanName, String encoding) throws JMException, UnsupportedEncodingException { return new WebMBeanAdapter(mBeanServer, mBeanName, encoding); }
java
public WebMBeanAdapter createWebMBeanAdapter(String mBeanName, String encoding) throws JMException, UnsupportedEncodingException { return new WebMBeanAdapter(mBeanServer, mBeanName, encoding); }
[ "public", "WebMBeanAdapter", "createWebMBeanAdapter", "(", "String", "mBeanName", ",", "String", "encoding", ")", "throws", "JMException", ",", "UnsupportedEncodingException", "{", "return", "new", "WebMBeanAdapter", "(", "mBeanServer", ",", "mBeanName", ",", "encoding", ")", ";", "}" ]
Create a WebMBeanAdaptor for a specified MBean name. @param mBeanName the MBean name (can be URL-encoded). @param encoding the string encoding to be used (i.e. UTF-8) @return the created WebMBeanAdaptor. @throws JMException Java Management Exception @throws UnsupportedEncodingException if the encoding is not supported.
[ "Create", "a", "WebMBeanAdaptor", "for", "a", "specified", "MBean", "name", "." ]
b6a5147c68ee733faf5616d49800abcbba67afe9
https://github.com/Comcast/jrugged/blob/b6a5147c68ee733faf5616d49800abcbba67afe9/jrugged-spring/src/main/java/org/fishwife/jrugged/spring/jmx/WebMBeanServerAdapter.java#L71-L74
159,154
Comcast/jrugged
jrugged-core/src/main/java/org/fishwife/jrugged/WindowedEventCounter.java
WindowedEventCounter.mark
public void mark() { final long currentTimeMillis = clock.currentTimeMillis(); synchronized (queue) { if (queue.size() == capacity) { /* * we're all filled up already, let's dequeue the oldest * timestamp to make room for this new one. */ queue.removeFirst(); } queue.addLast(currentTimeMillis); } }
java
public void mark() { final long currentTimeMillis = clock.currentTimeMillis(); synchronized (queue) { if (queue.size() == capacity) { /* * we're all filled up already, let's dequeue the oldest * timestamp to make room for this new one. */ queue.removeFirst(); } queue.addLast(currentTimeMillis); } }
[ "public", "void", "mark", "(", ")", "{", "final", "long", "currentTimeMillis", "=", "clock", ".", "currentTimeMillis", "(", ")", ";", "synchronized", "(", "queue", ")", "{", "if", "(", "queue", ".", "size", "(", ")", "==", "capacity", ")", "{", "/*\n * we're all filled up already, let's dequeue the oldest\n * timestamp to make room for this new one.\n */", "queue", ".", "removeFirst", "(", ")", ";", "}", "queue", ".", "addLast", "(", "currentTimeMillis", ")", ";", "}", "}" ]
Record a new event.
[ "Record", "a", "new", "event", "." ]
b6a5147c68ee733faf5616d49800abcbba67afe9
https://github.com/Comcast/jrugged/blob/b6a5147c68ee733faf5616d49800abcbba67afe9/jrugged-core/src/main/java/org/fishwife/jrugged/WindowedEventCounter.java#L75-L88
159,155
Comcast/jrugged
jrugged-core/src/main/java/org/fishwife/jrugged/WindowedEventCounter.java
WindowedEventCounter.tally
public int tally() { long currentTimeMillis = clock.currentTimeMillis(); // calculates time for which we remove any errors before final long removeTimesBeforeMillis = currentTimeMillis - windowMillis; synchronized (queue) { // drain out any expired timestamps but don't drain past empty while (!queue.isEmpty() && queue.peek() < removeTimesBeforeMillis) { queue.removeFirst(); } return queue.size(); } }
java
public int tally() { long currentTimeMillis = clock.currentTimeMillis(); // calculates time for which we remove any errors before final long removeTimesBeforeMillis = currentTimeMillis - windowMillis; synchronized (queue) { // drain out any expired timestamps but don't drain past empty while (!queue.isEmpty() && queue.peek() < removeTimesBeforeMillis) { queue.removeFirst(); } return queue.size(); } }
[ "public", "int", "tally", "(", ")", "{", "long", "currentTimeMillis", "=", "clock", ".", "currentTimeMillis", "(", ")", ";", "// calculates time for which we remove any errors before", "final", "long", "removeTimesBeforeMillis", "=", "currentTimeMillis", "-", "windowMillis", ";", "synchronized", "(", "queue", ")", "{", "// drain out any expired timestamps but don't drain past empty", "while", "(", "!", "queue", ".", "isEmpty", "(", ")", "&&", "queue", ".", "peek", "(", ")", "<", "removeTimesBeforeMillis", ")", "{", "queue", ".", "removeFirst", "(", ")", ";", "}", "return", "queue", ".", "size", "(", ")", ";", "}", "}" ]
Returns a count of in-window events. @return the the count of in-window events.
[ "Returns", "a", "count", "of", "in", "-", "window", "events", "." ]
b6a5147c68ee733faf5616d49800abcbba67afe9
https://github.com/Comcast/jrugged/blob/b6a5147c68ee733faf5616d49800abcbba67afe9/jrugged-core/src/main/java/org/fishwife/jrugged/WindowedEventCounter.java#L95-L108
159,156
Comcast/jrugged
jrugged-core/src/main/java/org/fishwife/jrugged/WindowedEventCounter.java
WindowedEventCounter.setCapacity
public void setCapacity(int capacity) { if (capacity <= 0) { throw new IllegalArgumentException("capacity must be greater than 0"); } synchronized (queue) { // If the capacity was reduced, we remove oldest elements until the // queue fits inside the specified capacity if (capacity < this.capacity) { while (queue.size() > capacity) { queue.removeFirst(); } } } this.capacity = capacity; }
java
public void setCapacity(int capacity) { if (capacity <= 0) { throw new IllegalArgumentException("capacity must be greater than 0"); } synchronized (queue) { // If the capacity was reduced, we remove oldest elements until the // queue fits inside the specified capacity if (capacity < this.capacity) { while (queue.size() > capacity) { queue.removeFirst(); } } } this.capacity = capacity; }
[ "public", "void", "setCapacity", "(", "int", "capacity", ")", "{", "if", "(", "capacity", "<=", "0", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"capacity must be greater than 0\"", ")", ";", "}", "synchronized", "(", "queue", ")", "{", "// If the capacity was reduced, we remove oldest elements until the", "// queue fits inside the specified capacity", "if", "(", "capacity", "<", "this", ".", "capacity", ")", "{", "while", "(", "queue", ".", "size", "(", ")", ">", "capacity", ")", "{", "queue", ".", "removeFirst", "(", ")", ";", "}", "}", "}", "this", ".", "capacity", "=", "capacity", ";", "}" ]
Specifies the maximum capacity of the counter. @param capacity <code>long</code> @throws IllegalArgumentException if windowMillis is less than 1.
[ "Specifies", "the", "maximum", "capacity", "of", "the", "counter", "." ]
b6a5147c68ee733faf5616d49800abcbba67afe9
https://github.com/Comcast/jrugged/blob/b6a5147c68ee733faf5616d49800abcbba67afe9/jrugged-core/src/main/java/org/fishwife/jrugged/WindowedEventCounter.java#L128-L144
159,157
Comcast/jrugged
jrugged-aspects/src/main/java/org/fishwife/jrugged/aspects/RetryableAspect.java
RetryableAspect.call
@Around("@annotation(retryableAnnotation)") public Object call(final ProceedingJoinPoint pjp, Retryable retryableAnnotation) throws Throwable { final int maxTries = retryableAnnotation.maxTries(); final int retryDelayMillies = retryableAnnotation.retryDelayMillis(); final Class<? extends Throwable>[] retryOn = retryableAnnotation.retryOn(); final boolean doubleDelay = retryableAnnotation.doubleDelay(); final boolean throwCauseException = retryableAnnotation.throwCauseException(); if (logger.isDebugEnabled()) { logger.debug("Have @Retryable method wrapping call on method {} of target object {}", new Object[] { pjp.getSignature().getName(), pjp.getTarget() }); } ServiceRetrier serviceRetrier = new ServiceRetrier(retryDelayMillies, maxTries, doubleDelay, throwCauseException, retryOn); return serviceRetrier.invoke( new Callable<Object>() { public Object call() throws Exception { try { return pjp.proceed(); } catch (Exception e) { throw e; } catch (Error e) { throw e; } catch (Throwable t) { throw new RuntimeException(t); } } } ); }
java
@Around("@annotation(retryableAnnotation)") public Object call(final ProceedingJoinPoint pjp, Retryable retryableAnnotation) throws Throwable { final int maxTries = retryableAnnotation.maxTries(); final int retryDelayMillies = retryableAnnotation.retryDelayMillis(); final Class<? extends Throwable>[] retryOn = retryableAnnotation.retryOn(); final boolean doubleDelay = retryableAnnotation.doubleDelay(); final boolean throwCauseException = retryableAnnotation.throwCauseException(); if (logger.isDebugEnabled()) { logger.debug("Have @Retryable method wrapping call on method {} of target object {}", new Object[] { pjp.getSignature().getName(), pjp.getTarget() }); } ServiceRetrier serviceRetrier = new ServiceRetrier(retryDelayMillies, maxTries, doubleDelay, throwCauseException, retryOn); return serviceRetrier.invoke( new Callable<Object>() { public Object call() throws Exception { try { return pjp.proceed(); } catch (Exception e) { throw e; } catch (Error e) { throw e; } catch (Throwable t) { throw new RuntimeException(t); } } } ); }
[ "@", "Around", "(", "\"@annotation(retryableAnnotation)\"", ")", "public", "Object", "call", "(", "final", "ProceedingJoinPoint", "pjp", ",", "Retryable", "retryableAnnotation", ")", "throws", "Throwable", "{", "final", "int", "maxTries", "=", "retryableAnnotation", ".", "maxTries", "(", ")", ";", "final", "int", "retryDelayMillies", "=", "retryableAnnotation", ".", "retryDelayMillis", "(", ")", ";", "final", "Class", "<", "?", "extends", "Throwable", ">", "[", "]", "retryOn", "=", "retryableAnnotation", ".", "retryOn", "(", ")", ";", "final", "boolean", "doubleDelay", "=", "retryableAnnotation", ".", "doubleDelay", "(", ")", ";", "final", "boolean", "throwCauseException", "=", "retryableAnnotation", ".", "throwCauseException", "(", ")", ";", "if", "(", "logger", ".", "isDebugEnabled", "(", ")", ")", "{", "logger", ".", "debug", "(", "\"Have @Retryable method wrapping call on method {} of target object {}\"", ",", "new", "Object", "[", "]", "{", "pjp", ".", "getSignature", "(", ")", ".", "getName", "(", ")", ",", "pjp", ".", "getTarget", "(", ")", "}", ")", ";", "}", "ServiceRetrier", "serviceRetrier", "=", "new", "ServiceRetrier", "(", "retryDelayMillies", ",", "maxTries", ",", "doubleDelay", ",", "throwCauseException", ",", "retryOn", ")", ";", "return", "serviceRetrier", ".", "invoke", "(", "new", "Callable", "<", "Object", ">", "(", ")", "{", "public", "Object", "call", "(", ")", "throws", "Exception", "{", "try", "{", "return", "pjp", ".", "proceed", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "e", ";", "}", "catch", "(", "Error", "e", ")", "{", "throw", "e", ";", "}", "catch", "(", "Throwable", "t", ")", "{", "throw", "new", "RuntimeException", "(", "t", ")", ";", "}", "}", "}", ")", ";", "}" ]
Runs a method call with retries. @param pjp a {@link ProceedingJoinPoint} representing an annotated method call. @param retryableAnnotation the {@link org.fishwife.jrugged.aspects.Retryable} annotation that wrapped the method. @throws Throwable if the method invocation itself throws one during execution. @return The return value from the method call.
[ "Runs", "a", "method", "call", "with", "retries", "." ]
b6a5147c68ee733faf5616d49800abcbba67afe9
https://github.com/Comcast/jrugged/blob/b6a5147c68ee733faf5616d49800abcbba67afe9/jrugged-aspects/src/main/java/org/fishwife/jrugged/aspects/RetryableAspect.java#L49-L86
159,158
Comcast/jrugged
jrugged-spring/src/main/java/org/fishwife/jrugged/spring/jmx/WebMBeanAdapter.java
WebMBeanAdapter.getAttributeMetadata
public Map<String, MBeanAttributeInfo> getAttributeMetadata() { MBeanAttributeInfo[] attributeList = mBeanInfo.getAttributes(); Map<String, MBeanAttributeInfo> attributeMap = new TreeMap<String, MBeanAttributeInfo>(); for (MBeanAttributeInfo attribute: attributeList) { attributeMap.put(attribute.getName(), attribute); } return attributeMap; }
java
public Map<String, MBeanAttributeInfo> getAttributeMetadata() { MBeanAttributeInfo[] attributeList = mBeanInfo.getAttributes(); Map<String, MBeanAttributeInfo> attributeMap = new TreeMap<String, MBeanAttributeInfo>(); for (MBeanAttributeInfo attribute: attributeList) { attributeMap.put(attribute.getName(), attribute); } return attributeMap; }
[ "public", "Map", "<", "String", ",", "MBeanAttributeInfo", ">", "getAttributeMetadata", "(", ")", "{", "MBeanAttributeInfo", "[", "]", "attributeList", "=", "mBeanInfo", ".", "getAttributes", "(", ")", ";", "Map", "<", "String", ",", "MBeanAttributeInfo", ">", "attributeMap", "=", "new", "TreeMap", "<", "String", ",", "MBeanAttributeInfo", ">", "(", ")", ";", "for", "(", "MBeanAttributeInfo", "attribute", ":", "attributeList", ")", "{", "attributeMap", ".", "put", "(", "attribute", ".", "getName", "(", ")", ",", "attribute", ")", ";", "}", "return", "attributeMap", ";", "}" ]
Get the Attribute metadata for an MBean by name. @return the {@link Map} of {@link String} attribute names to {@link MBeanAttributeInfo} values.
[ "Get", "the", "Attribute", "metadata", "for", "an", "MBean", "by", "name", "." ]
b6a5147c68ee733faf5616d49800abcbba67afe9
https://github.com/Comcast/jrugged/blob/b6a5147c68ee733faf5616d49800abcbba67afe9/jrugged-spring/src/main/java/org/fishwife/jrugged/spring/jmx/WebMBeanAdapter.java#L73-L82
159,159
Comcast/jrugged
jrugged-spring/src/main/java/org/fishwife/jrugged/spring/jmx/WebMBeanAdapter.java
WebMBeanAdapter.getOperationMetadata
public Map<String, MBeanOperationInfo> getOperationMetadata() { MBeanOperationInfo[] operations = mBeanInfo.getOperations(); Map<String, MBeanOperationInfo> operationMap = new TreeMap<String, MBeanOperationInfo>(); for (MBeanOperationInfo operation: operations) { operationMap.put(operation.getName(), operation); } return operationMap; }
java
public Map<String, MBeanOperationInfo> getOperationMetadata() { MBeanOperationInfo[] operations = mBeanInfo.getOperations(); Map<String, MBeanOperationInfo> operationMap = new TreeMap<String, MBeanOperationInfo>(); for (MBeanOperationInfo operation: operations) { operationMap.put(operation.getName(), operation); } return operationMap; }
[ "public", "Map", "<", "String", ",", "MBeanOperationInfo", ">", "getOperationMetadata", "(", ")", "{", "MBeanOperationInfo", "[", "]", "operations", "=", "mBeanInfo", ".", "getOperations", "(", ")", ";", "Map", "<", "String", ",", "MBeanOperationInfo", ">", "operationMap", "=", "new", "TreeMap", "<", "String", ",", "MBeanOperationInfo", ">", "(", ")", ";", "for", "(", "MBeanOperationInfo", "operation", ":", "operations", ")", "{", "operationMap", ".", "put", "(", "operation", ".", "getName", "(", ")", ",", "operation", ")", ";", "}", "return", "operationMap", ";", "}" ]
Get the Operation metadata for an MBean by name. @return the {@link Map} of {@link String} operation names to {@link MBeanOperationInfo} values.
[ "Get", "the", "Operation", "metadata", "for", "an", "MBean", "by", "name", "." ]
b6a5147c68ee733faf5616d49800abcbba67afe9
https://github.com/Comcast/jrugged/blob/b6a5147c68ee733faf5616d49800abcbba67afe9/jrugged-spring/src/main/java/org/fishwife/jrugged/spring/jmx/WebMBeanAdapter.java#L88-L97
159,160
Comcast/jrugged
jrugged-spring/src/main/java/org/fishwife/jrugged/spring/jmx/WebMBeanAdapter.java
WebMBeanAdapter.getOperationInfo
public MBeanOperationInfo getOperationInfo(String operationName) throws OperationNotFoundException, UnsupportedEncodingException { String decodedOperationName = sanitizer.urlDecode(operationName, encoding); Map<String, MBeanOperationInfo> operationMap = getOperationMetadata(); if (operationMap.containsKey(decodedOperationName)) { return operationMap.get(decodedOperationName); } throw new OperationNotFoundException("Could not find operation " + operationName + " on MBean " + objectName.getCanonicalName()); }
java
public MBeanOperationInfo getOperationInfo(String operationName) throws OperationNotFoundException, UnsupportedEncodingException { String decodedOperationName = sanitizer.urlDecode(operationName, encoding); Map<String, MBeanOperationInfo> operationMap = getOperationMetadata(); if (operationMap.containsKey(decodedOperationName)) { return operationMap.get(decodedOperationName); } throw new OperationNotFoundException("Could not find operation " + operationName + " on MBean " + objectName.getCanonicalName()); }
[ "public", "MBeanOperationInfo", "getOperationInfo", "(", "String", "operationName", ")", "throws", "OperationNotFoundException", ",", "UnsupportedEncodingException", "{", "String", "decodedOperationName", "=", "sanitizer", ".", "urlDecode", "(", "operationName", ",", "encoding", ")", ";", "Map", "<", "String", ",", "MBeanOperationInfo", ">", "operationMap", "=", "getOperationMetadata", "(", ")", ";", "if", "(", "operationMap", ".", "containsKey", "(", "decodedOperationName", ")", ")", "{", "return", "operationMap", ".", "get", "(", "decodedOperationName", ")", ";", "}", "throw", "new", "OperationNotFoundException", "(", "\"Could not find operation \"", "+", "operationName", "+", "\" on MBean \"", "+", "objectName", ".", "getCanonicalName", "(", ")", ")", ";", "}" ]
Get the Operation metadata for a single operation on an MBean by name. @param operationName the Operation name (can be URL-encoded). @return the {@link MBeanOperationInfo} for the operation. @throws OperationNotFoundException Method was not found @throws UnsupportedEncodingException if the encoding is not supported.
[ "Get", "the", "Operation", "metadata", "for", "a", "single", "operation", "on", "an", "MBean", "by", "name", "." ]
b6a5147c68ee733faf5616d49800abcbba67afe9
https://github.com/Comcast/jrugged/blob/b6a5147c68ee733faf5616d49800abcbba67afe9/jrugged-spring/src/main/java/org/fishwife/jrugged/spring/jmx/WebMBeanAdapter.java#L106-L116
159,161
Comcast/jrugged
jrugged-spring/src/main/java/org/fishwife/jrugged/spring/jmx/WebMBeanAdapter.java
WebMBeanAdapter.getAttributeValues
public Map<String,Object> getAttributeValues() throws AttributeNotFoundException, InstanceNotFoundException, ReflectionException { HashSet<String> attributeSet = new HashSet<String>(); for (MBeanAttributeInfo attributeInfo : mBeanInfo.getAttributes()) { attributeSet.add(attributeInfo.getName()); } AttributeList attributeList = mBeanServer.getAttributes(objectName, attributeSet.toArray(new String[attributeSet.size()])); Map<String, Object> attributeValueMap = new TreeMap<String, Object>(); for (Attribute attribute : attributeList.asList()) { attributeValueMap.put(attribute.getName(), sanitizer.escapeValue(attribute.getValue())); } return attributeValueMap; }
java
public Map<String,Object> getAttributeValues() throws AttributeNotFoundException, InstanceNotFoundException, ReflectionException { HashSet<String> attributeSet = new HashSet<String>(); for (MBeanAttributeInfo attributeInfo : mBeanInfo.getAttributes()) { attributeSet.add(attributeInfo.getName()); } AttributeList attributeList = mBeanServer.getAttributes(objectName, attributeSet.toArray(new String[attributeSet.size()])); Map<String, Object> attributeValueMap = new TreeMap<String, Object>(); for (Attribute attribute : attributeList.asList()) { attributeValueMap.put(attribute.getName(), sanitizer.escapeValue(attribute.getValue())); } return attributeValueMap; }
[ "public", "Map", "<", "String", ",", "Object", ">", "getAttributeValues", "(", ")", "throws", "AttributeNotFoundException", ",", "InstanceNotFoundException", ",", "ReflectionException", "{", "HashSet", "<", "String", ">", "attributeSet", "=", "new", "HashSet", "<", "String", ">", "(", ")", ";", "for", "(", "MBeanAttributeInfo", "attributeInfo", ":", "mBeanInfo", ".", "getAttributes", "(", ")", ")", "{", "attributeSet", ".", "add", "(", "attributeInfo", ".", "getName", "(", ")", ")", ";", "}", "AttributeList", "attributeList", "=", "mBeanServer", ".", "getAttributes", "(", "objectName", ",", "attributeSet", ".", "toArray", "(", "new", "String", "[", "attributeSet", ".", "size", "(", ")", "]", ")", ")", ";", "Map", "<", "String", ",", "Object", ">", "attributeValueMap", "=", "new", "TreeMap", "<", "String", ",", "Object", ">", "(", ")", ";", "for", "(", "Attribute", "attribute", ":", "attributeList", ".", "asList", "(", ")", ")", "{", "attributeValueMap", ".", "put", "(", "attribute", ".", "getName", "(", ")", ",", "sanitizer", ".", "escapeValue", "(", "attribute", ".", "getValue", "(", ")", ")", ")", ";", "}", "return", "attributeValueMap", ";", "}" ]
Get all the attribute values for an MBean by name. The values are HTML escaped. @return the {@link Map} of attribute names and values. @throws javax.management.AttributeNotFoundException Unable to find the 'attribute' @throws InstanceNotFoundException unable to find the specific bean @throws ReflectionException unable to interrogate the bean
[ "Get", "all", "the", "attribute", "values", "for", "an", "MBean", "by", "name", ".", "The", "values", "are", "HTML", "escaped", "." ]
b6a5147c68ee733faf5616d49800abcbba67afe9
https://github.com/Comcast/jrugged/blob/b6a5147c68ee733faf5616d49800abcbba67afe9/jrugged-spring/src/main/java/org/fishwife/jrugged/spring/jmx/WebMBeanAdapter.java#L125-L143
159,162
Comcast/jrugged
jrugged-spring/src/main/java/org/fishwife/jrugged/spring/jmx/WebMBeanAdapter.java
WebMBeanAdapter.getAttributeValue
public String getAttributeValue(String attributeName) throws JMException, UnsupportedEncodingException { String decodedAttributeName = sanitizer.urlDecode(attributeName, encoding); return sanitizer.escapeValue(mBeanServer.getAttribute(objectName, decodedAttributeName)); }
java
public String getAttributeValue(String attributeName) throws JMException, UnsupportedEncodingException { String decodedAttributeName = sanitizer.urlDecode(attributeName, encoding); return sanitizer.escapeValue(mBeanServer.getAttribute(objectName, decodedAttributeName)); }
[ "public", "String", "getAttributeValue", "(", "String", "attributeName", ")", "throws", "JMException", ",", "UnsupportedEncodingException", "{", "String", "decodedAttributeName", "=", "sanitizer", ".", "urlDecode", "(", "attributeName", ",", "encoding", ")", ";", "return", "sanitizer", ".", "escapeValue", "(", "mBeanServer", ".", "getAttribute", "(", "objectName", ",", "decodedAttributeName", ")", ")", ";", "}" ]
Get the value for a single attribute on an MBean by name. @param attributeName the attribute name (can be URL-encoded). @return the value as a String. @throws JMException Java Management Exception @throws UnsupportedEncodingException if the encoding is not supported.
[ "Get", "the", "value", "for", "a", "single", "attribute", "on", "an", "MBean", "by", "name", "." ]
b6a5147c68ee733faf5616d49800abcbba67afe9
https://github.com/Comcast/jrugged/blob/b6a5147c68ee733faf5616d49800abcbba67afe9/jrugged-spring/src/main/java/org/fishwife/jrugged/spring/jmx/WebMBeanAdapter.java#L152-L156
159,163
Comcast/jrugged
jrugged-spring/src/main/java/org/fishwife/jrugged/spring/jmx/WebMBeanAdapter.java
WebMBeanAdapter.invokeOperation
public String invokeOperation(String operationName, Map<String, String[]> parameterMap) throws JMException, UnsupportedEncodingException { MBeanOperationInfo operationInfo = getOperationInfo(operationName); MBeanOperationInvoker invoker = createMBeanOperationInvoker(mBeanServer, objectName, operationInfo); return sanitizer.escapeValue(invoker.invokeOperation(parameterMap)); }
java
public String invokeOperation(String operationName, Map<String, String[]> parameterMap) throws JMException, UnsupportedEncodingException { MBeanOperationInfo operationInfo = getOperationInfo(operationName); MBeanOperationInvoker invoker = createMBeanOperationInvoker(mBeanServer, objectName, operationInfo); return sanitizer.escapeValue(invoker.invokeOperation(parameterMap)); }
[ "public", "String", "invokeOperation", "(", "String", "operationName", ",", "Map", "<", "String", ",", "String", "[", "]", ">", "parameterMap", ")", "throws", "JMException", ",", "UnsupportedEncodingException", "{", "MBeanOperationInfo", "operationInfo", "=", "getOperationInfo", "(", "operationName", ")", ";", "MBeanOperationInvoker", "invoker", "=", "createMBeanOperationInvoker", "(", "mBeanServer", ",", "objectName", ",", "operationInfo", ")", ";", "return", "sanitizer", ".", "escapeValue", "(", "invoker", ".", "invokeOperation", "(", "parameterMap", ")", ")", ";", "}" ]
Invoke an operation on an MBean by name. Note that only basic data types are supported for parameter values. @param operationName the operation name (can be URL-encoded). @param parameterMap the {@link Map} of parameter names and value arrays. @return the returned value from the operation. @throws JMException Java Management Exception @throws UnsupportedEncodingException if the encoding is not supported.
[ "Invoke", "an", "operation", "on", "an", "MBean", "by", "name", ".", "Note", "that", "only", "basic", "data", "types", "are", "supported", "for", "parameter", "values", "." ]
b6a5147c68ee733faf5616d49800abcbba67afe9
https://github.com/Comcast/jrugged/blob/b6a5147c68ee733faf5616d49800abcbba67afe9/jrugged-spring/src/main/java/org/fishwife/jrugged/spring/jmx/WebMBeanAdapter.java#L167-L172
159,164
Comcast/jrugged
jrugged-spring/src/main/java/org/fishwife/jrugged/spring/jmx/MBeanStringSanitizer.java
MBeanStringSanitizer.urlDecode
String urlDecode(String name, String encoding) throws UnsupportedEncodingException { return URLDecoder.decode(name, encoding); }
java
String urlDecode(String name, String encoding) throws UnsupportedEncodingException { return URLDecoder.decode(name, encoding); }
[ "String", "urlDecode", "(", "String", "name", ",", "String", "encoding", ")", "throws", "UnsupportedEncodingException", "{", "return", "URLDecoder", ".", "decode", "(", "name", ",", "encoding", ")", ";", "}" ]
Convert a URL Encoded name back to the original form. @param name the name to URL urlDecode. @param encoding the string encoding to be used (i.e. UTF-8) @return the name in original form. @throws UnsupportedEncodingException if the encoding is not supported.
[ "Convert", "a", "URL", "Encoded", "name", "back", "to", "the", "original", "form", "." ]
b6a5147c68ee733faf5616d49800abcbba67afe9
https://github.com/Comcast/jrugged/blob/b6a5147c68ee733faf5616d49800abcbba67afe9/jrugged-spring/src/main/java/org/fishwife/jrugged/spring/jmx/MBeanStringSanitizer.java#L37-L39
159,165
Comcast/jrugged
jrugged-spring/src/main/java/org/fishwife/jrugged/spring/jmx/MBeanStringSanitizer.java
MBeanStringSanitizer.escapeValue
String escapeValue(Object value) { return HtmlUtils.htmlEscape(value != null ? value.toString() : "<null>"); }
java
String escapeValue(Object value) { return HtmlUtils.htmlEscape(value != null ? value.toString() : "<null>"); }
[ "String", "escapeValue", "(", "Object", "value", ")", "{", "return", "HtmlUtils", ".", "htmlEscape", "(", "value", "!=", "null", "?", "value", ".", "toString", "(", ")", ":", "\"<null>\"", ")", ";", "}" ]
Escape a value to be HTML friendly. @param value the Object value. @return the HTML-escaped String, or <null> if the value is null.
[ "Escape", "a", "value", "to", "be", "HTML", "friendly", "." ]
b6a5147c68ee733faf5616d49800abcbba67afe9
https://github.com/Comcast/jrugged/blob/b6a5147c68ee733faf5616d49800abcbba67afe9/jrugged-spring/src/main/java/org/fishwife/jrugged/spring/jmx/MBeanStringSanitizer.java#L46-L48
159,166
Comcast/jrugged
jrugged-spring/src/main/java/org/fishwife/jrugged/spring/config/PerformanceMonitorBeanDefinitionDecorator.java
PerformanceMonitorBeanDefinitionDecorator.registerProxyCreator
private void registerProxyCreator(Node source, BeanDefinitionHolder holder, ParserContext context) { String beanName = holder.getBeanName(); String proxyName = beanName + "Proxy"; String interceptorName = beanName + "PerformanceMonitorInterceptor"; BeanDefinitionBuilder initializer = BeanDefinitionBuilder.rootBeanDefinition(BeanNameAutoProxyCreator.class); initializer.addPropertyValue("beanNames", beanName); initializer.addPropertyValue("interceptorNames", interceptorName); BeanDefinitionRegistry registry = context.getRegistry(); registry.registerBeanDefinition(proxyName, initializer.getBeanDefinition()); }
java
private void registerProxyCreator(Node source, BeanDefinitionHolder holder, ParserContext context) { String beanName = holder.getBeanName(); String proxyName = beanName + "Proxy"; String interceptorName = beanName + "PerformanceMonitorInterceptor"; BeanDefinitionBuilder initializer = BeanDefinitionBuilder.rootBeanDefinition(BeanNameAutoProxyCreator.class); initializer.addPropertyValue("beanNames", beanName); initializer.addPropertyValue("interceptorNames", interceptorName); BeanDefinitionRegistry registry = context.getRegistry(); registry.registerBeanDefinition(proxyName, initializer.getBeanDefinition()); }
[ "private", "void", "registerProxyCreator", "(", "Node", "source", ",", "BeanDefinitionHolder", "holder", ",", "ParserContext", "context", ")", "{", "String", "beanName", "=", "holder", ".", "getBeanName", "(", ")", ";", "String", "proxyName", "=", "beanName", "+", "\"Proxy\"", ";", "String", "interceptorName", "=", "beanName", "+", "\"PerformanceMonitorInterceptor\"", ";", "BeanDefinitionBuilder", "initializer", "=", "BeanDefinitionBuilder", ".", "rootBeanDefinition", "(", "BeanNameAutoProxyCreator", ".", "class", ")", ";", "initializer", ".", "addPropertyValue", "(", "\"beanNames\"", ",", "beanName", ")", ";", "initializer", ".", "addPropertyValue", "(", "\"interceptorNames\"", ",", "interceptorName", ")", ";", "BeanDefinitionRegistry", "registry", "=", "context", ".", "getRegistry", "(", ")", ";", "registry", ".", "registerBeanDefinition", "(", "proxyName", ",", "initializer", ".", "getBeanDefinition", "(", ")", ")", ";", "}" ]
Registers a BeanNameAutoProxyCreator class that wraps the bean being monitored. The proxy is associated with the PerformanceMonitorInterceptor for the bean, which is created when parsing the methods attribute from the springconfiguration xml file. @param source An Attribute node from the spring configuration @param holder A container for the beans I will create @param context the context currently parsing my spring config
[ "Registers", "a", "BeanNameAutoProxyCreator", "class", "that", "wraps", "the", "bean", "being", "monitored", ".", "The", "proxy", "is", "associated", "with", "the", "PerformanceMonitorInterceptor", "for", "the", "bean", "which", "is", "created", "when", "parsing", "the", "methods", "attribute", "from", "the", "springconfiguration", "xml", "file", "." ]
b6a5147c68ee733faf5616d49800abcbba67afe9
https://github.com/Comcast/jrugged/blob/b6a5147c68ee733faf5616d49800abcbba67afe9/jrugged-spring/src/main/java/org/fishwife/jrugged/spring/config/PerformanceMonitorBeanDefinitionDecorator.java#L78-L94
159,167
Comcast/jrugged
jrugged-core/src/main/java/org/fishwife/jrugged/CircuitBreakerFactory.java
CircuitBreakerFactory.getIntegerPropertyOverrideValue
private Integer getIntegerPropertyOverrideValue(String name, String key) { if (properties != null) { String propertyName = getPropertyName(name, key); String propertyOverrideValue = properties.getProperty(propertyName); if (propertyOverrideValue != null) { try { return Integer.parseInt(propertyOverrideValue); } catch (NumberFormatException e) { logger.error("Could not parse property override key={}, value={}", key, propertyOverrideValue); } } } return null; }
java
private Integer getIntegerPropertyOverrideValue(String name, String key) { if (properties != null) { String propertyName = getPropertyName(name, key); String propertyOverrideValue = properties.getProperty(propertyName); if (propertyOverrideValue != null) { try { return Integer.parseInt(propertyOverrideValue); } catch (NumberFormatException e) { logger.error("Could not parse property override key={}, value={}", key, propertyOverrideValue); } } } return null; }
[ "private", "Integer", "getIntegerPropertyOverrideValue", "(", "String", "name", ",", "String", "key", ")", "{", "if", "(", "properties", "!=", "null", ")", "{", "String", "propertyName", "=", "getPropertyName", "(", "name", ",", "key", ")", ";", "String", "propertyOverrideValue", "=", "properties", ".", "getProperty", "(", "propertyName", ")", ";", "if", "(", "propertyOverrideValue", "!=", "null", ")", "{", "try", "{", "return", "Integer", ".", "parseInt", "(", "propertyOverrideValue", ")", ";", "}", "catch", "(", "NumberFormatException", "e", ")", "{", "logger", ".", "error", "(", "\"Could not parse property override key={}, value={}\"", ",", "key", ",", "propertyOverrideValue", ")", ";", "}", "}", "}", "return", "null", ";", "}" ]
Get an integer property override value. @param name the {@link CircuitBreaker} name. @param key the property override key. @return the property override value, or null if it is not found.
[ "Get", "an", "integer", "property", "override", "value", "." ]
b6a5147c68ee733faf5616d49800abcbba67afe9
https://github.com/Comcast/jrugged/blob/b6a5147c68ee733faf5616d49800abcbba67afe9/jrugged-core/src/main/java/org/fishwife/jrugged/CircuitBreakerFactory.java#L174-L191
159,168
Comcast/jrugged
jrugged-spring/src/main/java/org/fishwife/jrugged/spring/config/SingleServiceWrapperInterceptor.java
SingleServiceWrapperInterceptor.shouldWrapMethodCall
private boolean shouldWrapMethodCall(String methodName) { if (methodList == null) { return true; // Wrap all by default } if (methodList.contains(methodName)) { return true; //Wrap a specific method } // If I get to this point, I should not wrap the call. return false; }
java
private boolean shouldWrapMethodCall(String methodName) { if (methodList == null) { return true; // Wrap all by default } if (methodList.contains(methodName)) { return true; //Wrap a specific method } // If I get to this point, I should not wrap the call. return false; }
[ "private", "boolean", "shouldWrapMethodCall", "(", "String", "methodName", ")", "{", "if", "(", "methodList", "==", "null", ")", "{", "return", "true", ";", "// Wrap all by default", "}", "if", "(", "methodList", ".", "contains", "(", "methodName", ")", ")", "{", "return", "true", ";", "//Wrap a specific method", "}", "// If I get to this point, I should not wrap the call.", "return", "false", ";", "}" ]
Checks if the method being invoked should be wrapped by a service. It looks the method name up in the methodList. If its in the list, then the method should be wrapped. If the list is null, then all methods are wrapped. @param methodName The method being called @return boolean
[ "Checks", "if", "the", "method", "being", "invoked", "should", "be", "wrapped", "by", "a", "service", ".", "It", "looks", "the", "method", "name", "up", "in", "the", "methodList", ".", "If", "its", "in", "the", "list", "then", "the", "method", "should", "be", "wrapped", ".", "If", "the", "list", "is", "null", "then", "all", "methods", "are", "wrapped", "." ]
b6a5147c68ee733faf5616d49800abcbba67afe9
https://github.com/Comcast/jrugged/blob/b6a5147c68ee733faf5616d49800abcbba67afe9/jrugged-spring/src/main/java/org/fishwife/jrugged/spring/config/SingleServiceWrapperInterceptor.java#L79-L90
159,169
Comcast/jrugged
jrugged-spring/src/main/java/org/fishwife/jrugged/spring/jmx/MBeanOperationInvoker.java
MBeanOperationInvoker.invokeOperation
public Object invokeOperation(Map<String, String[]> parameterMap) throws JMException { MBeanParameterInfo[] parameterInfoArray = operationInfo.getSignature(); Object[] values = new Object[parameterInfoArray.length]; String[] types = new String[parameterInfoArray.length]; MBeanValueConverter valueConverter = createMBeanValueConverter(parameterMap); for (int parameterNum = 0; parameterNum < parameterInfoArray.length; parameterNum++) { MBeanParameterInfo parameterInfo = parameterInfoArray[parameterNum]; String type = parameterInfo.getType(); types[parameterNum] = type; values[parameterNum] = valueConverter.convertParameterValue(parameterInfo.getName(), type); } return mBeanServer.invoke(objectName, operationInfo.getName(), values, types); }
java
public Object invokeOperation(Map<String, String[]> parameterMap) throws JMException { MBeanParameterInfo[] parameterInfoArray = operationInfo.getSignature(); Object[] values = new Object[parameterInfoArray.length]; String[] types = new String[parameterInfoArray.length]; MBeanValueConverter valueConverter = createMBeanValueConverter(parameterMap); for (int parameterNum = 0; parameterNum < parameterInfoArray.length; parameterNum++) { MBeanParameterInfo parameterInfo = parameterInfoArray[parameterNum]; String type = parameterInfo.getType(); types[parameterNum] = type; values[parameterNum] = valueConverter.convertParameterValue(parameterInfo.getName(), type); } return mBeanServer.invoke(objectName, operationInfo.getName(), values, types); }
[ "public", "Object", "invokeOperation", "(", "Map", "<", "String", ",", "String", "[", "]", ">", "parameterMap", ")", "throws", "JMException", "{", "MBeanParameterInfo", "[", "]", "parameterInfoArray", "=", "operationInfo", ".", "getSignature", "(", ")", ";", "Object", "[", "]", "values", "=", "new", "Object", "[", "parameterInfoArray", ".", "length", "]", ";", "String", "[", "]", "types", "=", "new", "String", "[", "parameterInfoArray", ".", "length", "]", ";", "MBeanValueConverter", "valueConverter", "=", "createMBeanValueConverter", "(", "parameterMap", ")", ";", "for", "(", "int", "parameterNum", "=", "0", ";", "parameterNum", "<", "parameterInfoArray", ".", "length", ";", "parameterNum", "++", ")", "{", "MBeanParameterInfo", "parameterInfo", "=", "parameterInfoArray", "[", "parameterNum", "]", ";", "String", "type", "=", "parameterInfo", ".", "getType", "(", ")", ";", "types", "[", "parameterNum", "]", "=", "type", ";", "values", "[", "parameterNum", "]", "=", "valueConverter", ".", "convertParameterValue", "(", "parameterInfo", ".", "getName", "(", ")", ",", "type", ")", ";", "}", "return", "mBeanServer", ".", "invoke", "(", "objectName", ",", "operationInfo", ".", "getName", "(", ")", ",", "values", ",", "types", ")", ";", "}" ]
Invoke the operation. @param parameterMap the {@link Map} of parameter names to value arrays. @return the {@link Object} return value from the operation. @throws JMException Java Management Exception
[ "Invoke", "the", "operation", "." ]
b6a5147c68ee733faf5616d49800abcbba67afe9
https://github.com/Comcast/jrugged/blob/b6a5147c68ee733faf5616d49800abcbba67afe9/jrugged-spring/src/main/java/org/fishwife/jrugged/spring/jmx/MBeanOperationInvoker.java#L52-L68
159,170
Comcast/jrugged
jrugged-spring/src/main/java/org/fishwife/jrugged/spring/config/MonitorMethodInterceptorDefinitionDecorator.java
MonitorMethodInterceptorDefinitionDecorator.registerInterceptor
private void registerInterceptor(Node source, String beanName, BeanDefinitionRegistry registry) { List<String> methodList = buildMethodList(source); BeanDefinitionBuilder initializer = BeanDefinitionBuilder.rootBeanDefinition(SingleServiceWrapperInterceptor.class); initializer.addPropertyValue("methods", methodList); String perfMonitorName = beanName + "PerformanceMonitor"; initializer.addPropertyReference("serviceWrapper", perfMonitorName); String interceptorName = beanName + "PerformanceMonitorInterceptor"; registry.registerBeanDefinition(interceptorName, initializer.getBeanDefinition()); }
java
private void registerInterceptor(Node source, String beanName, BeanDefinitionRegistry registry) { List<String> methodList = buildMethodList(source); BeanDefinitionBuilder initializer = BeanDefinitionBuilder.rootBeanDefinition(SingleServiceWrapperInterceptor.class); initializer.addPropertyValue("methods", methodList); String perfMonitorName = beanName + "PerformanceMonitor"; initializer.addPropertyReference("serviceWrapper", perfMonitorName); String interceptorName = beanName + "PerformanceMonitorInterceptor"; registry.registerBeanDefinition(interceptorName, initializer.getBeanDefinition()); }
[ "private", "void", "registerInterceptor", "(", "Node", "source", ",", "String", "beanName", ",", "BeanDefinitionRegistry", "registry", ")", "{", "List", "<", "String", ">", "methodList", "=", "buildMethodList", "(", "source", ")", ";", "BeanDefinitionBuilder", "initializer", "=", "BeanDefinitionBuilder", ".", "rootBeanDefinition", "(", "SingleServiceWrapperInterceptor", ".", "class", ")", ";", "initializer", ".", "addPropertyValue", "(", "\"methods\"", ",", "methodList", ")", ";", "String", "perfMonitorName", "=", "beanName", "+", "\"PerformanceMonitor\"", ";", "initializer", ".", "addPropertyReference", "(", "\"serviceWrapper\"", ",", "perfMonitorName", ")", ";", "String", "interceptorName", "=", "beanName", "+", "\"PerformanceMonitorInterceptor\"", ";", "registry", ".", "registerBeanDefinition", "(", "interceptorName", ",", "initializer", ".", "getBeanDefinition", "(", ")", ")", ";", "}" ]
Register a new SingleServiceWrapperInterceptor for the bean being wrapped, associate it with the PerformanceMonitor and tell it which methods to intercept. @param source An Attribute node from the spring configuration @param beanName The name of the bean that this performance monitor is wrapped around @param registry The registry where all the spring beans are registered
[ "Register", "a", "new", "SingleServiceWrapperInterceptor", "for", "the", "bean", "being", "wrapped", "associate", "it", "with", "the", "PerformanceMonitor", "and", "tell", "it", "which", "methods", "to", "intercept", "." ]
b6a5147c68ee733faf5616d49800abcbba67afe9
https://github.com/Comcast/jrugged/blob/b6a5147c68ee733faf5616d49800abcbba67afe9/jrugged-spring/src/main/java/org/fishwife/jrugged/spring/config/MonitorMethodInterceptorDefinitionDecorator.java#L69-L83
159,171
Comcast/jrugged
jrugged-spring/src/main/java/org/fishwife/jrugged/spring/config/MonitorMethodInterceptorDefinitionDecorator.java
MonitorMethodInterceptorDefinitionDecorator.parseMethodList
public List<String> parseMethodList(String methods) { String[] methodArray = StringUtils.delimitedListToStringArray(methods, ","); List<String> methodList = new ArrayList<String>(); for (String methodName : methodArray) { methodList.add(methodName.trim()); } return methodList; }
java
public List<String> parseMethodList(String methods) { String[] methodArray = StringUtils.delimitedListToStringArray(methods, ","); List<String> methodList = new ArrayList<String>(); for (String methodName : methodArray) { methodList.add(methodName.trim()); } return methodList; }
[ "public", "List", "<", "String", ">", "parseMethodList", "(", "String", "methods", ")", "{", "String", "[", "]", "methodArray", "=", "StringUtils", ".", "delimitedListToStringArray", "(", "methods", ",", "\",\"", ")", ";", "List", "<", "String", ">", "methodList", "=", "new", "ArrayList", "<", "String", ">", "(", ")", ";", "for", "(", "String", "methodName", ":", "methodArray", ")", "{", "methodList", ".", "add", "(", "methodName", ".", "trim", "(", ")", ")", ";", "}", "return", "methodList", ";", "}" ]
Parse a comma-delimited list of method names into a List of strings. Whitespace is ignored. @param methods the comma delimited list of methods from the spring configuration @return List&lt;String&gt;
[ "Parse", "a", "comma", "-", "delimited", "list", "of", "method", "names", "into", "a", "List", "of", "strings", ".", "Whitespace", "is", "ignored", "." ]
b6a5147c68ee733faf5616d49800abcbba67afe9
https://github.com/Comcast/jrugged/blob/b6a5147c68ee733faf5616d49800abcbba67afe9/jrugged-spring/src/main/java/org/fishwife/jrugged/spring/config/MonitorMethodInterceptorDefinitionDecorator.java#L107-L117
159,172
Comcast/jrugged
jrugged-spring/src/main/java/org/fishwife/jrugged/spring/config/MonitorMethodInterceptorDefinitionDecorator.java
MonitorMethodInterceptorDefinitionDecorator.registerPerformanceMonitor
private void registerPerformanceMonitor(String beanName, BeanDefinitionRegistry registry) { String perfMonitorName = beanName + "PerformanceMonitor"; if (!registry.containsBeanDefinition(perfMonitorName)) { BeanDefinitionBuilder initializer = BeanDefinitionBuilder.rootBeanDefinition(PerformanceMonitorBean.class); registry.registerBeanDefinition(perfMonitorName, initializer.getBeanDefinition()); } }
java
private void registerPerformanceMonitor(String beanName, BeanDefinitionRegistry registry) { String perfMonitorName = beanName + "PerformanceMonitor"; if (!registry.containsBeanDefinition(perfMonitorName)) { BeanDefinitionBuilder initializer = BeanDefinitionBuilder.rootBeanDefinition(PerformanceMonitorBean.class); registry.registerBeanDefinition(perfMonitorName, initializer.getBeanDefinition()); } }
[ "private", "void", "registerPerformanceMonitor", "(", "String", "beanName", ",", "BeanDefinitionRegistry", "registry", ")", "{", "String", "perfMonitorName", "=", "beanName", "+", "\"PerformanceMonitor\"", ";", "if", "(", "!", "registry", ".", "containsBeanDefinition", "(", "perfMonitorName", ")", ")", "{", "BeanDefinitionBuilder", "initializer", "=", "BeanDefinitionBuilder", ".", "rootBeanDefinition", "(", "PerformanceMonitorBean", ".", "class", ")", ";", "registry", ".", "registerBeanDefinition", "(", "perfMonitorName", ",", "initializer", ".", "getBeanDefinition", "(", ")", ")", ";", "}", "}" ]
Register a new PerformanceMonitor with Spring if it does not already exist. @param beanName The name of the bean that this performance monitor is wrapped around @param registry The registry where all the spring beans are registered
[ "Register", "a", "new", "PerformanceMonitor", "with", "Spring", "if", "it", "does", "not", "already", "exist", "." ]
b6a5147c68ee733faf5616d49800abcbba67afe9
https://github.com/Comcast/jrugged/blob/b6a5147c68ee733faf5616d49800abcbba67afe9/jrugged-spring/src/main/java/org/fishwife/jrugged/spring/config/MonitorMethodInterceptorDefinitionDecorator.java#L125-L134
159,173
flapdoodle-oss/de.flapdoodle.embed.process
src/main/java/de/flapdoodle/embed/process/io/file/Files.java
Files.forceDelete
public static void forceDelete(final Path path) throws IOException { if (!java.nio.file.Files.isDirectory(path)) { java.nio.file.Files.delete(path); } else { java.nio.file.Files.walkFileTree(path, DeleteDirVisitor.getInstance()); } }
java
public static void forceDelete(final Path path) throws IOException { if (!java.nio.file.Files.isDirectory(path)) { java.nio.file.Files.delete(path); } else { java.nio.file.Files.walkFileTree(path, DeleteDirVisitor.getInstance()); } }
[ "public", "static", "void", "forceDelete", "(", "final", "Path", "path", ")", "throws", "IOException", "{", "if", "(", "!", "java", ".", "nio", ".", "file", ".", "Files", ".", "isDirectory", "(", "path", ")", ")", "{", "java", ".", "nio", ".", "file", ".", "Files", ".", "delete", "(", "path", ")", ";", "}", "else", "{", "java", ".", "nio", ".", "file", ".", "Files", ".", "walkFileTree", "(", "path", ",", "DeleteDirVisitor", ".", "getInstance", "(", ")", ")", ";", "}", "}" ]
Deletes a path from the filesystem If the path is a directory its contents will be recursively deleted before it itself is deleted. Note that removal of a directory is not an atomic-operation and so if an error occurs during removal, some of the directories descendants may have already been removed @throws IOException if an error occurs whilst removing a file or directory
[ "Deletes", "a", "path", "from", "the", "filesystem" ]
c6eebcf6705372ab15d4c438dcefcd50ffbde6d0
https://github.com/flapdoodle-oss/de.flapdoodle.embed.process/blob/c6eebcf6705372ab15d4c438dcefcd50ffbde6d0/src/main/java/de/flapdoodle/embed/process/io/file/Files.java#L143-L149
159,174
jkrasnay/sqlbuilder
src/main/java/ca/krasnay/sqlbuilder/SelectCreator.java
SelectCreator.count
public PreparedStatementCreator count(final Dialect dialect) { return new PreparedStatementCreator() { public PreparedStatement createPreparedStatement(Connection con) throws SQLException { return getPreparedStatementCreator() .setSql(dialect.createCountSelect(builder.toString())) .createPreparedStatement(con); } }; }
java
public PreparedStatementCreator count(final Dialect dialect) { return new PreparedStatementCreator() { public PreparedStatement createPreparedStatement(Connection con) throws SQLException { return getPreparedStatementCreator() .setSql(dialect.createCountSelect(builder.toString())) .createPreparedStatement(con); } }; }
[ "public", "PreparedStatementCreator", "count", "(", "final", "Dialect", "dialect", ")", "{", "return", "new", "PreparedStatementCreator", "(", ")", "{", "public", "PreparedStatement", "createPreparedStatement", "(", "Connection", "con", ")", "throws", "SQLException", "{", "return", "getPreparedStatementCreator", "(", ")", ".", "setSql", "(", "dialect", ".", "createCountSelect", "(", "builder", ".", "toString", "(", ")", ")", ")", ".", "createPreparedStatement", "(", "con", ")", ";", "}", "}", ";", "}" ]
Returns a PreparedStatementCreator that returns a count of the rows that this creator would return. @param dialect Database dialect.
[ "Returns", "a", "PreparedStatementCreator", "that", "returns", "a", "count", "of", "the", "rows", "that", "this", "creator", "would", "return", "." ]
8e6acedc51cfad0527263376af51e1ef052f7147
https://github.com/jkrasnay/sqlbuilder/blob/8e6acedc51cfad0527263376af51e1ef052f7147/src/main/java/ca/krasnay/sqlbuilder/SelectCreator.java#L80-L89
159,175
jkrasnay/sqlbuilder
src/main/java/ca/krasnay/sqlbuilder/SelectCreator.java
SelectCreator.page
public PreparedStatementCreator page(final Dialect dialect, final int limit, final int offset) { return new PreparedStatementCreator() { public PreparedStatement createPreparedStatement(Connection con) throws SQLException { return getPreparedStatementCreator() .setSql(dialect.createPageSelect(builder.toString(), limit, offset)) .createPreparedStatement(con); } }; }
java
public PreparedStatementCreator page(final Dialect dialect, final int limit, final int offset) { return new PreparedStatementCreator() { public PreparedStatement createPreparedStatement(Connection con) throws SQLException { return getPreparedStatementCreator() .setSql(dialect.createPageSelect(builder.toString(), limit, offset)) .createPreparedStatement(con); } }; }
[ "public", "PreparedStatementCreator", "page", "(", "final", "Dialect", "dialect", ",", "final", "int", "limit", ",", "final", "int", "offset", ")", "{", "return", "new", "PreparedStatementCreator", "(", ")", "{", "public", "PreparedStatement", "createPreparedStatement", "(", "Connection", "con", ")", "throws", "SQLException", "{", "return", "getPreparedStatementCreator", "(", ")", ".", "setSql", "(", "dialect", ".", "createPageSelect", "(", "builder", ".", "toString", "(", ")", ",", "limit", ",", "offset", ")", ")", ".", "createPreparedStatement", "(", "con", ")", ";", "}", "}", ";", "}" ]
Returns a PreparedStatementCreator that returns a page of the underlying result set. @param dialect Database dialect to use. @param limit Maximum number of rows to return. @param offset Index of the first row to return.
[ "Returns", "a", "PreparedStatementCreator", "that", "returns", "a", "page", "of", "the", "underlying", "result", "set", "." ]
8e6acedc51cfad0527263376af51e1ef052f7147
https://github.com/jkrasnay/sqlbuilder/blob/8e6acedc51cfad0527263376af51e1ef052f7147/src/main/java/ca/krasnay/sqlbuilder/SelectCreator.java#L165-L173
159,176
jkrasnay/sqlbuilder
src/main/java/ca/krasnay/sqlbuilder/orm/Column.java
Column.toColumnName
private static String toColumnName(String fieldName) { int lastDot = fieldName.indexOf('.'); if (lastDot > -1) { return fieldName.substring(lastDot + 1); } else { return fieldName; } }
java
private static String toColumnName(String fieldName) { int lastDot = fieldName.indexOf('.'); if (lastDot > -1) { return fieldName.substring(lastDot + 1); } else { return fieldName; } }
[ "private", "static", "String", "toColumnName", "(", "String", "fieldName", ")", "{", "int", "lastDot", "=", "fieldName", ".", "indexOf", "(", "'", "'", ")", ";", "if", "(", "lastDot", ">", "-", "1", ")", "{", "return", "fieldName", ".", "substring", "(", "lastDot", "+", "1", ")", ";", "}", "else", "{", "return", "fieldName", ";", "}", "}" ]
Returns the portion of the field name after the last dot, as field names may actually be paths.
[ "Returns", "the", "portion", "of", "the", "field", "name", "after", "the", "last", "dot", "as", "field", "names", "may", "actually", "be", "paths", "." ]
8e6acedc51cfad0527263376af51e1ef052f7147
https://github.com/jkrasnay/sqlbuilder/blob/8e6acedc51cfad0527263376af51e1ef052f7147/src/main/java/ca/krasnay/sqlbuilder/orm/Column.java#L15-L22
159,177
jkrasnay/sqlbuilder
src/main/java/ca/krasnay/sqlbuilder/Predicates.java
Predicates.anyBitsSet
public static Predicate anyBitsSet(final String expr, final long bits) { return new Predicate() { private String param; public void init(AbstractSqlCreator creator) { param = creator.allocateParameter(); creator.setParameter(param, bits); } public String toSql() { return String.format("(%s & :%s) > 0", expr, param); } }; }
java
public static Predicate anyBitsSet(final String expr, final long bits) { return new Predicate() { private String param; public void init(AbstractSqlCreator creator) { param = creator.allocateParameter(); creator.setParameter(param, bits); } public String toSql() { return String.format("(%s & :%s) > 0", expr, param); } }; }
[ "public", "static", "Predicate", "anyBitsSet", "(", "final", "String", "expr", ",", "final", "long", "bits", ")", "{", "return", "new", "Predicate", "(", ")", "{", "private", "String", "param", ";", "public", "void", "init", "(", "AbstractSqlCreator", "creator", ")", "{", "param", "=", "creator", ".", "allocateParameter", "(", ")", ";", "creator", ".", "setParameter", "(", "param", ",", "bits", ")", ";", "}", "public", "String", "toSql", "(", ")", "{", "return", "String", ".", "format", "(", "\"(%s & :%s) > 0\"", ",", "expr", ",", "param", ")", ";", "}", "}", ";", "}" ]
Adds a clause that checks whether ANY set bits in a bitmask are present in a numeric expression. @param expr SQL numeric expression to check. @param bits Integer containing the bits for which to check.
[ "Adds", "a", "clause", "that", "checks", "whether", "ANY", "set", "bits", "in", "a", "bitmask", "are", "present", "in", "a", "numeric", "expression", "." ]
8e6acedc51cfad0527263376af51e1ef052f7147
https://github.com/jkrasnay/sqlbuilder/blob/8e6acedc51cfad0527263376af51e1ef052f7147/src/main/java/ca/krasnay/sqlbuilder/Predicates.java#L74-L85
159,178
jkrasnay/sqlbuilder
src/main/java/ca/krasnay/sqlbuilder/Predicates.java
Predicates.is
public static Predicate is(final String sql) { return new Predicate() { public String toSql() { return sql; } public void init(AbstractSqlCreator creator) { } }; }
java
public static Predicate is(final String sql) { return new Predicate() { public String toSql() { return sql; } public void init(AbstractSqlCreator creator) { } }; }
[ "public", "static", "Predicate", "is", "(", "final", "String", "sql", ")", "{", "return", "new", "Predicate", "(", ")", "{", "public", "String", "toSql", "(", ")", "{", "return", "sql", ";", "}", "public", "void", "init", "(", "AbstractSqlCreator", "creator", ")", "{", "}", "}", ";", "}" ]
Returns a predicate that takes no parameters. The given SQL expression is used directly. @param sql SQL text of the expression
[ "Returns", "a", "predicate", "that", "takes", "no", "parameters", ".", "The", "given", "SQL", "expression", "is", "used", "directly", "." ]
8e6acedc51cfad0527263376af51e1ef052f7147
https://github.com/jkrasnay/sqlbuilder/blob/8e6acedc51cfad0527263376af51e1ef052f7147/src/main/java/ca/krasnay/sqlbuilder/Predicates.java#L171-L179
159,179
jkrasnay/sqlbuilder
src/main/java/ca/krasnay/sqlbuilder/Predicates.java
Predicates.join
private static Predicate join(final String joinWord, final List<Predicate> preds) { return new Predicate() { public void init(AbstractSqlCreator creator) { for (Predicate p : preds) { p.init(creator); } } public String toSql() { StringBuilder sb = new StringBuilder() .append("("); boolean first = true; for (Predicate p : preds) { if (!first) { sb.append(" ").append(joinWord).append(" "); } sb.append(p.toSql()); first = false; } return sb.append(")").toString(); } }; }
java
private static Predicate join(final String joinWord, final List<Predicate> preds) { return new Predicate() { public void init(AbstractSqlCreator creator) { for (Predicate p : preds) { p.init(creator); } } public String toSql() { StringBuilder sb = new StringBuilder() .append("("); boolean first = true; for (Predicate p : preds) { if (!first) { sb.append(" ").append(joinWord).append(" "); } sb.append(p.toSql()); first = false; } return sb.append(")").toString(); } }; }
[ "private", "static", "Predicate", "join", "(", "final", "String", "joinWord", ",", "final", "List", "<", "Predicate", ">", "preds", ")", "{", "return", "new", "Predicate", "(", ")", "{", "public", "void", "init", "(", "AbstractSqlCreator", "creator", ")", "{", "for", "(", "Predicate", "p", ":", "preds", ")", "{", "p", ".", "init", "(", "creator", ")", ";", "}", "}", "public", "String", "toSql", "(", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ".", "append", "(", "\"(\"", ")", ";", "boolean", "first", "=", "true", ";", "for", "(", "Predicate", "p", ":", "preds", ")", "{", "if", "(", "!", "first", ")", "{", "sb", ".", "append", "(", "\" \"", ")", ".", "append", "(", "joinWord", ")", ".", "append", "(", "\" \"", ")", ";", "}", "sb", ".", "append", "(", "p", ".", "toSql", "(", ")", ")", ";", "first", "=", "false", ";", "}", "return", "sb", ".", "append", "(", "\")\"", ")", ".", "toString", "(", ")", ";", "}", "}", ";", "}" ]
Factory for 'and' and 'or' predicates.
[ "Factory", "for", "and", "and", "or", "predicates", "." ]
8e6acedc51cfad0527263376af51e1ef052f7147
https://github.com/jkrasnay/sqlbuilder/blob/8e6acedc51cfad0527263376af51e1ef052f7147/src/main/java/ca/krasnay/sqlbuilder/Predicates.java#L184-L205
159,180
jkrasnay/sqlbuilder
src/main/java/ca/krasnay/sqlbuilder/orm/Mapping.java
Mapping.addFields
public Mapping<T> addFields() { if (idColumn == null) { throw new RuntimeException("Map ID column before adding class fields"); } for (Field f : ReflectionUtils.getDeclaredFieldsInHierarchy(clazz)) { if (!Modifier.isStatic(f.getModifiers()) && !isFieldMapped(f.getName()) && !ignoredFields.contains(f.getName())) { addColumn(f.getName()); } } return this; }
java
public Mapping<T> addFields() { if (idColumn == null) { throw new RuntimeException("Map ID column before adding class fields"); } for (Field f : ReflectionUtils.getDeclaredFieldsInHierarchy(clazz)) { if (!Modifier.isStatic(f.getModifiers()) && !isFieldMapped(f.getName()) && !ignoredFields.contains(f.getName())) { addColumn(f.getName()); } } return this; }
[ "public", "Mapping", "<", "T", ">", "addFields", "(", ")", "{", "if", "(", "idColumn", "==", "null", ")", "{", "throw", "new", "RuntimeException", "(", "\"Map ID column before adding class fields\"", ")", ";", "}", "for", "(", "Field", "f", ":", "ReflectionUtils", ".", "getDeclaredFieldsInHierarchy", "(", "clazz", ")", ")", "{", "if", "(", "!", "Modifier", ".", "isStatic", "(", "f", ".", "getModifiers", "(", ")", ")", "&&", "!", "isFieldMapped", "(", "f", ".", "getName", "(", ")", ")", "&&", "!", "ignoredFields", ".", "contains", "(", "f", ".", "getName", "(", ")", ")", ")", "{", "addColumn", "(", "f", ".", "getName", "(", ")", ")", ";", "}", "}", "return", "this", ";", "}" ]
Adds mappings for each declared field in the mapped class. Any fields already mapped by addColumn are skipped.
[ "Adds", "mappings", "for", "each", "declared", "field", "in", "the", "mapped", "class", ".", "Any", "fields", "already", "mapped", "by", "addColumn", "are", "skipped", "." ]
8e6acedc51cfad0527263376af51e1ef052f7147
https://github.com/jkrasnay/sqlbuilder/blob/8e6acedc51cfad0527263376af51e1ef052f7147/src/main/java/ca/krasnay/sqlbuilder/orm/Mapping.java#L300-L315
159,181
jkrasnay/sqlbuilder
src/main/java/ca/krasnay/sqlbuilder/orm/Mapping.java
Mapping.createInstance
protected T createInstance() { try { Constructor<T> ctor = clazz.getDeclaredConstructor(); ctor.setAccessible(true); return ctor.newInstance(); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (SecurityException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } catch (IllegalArgumentException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } }
java
protected T createInstance() { try { Constructor<T> ctor = clazz.getDeclaredConstructor(); ctor.setAccessible(true); return ctor.newInstance(); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (SecurityException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } catch (IllegalArgumentException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } }
[ "protected", "T", "createInstance", "(", ")", "{", "try", "{", "Constructor", "<", "T", ">", "ctor", "=", "clazz", ".", "getDeclaredConstructor", "(", ")", ";", "ctor", ".", "setAccessible", "(", "true", ")", ";", "return", "ctor", ".", "newInstance", "(", ")", ";", "}", "catch", "(", "InstantiationException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "catch", "(", "IllegalAccessException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "catch", "(", "SecurityException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "catch", "(", "NoSuchMethodException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "catch", "(", "IllegalArgumentException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "catch", "(", "InvocationTargetException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "}" ]
Creates instance of the entity class. This method is called to create the object instances when returning query results.
[ "Creates", "instance", "of", "the", "entity", "class", ".", "This", "method", "is", "called", "to", "create", "the", "object", "instances", "when", "returning", "query", "results", "." ]
8e6acedc51cfad0527263376af51e1ef052f7147
https://github.com/jkrasnay/sqlbuilder/blob/8e6acedc51cfad0527263376af51e1ef052f7147/src/main/java/ca/krasnay/sqlbuilder/orm/Mapping.java#L330-L348
159,182
jkrasnay/sqlbuilder
src/main/java/ca/krasnay/sqlbuilder/orm/Mapping.java
Mapping.deleteById
public void deleteById(Object id) { int count = beginDelete().whereEquals(idColumn.getColumnName(), id).delete(); if (count == 0) { throw new RowNotFoundException(table, id); } }
java
public void deleteById(Object id) { int count = beginDelete().whereEquals(idColumn.getColumnName(), id).delete(); if (count == 0) { throw new RowNotFoundException(table, id); } }
[ "public", "void", "deleteById", "(", "Object", "id", ")", "{", "int", "count", "=", "beginDelete", "(", ")", ".", "whereEquals", "(", "idColumn", ".", "getColumnName", "(", ")", ",", "id", ")", ".", "delete", "(", ")", ";", "if", "(", "count", "==", "0", ")", "{", "throw", "new", "RowNotFoundException", "(", "table", ",", "id", ")", ";", "}", "}" ]
Deletes an entity by its primary key. @param id Primary key of the entity.
[ "Deletes", "an", "entity", "by", "its", "primary", "key", "." ]
8e6acedc51cfad0527263376af51e1ef052f7147
https://github.com/jkrasnay/sqlbuilder/blob/8e6acedc51cfad0527263376af51e1ef052f7147/src/main/java/ca/krasnay/sqlbuilder/orm/Mapping.java#L363-L370
159,183
jkrasnay/sqlbuilder
src/main/java/ca/krasnay/sqlbuilder/orm/Mapping.java
Mapping.findById
public T findById(Object id) throws RowNotFoundException, TooManyRowsException { return findWhere(eq(idColumn.getColumnName(), id)).getSingleResult(); }
java
public T findById(Object id) throws RowNotFoundException, TooManyRowsException { return findWhere(eq(idColumn.getColumnName(), id)).getSingleResult(); }
[ "public", "T", "findById", "(", "Object", "id", ")", "throws", "RowNotFoundException", ",", "TooManyRowsException", "{", "return", "findWhere", "(", "eq", "(", "idColumn", ".", "getColumnName", "(", ")", ",", "id", ")", ")", ".", "getSingleResult", "(", ")", ";", "}" ]
Finds an entity given its primary key. @throws RowNotFoundException If no such object was found. @throws TooManyRowsException If more that one object was returned for the given ID.
[ "Finds", "an", "entity", "given", "its", "primary", "key", "." ]
8e6acedc51cfad0527263376af51e1ef052f7147
https://github.com/jkrasnay/sqlbuilder/blob/8e6acedc51cfad0527263376af51e1ef052f7147/src/main/java/ca/krasnay/sqlbuilder/orm/Mapping.java#L380-L382
159,184
jkrasnay/sqlbuilder
src/main/java/ca/krasnay/sqlbuilder/orm/Mapping.java
Mapping.insert
public T insert(T entity) { if (!hasPrimaryKey(entity)) { throw new RuntimeException(String.format("Tried to insert entity of type %s with null or zero primary key", entity.getClass().getSimpleName())); } InsertCreator insert = new InsertCreator(table); insert.setValue(idColumn.getColumnName(), getPrimaryKey(entity)); if (versionColumn != null) { insert.setValue(versionColumn.getColumnName(), 0); } for (Column column : columns) { if (!column.isReadOnly()) { insert.setValue(column.getColumnName(), getFieldValueAsColumn(entity, column)); } } new JdbcTemplate(ormConfig.getDataSource()).update(insert); if (versionColumn != null) { ReflectionUtils.setFieldValue(entity, versionColumn.getFieldName(), 0); } return entity; }
java
public T insert(T entity) { if (!hasPrimaryKey(entity)) { throw new RuntimeException(String.format("Tried to insert entity of type %s with null or zero primary key", entity.getClass().getSimpleName())); } InsertCreator insert = new InsertCreator(table); insert.setValue(idColumn.getColumnName(), getPrimaryKey(entity)); if (versionColumn != null) { insert.setValue(versionColumn.getColumnName(), 0); } for (Column column : columns) { if (!column.isReadOnly()) { insert.setValue(column.getColumnName(), getFieldValueAsColumn(entity, column)); } } new JdbcTemplate(ormConfig.getDataSource()).update(insert); if (versionColumn != null) { ReflectionUtils.setFieldValue(entity, versionColumn.getFieldName(), 0); } return entity; }
[ "public", "T", "insert", "(", "T", "entity", ")", "{", "if", "(", "!", "hasPrimaryKey", "(", "entity", ")", ")", "{", "throw", "new", "RuntimeException", "(", "String", ".", "format", "(", "\"Tried to insert entity of type %s with null or zero primary key\"", ",", "entity", ".", "getClass", "(", ")", ".", "getSimpleName", "(", ")", ")", ")", ";", "}", "InsertCreator", "insert", "=", "new", "InsertCreator", "(", "table", ")", ";", "insert", ".", "setValue", "(", "idColumn", ".", "getColumnName", "(", ")", ",", "getPrimaryKey", "(", "entity", ")", ")", ";", "if", "(", "versionColumn", "!=", "null", ")", "{", "insert", ".", "setValue", "(", "versionColumn", ".", "getColumnName", "(", ")", ",", "0", ")", ";", "}", "for", "(", "Column", "column", ":", "columns", ")", "{", "if", "(", "!", "column", ".", "isReadOnly", "(", ")", ")", "{", "insert", ".", "setValue", "(", "column", ".", "getColumnName", "(", ")", ",", "getFieldValueAsColumn", "(", "entity", ",", "column", ")", ")", ";", "}", "}", "new", "JdbcTemplate", "(", "ormConfig", ".", "getDataSource", "(", ")", ")", ".", "update", "(", "insert", ")", ";", "if", "(", "versionColumn", "!=", "null", ")", "{", "ReflectionUtils", ".", "setFieldValue", "(", "entity", ",", "versionColumn", ".", "getFieldName", "(", ")", ",", "0", ")", ";", "}", "return", "entity", ";", "}" ]
Insert entity object. The caller must first initialize the primary key field.
[ "Insert", "entity", "object", ".", "The", "caller", "must", "first", "initialize", "the", "primary", "key", "field", "." ]
8e6acedc51cfad0527263376af51e1ef052f7147
https://github.com/jkrasnay/sqlbuilder/blob/8e6acedc51cfad0527263376af51e1ef052f7147/src/main/java/ca/krasnay/sqlbuilder/orm/Mapping.java#L454-L482
159,185
jkrasnay/sqlbuilder
src/main/java/ca/krasnay/sqlbuilder/orm/Mapping.java
Mapping.hasPrimaryKey
private boolean hasPrimaryKey(T entity) { Object pk = getPrimaryKey(entity); if (pk == null) { return false; } else { if (pk instanceof Number && ((Number) pk).longValue() == 0) { return false; } } return true; }
java
private boolean hasPrimaryKey(T entity) { Object pk = getPrimaryKey(entity); if (pk == null) { return false; } else { if (pk instanceof Number && ((Number) pk).longValue() == 0) { return false; } } return true; }
[ "private", "boolean", "hasPrimaryKey", "(", "T", "entity", ")", "{", "Object", "pk", "=", "getPrimaryKey", "(", "entity", ")", ";", "if", "(", "pk", "==", "null", ")", "{", "return", "false", ";", "}", "else", "{", "if", "(", "pk", "instanceof", "Number", "&&", "(", "(", "Number", ")", "pk", ")", ".", "longValue", "(", ")", "==", "0", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Returns true if this entity's primary key is not null, and for numeric fields, is non-zero.
[ "Returns", "true", "if", "this", "entity", "s", "primary", "key", "is", "not", "null", "and", "for", "numeric", "fields", "is", "non", "-", "zero", "." ]
8e6acedc51cfad0527263376af51e1ef052f7147
https://github.com/jkrasnay/sqlbuilder/blob/8e6acedc51cfad0527263376af51e1ef052f7147/src/main/java/ca/krasnay/sqlbuilder/orm/Mapping.java#L507-L517
159,186
jkrasnay/sqlbuilder
src/main/java/ca/krasnay/sqlbuilder/orm/Mapping.java
Mapping.update
public T update(T entity) throws RowNotFoundException, OptimisticLockException { if (!hasPrimaryKey(entity)) { throw new RuntimeException(String.format("Tried to update entity of type %s without a primary key", entity .getClass().getSimpleName())); } UpdateCreator update = new UpdateCreator(table); update.whereEquals(idColumn.getColumnName(), getPrimaryKey(entity)); if (versionColumn != null) { update.set(versionColumn.getColumnName() + " = " + versionColumn.getColumnName() + " + 1"); update.whereEquals(versionColumn.getColumnName(), getVersion(entity)); } for (Column column : columns) { if (!column.isReadOnly()) { update.setValue(column.getColumnName(), getFieldValueAsColumn(entity, column)); } } int rows = new JdbcTemplate(ormConfig.getDataSource()).update(update); if (rows == 1) { if (versionColumn != null) { ReflectionUtils.setFieldValue(entity, versionColumn.getFieldName(), getVersion(entity) + 1); } return entity; } else if (rows > 1) { throw new RuntimeException( String.format("Updating table %s with id %s updated %d rows. There must be a mapping problem. Is column %s really the primary key?", table, getPrimaryKey(entity), rows, idColumn)); } else { // // Updated zero rows. This could be because our ID is wrong, or // because our object is out-of date. Let's try querying just by ID. // SelectCreator selectById = new SelectCreator() .column("count(*)") .from(table) .whereEquals(idColumn.getColumnName(), getPrimaryKey(entity)); rows = new JdbcTemplate(ormConfig.getDataSource()).query(selectById, new ResultSetExtractor<Integer>() { @Override public Integer extractData(ResultSet rs) throws SQLException, DataAccessException { rs.next(); return rs.getInt(1); } }); if (rows == 0) { throw new RowNotFoundException(table, getPrimaryKey(entity)); } else { throw new OptimisticLockException(table, getPrimaryKey(entity)); } } }
java
public T update(T entity) throws RowNotFoundException, OptimisticLockException { if (!hasPrimaryKey(entity)) { throw new RuntimeException(String.format("Tried to update entity of type %s without a primary key", entity .getClass().getSimpleName())); } UpdateCreator update = new UpdateCreator(table); update.whereEquals(idColumn.getColumnName(), getPrimaryKey(entity)); if (versionColumn != null) { update.set(versionColumn.getColumnName() + " = " + versionColumn.getColumnName() + " + 1"); update.whereEquals(versionColumn.getColumnName(), getVersion(entity)); } for (Column column : columns) { if (!column.isReadOnly()) { update.setValue(column.getColumnName(), getFieldValueAsColumn(entity, column)); } } int rows = new JdbcTemplate(ormConfig.getDataSource()).update(update); if (rows == 1) { if (versionColumn != null) { ReflectionUtils.setFieldValue(entity, versionColumn.getFieldName(), getVersion(entity) + 1); } return entity; } else if (rows > 1) { throw new RuntimeException( String.format("Updating table %s with id %s updated %d rows. There must be a mapping problem. Is column %s really the primary key?", table, getPrimaryKey(entity), rows, idColumn)); } else { // // Updated zero rows. This could be because our ID is wrong, or // because our object is out-of date. Let's try querying just by ID. // SelectCreator selectById = new SelectCreator() .column("count(*)") .from(table) .whereEquals(idColumn.getColumnName(), getPrimaryKey(entity)); rows = new JdbcTemplate(ormConfig.getDataSource()).query(selectById, new ResultSetExtractor<Integer>() { @Override public Integer extractData(ResultSet rs) throws SQLException, DataAccessException { rs.next(); return rs.getInt(1); } }); if (rows == 0) { throw new RowNotFoundException(table, getPrimaryKey(entity)); } else { throw new OptimisticLockException(table, getPrimaryKey(entity)); } } }
[ "public", "T", "update", "(", "T", "entity", ")", "throws", "RowNotFoundException", ",", "OptimisticLockException", "{", "if", "(", "!", "hasPrimaryKey", "(", "entity", ")", ")", "{", "throw", "new", "RuntimeException", "(", "String", ".", "format", "(", "\"Tried to update entity of type %s without a primary key\"", ",", "entity", ".", "getClass", "(", ")", ".", "getSimpleName", "(", ")", ")", ")", ";", "}", "UpdateCreator", "update", "=", "new", "UpdateCreator", "(", "table", ")", ";", "update", ".", "whereEquals", "(", "idColumn", ".", "getColumnName", "(", ")", ",", "getPrimaryKey", "(", "entity", ")", ")", ";", "if", "(", "versionColumn", "!=", "null", ")", "{", "update", ".", "set", "(", "versionColumn", ".", "getColumnName", "(", ")", "+", "\" = \"", "+", "versionColumn", ".", "getColumnName", "(", ")", "+", "\" + 1\"", ")", ";", "update", ".", "whereEquals", "(", "versionColumn", ".", "getColumnName", "(", ")", ",", "getVersion", "(", "entity", ")", ")", ";", "}", "for", "(", "Column", "column", ":", "columns", ")", "{", "if", "(", "!", "column", ".", "isReadOnly", "(", ")", ")", "{", "update", ".", "setValue", "(", "column", ".", "getColumnName", "(", ")", ",", "getFieldValueAsColumn", "(", "entity", ",", "column", ")", ")", ";", "}", "}", "int", "rows", "=", "new", "JdbcTemplate", "(", "ormConfig", ".", "getDataSource", "(", ")", ")", ".", "update", "(", "update", ")", ";", "if", "(", "rows", "==", "1", ")", "{", "if", "(", "versionColumn", "!=", "null", ")", "{", "ReflectionUtils", ".", "setFieldValue", "(", "entity", ",", "versionColumn", ".", "getFieldName", "(", ")", ",", "getVersion", "(", "entity", ")", "+", "1", ")", ";", "}", "return", "entity", ";", "}", "else", "if", "(", "rows", ">", "1", ")", "{", "throw", "new", "RuntimeException", "(", "String", ".", "format", "(", "\"Updating table %s with id %s updated %d rows. There must be a mapping problem. Is column %s really the primary key?\"", ",", "table", ",", "getPrimaryKey", "(", "entity", ")", ",", "rows", ",", "idColumn", ")", ")", ";", "}", "else", "{", "//", "// Updated zero rows. This could be because our ID is wrong, or", "// because our object is out-of date. Let's try querying just by ID.", "//", "SelectCreator", "selectById", "=", "new", "SelectCreator", "(", ")", ".", "column", "(", "\"count(*)\"", ")", ".", "from", "(", "table", ")", ".", "whereEquals", "(", "idColumn", ".", "getColumnName", "(", ")", ",", "getPrimaryKey", "(", "entity", ")", ")", ";", "rows", "=", "new", "JdbcTemplate", "(", "ormConfig", ".", "getDataSource", "(", ")", ")", ".", "query", "(", "selectById", ",", "new", "ResultSetExtractor", "<", "Integer", ">", "(", ")", "{", "@", "Override", "public", "Integer", "extractData", "(", "ResultSet", "rs", ")", "throws", "SQLException", ",", "DataAccessException", "{", "rs", ".", "next", "(", ")", ";", "return", "rs", ".", "getInt", "(", "1", ")", ";", "}", "}", ")", ";", "if", "(", "rows", "==", "0", ")", "{", "throw", "new", "RowNotFoundException", "(", "table", ",", "getPrimaryKey", "(", "entity", ")", ")", ";", "}", "else", "{", "throw", "new", "OptimisticLockException", "(", "table", ",", "getPrimaryKey", "(", "entity", ")", ")", ";", "}", "}", "}" ]
Updates value of entity in the table.
[ "Updates", "value", "of", "entity", "in", "the", "table", "." ]
8e6acedc51cfad0527263376af51e1ef052f7147
https://github.com/jkrasnay/sqlbuilder/blob/8e6acedc51cfad0527263376af51e1ef052f7147/src/main/java/ca/krasnay/sqlbuilder/orm/Mapping.java#L558-L622
159,187
jkrasnay/sqlbuilder
src/main/java/ca/krasnay/sqlbuilder/AbstractSqlCreator.java
AbstractSqlCreator.setParameter
public AbstractSqlCreator setParameter(String name, Object value) { ppsc.setParameter(name, value); return this; }
java
public AbstractSqlCreator setParameter(String name, Object value) { ppsc.setParameter(name, value); return this; }
[ "public", "AbstractSqlCreator", "setParameter", "(", "String", "name", ",", "Object", "value", ")", "{", "ppsc", ".", "setParameter", "(", "name", ",", "value", ")", ";", "return", "this", ";", "}" ]
Sets a parameter for the creator.
[ "Sets", "a", "parameter", "for", "the", "creator", "." ]
8e6acedc51cfad0527263376af51e1ef052f7147
https://github.com/jkrasnay/sqlbuilder/blob/8e6acedc51cfad0527263376af51e1ef052f7147/src/main/java/ca/krasnay/sqlbuilder/AbstractSqlCreator.java#L64-L67
159,188
jkrasnay/sqlbuilder
src/main/java/ca/krasnay/sqlbuilder/InsertBuilder.java
InsertBuilder.set
public InsertBuilder set(String column, String value) { columns.add(column); values.add(value); return this; }
java
public InsertBuilder set(String column, String value) { columns.add(column); values.add(value); return this; }
[ "public", "InsertBuilder", "set", "(", "String", "column", ",", "String", "value", ")", "{", "columns", ".", "add", "(", "column", ")", ";", "values", ".", "add", "(", "value", ")", ";", "return", "this", ";", "}" ]
Inserts a column name, value pair into the SQL. @param column Name of the table column. @param value Value to substitute in. InsertBuilder does *no* interpretation of this. If you want a string constant inserted, you must provide the single quotes and escape the internal quotes. It is more common to use a question mark or a token in the style of {@link ParameterizedPreparedStatementCreator}, e.g. ":foo".
[ "Inserts", "a", "column", "name", "value", "pair", "into", "the", "SQL", "." ]
8e6acedc51cfad0527263376af51e1ef052f7147
https://github.com/jkrasnay/sqlbuilder/blob/8e6acedc51cfad0527263376af51e1ef052f7147/src/main/java/ca/krasnay/sqlbuilder/InsertBuilder.java#L44-L48
159,189
jkrasnay/sqlbuilder
src/main/java/ca/krasnay/sqlbuilder/SelectBuilder.java
SelectBuilder.orderBy
public SelectBuilder orderBy(String name, boolean ascending) { if (ascending) { orderBys.add(name + " asc"); } else { orderBys.add(name + " desc"); } return this; }
java
public SelectBuilder orderBy(String name, boolean ascending) { if (ascending) { orderBys.add(name + " asc"); } else { orderBys.add(name + " desc"); } return this; }
[ "public", "SelectBuilder", "orderBy", "(", "String", "name", ",", "boolean", "ascending", ")", "{", "if", "(", "ascending", ")", "{", "orderBys", ".", "add", "(", "name", "+", "\" asc\"", ")", ";", "}", "else", "{", "orderBys", ".", "add", "(", "name", "+", "\" desc\"", ")", ";", "}", "return", "this", ";", "}" ]
Adds an ORDER BY item with a direction indicator. @param name Name of the column by which to sort. @param ascending If true, specifies the direction "asc", otherwise, specifies the direction "desc".
[ "Adds", "an", "ORDER", "BY", "item", "with", "a", "direction", "indicator", "." ]
8e6acedc51cfad0527263376af51e1ef052f7147
https://github.com/jkrasnay/sqlbuilder/blob/8e6acedc51cfad0527263376af51e1ef052f7147/src/main/java/ca/krasnay/sqlbuilder/SelectBuilder.java#L248-L255
159,190
jkrasnay/sqlbuilder
src/main/java/ca/krasnay/sqlbuilder/orm/StringListFlattener.java
StringListFlattener.split
public List<String> split(String s) { List<String> result = new ArrayList<String>(); if (s == null) { return result; } boolean seenEscape = false; // Used to detect if the last char was a separator, // in which case we append an empty string boolean seenSeparator = false; StringBuilder sb = new StringBuilder(); for (int i = 0; i < s.length(); i++) { seenSeparator = false; char c = s.charAt(i); if (seenEscape) { if (c == escapeChar || c == separator) { sb.append(c); } else { sb.append(escapeChar).append(c); } seenEscape = false; } else { if (c == escapeChar) { seenEscape = true; } else if (c == separator) { if (sb.length() == 0 && convertEmptyToNull) { result.add(null); } else { result.add(sb.toString()); } sb.setLength(0); seenSeparator = true; } else { sb.append(c); } } } // Clean up if (seenEscape) { sb.append(escapeChar); } if (sb.length() > 0 || seenSeparator) { if (sb.length() == 0 && convertEmptyToNull) { result.add(null); } else { result.add(sb.toString()); } } return result; }
java
public List<String> split(String s) { List<String> result = new ArrayList<String>(); if (s == null) { return result; } boolean seenEscape = false; // Used to detect if the last char was a separator, // in which case we append an empty string boolean seenSeparator = false; StringBuilder sb = new StringBuilder(); for (int i = 0; i < s.length(); i++) { seenSeparator = false; char c = s.charAt(i); if (seenEscape) { if (c == escapeChar || c == separator) { sb.append(c); } else { sb.append(escapeChar).append(c); } seenEscape = false; } else { if (c == escapeChar) { seenEscape = true; } else if (c == separator) { if (sb.length() == 0 && convertEmptyToNull) { result.add(null); } else { result.add(sb.toString()); } sb.setLength(0); seenSeparator = true; } else { sb.append(c); } } } // Clean up if (seenEscape) { sb.append(escapeChar); } if (sb.length() > 0 || seenSeparator) { if (sb.length() == 0 && convertEmptyToNull) { result.add(null); } else { result.add(sb.toString()); } } return result; }
[ "public", "List", "<", "String", ">", "split", "(", "String", "s", ")", "{", "List", "<", "String", ">", "result", "=", "new", "ArrayList", "<", "String", ">", "(", ")", ";", "if", "(", "s", "==", "null", ")", "{", "return", "result", ";", "}", "boolean", "seenEscape", "=", "false", ";", "// Used to detect if the last char was a separator,", "// in which case we append an empty string", "boolean", "seenSeparator", "=", "false", ";", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "s", ".", "length", "(", ")", ";", "i", "++", ")", "{", "seenSeparator", "=", "false", ";", "char", "c", "=", "s", ".", "charAt", "(", "i", ")", ";", "if", "(", "seenEscape", ")", "{", "if", "(", "c", "==", "escapeChar", "||", "c", "==", "separator", ")", "{", "sb", ".", "append", "(", "c", ")", ";", "}", "else", "{", "sb", ".", "append", "(", "escapeChar", ")", ".", "append", "(", "c", ")", ";", "}", "seenEscape", "=", "false", ";", "}", "else", "{", "if", "(", "c", "==", "escapeChar", ")", "{", "seenEscape", "=", "true", ";", "}", "else", "if", "(", "c", "==", "separator", ")", "{", "if", "(", "sb", ".", "length", "(", ")", "==", "0", "&&", "convertEmptyToNull", ")", "{", "result", ".", "add", "(", "null", ")", ";", "}", "else", "{", "result", ".", "add", "(", "sb", ".", "toString", "(", ")", ")", ";", "}", "sb", ".", "setLength", "(", "0", ")", ";", "seenSeparator", "=", "true", ";", "}", "else", "{", "sb", ".", "append", "(", "c", ")", ";", "}", "}", "}", "// Clean up", "if", "(", "seenEscape", ")", "{", "sb", ".", "append", "(", "escapeChar", ")", ";", "}", "if", "(", "sb", ".", "length", "(", ")", ">", "0", "||", "seenSeparator", ")", "{", "if", "(", "sb", ".", "length", "(", ")", "==", "0", "&&", "convertEmptyToNull", ")", "{", "result", ".", "add", "(", "null", ")", ";", "}", "else", "{", "result", ".", "add", "(", "sb", ".", "toString", "(", ")", ")", ";", "}", "}", "return", "result", ";", "}" ]
Splits the given string.
[ "Splits", "the", "given", "string", "." ]
8e6acedc51cfad0527263376af51e1ef052f7147
https://github.com/jkrasnay/sqlbuilder/blob/8e6acedc51cfad0527263376af51e1ef052f7147/src/main/java/ca/krasnay/sqlbuilder/orm/StringListFlattener.java#L35-L93
159,191
jkrasnay/sqlbuilder
src/main/java/ca/krasnay/sqlbuilder/orm/StringListFlattener.java
StringListFlattener.join
public String join(List<String> list) { if (list == null) { return null; } StringBuilder sb = new StringBuilder(); boolean first = true; for (String s : list) { if (s == null) { if (convertEmptyToNull) { s = ""; } else { throw new IllegalArgumentException("StringListFlattener does not support null strings in the list. Consider calling setConvertEmptyToNull(true)."); } } if (!first) { sb.append(separator); } for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c == escapeChar || c == separator) { sb.append(escapeChar); } sb.append(c); } first = false; } return sb.toString(); }
java
public String join(List<String> list) { if (list == null) { return null; } StringBuilder sb = new StringBuilder(); boolean first = true; for (String s : list) { if (s == null) { if (convertEmptyToNull) { s = ""; } else { throw new IllegalArgumentException("StringListFlattener does not support null strings in the list. Consider calling setConvertEmptyToNull(true)."); } } if (!first) { sb.append(separator); } for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c == escapeChar || c == separator) { sb.append(escapeChar); } sb.append(c); } first = false; } return sb.toString(); }
[ "public", "String", "join", "(", "List", "<", "String", ">", "list", ")", "{", "if", "(", "list", "==", "null", ")", "{", "return", "null", ";", "}", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "boolean", "first", "=", "true", ";", "for", "(", "String", "s", ":", "list", ")", "{", "if", "(", "s", "==", "null", ")", "{", "if", "(", "convertEmptyToNull", ")", "{", "s", "=", "\"\"", ";", "}", "else", "{", "throw", "new", "IllegalArgumentException", "(", "\"StringListFlattener does not support null strings in the list. Consider calling setConvertEmptyToNull(true).\"", ")", ";", "}", "}", "if", "(", "!", "first", ")", "{", "sb", ".", "append", "(", "separator", ")", ";", "}", "for", "(", "int", "i", "=", "0", ";", "i", "<", "s", ".", "length", "(", ")", ";", "i", "++", ")", "{", "char", "c", "=", "s", ".", "charAt", "(", "i", ")", ";", "if", "(", "c", "==", "escapeChar", "||", "c", "==", "separator", ")", "{", "sb", ".", "append", "(", "escapeChar", ")", ";", "}", "sb", ".", "append", "(", "c", ")", ";", "}", "first", "=", "false", ";", "}", "return", "sb", ".", "toString", "(", ")", ";", "}" ]
Joins the given list into a single string.
[ "Joins", "the", "given", "list", "into", "a", "single", "string", "." ]
8e6acedc51cfad0527263376af51e1ef052f7147
https://github.com/jkrasnay/sqlbuilder/blob/8e6acedc51cfad0527263376af51e1ef052f7147/src/main/java/ca/krasnay/sqlbuilder/orm/StringListFlattener.java#L98-L131
159,192
jkrasnay/sqlbuilder
src/main/java/ca/krasnay/sqlbuilder/AbstractSqlBuilder.java
AbstractSqlBuilder.appendList
protected void appendList(StringBuilder sql, List<?> list, String init, String sep) { boolean first = true; for (Object s : list) { if (first) { sql.append(init); } else { sql.append(sep); } sql.append(s); first = false; } }
java
protected void appendList(StringBuilder sql, List<?> list, String init, String sep) { boolean first = true; for (Object s : list) { if (first) { sql.append(init); } else { sql.append(sep); } sql.append(s); first = false; } }
[ "protected", "void", "appendList", "(", "StringBuilder", "sql", ",", "List", "<", "?", ">", "list", ",", "String", "init", ",", "String", "sep", ")", "{", "boolean", "first", "=", "true", ";", "for", "(", "Object", "s", ":", "list", ")", "{", "if", "(", "first", ")", "{", "sql", ".", "append", "(", "init", ")", ";", "}", "else", "{", "sql", ".", "append", "(", "sep", ")", ";", "}", "sql", ".", "append", "(", "s", ")", ";", "first", "=", "false", ";", "}", "}" ]
Constructs a list of items with given separators. @param sql StringBuilder to which the constructed string will be appended. @param list List of objects (usually strings) to join. @param init String to be added to the start of the list, before any of the items. @param sep Separator string to be added between items in the list.
[ "Constructs", "a", "list", "of", "items", "with", "given", "separators", "." ]
8e6acedc51cfad0527263376af51e1ef052f7147
https://github.com/jkrasnay/sqlbuilder/blob/8e6acedc51cfad0527263376af51e1ef052f7147/src/main/java/ca/krasnay/sqlbuilder/AbstractSqlBuilder.java#L26-L39
159,193
jkrasnay/sqlbuilder
src/main/java/ca/krasnay/sqlbuilder/orm/EnumStringConverter.java
EnumStringConverter.create
public static <E extends Enum<E>> EnumStringConverter<E> create(Class<E> enumType) { return new EnumStringConverter<E>(enumType); }
java
public static <E extends Enum<E>> EnumStringConverter<E> create(Class<E> enumType) { return new EnumStringConverter<E>(enumType); }
[ "public", "static", "<", "E", "extends", "Enum", "<", "E", ">", ">", "EnumStringConverter", "<", "E", ">", "create", "(", "Class", "<", "E", ">", "enumType", ")", "{", "return", "new", "EnumStringConverter", "<", "E", ">", "(", "enumType", ")", ";", "}" ]
Factory method to create EnumStringConverter @param <E> enum type inferred from enumType parameter @param enumType particular enum class @return instance of EnumConverter
[ "Factory", "method", "to", "create", "EnumStringConverter" ]
8e6acedc51cfad0527263376af51e1ef052f7147
https://github.com/jkrasnay/sqlbuilder/blob/8e6acedc51cfad0527263376af51e1ef052f7147/src/main/java/ca/krasnay/sqlbuilder/orm/EnumStringConverter.java#L26-L28
159,194
jkrasnay/sqlbuilder
src/main/java/ca/krasnay/sqlbuilder/orm/ReflectionUtils.java
ReflectionUtils.getDeclaredFieldsInHierarchy
public static Field[] getDeclaredFieldsInHierarchy(Class<?> clazz) { if (clazz.isPrimitive()) { throw new IllegalArgumentException("Primitive types not supported."); } List<Field> result = new ArrayList<Field>(); while (true) { if (clazz == Object.class) { break; } result.addAll(Arrays.asList(clazz.getDeclaredFields())); clazz = clazz.getSuperclass(); } return result.toArray(new Field[result.size()]); }
java
public static Field[] getDeclaredFieldsInHierarchy(Class<?> clazz) { if (clazz.isPrimitive()) { throw new IllegalArgumentException("Primitive types not supported."); } List<Field> result = new ArrayList<Field>(); while (true) { if (clazz == Object.class) { break; } result.addAll(Arrays.asList(clazz.getDeclaredFields())); clazz = clazz.getSuperclass(); } return result.toArray(new Field[result.size()]); }
[ "public", "static", "Field", "[", "]", "getDeclaredFieldsInHierarchy", "(", "Class", "<", "?", ">", "clazz", ")", "{", "if", "(", "clazz", ".", "isPrimitive", "(", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Primitive types not supported.\"", ")", ";", "}", "List", "<", "Field", ">", "result", "=", "new", "ArrayList", "<", "Field", ">", "(", ")", ";", "while", "(", "true", ")", "{", "if", "(", "clazz", "==", "Object", ".", "class", ")", "{", "break", ";", "}", "result", ".", "addAll", "(", "Arrays", ".", "asList", "(", "clazz", ".", "getDeclaredFields", "(", ")", ")", ")", ";", "clazz", "=", "clazz", ".", "getSuperclass", "(", ")", ";", "}", "return", "result", ".", "toArray", "(", "new", "Field", "[", "result", ".", "size", "(", ")", "]", ")", ";", "}" ]
Returns an array of all declared fields in the given class and all super-classes.
[ "Returns", "an", "array", "of", "all", "declared", "fields", "in", "the", "given", "class", "and", "all", "super", "-", "classes", "." ]
8e6acedc51cfad0527263376af51e1ef052f7147
https://github.com/jkrasnay/sqlbuilder/blob/8e6acedc51cfad0527263376af51e1ef052f7147/src/main/java/ca/krasnay/sqlbuilder/orm/ReflectionUtils.java#L14-L33
159,195
jkrasnay/sqlbuilder
src/main/java/ca/krasnay/sqlbuilder/orm/ReflectionUtils.java
ReflectionUtils.getDeclaredFieldWithPath
public static Field getDeclaredFieldWithPath(Class<?> clazz, String path) { int lastDot = path.lastIndexOf('.'); if (lastDot > -1) { String parentPath = path.substring(0, lastDot); String fieldName = path.substring(lastDot + 1); Field parentField = getDeclaredFieldWithPath(clazz, parentPath); return getDeclaredFieldInHierarchy(parentField.getType(), fieldName); } else { return getDeclaredFieldInHierarchy(clazz, path); } }
java
public static Field getDeclaredFieldWithPath(Class<?> clazz, String path) { int lastDot = path.lastIndexOf('.'); if (lastDot > -1) { String parentPath = path.substring(0, lastDot); String fieldName = path.substring(lastDot + 1); Field parentField = getDeclaredFieldWithPath(clazz, parentPath); return getDeclaredFieldInHierarchy(parentField.getType(), fieldName); } else { return getDeclaredFieldInHierarchy(clazz, path); } }
[ "public", "static", "Field", "getDeclaredFieldWithPath", "(", "Class", "<", "?", ">", "clazz", ",", "String", "path", ")", "{", "int", "lastDot", "=", "path", ".", "lastIndexOf", "(", "'", "'", ")", ";", "if", "(", "lastDot", ">", "-", "1", ")", "{", "String", "parentPath", "=", "path", ".", "substring", "(", "0", ",", "lastDot", ")", ";", "String", "fieldName", "=", "path", ".", "substring", "(", "lastDot", "+", "1", ")", ";", "Field", "parentField", "=", "getDeclaredFieldWithPath", "(", "clazz", ",", "parentPath", ")", ";", "return", "getDeclaredFieldInHierarchy", "(", "parentField", ".", "getType", "(", ")", ",", "fieldName", ")", ";", "}", "else", "{", "return", "getDeclaredFieldInHierarchy", "(", "clazz", ",", "path", ")", ";", "}", "}" ]
Returns the Field for a given parent class and a dot-separated path of field names. @param clazz Parent class. @param path Path to the desired field.
[ "Returns", "the", "Field", "for", "a", "given", "parent", "class", "and", "a", "dot", "-", "separated", "path", "of", "field", "names", "." ]
8e6acedc51cfad0527263376af51e1ef052f7147
https://github.com/jkrasnay/sqlbuilder/blob/8e6acedc51cfad0527263376af51e1ef052f7147/src/main/java/ca/krasnay/sqlbuilder/orm/ReflectionUtils.java#L44-L56
159,196
jkrasnay/sqlbuilder
src/main/java/ca/krasnay/sqlbuilder/orm/ReflectionUtils.java
ReflectionUtils.getFieldValue
public static Object getFieldValue(Object object, String fieldName) { try { return getDeclaredFieldInHierarchy(object.getClass(), fieldName).get(object); } catch (IllegalArgumentException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } }
java
public static Object getFieldValue(Object object, String fieldName) { try { return getDeclaredFieldInHierarchy(object.getClass(), fieldName).get(object); } catch (IllegalArgumentException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } }
[ "public", "static", "Object", "getFieldValue", "(", "Object", "object", ",", "String", "fieldName", ")", "{", "try", "{", "return", "getDeclaredFieldInHierarchy", "(", "object", ".", "getClass", "(", ")", ",", "fieldName", ")", ".", "get", "(", "object", ")", ";", "}", "catch", "(", "IllegalArgumentException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "catch", "(", "IllegalAccessException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "}" ]
Convenience method for getting the value of a private object field, without the stress of checked exceptions in the reflection API. @param object Object containing the field. @param fieldName Name of the field whose value to return.
[ "Convenience", "method", "for", "getting", "the", "value", "of", "a", "private", "object", "field", "without", "the", "stress", "of", "checked", "exceptions", "in", "the", "reflection", "API", "." ]
8e6acedc51cfad0527263376af51e1ef052f7147
https://github.com/jkrasnay/sqlbuilder/blob/8e6acedc51cfad0527263376af51e1ef052f7147/src/main/java/ca/krasnay/sqlbuilder/orm/ReflectionUtils.java#L85-L93
159,197
jkrasnay/sqlbuilder
src/main/java/ca/krasnay/sqlbuilder/orm/ReflectionUtils.java
ReflectionUtils.setFieldValue
public static void setFieldValue(Object object, String fieldName, Object value) { try { getDeclaredFieldInHierarchy(object.getClass(), fieldName).set(object, value); } catch (IllegalArgumentException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } }
java
public static void setFieldValue(Object object, String fieldName, Object value) { try { getDeclaredFieldInHierarchy(object.getClass(), fieldName).set(object, value); } catch (IllegalArgumentException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } }
[ "public", "static", "void", "setFieldValue", "(", "Object", "object", ",", "String", "fieldName", ",", "Object", "value", ")", "{", "try", "{", "getDeclaredFieldInHierarchy", "(", "object", ".", "getClass", "(", ")", ",", "fieldName", ")", ".", "set", "(", "object", ",", "value", ")", ";", "}", "catch", "(", "IllegalArgumentException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "catch", "(", "IllegalAccessException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "}" ]
Convenience method for setting the value of a private object field, without the stress of checked exceptions in the reflection API. @param object Object containing the field. @param fieldName Name of the field to set. @param value Value to which to set the field.
[ "Convenience", "method", "for", "setting", "the", "value", "of", "a", "private", "object", "field", "without", "the", "stress", "of", "checked", "exceptions", "in", "the", "reflection", "API", "." ]
8e6acedc51cfad0527263376af51e1ef052f7147
https://github.com/jkrasnay/sqlbuilder/blob/8e6acedc51cfad0527263376af51e1ef052f7147/src/main/java/ca/krasnay/sqlbuilder/orm/ReflectionUtils.java#L139-L147
159,198
super-csv/super-csv
super-csv/src/main/java/org/supercsv/cellprocessor/constraint/LMinMax.java
LMinMax.checkPreconditions
private static void checkPreconditions(final long min, final long max) { if( max < min ) { throw new IllegalArgumentException(String.format("max (%d) should not be < min (%d)", max, min)); } }
java
private static void checkPreconditions(final long min, final long max) { if( max < min ) { throw new IllegalArgumentException(String.format("max (%d) should not be < min (%d)", max, min)); } }
[ "private", "static", "void", "checkPreconditions", "(", "final", "long", "min", ",", "final", "long", "max", ")", "{", "if", "(", "max", "<", "min", ")", "{", "throw", "new", "IllegalArgumentException", "(", "String", ".", "format", "(", "\"max (%d) should not be < min (%d)\"", ",", "max", ",", "min", ")", ")", ";", "}", "}" ]
Checks the preconditions for creating a new LMinMax processor. @param min the minimum value (inclusive) @param max the maximum value (inclusive) @throws IllegalArgumentException if {@code max < min}
[ "Checks", "the", "preconditions", "for", "creating", "a", "new", "LMinMax", "processor", "." ]
f18db724674dc1c4116e25142c1b5403ebf43e96
https://github.com/super-csv/super-csv/blob/f18db724674dc1c4116e25142c1b5403ebf43e96/super-csv/src/main/java/org/supercsv/cellprocessor/constraint/LMinMax.java#L125-L129
159,199
super-csv/super-csv
super-csv/src/main/java/org/supercsv/util/ReflectionUtils.java
ReflectionUtils.findGetter
public static Method findGetter(final Object object, final String fieldName) { if( object == null ) { throw new NullPointerException("object should not be null"); } else if( fieldName == null ) { throw new NullPointerException("fieldName should not be null"); } final Class<?> clazz = object.getClass(); // find a standard getter final String standardGetterName = getMethodNameForField(GET_PREFIX, fieldName); Method getter = findGetterWithCompatibleReturnType(standardGetterName, clazz, false); // if that fails, try for an isX() style boolean getter if( getter == null ) { final String booleanGetterName = getMethodNameForField(IS_PREFIX, fieldName); getter = findGetterWithCompatibleReturnType(booleanGetterName, clazz, true); } if( getter == null ) { throw new SuperCsvReflectionException( String .format( "unable to find getter for field %s in class %s - check that the corresponding nameMapping element matches the field name in the bean", fieldName, clazz.getName())); } return getter; }
java
public static Method findGetter(final Object object, final String fieldName) { if( object == null ) { throw new NullPointerException("object should not be null"); } else if( fieldName == null ) { throw new NullPointerException("fieldName should not be null"); } final Class<?> clazz = object.getClass(); // find a standard getter final String standardGetterName = getMethodNameForField(GET_PREFIX, fieldName); Method getter = findGetterWithCompatibleReturnType(standardGetterName, clazz, false); // if that fails, try for an isX() style boolean getter if( getter == null ) { final String booleanGetterName = getMethodNameForField(IS_PREFIX, fieldName); getter = findGetterWithCompatibleReturnType(booleanGetterName, clazz, true); } if( getter == null ) { throw new SuperCsvReflectionException( String .format( "unable to find getter for field %s in class %s - check that the corresponding nameMapping element matches the field name in the bean", fieldName, clazz.getName())); } return getter; }
[ "public", "static", "Method", "findGetter", "(", "final", "Object", "object", ",", "final", "String", "fieldName", ")", "{", "if", "(", "object", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", "\"object should not be null\"", ")", ";", "}", "else", "if", "(", "fieldName", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", "\"fieldName should not be null\"", ")", ";", "}", "final", "Class", "<", "?", ">", "clazz", "=", "object", ".", "getClass", "(", ")", ";", "// find a standard getter", "final", "String", "standardGetterName", "=", "getMethodNameForField", "(", "GET_PREFIX", ",", "fieldName", ")", ";", "Method", "getter", "=", "findGetterWithCompatibleReturnType", "(", "standardGetterName", ",", "clazz", ",", "false", ")", ";", "// if that fails, try for an isX() style boolean getter", "if", "(", "getter", "==", "null", ")", "{", "final", "String", "booleanGetterName", "=", "getMethodNameForField", "(", "IS_PREFIX", ",", "fieldName", ")", ";", "getter", "=", "findGetterWithCompatibleReturnType", "(", "booleanGetterName", ",", "clazz", ",", "true", ")", ";", "}", "if", "(", "getter", "==", "null", ")", "{", "throw", "new", "SuperCsvReflectionException", "(", "String", ".", "format", "(", "\"unable to find getter for field %s in class %s - check that the corresponding nameMapping element matches the field name in the bean\"", ",", "fieldName", ",", "clazz", ".", "getName", "(", ")", ")", ")", ";", "}", "return", "getter", ";", "}" ]
Returns the getter method associated with the object's field. @param object the object @param fieldName the name of the field @return the getter method @throws NullPointerException if object or fieldName is null @throws SuperCsvReflectionException if the getter doesn't exist or is not visible
[ "Returns", "the", "getter", "method", "associated", "with", "the", "object", "s", "field", "." ]
f18db724674dc1c4116e25142c1b5403ebf43e96
https://github.com/super-csv/super-csv/blob/f18db724674dc1c4116e25142c1b5403ebf43e96/super-csv/src/main/java/org/supercsv/util/ReflectionUtils.java#L77-L105