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
142,200
petergeneric/stdlib
guice/webapp/src/main/java/com/peterphi/std/guice/web/rest/auth/oauth2/OAuth2SessionRef.java
OAuth2SessionRef.getAuthFlowStartEndpoint
public URI getAuthFlowStartEndpoint(final String returnTo, final String scope) { final String oauthServiceRoot = (oauthServiceRedirectEndpoint != null) ? oauthServiceRedirectEndpoint : oauthServiceEndpoint; final String endpoint = oauthServiceRoot + "/oauth2/authorize"; UriBuilder builder = UriBuilder.fromUri(endpoint); builder.replaceQueryParam("response_type", "code"); builder.replaceQueryParam("client_id", clientId); builder.replaceQueryParam("redirect_uri", getOwnCallbackUri()); if (scope != null) builder.replaceQueryParam("scope", scope); if (returnTo != null) builder.replaceQueryParam("state", encodeState(callbackNonce + " " + returnTo)); return builder.build(); }
java
public URI getAuthFlowStartEndpoint(final String returnTo, final String scope) { final String oauthServiceRoot = (oauthServiceRedirectEndpoint != null) ? oauthServiceRedirectEndpoint : oauthServiceEndpoint; final String endpoint = oauthServiceRoot + "/oauth2/authorize"; UriBuilder builder = UriBuilder.fromUri(endpoint); builder.replaceQueryParam("response_type", "code"); builder.replaceQueryParam("client_id", clientId); builder.replaceQueryParam("redirect_uri", getOwnCallbackUri()); if (scope != null) builder.replaceQueryParam("scope", scope); if (returnTo != null) builder.replaceQueryParam("state", encodeState(callbackNonce + " " + returnTo)); return builder.build(); }
[ "public", "URI", "getAuthFlowStartEndpoint", "(", "final", "String", "returnTo", ",", "final", "String", "scope", ")", "{", "final", "String", "oauthServiceRoot", "=", "(", "oauthServiceRedirectEndpoint", "!=", "null", ")", "?", "oauthServiceRedirectEndpoint", ":", "oauthServiceEndpoint", ";", "final", "String", "endpoint", "=", "oauthServiceRoot", "+", "\"/oauth2/authorize\"", ";", "UriBuilder", "builder", "=", "UriBuilder", ".", "fromUri", "(", "endpoint", ")", ";", "builder", ".", "replaceQueryParam", "(", "\"response_type\"", ",", "\"code\"", ")", ";", "builder", ".", "replaceQueryParam", "(", "\"client_id\"", ",", "clientId", ")", ";", "builder", ".", "replaceQueryParam", "(", "\"redirect_uri\"", ",", "getOwnCallbackUri", "(", ")", ")", ";", "if", "(", "scope", "!=", "null", ")", "builder", ".", "replaceQueryParam", "(", "\"scope\"", ",", "scope", ")", ";", "if", "(", "returnTo", "!=", "null", ")", "builder", ".", "replaceQueryParam", "(", "\"state\"", ",", "encodeState", "(", "callbackNonce", "+", "\" \"", "+", "returnTo", ")", ")", ";", "return", "builder", ".", "build", "(", ")", ";", "}" ]
Get the endpoint to redirect a client to in order to start an OAuth2 Authorisation Flow @param returnTo The URI to redirect the user back to once the authorisation flow completes successfully. If not specified then the user will be directed to the root of this webapp. @return
[ "Get", "the", "endpoint", "to", "redirect", "a", "client", "to", "in", "order", "to", "start", "an", "OAuth2", "Authorisation", "Flow" ]
d4025d2f881bc0542b1e004c5f65a1ccaf895836
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/guice/webapp/src/main/java/com/peterphi/std/guice/web/rest/auth/oauth2/OAuth2SessionRef.java#L140-L159
142,201
petergeneric/stdlib
guice/webapp/src/main/java/com/peterphi/std/guice/web/rest/auth/oauth2/OAuth2SessionRef.java
OAuth2SessionRef.getRedirectToFromState
public URI getRedirectToFromState(final String state) { final String[] pieces = decodeState(state).split(" ", 2); if (!StringUtils.equals(callbackNonce, pieces[0])) { // The callback nonce is not what we expect; this is usually caused by: // - The user has followed a previous oauth callback entry from their history // - The user has accessed a service via a non-canonical endpoint and been redirected by the oauth server to the canonical one // which means the original nonce stored in the session is not available to this session. // To get around this, we simply redirect the user to the root of this service so they can start the oauth flow again throw new LiteralRestResponseException(Response.seeOther(URI.create("/")).build()); } if (pieces.length == 2) return URI.create(pieces[1]); else return null; }
java
public URI getRedirectToFromState(final String state) { final String[] pieces = decodeState(state).split(" ", 2); if (!StringUtils.equals(callbackNonce, pieces[0])) { // The callback nonce is not what we expect; this is usually caused by: // - The user has followed a previous oauth callback entry from their history // - The user has accessed a service via a non-canonical endpoint and been redirected by the oauth server to the canonical one // which means the original nonce stored in the session is not available to this session. // To get around this, we simply redirect the user to the root of this service so they can start the oauth flow again throw new LiteralRestResponseException(Response.seeOther(URI.create("/")).build()); } if (pieces.length == 2) return URI.create(pieces[1]); else return null; }
[ "public", "URI", "getRedirectToFromState", "(", "final", "String", "state", ")", "{", "final", "String", "[", "]", "pieces", "=", "decodeState", "(", "state", ")", ".", "split", "(", "\" \"", ",", "2", ")", ";", "if", "(", "!", "StringUtils", ".", "equals", "(", "callbackNonce", ",", "pieces", "[", "0", "]", ")", ")", "{", "// The callback nonce is not what we expect; this is usually caused by:", "// - The user has followed a previous oauth callback entry from their history", "// - The user has accessed a service via a non-canonical endpoint and been redirected by the oauth server to the canonical one", "// which means the original nonce stored in the session is not available to this session.", "// To get around this, we simply redirect the user to the root of this service so they can start the oauth flow again", "throw", "new", "LiteralRestResponseException", "(", "Response", ".", "seeOther", "(", "URI", ".", "create", "(", "\"/\"", ")", ")", ".", "build", "(", ")", ")", ";", "}", "if", "(", "pieces", ".", "length", "==", "2", ")", "return", "URI", ".", "create", "(", "pieces", "[", "1", "]", ")", ";", "else", "return", "null", ";", "}" ]
Decode the state to retrieve the redirectTo value @param state @return
[ "Decode", "the", "state", "to", "retrieve", "the", "redirectTo", "value" ]
d4025d2f881bc0542b1e004c5f65a1ccaf895836
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/guice/webapp/src/main/java/com/peterphi/std/guice/web/rest/auth/oauth2/OAuth2SessionRef.java#L195-L214
142,202
petergeneric/stdlib
guice/webapp/src/main/java/com/peterphi/std/guice/web/rest/auth/oauth2/OAuth2SessionRef.java
OAuth2SessionRef.refreshToken
public synchronized void refreshToken() { final String refreshToken = this.response.refresh_token; this.response = null; this.cachedInfo = null; final String responseStr = authService.getToken(UserManagerOAuthService.GRANT_TYPE_REFRESH_TOKEN, null, null, clientId, clientSecret, refreshToken, null, null, null); loadAuthResponse(responseStr); }
java
public synchronized void refreshToken() { final String refreshToken = this.response.refresh_token; this.response = null; this.cachedInfo = null; final String responseStr = authService.getToken(UserManagerOAuthService.GRANT_TYPE_REFRESH_TOKEN, null, null, clientId, clientSecret, refreshToken, null, null, null); loadAuthResponse(responseStr); }
[ "public", "synchronized", "void", "refreshToken", "(", ")", "{", "final", "String", "refreshToken", "=", "this", ".", "response", ".", "refresh_token", ";", "this", ".", "response", "=", "null", ";", "this", ".", "cachedInfo", "=", "null", ";", "final", "String", "responseStr", "=", "authService", ".", "getToken", "(", "UserManagerOAuthService", ".", "GRANT_TYPE_REFRESH_TOKEN", ",", "null", ",", "null", ",", "clientId", ",", "clientSecret", ",", "refreshToken", ",", "null", ",", "null", ",", "null", ")", ";", "loadAuthResponse", "(", "responseStr", ")", ";", "}" ]
Use the refresh token to get a new token with a longer lifespan
[ "Use", "the", "refresh", "token", "to", "get", "a", "new", "token", "with", "a", "longer", "lifespan" ]
d4025d2f881bc0542b1e004c5f65a1ccaf895836
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/guice/webapp/src/main/java/com/peterphi/std/guice/web/rest/auth/oauth2/OAuth2SessionRef.java#L242-L260
142,203
ziccardi/jnrpe
jnrpe-lib/src/main/java/it/jnrpe/utils/PluginRepositoryUtil.java
PluginRepositoryUtil.loadFromXmlPluginPackageDefinitions
public static void loadFromXmlPluginPackageDefinitions(final IPluginRepository repo, final ClassLoader cl, final InputStream in) throws PluginConfigurationException { for (PluginDefinition pd : loadFromXmlPluginPackageDefinitions(cl, in)) { repo.addPluginDefinition(pd); } }
java
public static void loadFromXmlPluginPackageDefinitions(final IPluginRepository repo, final ClassLoader cl, final InputStream in) throws PluginConfigurationException { for (PluginDefinition pd : loadFromXmlPluginPackageDefinitions(cl, in)) { repo.addPluginDefinition(pd); } }
[ "public", "static", "void", "loadFromXmlPluginPackageDefinitions", "(", "final", "IPluginRepository", "repo", ",", "final", "ClassLoader", "cl", ",", "final", "InputStream", "in", ")", "throws", "PluginConfigurationException", "{", "for", "(", "PluginDefinition", "pd", ":", "loadFromXmlPluginPackageDefinitions", "(", "cl", ",", "in", ")", ")", "{", "repo", ".", "addPluginDefinition", "(", "pd", ")", ";", "}", "}" ]
Loads a full repository definition from an XML file. @param repo The repository that must be loaded @param cl The classloader to be used to instantiate the plugin classes @param in The stream to the XML file @throws PluginConfigurationException -
[ "Loads", "a", "full", "repository", "definition", "from", "an", "XML", "file", "." ]
ac9046355851136994388442b01ba4063305f9c4
https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-lib/src/main/java/it/jnrpe/utils/PluginRepositoryUtil.java#L69-L74
142,204
ziccardi/jnrpe
jnrpe-lib/src/main/java/it/jnrpe/utils/PluginRepositoryUtil.java
PluginRepositoryUtil.loadFromXmlPluginPackageDefinitions
@SuppressWarnings("unchecked") public static Collection<PluginDefinition> loadFromXmlPluginPackageDefinitions(final ClassLoader cl, final InputStream in) throws PluginConfigurationException { List<PluginDefinition> res = new ArrayList<PluginDefinition>(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); Document document; try { DocumentBuilder loader = factory.newDocumentBuilder(); DOMReader reader = new DOMReader(); document = reader.read(loader.parse(in)); } catch (Exception e) { throw new PluginConfigurationException(e.getMessage(), e); } Element plugins = document.getRootElement(); // TODO : validate against schema // iterate through child elements of root for (Iterator<Element> i = plugins.elementIterator(); i.hasNext();) { res.add(parsePluginDefinition(cl, i.next())); } return res; }
java
@SuppressWarnings("unchecked") public static Collection<PluginDefinition> loadFromXmlPluginPackageDefinitions(final ClassLoader cl, final InputStream in) throws PluginConfigurationException { List<PluginDefinition> res = new ArrayList<PluginDefinition>(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); Document document; try { DocumentBuilder loader = factory.newDocumentBuilder(); DOMReader reader = new DOMReader(); document = reader.read(loader.parse(in)); } catch (Exception e) { throw new PluginConfigurationException(e.getMessage(), e); } Element plugins = document.getRootElement(); // TODO : validate against schema // iterate through child elements of root for (Iterator<Element> i = plugins.elementIterator(); i.hasNext();) { res.add(parsePluginDefinition(cl, i.next())); } return res; }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "static", "Collection", "<", "PluginDefinition", ">", "loadFromXmlPluginPackageDefinitions", "(", "final", "ClassLoader", "cl", ",", "final", "InputStream", "in", ")", "throws", "PluginConfigurationException", "{", "List", "<", "PluginDefinition", ">", "res", "=", "new", "ArrayList", "<", "PluginDefinition", ">", "(", ")", ";", "DocumentBuilderFactory", "factory", "=", "DocumentBuilderFactory", ".", "newInstance", "(", ")", ";", "Document", "document", ";", "try", "{", "DocumentBuilder", "loader", "=", "factory", ".", "newDocumentBuilder", "(", ")", ";", "DOMReader", "reader", "=", "new", "DOMReader", "(", ")", ";", "document", "=", "reader", ".", "read", "(", "loader", ".", "parse", "(", "in", ")", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "PluginConfigurationException", "(", "e", ".", "getMessage", "(", ")", ",", "e", ")", ";", "}", "Element", "plugins", "=", "document", ".", "getRootElement", "(", ")", ";", "// TODO : validate against schema", "// iterate through child elements of root", "for", "(", "Iterator", "<", "Element", ">", "i", "=", "plugins", ".", "elementIterator", "(", ")", ";", "i", ".", "hasNext", "(", ")", ";", ")", "{", "res", ".", "add", "(", "parsePluginDefinition", "(", "cl", ",", "i", ".", "next", "(", ")", ")", ")", ";", "}", "return", "res", ";", "}" ]
Loads the plugins definitions from the jnrpe_plugins.xml file. @param cl Classloader to be used to load classes @param in InputStream to the jnrpe_plugins.xml file @return a collection of all the declared plugins @throws PluginConfigurationException on any error reading the plugin configuration
[ "Loads", "the", "plugins", "definitions", "from", "the", "jnrpe_plugins", ".", "xml", "file", "." ]
ac9046355851136994388442b01ba4063305f9c4
https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-lib/src/main/java/it/jnrpe/utils/PluginRepositoryUtil.java#L84-L113
142,205
ziccardi/jnrpe
jnrpe-lib/src/main/java/it/jnrpe/utils/PluginRepositoryUtil.java
PluginRepositoryUtil.parseXmlPluginDefinition
public static PluginDefinition parseXmlPluginDefinition(final ClassLoader cl, final InputStream in) throws PluginConfigurationException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); Document document; try { DocumentBuilder loader = factory.newDocumentBuilder(); DOMReader reader = new DOMReader(); document = reader.read(loader.parse(in)); } catch (Exception e) { throw new PluginConfigurationException(e.getMessage(), e); } Element plugin = document.getRootElement(); // TODO : validate against schema return parsePluginDefinition(cl, plugin); }
java
public static PluginDefinition parseXmlPluginDefinition(final ClassLoader cl, final InputStream in) throws PluginConfigurationException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); Document document; try { DocumentBuilder loader = factory.newDocumentBuilder(); DOMReader reader = new DOMReader(); document = reader.read(loader.parse(in)); } catch (Exception e) { throw new PluginConfigurationException(e.getMessage(), e); } Element plugin = document.getRootElement(); // TODO : validate against schema return parsePluginDefinition(cl, plugin); }
[ "public", "static", "PluginDefinition", "parseXmlPluginDefinition", "(", "final", "ClassLoader", "cl", ",", "final", "InputStream", "in", ")", "throws", "PluginConfigurationException", "{", "DocumentBuilderFactory", "factory", "=", "DocumentBuilderFactory", ".", "newInstance", "(", ")", ";", "Document", "document", ";", "try", "{", "DocumentBuilder", "loader", "=", "factory", ".", "newDocumentBuilder", "(", ")", ";", "DOMReader", "reader", "=", "new", "DOMReader", "(", ")", ";", "document", "=", "reader", ".", "read", "(", "loader", ".", "parse", "(", "in", ")", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "PluginConfigurationException", "(", "e", ".", "getMessage", "(", ")", ",", "e", ")", ";", "}", "Element", "plugin", "=", "document", ".", "getRootElement", "(", ")", ";", "// TODO : validate against schema", "return", "parsePluginDefinition", "(", "cl", ",", "plugin", ")", ";", "}" ]
Loads the definition of a single plugin from an XML file. @param cl The classloader to be used to instantiate the plugin class @param in The stream to the XML file @return The plugin definition @throws PluginConfigurationException if an error occurs parsing the plugin definition
[ "Loads", "the", "definition", "of", "a", "single", "plugin", "from", "an", "XML", "file", "." ]
ac9046355851136994388442b01ba4063305f9c4
https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-lib/src/main/java/it/jnrpe/utils/PluginRepositoryUtil.java#L125-L145
142,206
ziccardi/jnrpe
jnrpe-lib/src/main/java/it/jnrpe/utils/PluginRepositoryUtil.java
PluginRepositoryUtil.parsePluginDefinition
@SuppressWarnings("rawtypes") private static PluginDefinition parsePluginDefinition(final ClassLoader cl, final Element plugin) throws PluginConfigurationException { // Check if the plugin definition is inside its own file if (getAttributeValue(plugin, "definedIn", false) != null) { StreamManager sm = new StreamManager(); String sFileName = getAttributeValue(plugin, "definedIn", false); try { InputStream in = sm.handle(cl.getResourceAsStream(sFileName)); return parseXmlPluginDefinition(cl, in); } finally { sm.closeAll(); } } String pluginClass = getAttributeValue(plugin, "class", true); Class clazz; try { clazz = LoadedClassCache.getClass(cl, pluginClass); if (!IPluginInterface.class.isAssignableFrom(clazz)) { throw new PluginConfigurationException("Specified class '" + clazz.getName() + "' in the plugin.xml file does not implement " + "the IPluginInterface interface"); } if (isAnnotated(clazz)) { return loadFromPluginAnnotation(clazz); } } catch (ClassNotFoundException e) { throw new PluginConfigurationException(e.getMessage(), e); } // The class is not annotated not has an external definition file... // Loading from current xml file... String sDescription = getAttributeValue(plugin, "description", false); @SuppressWarnings("unchecked") PluginDefinition pluginDef = new PluginDefinition(getAttributeValue(plugin, "name", true), sDescription, clazz); parseCommandLine(pluginDef, plugin); return pluginDef; }
java
@SuppressWarnings("rawtypes") private static PluginDefinition parsePluginDefinition(final ClassLoader cl, final Element plugin) throws PluginConfigurationException { // Check if the plugin definition is inside its own file if (getAttributeValue(plugin, "definedIn", false) != null) { StreamManager sm = new StreamManager(); String sFileName = getAttributeValue(plugin, "definedIn", false); try { InputStream in = sm.handle(cl.getResourceAsStream(sFileName)); return parseXmlPluginDefinition(cl, in); } finally { sm.closeAll(); } } String pluginClass = getAttributeValue(plugin, "class", true); Class clazz; try { clazz = LoadedClassCache.getClass(cl, pluginClass); if (!IPluginInterface.class.isAssignableFrom(clazz)) { throw new PluginConfigurationException("Specified class '" + clazz.getName() + "' in the plugin.xml file does not implement " + "the IPluginInterface interface"); } if (isAnnotated(clazz)) { return loadFromPluginAnnotation(clazz); } } catch (ClassNotFoundException e) { throw new PluginConfigurationException(e.getMessage(), e); } // The class is not annotated not has an external definition file... // Loading from current xml file... String sDescription = getAttributeValue(plugin, "description", false); @SuppressWarnings("unchecked") PluginDefinition pluginDef = new PluginDefinition(getAttributeValue(plugin, "name", true), sDescription, clazz); parseCommandLine(pluginDef, plugin); return pluginDef; }
[ "@", "SuppressWarnings", "(", "\"rawtypes\"", ")", "private", "static", "PluginDefinition", "parsePluginDefinition", "(", "final", "ClassLoader", "cl", ",", "final", "Element", "plugin", ")", "throws", "PluginConfigurationException", "{", "// Check if the plugin definition is inside its own file", "if", "(", "getAttributeValue", "(", "plugin", ",", "\"definedIn\"", ",", "false", ")", "!=", "null", ")", "{", "StreamManager", "sm", "=", "new", "StreamManager", "(", ")", ";", "String", "sFileName", "=", "getAttributeValue", "(", "plugin", ",", "\"definedIn\"", ",", "false", ")", ";", "try", "{", "InputStream", "in", "=", "sm", ".", "handle", "(", "cl", ".", "getResourceAsStream", "(", "sFileName", ")", ")", ";", "return", "parseXmlPluginDefinition", "(", "cl", ",", "in", ")", ";", "}", "finally", "{", "sm", ".", "closeAll", "(", ")", ";", "}", "}", "String", "pluginClass", "=", "getAttributeValue", "(", "plugin", ",", "\"class\"", ",", "true", ")", ";", "Class", "clazz", ";", "try", "{", "clazz", "=", "LoadedClassCache", ".", "getClass", "(", "cl", ",", "pluginClass", ")", ";", "if", "(", "!", "IPluginInterface", ".", "class", ".", "isAssignableFrom", "(", "clazz", ")", ")", "{", "throw", "new", "PluginConfigurationException", "(", "\"Specified class '\"", "+", "clazz", ".", "getName", "(", ")", "+", "\"' in the plugin.xml file does not implement \"", "+", "\"the IPluginInterface interface\"", ")", ";", "}", "if", "(", "isAnnotated", "(", "clazz", ")", ")", "{", "return", "loadFromPluginAnnotation", "(", "clazz", ")", ";", "}", "}", "catch", "(", "ClassNotFoundException", "e", ")", "{", "throw", "new", "PluginConfigurationException", "(", "e", ".", "getMessage", "(", ")", ",", "e", ")", ";", "}", "// The class is not annotated not has an external definition file...", "// Loading from current xml file...", "String", "sDescription", "=", "getAttributeValue", "(", "plugin", ",", "\"description\"", ",", "false", ")", ";", "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "PluginDefinition", "pluginDef", "=", "new", "PluginDefinition", "(", "getAttributeValue", "(", "plugin", ",", "\"name\"", ",", "true", ")", ",", "sDescription", ",", "clazz", ")", ";", "parseCommandLine", "(", "pluginDef", ",", "plugin", ")", ";", "return", "pluginDef", ";", "}" ]
Parse an XML plugin definition. @param cl The classloader to be used to load classes @param plugin The plugin XML element @return the parsed plugin definition * @throws PluginConfigurationException -
[ "Parse", "an", "XML", "plugin", "definition", "." ]
ac9046355851136994388442b01ba4063305f9c4
https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-lib/src/main/java/it/jnrpe/utils/PluginRepositoryUtil.java#L187-L234
142,207
ziccardi/jnrpe
jnrpe-lib/src/main/java/it/jnrpe/utils/PluginRepositoryUtil.java
PluginRepositoryUtil.parseCommandLine
@SuppressWarnings("rawtypes") private static void parseCommandLine(final PluginDefinition pluginDef, final Element xmlPluginElement) { Element commandLine = xmlPluginElement.element("command-line"); if (commandLine != null) { // The plugin has a command line... Element options = commandLine.element("options"); if (options == null) { // The command line is empty... return; } for (Iterator<Element> i = options.elementIterator(); i.hasNext();) { pluginDef.addOption(parsePluginOption(i.next())); } } }
java
@SuppressWarnings("rawtypes") private static void parseCommandLine(final PluginDefinition pluginDef, final Element xmlPluginElement) { Element commandLine = xmlPluginElement.element("command-line"); if (commandLine != null) { // The plugin has a command line... Element options = commandLine.element("options"); if (options == null) { // The command line is empty... return; } for (Iterator<Element> i = options.elementIterator(); i.hasNext();) { pluginDef.addOption(parsePluginOption(i.next())); } } }
[ "@", "SuppressWarnings", "(", "\"rawtypes\"", ")", "private", "static", "void", "parseCommandLine", "(", "final", "PluginDefinition", "pluginDef", ",", "final", "Element", "xmlPluginElement", ")", "{", "Element", "commandLine", "=", "xmlPluginElement", ".", "element", "(", "\"command-line\"", ")", ";", "if", "(", "commandLine", "!=", "null", ")", "{", "// The plugin has a command line...", "Element", "options", "=", "commandLine", ".", "element", "(", "\"options\"", ")", ";", "if", "(", "options", "==", "null", ")", "{", "// The command line is empty...", "return", ";", "}", "for", "(", "Iterator", "<", "Element", ">", "i", "=", "options", ".", "elementIterator", "(", ")", ";", "i", ".", "hasNext", "(", ")", ";", ")", "{", "pluginDef", ".", "addOption", "(", "parsePluginOption", "(", "i", ".", "next", "(", ")", ")", ")", ";", "}", "}", "}" ]
Updates the plugin definition with the commandline read from the xml file. @param pluginDef The plugin definition to be updated @param xmlPluginElement the xml element to be parsed
[ "Updates", "the", "plugin", "definition", "with", "the", "commandline", "read", "from", "the", "xml", "file", "." ]
ac9046355851136994388442b01ba4063305f9c4
https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-lib/src/main/java/it/jnrpe/utils/PluginRepositoryUtil.java#L245-L262
142,208
ziccardi/jnrpe
jnrpe-lib/src/main/java/it/jnrpe/utils/PluginRepositoryUtil.java
PluginRepositoryUtil.parsePluginOption
private static PluginOption parsePluginOption(final Element option) { PluginOption po = new PluginOption(); po.setArgName(option.attributeValue("argName")); po.setArgsCount(Integer.valueOf(option.attributeValue("argsCount", "1"))); po.setArgsOptional(Boolean.valueOf(option.attributeValue("optionalArgs", "false"))); po.setDescription(option.attributeValue("description")); po.setHasArgs(Boolean.parseBoolean(option.attributeValue("hasArgs", "false"))); po.setLongOpt(option.attributeValue("longName")); po.setOption(option.attributeValue("shortName")); po.setRequired(Boolean.parseBoolean(option.attributeValue("required", "false"))); po.setType(option.attributeValue("type")); po.setValueSeparator(option.attributeValue("separator")); return po; }
java
private static PluginOption parsePluginOption(final Element option) { PluginOption po = new PluginOption(); po.setArgName(option.attributeValue("argName")); po.setArgsCount(Integer.valueOf(option.attributeValue("argsCount", "1"))); po.setArgsOptional(Boolean.valueOf(option.attributeValue("optionalArgs", "false"))); po.setDescription(option.attributeValue("description")); po.setHasArgs(Boolean.parseBoolean(option.attributeValue("hasArgs", "false"))); po.setLongOpt(option.attributeValue("longName")); po.setOption(option.attributeValue("shortName")); po.setRequired(Boolean.parseBoolean(option.attributeValue("required", "false"))); po.setType(option.attributeValue("type")); po.setValueSeparator(option.attributeValue("separator")); return po; }
[ "private", "static", "PluginOption", "parsePluginOption", "(", "final", "Element", "option", ")", "{", "PluginOption", "po", "=", "new", "PluginOption", "(", ")", ";", "po", ".", "setArgName", "(", "option", ".", "attributeValue", "(", "\"argName\"", ")", ")", ";", "po", ".", "setArgsCount", "(", "Integer", ".", "valueOf", "(", "option", ".", "attributeValue", "(", "\"argsCount\"", ",", "\"1\"", ")", ")", ")", ";", "po", ".", "setArgsOptional", "(", "Boolean", ".", "valueOf", "(", "option", ".", "attributeValue", "(", "\"optionalArgs\"", ",", "\"false\"", ")", ")", ")", ";", "po", ".", "setDescription", "(", "option", ".", "attributeValue", "(", "\"description\"", ")", ")", ";", "po", ".", "setHasArgs", "(", "Boolean", ".", "parseBoolean", "(", "option", ".", "attributeValue", "(", "\"hasArgs\"", ",", "\"false\"", ")", ")", ")", ";", "po", ".", "setLongOpt", "(", "option", ".", "attributeValue", "(", "\"longName\"", ")", ")", ";", "po", ".", "setOption", "(", "option", ".", "attributeValue", "(", "\"shortName\"", ")", ")", ";", "po", ".", "setRequired", "(", "Boolean", ".", "parseBoolean", "(", "option", ".", "attributeValue", "(", "\"required\"", ",", "\"false\"", ")", ")", ")", ";", "po", ".", "setType", "(", "option", ".", "attributeValue", "(", "\"type\"", ")", ")", ";", "po", ".", "setValueSeparator", "(", "option", ".", "attributeValue", "(", "\"separator\"", ")", ")", ";", "return", "po", ";", "}" ]
Parses a plugin option XML definition. @param option The plugin option XML definition @return The parsed plugin option
[ "Parses", "a", "plugin", "option", "XML", "definition", "." ]
ac9046355851136994388442b01ba4063305f9c4
https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-lib/src/main/java/it/jnrpe/utils/PluginRepositoryUtil.java#L319-L333
142,209
ziccardi/jnrpe
jnrpe-lib/src/main/java/it/jnrpe/utils/PluginRepositoryUtil.java
PluginRepositoryUtil.parsePluginOption
private static PluginOption parsePluginOption(final Option option) { PluginOption po = new PluginOption(); po.setArgName(option.argName()); po.setArgsOptional(option.optionalArgs()); po.setDescription(option.description()); po.setHasArgs(option.hasArgs()); po.setLongOpt(option.longName()); po.setOption(option.shortName()); po.setRequired(option.required()); return po; }
java
private static PluginOption parsePluginOption(final Option option) { PluginOption po = new PluginOption(); po.setArgName(option.argName()); po.setArgsOptional(option.optionalArgs()); po.setDescription(option.description()); po.setHasArgs(option.hasArgs()); po.setLongOpt(option.longName()); po.setOption(option.shortName()); po.setRequired(option.required()); return po; }
[ "private", "static", "PluginOption", "parsePluginOption", "(", "final", "Option", "option", ")", "{", "PluginOption", "po", "=", "new", "PluginOption", "(", ")", ";", "po", ".", "setArgName", "(", "option", ".", "argName", "(", ")", ")", ";", "po", ".", "setArgsOptional", "(", "option", ".", "optionalArgs", "(", ")", ")", ";", "po", ".", "setDescription", "(", "option", ".", "description", "(", ")", ")", ";", "po", ".", "setHasArgs", "(", "option", ".", "hasArgs", "(", ")", ")", ";", "po", ".", "setLongOpt", "(", "option", ".", "longName", "(", ")", ")", ";", "po", ".", "setOption", "(", "option", ".", "shortName", "(", ")", ")", ";", "po", ".", "setRequired", "(", "option", ".", "required", "(", ")", ")", ";", "return", "po", ";", "}" ]
Parses a plugin option from the annotation definition. @param option the plugin option @return PluginOption
[ "Parses", "a", "plugin", "option", "from", "the", "annotation", "definition", "." ]
ac9046355851136994388442b01ba4063305f9c4
https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-lib/src/main/java/it/jnrpe/utils/PluginRepositoryUtil.java#L342-L353
142,210
petergeneric/stdlib
guice/webapp/src/main/java/com/peterphi/std/guice/web/rest/jaxrs/GuiceDynamicProxyProvider.java
GuiceDynamicProxyProvider.invoke
@Override public Object invoke(Object self, Method thisMethod, Method proceed, Object[] args) throws Throwable { // Get an instance of the implementing class via Guice final Object instance = registry.getInjector().getInstance(clazz); return thisMethod.invoke(instance, args); }
java
@Override public Object invoke(Object self, Method thisMethod, Method proceed, Object[] args) throws Throwable { // Get an instance of the implementing class via Guice final Object instance = registry.getInjector().getInstance(clazz); return thisMethod.invoke(instance, args); }
[ "@", "Override", "public", "Object", "invoke", "(", "Object", "self", ",", "Method", "thisMethod", ",", "Method", "proceed", ",", "Object", "[", "]", "args", ")", "throws", "Throwable", "{", "// Get an instance of the implementing class via Guice", "final", "Object", "instance", "=", "registry", ".", "getInjector", "(", ")", ".", "getInstance", "(", "clazz", ")", ";", "return", "thisMethod", ".", "invoke", "(", "instance", ",", "args", ")", ";", "}" ]
A MethodHandler that proxies the Method invocation through to a Guice-acquired instance
[ "A", "MethodHandler", "that", "proxies", "the", "Method", "invocation", "through", "to", "a", "Guice", "-", "acquired", "instance" ]
d4025d2f881bc0542b1e004c5f65a1ccaf895836
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/guice/webapp/src/main/java/com/peterphi/std/guice/web/rest/jaxrs/GuiceDynamicProxyProvider.java#L48-L55
142,211
petergeneric/stdlib
service-manager/host-agent/src/main/java/com/peterphi/servicemanager/hostagent/cmdline/NginxSiteGenerator.java
NginxSiteGenerator.main
public static void main(String[] args) throws Exception { final String name = args[0]; final File sslCert = new File(args[1]); final File sslKey = new File(args[2]); final Map<File, Integer> foldersAndPorts = getFoldersAndPorts(3, args); NginxSiteGenerator generator = new NginxSiteGenerator(); final String config = generator.render(name, sslCert, sslKey, foldersAndPorts); System.out.println(config); }
java
public static void main(String[] args) throws Exception { final String name = args[0]; final File sslCert = new File(args[1]); final File sslKey = new File(args[2]); final Map<File, Integer> foldersAndPorts = getFoldersAndPorts(3, args); NginxSiteGenerator generator = new NginxSiteGenerator(); final String config = generator.render(name, sslCert, sslKey, foldersAndPorts); System.out.println(config); }
[ "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "throws", "Exception", "{", "final", "String", "name", "=", "args", "[", "0", "]", ";", "final", "File", "sslCert", "=", "new", "File", "(", "args", "[", "1", "]", ")", ";", "final", "File", "sslKey", "=", "new", "File", "(", "args", "[", "2", "]", ")", ";", "final", "Map", "<", "File", ",", "Integer", ">", "foldersAndPorts", "=", "getFoldersAndPorts", "(", "3", ",", "args", ")", ";", "NginxSiteGenerator", "generator", "=", "new", "NginxSiteGenerator", "(", ")", ";", "final", "String", "config", "=", "generator", ".", "render", "(", "name", ",", "sslCert", ",", "sslKey", ",", "foldersAndPorts", ")", ";", "System", ".", "out", ".", "println", "(", "config", ")", ";", "}" ]
Entry point for initial generation, called from the commandline @param args @throws Exception
[ "Entry", "point", "for", "initial", "generation", "called", "from", "the", "commandline" ]
d4025d2f881bc0542b1e004c5f65a1ccaf895836
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/service-manager/host-agent/src/main/java/com/peterphi/servicemanager/hostagent/cmdline/NginxSiteGenerator.java#L238-L250
142,212
petergeneric/stdlib
stdlib/src/main/java/com/peterphi/std/util/jaxb/MultiXSDSchemaCollector.java
MultiXSDSchemaCollector.encode
public MultiXSDSchemaFiles encode() { MultiXSDSchemaFiles files = new MultiXSDSchemaFiles(); for (Map.Entry<String, DOMResult> entry : schemas.entrySet()) { MultiXSDSchemaFile file = new MultiXSDSchemaFile(); file.name = entry.getKey(); file.schema = getElement(entry.getValue().getNode()); files.files.add(file); } // Now loosen xml:any namespace=##other to xml:any namespace=##any if (loosenXmlAnyConstraints) MultiXSDSchemaLoosener.loosenXmlAnyOtherNamespaceToXmlAnyAnyNamespace(files); return files; }
java
public MultiXSDSchemaFiles encode() { MultiXSDSchemaFiles files = new MultiXSDSchemaFiles(); for (Map.Entry<String, DOMResult> entry : schemas.entrySet()) { MultiXSDSchemaFile file = new MultiXSDSchemaFile(); file.name = entry.getKey(); file.schema = getElement(entry.getValue().getNode()); files.files.add(file); } // Now loosen xml:any namespace=##other to xml:any namespace=##any if (loosenXmlAnyConstraints) MultiXSDSchemaLoosener.loosenXmlAnyOtherNamespaceToXmlAnyAnyNamespace(files); return files; }
[ "public", "MultiXSDSchemaFiles", "encode", "(", ")", "{", "MultiXSDSchemaFiles", "files", "=", "new", "MultiXSDSchemaFiles", "(", ")", ";", "for", "(", "Map", ".", "Entry", "<", "String", ",", "DOMResult", ">", "entry", ":", "schemas", ".", "entrySet", "(", ")", ")", "{", "MultiXSDSchemaFile", "file", "=", "new", "MultiXSDSchemaFile", "(", ")", ";", "file", ".", "name", "=", "entry", ".", "getKey", "(", ")", ";", "file", ".", "schema", "=", "getElement", "(", "entry", ".", "getValue", "(", ")", ".", "getNode", "(", ")", ")", ";", "files", ".", "files", ".", "add", "(", "file", ")", ";", "}", "// Now loosen xml:any namespace=##other to xml:any namespace=##any", "if", "(", "loosenXmlAnyConstraints", ")", "MultiXSDSchemaLoosener", ".", "loosenXmlAnyOtherNamespaceToXmlAnyAnyNamespace", "(", "files", ")", ";", "return", "files", ";", "}" ]
Produces an XML Schema or a Stdlib SchemaFiles document containing the XML Schemas @return
[ "Produces", "an", "XML", "Schema", "or", "a", "Stdlib", "SchemaFiles", "document", "containing", "the", "XML", "Schemas" ]
d4025d2f881bc0542b1e004c5f65a1ccaf895836
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/stdlib/src/main/java/com/peterphi/std/util/jaxb/MultiXSDSchemaCollector.java#L49-L68
142,213
petergeneric/stdlib
guice/webapp/src/main/java/com/peterphi/std/guice/web/rest/CoreRestServicesModule.java
CoreRestServicesModule.getRestServicesPrefix
@Provides @Singleton @Named(GuiceProperties.REST_SERVICES_PREFIX) public String getRestServicesPrefix(ServletContext context) { String restPath = context.getInitParameter(RESTEASY_MAPPING_PREFIX); if (restPath == null || restPath.isEmpty() || restPath.equals("/")) { return ""; } else { return restPath; } }
java
@Provides @Singleton @Named(GuiceProperties.REST_SERVICES_PREFIX) public String getRestServicesPrefix(ServletContext context) { String restPath = context.getInitParameter(RESTEASY_MAPPING_PREFIX); if (restPath == null || restPath.isEmpty() || restPath.equals("/")) { return ""; } else { return restPath; } }
[ "@", "Provides", "@", "Singleton", "@", "Named", "(", "GuiceProperties", ".", "REST_SERVICES_PREFIX", ")", "public", "String", "getRestServicesPrefix", "(", "ServletContext", "context", ")", "{", "String", "restPath", "=", "context", ".", "getInitParameter", "(", "RESTEASY_MAPPING_PREFIX", ")", ";", "if", "(", "restPath", "==", "null", "||", "restPath", ".", "isEmpty", "(", ")", "||", "restPath", ".", "equals", "(", "\"/\"", ")", ")", "{", "return", "\"\"", ";", "}", "else", "{", "return", "restPath", ";", "}", "}" ]
Retrieves the RESTeasy mapping prefix - this is the path under the webapp root where RESTeasy services are mapped. @param context @return
[ "Retrieves", "the", "RESTeasy", "mapping", "prefix", "-", "this", "is", "the", "path", "under", "the", "webapp", "root", "where", "RESTeasy", "services", "are", "mapped", "." ]
d4025d2f881bc0542b1e004c5f65a1ccaf895836
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/guice/webapp/src/main/java/com/peterphi/std/guice/web/rest/CoreRestServicesModule.java#L59-L74
142,214
petergeneric/stdlib
guice/webapp/src/main/java/com/peterphi/std/guice/web/rest/CoreRestServicesModule.java
CoreRestServicesModule.getRestServicesEndpoint
@Provides @Singleton @Named(GuiceProperties.LOCAL_REST_SERVICES_ENDPOINT) public URI getRestServicesEndpoint(@Named(GuiceProperties.STATIC_ENDPOINT_CONFIG_NAME) URI webappUri, @Named(GuiceProperties.REST_SERVICES_PREFIX) String restPrefix, ServletContext context) { if (restPrefix.equals("")) { // resteasy mapped to / return webappUri; } else { // Strip the leading / from the restpath while (restPrefix.startsWith("/")) restPrefix = restPrefix.substring(1); final String webappPath = webappUri.toString(); if (webappPath.endsWith("/")) return URI.create(webappPath + restPrefix); else return URI.create(webappPath + "/" + restPrefix); } }
java
@Provides @Singleton @Named(GuiceProperties.LOCAL_REST_SERVICES_ENDPOINT) public URI getRestServicesEndpoint(@Named(GuiceProperties.STATIC_ENDPOINT_CONFIG_NAME) URI webappUri, @Named(GuiceProperties.REST_SERVICES_PREFIX) String restPrefix, ServletContext context) { if (restPrefix.equals("")) { // resteasy mapped to / return webappUri; } else { // Strip the leading / from the restpath while (restPrefix.startsWith("/")) restPrefix = restPrefix.substring(1); final String webappPath = webappUri.toString(); if (webappPath.endsWith("/")) return URI.create(webappPath + restPrefix); else return URI.create(webappPath + "/" + restPrefix); } }
[ "@", "Provides", "@", "Singleton", "@", "Named", "(", "GuiceProperties", ".", "LOCAL_REST_SERVICES_ENDPOINT", ")", "public", "URI", "getRestServicesEndpoint", "(", "@", "Named", "(", "GuiceProperties", ".", "STATIC_ENDPOINT_CONFIG_NAME", ")", "URI", "webappUri", ",", "@", "Named", "(", "GuiceProperties", ".", "REST_SERVICES_PREFIX", ")", "String", "restPrefix", ",", "ServletContext", "context", ")", "{", "if", "(", "restPrefix", ".", "equals", "(", "\"\"", ")", ")", "{", "// resteasy mapped to /", "return", "webappUri", ";", "}", "else", "{", "// Strip the leading / from the restpath", "while", "(", "restPrefix", ".", "startsWith", "(", "\"/\"", ")", ")", "restPrefix", "=", "restPrefix", ".", "substring", "(", "1", ")", ";", "final", "String", "webappPath", "=", "webappUri", ".", "toString", "(", ")", ";", "if", "(", "webappPath", ".", "endsWith", "(", "\"/\"", ")", ")", "return", "URI", ".", "create", "(", "webappPath", "+", "restPrefix", ")", ";", "else", "return", "URI", ".", "create", "(", "webappPath", "+", "\"/\"", "+", "restPrefix", ")", ";", "}", "}" ]
Return the base path for all REST services in this webapp @param webappUri @param restPrefix the prefix for rest services (added after the webapp endpoint to form the base path for the JAX-RS container) @param context @return
[ "Return", "the", "base", "path", "for", "all", "REST", "services", "in", "this", "webapp" ]
d4025d2f881bc0542b1e004c5f65a1ccaf895836
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/guice/webapp/src/main/java/com/peterphi/std/guice/web/rest/CoreRestServicesModule.java#L87-L112
142,215
petergeneric/stdlib
guice/webapp/src/main/java/com/peterphi/std/guice/web/rest/CoreRestServicesModule.java
CoreRestServicesModule.getRestServicesEndpoint
@Provides @Singleton @Named(GuiceProperties.STATIC_ENDPOINT_CONFIG_NAME) public URI getRestServicesEndpoint(LocalEndpointDiscovery localEndpointDiscovery) { final URI base = localEndpointDiscovery.getLocalEndpoint(); return base; }
java
@Provides @Singleton @Named(GuiceProperties.STATIC_ENDPOINT_CONFIG_NAME) public URI getRestServicesEndpoint(LocalEndpointDiscovery localEndpointDiscovery) { final URI base = localEndpointDiscovery.getLocalEndpoint(); return base; }
[ "@", "Provides", "@", "Singleton", "@", "Named", "(", "GuiceProperties", ".", "STATIC_ENDPOINT_CONFIG_NAME", ")", "public", "URI", "getRestServicesEndpoint", "(", "LocalEndpointDiscovery", "localEndpointDiscovery", ")", "{", "final", "URI", "base", "=", "localEndpointDiscovery", ".", "getLocalEndpoint", "(", ")", ";", "return", "base", ";", "}" ]
Return the base path for this webapp @param localEndpointDiscovery @return
[ "Return", "the", "base", "path", "for", "this", "webapp" ]
d4025d2f881bc0542b1e004c5f65a1ccaf895836
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/guice/webapp/src/main/java/com/peterphi/std/guice/web/rest/CoreRestServicesModule.java#L122-L130
142,216
petergeneric/stdlib
guice/common/src/main/java/com/peterphi/std/guice/common/ClassScanner.java
ClassScanner.getSiblingClasses
public List<Class<?>> getSiblingClasses(final Class<?> clazz, boolean recursive, final Predicate<Class<?>> predicate) { return getClasses(getPackages(clazz)[0], recursive, predicate); }
java
public List<Class<?>> getSiblingClasses(final Class<?> clazz, boolean recursive, final Predicate<Class<?>> predicate) { return getClasses(getPackages(clazz)[0], recursive, predicate); }
[ "public", "List", "<", "Class", "<", "?", ">", ">", "getSiblingClasses", "(", "final", "Class", "<", "?", ">", "clazz", ",", "boolean", "recursive", ",", "final", "Predicate", "<", "Class", "<", "?", ">", ">", "predicate", ")", "{", "return", "getClasses", "(", "getPackages", "(", "clazz", ")", "[", "0", "]", ",", "recursive", ",", "predicate", ")", ";", "}" ]
Find all the classes that are siblings of the provided class @param clazz the class in whose package to search @param recursive if true, search all the child packages of the package containing the class @param predicate an optional additional predicate to filter the list against @return
[ "Find", "all", "the", "classes", "that", "are", "siblings", "of", "the", "provided", "class" ]
d4025d2f881bc0542b1e004c5f65a1ccaf895836
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/guice/common/src/main/java/com/peterphi/std/guice/common/ClassScanner.java#L113-L116
142,217
ziccardi/jnrpe
jnrpe-lib/src/main/java/it/jnrpe/commands/CommandDefinition.java
CommandDefinition.getCommandLine
public String[] getCommandLine() { String[] argsAry = argsString != null ? split(argsString) : EMPTY_ARRAY; List<String> argsList = new ArrayList<String>(); int startIndex = 0; for (CommandOption opt : optionsList) { String argName = opt.getName(); String argValueString = opt.getValue(); argsList.add((argName.length() == 1 ? "-" : "--") + argName); if (argValueString != null) { argsList.add(quote(argValueString)); } } String[] resAry = new String[argsAry.length + argsList.size()]; for (String argString : argsList) { resAry[startIndex++] = argString; } // vsRes = new String[args.length + m_vArguments.size()]; System.arraycopy(argsAry, 0, resAry, startIndex, argsAry.length); return resAry; }
java
public String[] getCommandLine() { String[] argsAry = argsString != null ? split(argsString) : EMPTY_ARRAY; List<String> argsList = new ArrayList<String>(); int startIndex = 0; for (CommandOption opt : optionsList) { String argName = opt.getName(); String argValueString = opt.getValue(); argsList.add((argName.length() == 1 ? "-" : "--") + argName); if (argValueString != null) { argsList.add(quote(argValueString)); } } String[] resAry = new String[argsAry.length + argsList.size()]; for (String argString : argsList) { resAry[startIndex++] = argString; } // vsRes = new String[args.length + m_vArguments.size()]; System.arraycopy(argsAry, 0, resAry, startIndex, argsAry.length); return resAry; }
[ "public", "String", "[", "]", "getCommandLine", "(", ")", "{", "String", "[", "]", "argsAry", "=", "argsString", "!=", "null", "?", "split", "(", "argsString", ")", ":", "EMPTY_ARRAY", ";", "List", "<", "String", ">", "argsList", "=", "new", "ArrayList", "<", "String", ">", "(", ")", ";", "int", "startIndex", "=", "0", ";", "for", "(", "CommandOption", "opt", ":", "optionsList", ")", "{", "String", "argName", "=", "opt", ".", "getName", "(", ")", ";", "String", "argValueString", "=", "opt", ".", "getValue", "(", ")", ";", "argsList", ".", "add", "(", "(", "argName", ".", "length", "(", ")", "==", "1", "?", "\"-\"", ":", "\"--\"", ")", "+", "argName", ")", ";", "if", "(", "argValueString", "!=", "null", ")", "{", "argsList", ".", "add", "(", "quote", "(", "argValueString", ")", ")", ";", "}", "}", "String", "[", "]", "resAry", "=", "new", "String", "[", "argsAry", ".", "length", "+", "argsList", ".", "size", "(", ")", "]", ";", "for", "(", "String", "argString", ":", "argsList", ")", "{", "resAry", "[", "startIndex", "++", "]", "=", "argString", ";", "}", "// vsRes = new String[args.length + m_vArguments.size()];", "System", ".", "arraycopy", "(", "argsAry", ",", "0", ",", "resAry", ",", "startIndex", ",", "argsAry", ".", "length", ")", ";", "return", "resAry", ";", "}" ]
Merges the command line definition read from the server config file with. the values received from check_nrpe and produces a clean command line. @return a parsable command line or an empty array for empty command line.
[ "Merges", "the", "command", "line", "definition", "read", "from", "the", "server", "config", "file", "with", ".", "the", "values", "received", "from", "check_nrpe", "and", "produces", "a", "clean", "command", "line", "." ]
ac9046355851136994388442b01ba4063305f9c4
https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-lib/src/main/java/it/jnrpe/commands/CommandDefinition.java#L124-L151
142,218
ziccardi/jnrpe
jnrpe-lib/src/main/java/it/jnrpe/utils/thresholds/Threshold.java
Threshold.parse
private void parse(final String definition) throws BadThresholdException { String[] thresholdComponentAry = definition.split(","); for (String thresholdComponent : thresholdComponentAry) { String[] nameValuePair = thresholdComponent.split("="); if (nameValuePair.length != 2 || StringUtils.isEmpty(nameValuePair[0]) || StringUtils.isEmpty(nameValuePair[1])) { throw new BadThresholdException("Invalid threshold syntax : " + definition); } if ("metric".equalsIgnoreCase(nameValuePair[0])) { metricName = nameValuePair[1]; continue; } if ("ok".equalsIgnoreCase(nameValuePair[0])) { Range thr = new Range(nameValuePair[1]); okThresholdList.add(thr); continue; } if ("warning".equalsIgnoreCase(nameValuePair[0]) || "warn".equalsIgnoreCase(nameValuePair[0]) || "w".equalsIgnoreCase(nameValuePair[0])) { Range thr = new Range(nameValuePair[1]); warningThresholdList.add(thr); continue; } if ("critical".equalsIgnoreCase(nameValuePair[0]) || "crit".equalsIgnoreCase(nameValuePair[0]) || "c".equalsIgnoreCase(nameValuePair[0])) { Range thr = new Range(nameValuePair[1]); criticalThresholdList.add(thr); continue; } if ("unit".equalsIgnoreCase(nameValuePair[0])) { unit = nameValuePair[1]; continue; } if ("prefix".equalsIgnoreCase(nameValuePair[0])) { prefix = Prefixes.fromString(nameValuePair[1]); continue; } // Threshold specification error } }
java
private void parse(final String definition) throws BadThresholdException { String[] thresholdComponentAry = definition.split(","); for (String thresholdComponent : thresholdComponentAry) { String[] nameValuePair = thresholdComponent.split("="); if (nameValuePair.length != 2 || StringUtils.isEmpty(nameValuePair[0]) || StringUtils.isEmpty(nameValuePair[1])) { throw new BadThresholdException("Invalid threshold syntax : " + definition); } if ("metric".equalsIgnoreCase(nameValuePair[0])) { metricName = nameValuePair[1]; continue; } if ("ok".equalsIgnoreCase(nameValuePair[0])) { Range thr = new Range(nameValuePair[1]); okThresholdList.add(thr); continue; } if ("warning".equalsIgnoreCase(nameValuePair[0]) || "warn".equalsIgnoreCase(nameValuePair[0]) || "w".equalsIgnoreCase(nameValuePair[0])) { Range thr = new Range(nameValuePair[1]); warningThresholdList.add(thr); continue; } if ("critical".equalsIgnoreCase(nameValuePair[0]) || "crit".equalsIgnoreCase(nameValuePair[0]) || "c".equalsIgnoreCase(nameValuePair[0])) { Range thr = new Range(nameValuePair[1]); criticalThresholdList.add(thr); continue; } if ("unit".equalsIgnoreCase(nameValuePair[0])) { unit = nameValuePair[1]; continue; } if ("prefix".equalsIgnoreCase(nameValuePair[0])) { prefix = Prefixes.fromString(nameValuePair[1]); continue; } // Threshold specification error } }
[ "private", "void", "parse", "(", "final", "String", "definition", ")", "throws", "BadThresholdException", "{", "String", "[", "]", "thresholdComponentAry", "=", "definition", ".", "split", "(", "\",\"", ")", ";", "for", "(", "String", "thresholdComponent", ":", "thresholdComponentAry", ")", "{", "String", "[", "]", "nameValuePair", "=", "thresholdComponent", ".", "split", "(", "\"=\"", ")", ";", "if", "(", "nameValuePair", ".", "length", "!=", "2", "||", "StringUtils", ".", "isEmpty", "(", "nameValuePair", "[", "0", "]", ")", "||", "StringUtils", ".", "isEmpty", "(", "nameValuePair", "[", "1", "]", ")", ")", "{", "throw", "new", "BadThresholdException", "(", "\"Invalid threshold syntax : \"", "+", "definition", ")", ";", "}", "if", "(", "\"metric\"", ".", "equalsIgnoreCase", "(", "nameValuePair", "[", "0", "]", ")", ")", "{", "metricName", "=", "nameValuePair", "[", "1", "]", ";", "continue", ";", "}", "if", "(", "\"ok\"", ".", "equalsIgnoreCase", "(", "nameValuePair", "[", "0", "]", ")", ")", "{", "Range", "thr", "=", "new", "Range", "(", "nameValuePair", "[", "1", "]", ")", ";", "okThresholdList", ".", "add", "(", "thr", ")", ";", "continue", ";", "}", "if", "(", "\"warning\"", ".", "equalsIgnoreCase", "(", "nameValuePair", "[", "0", "]", ")", "||", "\"warn\"", ".", "equalsIgnoreCase", "(", "nameValuePair", "[", "0", "]", ")", "||", "\"w\"", ".", "equalsIgnoreCase", "(", "nameValuePair", "[", "0", "]", ")", ")", "{", "Range", "thr", "=", "new", "Range", "(", "nameValuePair", "[", "1", "]", ")", ";", "warningThresholdList", ".", "add", "(", "thr", ")", ";", "continue", ";", "}", "if", "(", "\"critical\"", ".", "equalsIgnoreCase", "(", "nameValuePair", "[", "0", "]", ")", "||", "\"crit\"", ".", "equalsIgnoreCase", "(", "nameValuePair", "[", "0", "]", ")", "||", "\"c\"", ".", "equalsIgnoreCase", "(", "nameValuePair", "[", "0", "]", ")", ")", "{", "Range", "thr", "=", "new", "Range", "(", "nameValuePair", "[", "1", "]", ")", ";", "criticalThresholdList", ".", "add", "(", "thr", ")", ";", "continue", ";", "}", "if", "(", "\"unit\"", ".", "equalsIgnoreCase", "(", "nameValuePair", "[", "0", "]", ")", ")", "{", "unit", "=", "nameValuePair", "[", "1", "]", ";", "continue", ";", "}", "if", "(", "\"prefix\"", ".", "equalsIgnoreCase", "(", "nameValuePair", "[", "0", "]", ")", ")", "{", "prefix", "=", "Prefixes", ".", "fromString", "(", "nameValuePair", "[", "1", "]", ")", ";", "continue", ";", "}", "// Threshold specification error", "}", "}" ]
Parses a threshold definition. @param definition The threshold definition @throws BadThresholdException -
[ "Parses", "a", "threshold", "definition", "." ]
ac9046355851136994388442b01ba4063305f9c4
https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-lib/src/main/java/it/jnrpe/utils/thresholds/Threshold.java#L124-L166
142,219
ziccardi/jnrpe
jnrpe-lib/src/main/java/it/jnrpe/utils/thresholds/Threshold.java
Threshold.getRangesAsString
public final String getRangesAsString(final Status status) { List<String> ranges = new ArrayList<String>(); List<Range> rangeList; switch (status) { case OK: rangeList = okThresholdList; break; case WARNING: rangeList = warningThresholdList; break; case CRITICAL: default: rangeList = criticalThresholdList; break; } for (Range r : rangeList) { ranges.add(r.getRangeString()); } if (ranges.isEmpty()) { return null; } return StringUtils.join(ranges, ","); }
java
public final String getRangesAsString(final Status status) { List<String> ranges = new ArrayList<String>(); List<Range> rangeList; switch (status) { case OK: rangeList = okThresholdList; break; case WARNING: rangeList = warningThresholdList; break; case CRITICAL: default: rangeList = criticalThresholdList; break; } for (Range r : rangeList) { ranges.add(r.getRangeString()); } if (ranges.isEmpty()) { return null; } return StringUtils.join(ranges, ","); }
[ "public", "final", "String", "getRangesAsString", "(", "final", "Status", "status", ")", "{", "List", "<", "String", ">", "ranges", "=", "new", "ArrayList", "<", "String", ">", "(", ")", ";", "List", "<", "Range", ">", "rangeList", ";", "switch", "(", "status", ")", "{", "case", "OK", ":", "rangeList", "=", "okThresholdList", ";", "break", ";", "case", "WARNING", ":", "rangeList", "=", "warningThresholdList", ";", "break", ";", "case", "CRITICAL", ":", "default", ":", "rangeList", "=", "criticalThresholdList", ";", "break", ";", "}", "for", "(", "Range", "r", ":", "rangeList", ")", "{", "ranges", ".", "add", "(", "r", ".", "getRangeString", "(", ")", ")", ";", "}", "if", "(", "ranges", ".", "isEmpty", "(", ")", ")", "{", "return", "null", ";", "}", "return", "StringUtils", ".", "join", "(", "ranges", ",", "\",\"", ")", ";", "}" ]
Returns the requested range list as comma separated string. @param status The status for wich we are requesting the ranges. @return the requested range list as comma separated string. @see it.jnrpe.utils.thresholds.IThreshold#getRangesAsString(Status)
[ "Returns", "the", "requested", "range", "list", "as", "comma", "separated", "string", "." ]
ac9046355851136994388442b01ba4063305f9c4
https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-lib/src/main/java/it/jnrpe/utils/thresholds/Threshold.java#L206-L233
142,220
ops4j/org.ops4j.pax.swissbox
pax-swissbox-core/src/main/java/org/ops4j/pax/swissbox/core/BundleClassLoader.java
BundleClassLoader.newPriviledged
public static BundleClassLoader newPriviledged( final Bundle bundle, final ClassLoader parent ) { return AccessController.doPrivileged( new PrivilegedAction<BundleClassLoader>() { public BundleClassLoader run() { return new BundleClassLoader( bundle, parent ); } } ); }
java
public static BundleClassLoader newPriviledged( final Bundle bundle, final ClassLoader parent ) { return AccessController.doPrivileged( new PrivilegedAction<BundleClassLoader>() { public BundleClassLoader run() { return new BundleClassLoader( bundle, parent ); } } ); }
[ "public", "static", "BundleClassLoader", "newPriviledged", "(", "final", "Bundle", "bundle", ",", "final", "ClassLoader", "parent", ")", "{", "return", "AccessController", ".", "doPrivileged", "(", "new", "PrivilegedAction", "<", "BundleClassLoader", ">", "(", ")", "{", "public", "BundleClassLoader", "run", "(", ")", "{", "return", "new", "BundleClassLoader", "(", "bundle", ",", "parent", ")", ";", "}", "}", ")", ";", "}" ]
Privileged factory method. @param bundle bundle to be used for class loading. Cannot be null. @param parent parent class loader @return created bundle class loader @see BundleClassLoader#BundleClassLoader(Bundle,ClassLoader)
[ "Privileged", "factory", "method", "." ]
00b0ee16cdbe8017984a4d7ba808b10d985c5b5c
https://github.com/ops4j/org.ops4j.pax.swissbox/blob/00b0ee16cdbe8017984a4d7ba808b10d985c5b5c/pax-swissbox-core/src/main/java/org/ops4j/pax/swissbox/core/BundleClassLoader.java#L85-L94
142,221
ops4j/org.ops4j.pax.swissbox
pax-swissbox-core/src/main/java/org/ops4j/pax/swissbox/core/BundleClassLoader.java
BundleClassLoader.findResources
@Override @SuppressWarnings("unchecked") protected Enumeration<URL> findResources( final String name ) throws IOException { Enumeration<URL> resources = m_bundle.getResources( name ); // Bundle.getResources may return null, in such case return empty enumeration if( resources == null ) { return EMPTY_URL_ENUMERATION; } else { return resources; } }
java
@Override @SuppressWarnings("unchecked") protected Enumeration<URL> findResources( final String name ) throws IOException { Enumeration<URL> resources = m_bundle.getResources( name ); // Bundle.getResources may return null, in such case return empty enumeration if( resources == null ) { return EMPTY_URL_ENUMERATION; } else { return resources; } }
[ "@", "Override", "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "protected", "Enumeration", "<", "URL", ">", "findResources", "(", "final", "String", "name", ")", "throws", "IOException", "{", "Enumeration", "<", "URL", ">", "resources", "=", "m_bundle", ".", "getResources", "(", "name", ")", ";", "// Bundle.getResources may return null, in such case return empty enumeration", "if", "(", "resources", "==", "null", ")", "{", "return", "EMPTY_URL_ENUMERATION", ";", "}", "else", "{", "return", "resources", ";", "}", "}" ]
Use bundle to find resources. @see ClassLoader#findResources(String)
[ "Use", "bundle", "to", "find", "resources", "." ]
00b0ee16cdbe8017984a4d7ba808b10d985c5b5c
https://github.com/ops4j/org.ops4j.pax.swissbox/blob/00b0ee16cdbe8017984a4d7ba808b10d985c5b5c/pax-swissbox-core/src/main/java/org/ops4j/pax/swissbox/core/BundleClassLoader.java#L218-L233
142,222
petergeneric/stdlib
stdlib/src/main/java/com/peterphi/std/threading/ParamInvokeable.java
ParamInvokeable.call
public final void call(T param) { if (!run) { run = true; prepared = true; try { this.run(param); } catch (Throwable t) { log.error("[ParamInvokeable] {prepare} : " + t.getMessage(), t); } } }
java
public final void call(T param) { if (!run) { run = true; prepared = true; try { this.run(param); } catch (Throwable t) { log.error("[ParamInvokeable] {prepare} : " + t.getMessage(), t); } } }
[ "public", "final", "void", "call", "(", "T", "param", ")", "{", "if", "(", "!", "run", ")", "{", "run", "=", "true", ";", "prepared", "=", "true", ";", "try", "{", "this", ".", "run", "(", "param", ")", ";", "}", "catch", "(", "Throwable", "t", ")", "{", "log", ".", "error", "(", "\"[ParamInvokeable] {prepare} : \"", "+", "t", ".", "getMessage", "(", ")", ",", "t", ")", ";", "}", "}", "}" ]
Synchronously executes this Invokeable @param param
[ "Synchronously", "executes", "this", "Invokeable" ]
d4025d2f881bc0542b1e004c5f65a1ccaf895836
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/stdlib/src/main/java/com/peterphi/std/threading/ParamInvokeable.java#L47-L63
142,223
petergeneric/stdlib
guice/common/src/main/java/com/peterphi/std/guice/common/daemon/GuiceDaemonRegistry.java
GuiceDaemonRegistry.getRecurring
public synchronized List<GuiceRecurringDaemon> getRecurring() { return daemons.stream() .filter(d -> d instanceof GuiceRecurringDaemon) .map(d -> (GuiceRecurringDaemon) d) .sorted(Comparator.comparing(GuiceDaemon::getName)) .collect(Collectors.toList()); }
java
public synchronized List<GuiceRecurringDaemon> getRecurring() { return daemons.stream() .filter(d -> d instanceof GuiceRecurringDaemon) .map(d -> (GuiceRecurringDaemon) d) .sorted(Comparator.comparing(GuiceDaemon::getName)) .collect(Collectors.toList()); }
[ "public", "synchronized", "List", "<", "GuiceRecurringDaemon", ">", "getRecurring", "(", ")", "{", "return", "daemons", ".", "stream", "(", ")", ".", "filter", "(", "d", "->", "d", "instanceof", "GuiceRecurringDaemon", ")", ".", "map", "(", "d", "->", "(", "GuiceRecurringDaemon", ")", "d", ")", ".", "sorted", "(", "Comparator", ".", "comparing", "(", "GuiceDaemon", "::", "getName", ")", ")", ".", "collect", "(", "Collectors", ".", "toList", "(", ")", ")", ";", "}" ]
Return a list of all @return
[ "Return", "a", "list", "of", "all" ]
d4025d2f881bc0542b1e004c5f65a1ccaf895836
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/guice/common/src/main/java/com/peterphi/std/guice/common/daemon/GuiceDaemonRegistry.java#L48-L55
142,224
petergeneric/stdlib
stdlib/src/main/java/com/peterphi/std/util/HexHelper.java
HexHelper.fromHex
public static final byte[] fromHex(final String value) { if (value.length() == 0) return new byte[0]; else if (value.indexOf(':') != -1) return fromHex(':', value); else if (value.length() % 2 != 0) throw new IllegalArgumentException("Invalid hex specified: uneven number of digits passed for byte[] conversion"); final byte[] buffer = new byte[value.length() / 2]; // i tracks input position, j tracks output position int j = 0; for (int i = 0; i < buffer.length; i++) { buffer[i] = (byte) Integer.parseInt(value.substring(j, j + 2), 16); j += 2; } return buffer; }
java
public static final byte[] fromHex(final String value) { if (value.length() == 0) return new byte[0]; else if (value.indexOf(':') != -1) return fromHex(':', value); else if (value.length() % 2 != 0) throw new IllegalArgumentException("Invalid hex specified: uneven number of digits passed for byte[] conversion"); final byte[] buffer = new byte[value.length() / 2]; // i tracks input position, j tracks output position int j = 0; for (int i = 0; i < buffer.length; i++) { buffer[i] = (byte) Integer.parseInt(value.substring(j, j + 2), 16); j += 2; } return buffer; }
[ "public", "static", "final", "byte", "[", "]", "fromHex", "(", "final", "String", "value", ")", "{", "if", "(", "value", ".", "length", "(", ")", "==", "0", ")", "return", "new", "byte", "[", "0", "]", ";", "else", "if", "(", "value", ".", "indexOf", "(", "'", "'", ")", "!=", "-", "1", ")", "return", "fromHex", "(", "'", "'", ",", "value", ")", ";", "else", "if", "(", "value", ".", "length", "(", ")", "%", "2", "!=", "0", ")", "throw", "new", "IllegalArgumentException", "(", "\"Invalid hex specified: uneven number of digits passed for byte[] conversion\"", ")", ";", "final", "byte", "[", "]", "buffer", "=", "new", "byte", "[", "value", ".", "length", "(", ")", "/", "2", "]", ";", "// i tracks input position, j tracks output position", "int", "j", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "buffer", ".", "length", ";", "i", "++", ")", "{", "buffer", "[", "i", "]", "=", "(", "byte", ")", "Integer", ".", "parseInt", "(", "value", ".", "substring", "(", "j", ",", "j", "+", "2", ")", ",", "16", ")", ";", "j", "+=", "2", ";", "}", "return", "buffer", ";", "}" ]
Decodes a hexidecimal string into a series of bytes @param value @return
[ "Decodes", "a", "hexidecimal", "string", "into", "a", "series", "of", "bytes" ]
d4025d2f881bc0542b1e004c5f65a1ccaf895836
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/stdlib/src/main/java/com/peterphi/std/util/HexHelper.java#L24-L44
142,225
ziccardi/jnrpe
jnrpe-plugins/src/main/java/it/jnrpe/plugin/CheckHttp.java
CheckHttp.getHttpResponse
private String getHttpResponse(final ICommandLine cl, final String hostname, final String port, final String method, final String path, final int timeout, final boolean ssl, final List<Metric> metrics) throws MetricGatheringException { Properties props = null; try { props = getRequestProperties(cl, method); } catch (UnsupportedEncodingException e) { throw new MetricGatheringException("Error occurred: " + e.getMessage(), Status.CRITICAL, e); } String response = null; String redirect = cl.getOptionValue("onredirect"); boolean ignoreBody = false; try { String data = null; if ("POST".equals(method)) { data = getPostData(cl); } if (cl.hasOption("no-body")) { ignoreBody = true; } String urlString = hostname + ":" + port + path; if (cl.hasOption("authorization")) { urlString = cl.getOptionValue("authorization") + "@" + urlString; } else if (cl.hasOption("proxy-authorization")) { urlString = cl.getOptionValue("proxy-authorization") + "@" + urlString; } if (ssl) { urlString = "https://" + urlString; } else { urlString = "http://" + urlString; } URL url = new URL(urlString); if (cl.getOptionValue("certificate") != null) { checkCertificateExpiryDate(url, metrics); } else if (redirect != null) { response = checkRedirectResponse(url, method, timeout, props, data, redirect, ignoreBody, metrics); } else { try { if ("GET".equals(method)) { response = HttpUtils.doGET(url, props, timeout, true, ignoreBody); } else if ("POST".equals(method)) { response = HttpUtils.doPOST(url, props, null, data, true, ignoreBody); } else if ("HEAD".equals(method)) { response = HttpUtils.doHEAD(url, props, timeout, true, ignoreBody); } // @TODO complete for other http methods } catch (MalformedURLException e) { LOG.error(getContext(), "Bad url", e); throw new MetricGatheringException("Bad url string : " + urlString, Status.CRITICAL, e); } } } catch (Exception e) { LOG.error(getContext(), "Exception: " + e.getMessage(), e); throw new MetricGatheringException(e.getClass().getName() + ": " + e.getMessage(), Status.CRITICAL, e); } return response; }
java
private String getHttpResponse(final ICommandLine cl, final String hostname, final String port, final String method, final String path, final int timeout, final boolean ssl, final List<Metric> metrics) throws MetricGatheringException { Properties props = null; try { props = getRequestProperties(cl, method); } catch (UnsupportedEncodingException e) { throw new MetricGatheringException("Error occurred: " + e.getMessage(), Status.CRITICAL, e); } String response = null; String redirect = cl.getOptionValue("onredirect"); boolean ignoreBody = false; try { String data = null; if ("POST".equals(method)) { data = getPostData(cl); } if (cl.hasOption("no-body")) { ignoreBody = true; } String urlString = hostname + ":" + port + path; if (cl.hasOption("authorization")) { urlString = cl.getOptionValue("authorization") + "@" + urlString; } else if (cl.hasOption("proxy-authorization")) { urlString = cl.getOptionValue("proxy-authorization") + "@" + urlString; } if (ssl) { urlString = "https://" + urlString; } else { urlString = "http://" + urlString; } URL url = new URL(urlString); if (cl.getOptionValue("certificate") != null) { checkCertificateExpiryDate(url, metrics); } else if (redirect != null) { response = checkRedirectResponse(url, method, timeout, props, data, redirect, ignoreBody, metrics); } else { try { if ("GET".equals(method)) { response = HttpUtils.doGET(url, props, timeout, true, ignoreBody); } else if ("POST".equals(method)) { response = HttpUtils.doPOST(url, props, null, data, true, ignoreBody); } else if ("HEAD".equals(method)) { response = HttpUtils.doHEAD(url, props, timeout, true, ignoreBody); } // @TODO complete for other http methods } catch (MalformedURLException e) { LOG.error(getContext(), "Bad url", e); throw new MetricGatheringException("Bad url string : " + urlString, Status.CRITICAL, e); } } } catch (Exception e) { LOG.error(getContext(), "Exception: " + e.getMessage(), e); throw new MetricGatheringException(e.getClass().getName() + ": " + e.getMessage(), Status.CRITICAL, e); } return response; }
[ "private", "String", "getHttpResponse", "(", "final", "ICommandLine", "cl", ",", "final", "String", "hostname", ",", "final", "String", "port", ",", "final", "String", "method", ",", "final", "String", "path", ",", "final", "int", "timeout", ",", "final", "boolean", "ssl", ",", "final", "List", "<", "Metric", ">", "metrics", ")", "throws", "MetricGatheringException", "{", "Properties", "props", "=", "null", ";", "try", "{", "props", "=", "getRequestProperties", "(", "cl", ",", "method", ")", ";", "}", "catch", "(", "UnsupportedEncodingException", "e", ")", "{", "throw", "new", "MetricGatheringException", "(", "\"Error occurred: \"", "+", "e", ".", "getMessage", "(", ")", ",", "Status", ".", "CRITICAL", ",", "e", ")", ";", "}", "String", "response", "=", "null", ";", "String", "redirect", "=", "cl", ".", "getOptionValue", "(", "\"onredirect\"", ")", ";", "boolean", "ignoreBody", "=", "false", ";", "try", "{", "String", "data", "=", "null", ";", "if", "(", "\"POST\"", ".", "equals", "(", "method", ")", ")", "{", "data", "=", "getPostData", "(", "cl", ")", ";", "}", "if", "(", "cl", ".", "hasOption", "(", "\"no-body\"", ")", ")", "{", "ignoreBody", "=", "true", ";", "}", "String", "urlString", "=", "hostname", "+", "\":\"", "+", "port", "+", "path", ";", "if", "(", "cl", ".", "hasOption", "(", "\"authorization\"", ")", ")", "{", "urlString", "=", "cl", ".", "getOptionValue", "(", "\"authorization\"", ")", "+", "\"@\"", "+", "urlString", ";", "}", "else", "if", "(", "cl", ".", "hasOption", "(", "\"proxy-authorization\"", ")", ")", "{", "urlString", "=", "cl", ".", "getOptionValue", "(", "\"proxy-authorization\"", ")", "+", "\"@\"", "+", "urlString", ";", "}", "if", "(", "ssl", ")", "{", "urlString", "=", "\"https://\"", "+", "urlString", ";", "}", "else", "{", "urlString", "=", "\"http://\"", "+", "urlString", ";", "}", "URL", "url", "=", "new", "URL", "(", "urlString", ")", ";", "if", "(", "cl", ".", "getOptionValue", "(", "\"certificate\"", ")", "!=", "null", ")", "{", "checkCertificateExpiryDate", "(", "url", ",", "metrics", ")", ";", "}", "else", "if", "(", "redirect", "!=", "null", ")", "{", "response", "=", "checkRedirectResponse", "(", "url", ",", "method", ",", "timeout", ",", "props", ",", "data", ",", "redirect", ",", "ignoreBody", ",", "metrics", ")", ";", "}", "else", "{", "try", "{", "if", "(", "\"GET\"", ".", "equals", "(", "method", ")", ")", "{", "response", "=", "HttpUtils", ".", "doGET", "(", "url", ",", "props", ",", "timeout", ",", "true", ",", "ignoreBody", ")", ";", "}", "else", "if", "(", "\"POST\"", ".", "equals", "(", "method", ")", ")", "{", "response", "=", "HttpUtils", ".", "doPOST", "(", "url", ",", "props", ",", "null", ",", "data", ",", "true", ",", "ignoreBody", ")", ";", "}", "else", "if", "(", "\"HEAD\"", ".", "equals", "(", "method", ")", ")", "{", "response", "=", "HttpUtils", ".", "doHEAD", "(", "url", ",", "props", ",", "timeout", ",", "true", ",", "ignoreBody", ")", ";", "}", "// @TODO complete for other http methods", "}", "catch", "(", "MalformedURLException", "e", ")", "{", "LOG", ".", "error", "(", "getContext", "(", ")", ",", "\"Bad url\"", ",", "e", ")", ";", "throw", "new", "MetricGatheringException", "(", "\"Bad url string : \"", "+", "urlString", ",", "Status", ".", "CRITICAL", ",", "e", ")", ";", "}", "}", "}", "catch", "(", "Exception", "e", ")", "{", "LOG", ".", "error", "(", "getContext", "(", ")", ",", "\"Exception: \"", "+", "e", ".", "getMessage", "(", ")", ",", "e", ")", ";", "throw", "new", "MetricGatheringException", "(", "e", ".", "getClass", "(", ")", ".", "getName", "(", ")", "+", "\": \"", "+", "e", ".", "getMessage", "(", ")", ",", "Status", ".", "CRITICAL", ",", "e", ")", ";", "}", "return", "response", ";", "}" ]
Do the actual http request and return the response string. @param cl - The received command line @param hostname - The server hostname @param port - The server port @param method - The HTTP method @param path - The connection path @param timeout - The timeout @param ssl - if SSL must be used @param metrics - This list will be filled with the gathered metrics @return - the response @throws MetricGatheringException - if an error occurs during the execution
[ "Do", "the", "actual", "http", "request", "and", "return", "the", "response", "string", "." ]
ac9046355851136994388442b01ba4063305f9c4
https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-plugins/src/main/java/it/jnrpe/plugin/CheckHttp.java#L224-L282
142,226
ziccardi/jnrpe
jnrpe-plugins/src/main/java/it/jnrpe/plugin/CheckHttp.java
CheckHttp.checkRedirectResponse
private String checkRedirectResponse(final URL url, final String method, final Integer timeout, final Properties props, final String postData, final String redirect, final boolean ignoreBody, final List<Metric> metrics) throws Exception { // @todo handle sticky/port and follow param options String response = null; HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod(method); HttpUtils.setRequestProperties(props, conn, timeout); String initialUrl = String.valueOf(conn.getURL()); String redirectedUrl = null; if ("POST".equals(method)) { HttpUtils.sendPostData(conn, postData); } response = HttpUtils.parseHttpResponse(conn, false, ignoreBody); redirectedUrl = String.valueOf(conn.getURL()); if (!redirectedUrl.equals(initialUrl)) { Metric metric = new Metric("onredirect", "", new BigDecimal(1), null, null); metrics.add(metric); } return response; }
java
private String checkRedirectResponse(final URL url, final String method, final Integer timeout, final Properties props, final String postData, final String redirect, final boolean ignoreBody, final List<Metric> metrics) throws Exception { // @todo handle sticky/port and follow param options String response = null; HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod(method); HttpUtils.setRequestProperties(props, conn, timeout); String initialUrl = String.valueOf(conn.getURL()); String redirectedUrl = null; if ("POST".equals(method)) { HttpUtils.sendPostData(conn, postData); } response = HttpUtils.parseHttpResponse(conn, false, ignoreBody); redirectedUrl = String.valueOf(conn.getURL()); if (!redirectedUrl.equals(initialUrl)) { Metric metric = new Metric("onredirect", "", new BigDecimal(1), null, null); metrics.add(metric); } return response; }
[ "private", "String", "checkRedirectResponse", "(", "final", "URL", "url", ",", "final", "String", "method", ",", "final", "Integer", "timeout", ",", "final", "Properties", "props", ",", "final", "String", "postData", ",", "final", "String", "redirect", ",", "final", "boolean", "ignoreBody", ",", "final", "List", "<", "Metric", ">", "metrics", ")", "throws", "Exception", "{", "// @todo handle sticky/port and follow param options", "String", "response", "=", "null", ";", "HttpURLConnection", "conn", "=", "(", "HttpURLConnection", ")", "url", ".", "openConnection", "(", ")", ";", "conn", ".", "setRequestMethod", "(", "method", ")", ";", "HttpUtils", ".", "setRequestProperties", "(", "props", ",", "conn", ",", "timeout", ")", ";", "String", "initialUrl", "=", "String", ".", "valueOf", "(", "conn", ".", "getURL", "(", ")", ")", ";", "String", "redirectedUrl", "=", "null", ";", "if", "(", "\"POST\"", ".", "equals", "(", "method", ")", ")", "{", "HttpUtils", ".", "sendPostData", "(", "conn", ",", "postData", ")", ";", "}", "response", "=", "HttpUtils", ".", "parseHttpResponse", "(", "conn", ",", "false", ",", "ignoreBody", ")", ";", "redirectedUrl", "=", "String", ".", "valueOf", "(", "conn", ".", "getURL", "(", ")", ")", ";", "if", "(", "!", "redirectedUrl", ".", "equals", "(", "initialUrl", ")", ")", "{", "Metric", "metric", "=", "new", "Metric", "(", "\"onredirect\"", ",", "\"\"", ",", "new", "BigDecimal", "(", "1", ")", ",", "null", ",", "null", ")", ";", "metrics", ".", "add", "(", "metric", ")", ";", "}", "return", "response", ";", "}" ]
Apply the logic to check for url redirects. @param url - The server URL @param method - The HTTP method @param timeout - The timeout @param props - @param postData - @param redirect - @param ignoreBody - @param metrics - This list will be filled with the gathered metrics @return String @throws Exception -
[ "Apply", "the", "logic", "to", "check", "for", "url", "redirects", "." ]
ac9046355851136994388442b01ba4063305f9c4
https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-plugins/src/main/java/it/jnrpe/plugin/CheckHttp.java#L307-L328
142,227
ziccardi/jnrpe
jnrpe-plugins/src/main/java/it/jnrpe/plugin/CheckHttp.java
CheckHttp.analyzeResponse
private List<Metric> analyzeResponse(final ICommandLine opt, final String response, final int elapsed) throws MetricGatheringException { List<Metric> metrics = new ArrayList<Metric>(); metrics.add(new Metric("time", "", new BigDecimal(elapsed), null, null)); if (!opt.hasOption("certificate")) { if (opt.hasOption("string")) { boolean found = false; String string = opt.getOptionValue("string"); found = response.contains(string); metrics.add(new Metric("string", "", new BigDecimal(Utils.getIntValue(found)), null, null)); } if (opt.hasOption("expect")) { int count = 0; String[] values = opt.getOptionValue("expect").split(","); for (String value : values) { if (response.contains(value)) { count++; } } metrics.add(new Metric("expect", String.valueOf(count) + " times. ", new BigDecimal(count), null, null)); } if (opt.hasOption("regex")) { String regex = opt.getOptionValue("regex"); Pattern p = null; int flags = 0; if (opt.hasOption("eregi")) { flags = Pattern.CASE_INSENSITIVE; } if (opt.hasOption("linespan")) { flags = flags | Pattern.MULTILINE; } p = Pattern.compile(regex, flags); boolean found = p.matcher(response).find(); if (opt.hasOption("invert-regex")) { metrics.add(new Metric("invert-regex", String.valueOf(found), new BigDecimal(Utils.getIntValue(found)), null, null)); } else { metrics.add(new Metric("regex", String.valueOf(found), new BigDecimal(Utils.getIntValue(found)), null, null)); } } } return metrics; }
java
private List<Metric> analyzeResponse(final ICommandLine opt, final String response, final int elapsed) throws MetricGatheringException { List<Metric> metrics = new ArrayList<Metric>(); metrics.add(new Metric("time", "", new BigDecimal(elapsed), null, null)); if (!opt.hasOption("certificate")) { if (opt.hasOption("string")) { boolean found = false; String string = opt.getOptionValue("string"); found = response.contains(string); metrics.add(new Metric("string", "", new BigDecimal(Utils.getIntValue(found)), null, null)); } if (opt.hasOption("expect")) { int count = 0; String[] values = opt.getOptionValue("expect").split(","); for (String value : values) { if (response.contains(value)) { count++; } } metrics.add(new Metric("expect", String.valueOf(count) + " times. ", new BigDecimal(count), null, null)); } if (opt.hasOption("regex")) { String regex = opt.getOptionValue("regex"); Pattern p = null; int flags = 0; if (opt.hasOption("eregi")) { flags = Pattern.CASE_INSENSITIVE; } if (opt.hasOption("linespan")) { flags = flags | Pattern.MULTILINE; } p = Pattern.compile(regex, flags); boolean found = p.matcher(response).find(); if (opt.hasOption("invert-regex")) { metrics.add(new Metric("invert-regex", String.valueOf(found), new BigDecimal(Utils.getIntValue(found)), null, null)); } else { metrics.add(new Metric("regex", String.valueOf(found), new BigDecimal(Utils.getIntValue(found)), null, null)); } } } return metrics; }
[ "private", "List", "<", "Metric", ">", "analyzeResponse", "(", "final", "ICommandLine", "opt", ",", "final", "String", "response", ",", "final", "int", "elapsed", ")", "throws", "MetricGatheringException", "{", "List", "<", "Metric", ">", "metrics", "=", "new", "ArrayList", "<", "Metric", ">", "(", ")", ";", "metrics", ".", "add", "(", "new", "Metric", "(", "\"time\"", ",", "\"\"", ",", "new", "BigDecimal", "(", "elapsed", ")", ",", "null", ",", "null", ")", ")", ";", "if", "(", "!", "opt", ".", "hasOption", "(", "\"certificate\"", ")", ")", "{", "if", "(", "opt", ".", "hasOption", "(", "\"string\"", ")", ")", "{", "boolean", "found", "=", "false", ";", "String", "string", "=", "opt", ".", "getOptionValue", "(", "\"string\"", ")", ";", "found", "=", "response", ".", "contains", "(", "string", ")", ";", "metrics", ".", "add", "(", "new", "Metric", "(", "\"string\"", ",", "\"\"", ",", "new", "BigDecimal", "(", "Utils", ".", "getIntValue", "(", "found", ")", ")", ",", "null", ",", "null", ")", ")", ";", "}", "if", "(", "opt", ".", "hasOption", "(", "\"expect\"", ")", ")", "{", "int", "count", "=", "0", ";", "String", "[", "]", "values", "=", "opt", ".", "getOptionValue", "(", "\"expect\"", ")", ".", "split", "(", "\",\"", ")", ";", "for", "(", "String", "value", ":", "values", ")", "{", "if", "(", "response", ".", "contains", "(", "value", ")", ")", "{", "count", "++", ";", "}", "}", "metrics", ".", "add", "(", "new", "Metric", "(", "\"expect\"", ",", "String", ".", "valueOf", "(", "count", ")", "+", "\" times. \"", ",", "new", "BigDecimal", "(", "count", ")", ",", "null", ",", "null", ")", ")", ";", "}", "if", "(", "opt", ".", "hasOption", "(", "\"regex\"", ")", ")", "{", "String", "regex", "=", "opt", ".", "getOptionValue", "(", "\"regex\"", ")", ";", "Pattern", "p", "=", "null", ";", "int", "flags", "=", "0", ";", "if", "(", "opt", ".", "hasOption", "(", "\"eregi\"", ")", ")", "{", "flags", "=", "Pattern", ".", "CASE_INSENSITIVE", ";", "}", "if", "(", "opt", ".", "hasOption", "(", "\"linespan\"", ")", ")", "{", "flags", "=", "flags", "|", "Pattern", ".", "MULTILINE", ";", "}", "p", "=", "Pattern", ".", "compile", "(", "regex", ",", "flags", ")", ";", "boolean", "found", "=", "p", ".", "matcher", "(", "response", ")", ".", "find", "(", ")", ";", "if", "(", "opt", ".", "hasOption", "(", "\"invert-regex\"", ")", ")", "{", "metrics", ".", "add", "(", "new", "Metric", "(", "\"invert-regex\"", ",", "String", ".", "valueOf", "(", "found", ")", ",", "new", "BigDecimal", "(", "Utils", ".", "getIntValue", "(", "found", ")", ")", ",", "null", ",", "null", ")", ")", ";", "}", "else", "{", "metrics", ".", "add", "(", "new", "Metric", "(", "\"regex\"", ",", "String", ".", "valueOf", "(", "found", ")", ",", "new", "BigDecimal", "(", "Utils", ".", "getIntValue", "(", "found", ")", ")", ",", "null", ",", "null", ")", ")", ";", "}", "}", "}", "return", "metrics", ";", "}" ]
Apply logic to the http response and build metrics. @param opt - @param response - @param elapsed - @return - The metrics @throws MetricGatheringException List<Metric>
[ "Apply", "logic", "to", "the", "http", "response", "and", "build", "metrics", "." ]
ac9046355851136994388442b01ba4063305f9c4
https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-plugins/src/main/java/it/jnrpe/plugin/CheckHttp.java#L343-L384
142,228
ziccardi/jnrpe
jnrpe-plugins/src/main/java/it/jnrpe/plugin/CheckHttp.java
CheckHttp.getRequestProperties
private Properties getRequestProperties(final ICommandLine cl, final String method) throws UnsupportedEncodingException { Properties props = new Properties(); if (cl.hasOption("useragent")) { props.setProperty("User-Agent", cl.getOptionValue("useragent")); } else { props.setProperty("User-Agent", DEFAULT_USER_AGENT); } if (cl.hasOption("content-type") && "POST".equalsIgnoreCase(method)) { props.setProperty("Content-Type", cl.getOptionValue("content-type")); } if (cl.hasOption("header")) { List headers = cl.getOptionValues("header"); for (Object obj : headers) { String header = (String) obj; String key = header.split(":")[0].trim(); String value = header.split(":")[1].trim(); props.setProperty(key, value); } } String auth = null; String encoded = null; if (cl.hasOption("authorization")) { encoded = Base64.encodeBase64String(cl.getOptionValue("authorization").getBytes(CHARSET)); auth = "Authorization"; } else if (cl.hasOption("proxy-authorization")) { encoded = Base64.encodeBase64String(cl.getOptionValue("proxy-authorization").getBytes(CHARSET)); auth = "Proxy-Authorization"; } if (auth != null && encoded != null) { props.setProperty(auth, "Basic " + encoded); } return props; }
java
private Properties getRequestProperties(final ICommandLine cl, final String method) throws UnsupportedEncodingException { Properties props = new Properties(); if (cl.hasOption("useragent")) { props.setProperty("User-Agent", cl.getOptionValue("useragent")); } else { props.setProperty("User-Agent", DEFAULT_USER_AGENT); } if (cl.hasOption("content-type") && "POST".equalsIgnoreCase(method)) { props.setProperty("Content-Type", cl.getOptionValue("content-type")); } if (cl.hasOption("header")) { List headers = cl.getOptionValues("header"); for (Object obj : headers) { String header = (String) obj; String key = header.split(":")[0].trim(); String value = header.split(":")[1].trim(); props.setProperty(key, value); } } String auth = null; String encoded = null; if (cl.hasOption("authorization")) { encoded = Base64.encodeBase64String(cl.getOptionValue("authorization").getBytes(CHARSET)); auth = "Authorization"; } else if (cl.hasOption("proxy-authorization")) { encoded = Base64.encodeBase64String(cl.getOptionValue("proxy-authorization").getBytes(CHARSET)); auth = "Proxy-Authorization"; } if (auth != null && encoded != null) { props.setProperty(auth, "Basic " + encoded); } return props; }
[ "private", "Properties", "getRequestProperties", "(", "final", "ICommandLine", "cl", ",", "final", "String", "method", ")", "throws", "UnsupportedEncodingException", "{", "Properties", "props", "=", "new", "Properties", "(", ")", ";", "if", "(", "cl", ".", "hasOption", "(", "\"useragent\"", ")", ")", "{", "props", ".", "setProperty", "(", "\"User-Agent\"", ",", "cl", ".", "getOptionValue", "(", "\"useragent\"", ")", ")", ";", "}", "else", "{", "props", ".", "setProperty", "(", "\"User-Agent\"", ",", "DEFAULT_USER_AGENT", ")", ";", "}", "if", "(", "cl", ".", "hasOption", "(", "\"content-type\"", ")", "&&", "\"POST\"", ".", "equalsIgnoreCase", "(", "method", ")", ")", "{", "props", ".", "setProperty", "(", "\"Content-Type\"", ",", "cl", ".", "getOptionValue", "(", "\"content-type\"", ")", ")", ";", "}", "if", "(", "cl", ".", "hasOption", "(", "\"header\"", ")", ")", "{", "List", "headers", "=", "cl", ".", "getOptionValues", "(", "\"header\"", ")", ";", "for", "(", "Object", "obj", ":", "headers", ")", "{", "String", "header", "=", "(", "String", ")", "obj", ";", "String", "key", "=", "header", ".", "split", "(", "\":\"", ")", "[", "0", "]", ".", "trim", "(", ")", ";", "String", "value", "=", "header", ".", "split", "(", "\":\"", ")", "[", "1", "]", ".", "trim", "(", ")", ";", "props", ".", "setProperty", "(", "key", ",", "value", ")", ";", "}", "}", "String", "auth", "=", "null", ";", "String", "encoded", "=", "null", ";", "if", "(", "cl", ".", "hasOption", "(", "\"authorization\"", ")", ")", "{", "encoded", "=", "Base64", ".", "encodeBase64String", "(", "cl", ".", "getOptionValue", "(", "\"authorization\"", ")", ".", "getBytes", "(", "CHARSET", ")", ")", ";", "auth", "=", "\"Authorization\"", ";", "}", "else", "if", "(", "cl", ".", "hasOption", "(", "\"proxy-authorization\"", ")", ")", "{", "encoded", "=", "Base64", ".", "encodeBase64String", "(", "cl", ".", "getOptionValue", "(", "\"proxy-authorization\"", ")", ".", "getBytes", "(", "CHARSET", ")", ")", ";", "auth", "=", "\"Proxy-Authorization\"", ";", "}", "if", "(", "auth", "!=", "null", "&&", "encoded", "!=", "null", ")", "{", "props", ".", "setProperty", "(", "auth", ",", "\"Basic \"", "+", "encoded", ")", ";", "}", "return", "props", ";", "}" ]
Set the http request properties and headers. @param cl The received command line @param method The HTTP method @return Properties @throws UnsupportedEncodingException
[ "Set", "the", "http", "request", "properties", "and", "headers", "." ]
ac9046355851136994388442b01ba4063305f9c4
https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-plugins/src/main/java/it/jnrpe/plugin/CheckHttp.java#L396-L428
142,229
ziccardi/jnrpe
jnrpe-plugins/src/main/java/it/jnrpe/plugin/CheckHttp.java
CheckHttp.getPostData
private String getPostData(final ICommandLine cl) throws Exception { // String encoded = ""; StringBuilder encoded = new StringBuilder(); String data = cl.getOptionValue("post"); if (data == null) { return null; } String[] values = data.split("&"); for (String value : values) { String[] splitted = value.split("="); String key = splitted[0]; String val = ""; if (splitted.length > 1) { val = splitted[1]; } if (encoded.length() != 0) { encoded.append('&'); } encoded.append(key).append('=').append(URLEncoder.encode(val, "UTF-8")); // encoded += key + "=" + URLEncoder.encode(val, "UTF-8") + "&"; } // if (encoded.endsWith("&")) { // StringUtils.removeEnd(encoded, "&"); // } return encoded.toString(); }
java
private String getPostData(final ICommandLine cl) throws Exception { // String encoded = ""; StringBuilder encoded = new StringBuilder(); String data = cl.getOptionValue("post"); if (data == null) { return null; } String[] values = data.split("&"); for (String value : values) { String[] splitted = value.split("="); String key = splitted[0]; String val = ""; if (splitted.length > 1) { val = splitted[1]; } if (encoded.length() != 0) { encoded.append('&'); } encoded.append(key).append('=').append(URLEncoder.encode(val, "UTF-8")); // encoded += key + "=" + URLEncoder.encode(val, "UTF-8") + "&"; } // if (encoded.endsWith("&")) { // StringUtils.removeEnd(encoded, "&"); // } return encoded.toString(); }
[ "private", "String", "getPostData", "(", "final", "ICommandLine", "cl", ")", "throws", "Exception", "{", "// String encoded = \"\";", "StringBuilder", "encoded", "=", "new", "StringBuilder", "(", ")", ";", "String", "data", "=", "cl", ".", "getOptionValue", "(", "\"post\"", ")", ";", "if", "(", "data", "==", "null", ")", "{", "return", "null", ";", "}", "String", "[", "]", "values", "=", "data", ".", "split", "(", "\"&\"", ")", ";", "for", "(", "String", "value", ":", "values", ")", "{", "String", "[", "]", "splitted", "=", "value", ".", "split", "(", "\"=\"", ")", ";", "String", "key", "=", "splitted", "[", "0", "]", ";", "String", "val", "=", "\"\"", ";", "if", "(", "splitted", ".", "length", ">", "1", ")", "{", "val", "=", "splitted", "[", "1", "]", ";", "}", "if", "(", "encoded", ".", "length", "(", ")", "!=", "0", ")", "{", "encoded", ".", "append", "(", "'", "'", ")", ";", "}", "encoded", ".", "append", "(", "key", ")", ".", "append", "(", "'", "'", ")", ".", "append", "(", "URLEncoder", ".", "encode", "(", "val", ",", "\"UTF-8\"", ")", ")", ";", "// encoded += key + \"=\" + URLEncoder.encode(val, \"UTF-8\") + \"&\";", "}", "// if (encoded.endsWith(\"&\")) {", "// StringUtils.removeEnd(encoded, \"&\");", "// }", "return", "encoded", ".", "toString", "(", ")", ";", "}" ]
Returns encoded post data. @param cl - The received command line @return - The encoded post data @throws Exception -
[ "Returns", "encoded", "post", "data", "." ]
ac9046355851136994388442b01ba4063305f9c4
https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-plugins/src/main/java/it/jnrpe/plugin/CheckHttp.java#L439-L464
142,230
ziccardi/jnrpe
jnrpe-plugins/src/main/java/it/jnrpe/plugin/CheckHttp.java
CheckHttp.checkCertificateExpiryDate
private void checkCertificateExpiryDate(URL url, List<Metric> metrics) throws Exception { SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom()); SSLContext.setDefault(ctx); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setHostnameVerifier(new HostnameVerifier() { public boolean verify(final String arg0, final SSLSession arg1) { return true; } }); List<Date> expiryDates = new ArrayList<Date>(); conn.getResponseCode(); Certificate[] certs = conn.getServerCertificates(); for (Certificate cert : certs) { X509Certificate x509 = (X509Certificate) cert; Date expiry = x509.getNotAfter(); expiryDates.add(expiry); } conn.disconnect(); Date today = new Date(); for (Date date : expiryDates) { int diffInDays = (int) ((date.getTime() - today.getTime()) / (1000 * 60 * 60 * 24)); metrics.add(new Metric("certificate", "", new BigDecimal(diffInDays), null, null)); } }
java
private void checkCertificateExpiryDate(URL url, List<Metric> metrics) throws Exception { SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom()); SSLContext.setDefault(ctx); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setHostnameVerifier(new HostnameVerifier() { public boolean verify(final String arg0, final SSLSession arg1) { return true; } }); List<Date> expiryDates = new ArrayList<Date>(); conn.getResponseCode(); Certificate[] certs = conn.getServerCertificates(); for (Certificate cert : certs) { X509Certificate x509 = (X509Certificate) cert; Date expiry = x509.getNotAfter(); expiryDates.add(expiry); } conn.disconnect(); Date today = new Date(); for (Date date : expiryDates) { int diffInDays = (int) ((date.getTime() - today.getTime()) / (1000 * 60 * 60 * 24)); metrics.add(new Metric("certificate", "", new BigDecimal(diffInDays), null, null)); } }
[ "private", "void", "checkCertificateExpiryDate", "(", "URL", "url", ",", "List", "<", "Metric", ">", "metrics", ")", "throws", "Exception", "{", "SSLContext", "ctx", "=", "SSLContext", ".", "getInstance", "(", "\"TLS\"", ")", ";", "ctx", ".", "init", "(", "new", "KeyManager", "[", "0", "]", ",", "new", "TrustManager", "[", "]", "{", "new", "DefaultTrustManager", "(", ")", "}", ",", "new", "SecureRandom", "(", ")", ")", ";", "SSLContext", ".", "setDefault", "(", "ctx", ")", ";", "HttpsURLConnection", "conn", "=", "(", "HttpsURLConnection", ")", "url", ".", "openConnection", "(", ")", ";", "conn", ".", "setHostnameVerifier", "(", "new", "HostnameVerifier", "(", ")", "{", "public", "boolean", "verify", "(", "final", "String", "arg0", ",", "final", "SSLSession", "arg1", ")", "{", "return", "true", ";", "}", "}", ")", ";", "List", "<", "Date", ">", "expiryDates", "=", "new", "ArrayList", "<", "Date", ">", "(", ")", ";", "conn", ".", "getResponseCode", "(", ")", ";", "Certificate", "[", "]", "certs", "=", "conn", ".", "getServerCertificates", "(", ")", ";", "for", "(", "Certificate", "cert", ":", "certs", ")", "{", "X509Certificate", "x509", "=", "(", "X509Certificate", ")", "cert", ";", "Date", "expiry", "=", "x509", ".", "getNotAfter", "(", ")", ";", "expiryDates", ".", "add", "(", "expiry", ")", ";", "}", "conn", ".", "disconnect", "(", ")", ";", "Date", "today", "=", "new", "Date", "(", ")", ";", "for", "(", "Date", "date", ":", "expiryDates", ")", "{", "int", "diffInDays", "=", "(", "int", ")", "(", "(", "date", ".", "getTime", "(", ")", "-", "today", ".", "getTime", "(", ")", ")", "/", "(", "1000", "*", "60", "*", "60", "*", "24", ")", ")", ";", "metrics", ".", "add", "(", "new", "Metric", "(", "\"certificate\"", ",", "\"\"", ",", "new", "BigDecimal", "(", "diffInDays", ")", ",", "null", ",", "null", ")", ")", ";", "}", "}" ]
stuff for checking certificate
[ "stuff", "for", "checking", "certificate" ]
ac9046355851136994388442b01ba4063305f9c4
https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-plugins/src/main/java/it/jnrpe/plugin/CheckHttp.java#L477-L502
142,231
ziccardi/jnrpe
jnrpe-server/src/main/java/it/jnrpe/server/JNRPEConfigurationFactory.java
JNRPEConfigurationFactory.createConfiguration
public static JNRPEConfiguration createConfiguration(final String configurationFilePath) throws ConfigurationException { JNRPEConfiguration conf = null; if (configurationFilePath.toLowerCase().endsWith(".conf") || configurationFilePath.toLowerCase().endsWith(".ini")) { conf = new IniJNRPEConfiguration(); } else if (configurationFilePath.toLowerCase().endsWith(".xml")) { conf = new XmlJNRPEConfiguration(); } if (conf == null) { throw new ConfigurationException("Config file name must end with either '.ini' " + "(ini file) or '.xml' (xml file). Received file name is : " + new File(configurationFilePath).getName()); } conf.load(new File(configurationFilePath)); return conf; }
java
public static JNRPEConfiguration createConfiguration(final String configurationFilePath) throws ConfigurationException { JNRPEConfiguration conf = null; if (configurationFilePath.toLowerCase().endsWith(".conf") || configurationFilePath.toLowerCase().endsWith(".ini")) { conf = new IniJNRPEConfiguration(); } else if (configurationFilePath.toLowerCase().endsWith(".xml")) { conf = new XmlJNRPEConfiguration(); } if (conf == null) { throw new ConfigurationException("Config file name must end with either '.ini' " + "(ini file) or '.xml' (xml file). Received file name is : " + new File(configurationFilePath).getName()); } conf.load(new File(configurationFilePath)); return conf; }
[ "public", "static", "JNRPEConfiguration", "createConfiguration", "(", "final", "String", "configurationFilePath", ")", "throws", "ConfigurationException", "{", "JNRPEConfiguration", "conf", "=", "null", ";", "if", "(", "configurationFilePath", ".", "toLowerCase", "(", ")", ".", "endsWith", "(", "\".conf\"", ")", "||", "configurationFilePath", ".", "toLowerCase", "(", ")", ".", "endsWith", "(", "\".ini\"", ")", ")", "{", "conf", "=", "new", "IniJNRPEConfiguration", "(", ")", ";", "}", "else", "if", "(", "configurationFilePath", ".", "toLowerCase", "(", ")", ".", "endsWith", "(", "\".xml\"", ")", ")", "{", "conf", "=", "new", "XmlJNRPEConfiguration", "(", ")", ";", "}", "if", "(", "conf", "==", "null", ")", "{", "throw", "new", "ConfigurationException", "(", "\"Config file name must end with either '.ini' \"", "+", "\"(ini file) or '.xml' (xml file). Received file name is : \"", "+", "new", "File", "(", "configurationFilePath", ")", ".", "getName", "(", ")", ")", ";", "}", "conf", ".", "load", "(", "new", "File", "(", "configurationFilePath", ")", ")", ";", "return", "conf", ";", "}" ]
Creates a configuration object from the passed in configuration file. @param configurationFilePath Path to the configuration file @return The configuration object @throws ConfigurationException -
[ "Creates", "a", "configuration", "object", "from", "the", "passed", "in", "configuration", "file", "." ]
ac9046355851136994388442b01ba4063305f9c4
https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-server/src/main/java/it/jnrpe/server/JNRPEConfigurationFactory.java#L43-L60
142,232
ops4j/org.ops4j.pax.swissbox
pax-swissbox-core/src/main/java/org/ops4j/pax/swissbox/core/BundleUtils.java
BundleUtils.getBundleContext
public static BundleContext getBundleContext( final Bundle bundle ) { try { // first try to find the getBundleContext method (OSGi spec >= 4.10) final Method method = Bundle.class.getDeclaredMethod( "getBundleContext" ); if( !method.isAccessible() ) { method.setAccessible( true ); } return (BundleContext) method.invoke( bundle ); } catch( Exception e ) { // then try to find a field in the bundle that looks like a bundle context try { final Field[] fields = bundle.getClass().getDeclaredFields(); for( Field field : fields ) { if( BundleContext.class.isAssignableFrom( field.getType() ) ) { if( !field.isAccessible() ) { field.setAccessible( true ); } return (BundleContext) field.get( bundle ); } } } catch( Exception ignore ) { // ignore } } // well, discovery failed return null; }
java
public static BundleContext getBundleContext( final Bundle bundle ) { try { // first try to find the getBundleContext method (OSGi spec >= 4.10) final Method method = Bundle.class.getDeclaredMethod( "getBundleContext" ); if( !method.isAccessible() ) { method.setAccessible( true ); } return (BundleContext) method.invoke( bundle ); } catch( Exception e ) { // then try to find a field in the bundle that looks like a bundle context try { final Field[] fields = bundle.getClass().getDeclaredFields(); for( Field field : fields ) { if( BundleContext.class.isAssignableFrom( field.getType() ) ) { if( !field.isAccessible() ) { field.setAccessible( true ); } return (BundleContext) field.get( bundle ); } } } catch( Exception ignore ) { // ignore } } // well, discovery failed return null; }
[ "public", "static", "BundleContext", "getBundleContext", "(", "final", "Bundle", "bundle", ")", "{", "try", "{", "// first try to find the getBundleContext method (OSGi spec >= 4.10)", "final", "Method", "method", "=", "Bundle", ".", "class", ".", "getDeclaredMethod", "(", "\"getBundleContext\"", ")", ";", "if", "(", "!", "method", ".", "isAccessible", "(", ")", ")", "{", "method", ".", "setAccessible", "(", "true", ")", ";", "}", "return", "(", "BundleContext", ")", "method", ".", "invoke", "(", "bundle", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "// then try to find a field in the bundle that looks like a bundle context", "try", "{", "final", "Field", "[", "]", "fields", "=", "bundle", ".", "getClass", "(", ")", ".", "getDeclaredFields", "(", ")", ";", "for", "(", "Field", "field", ":", "fields", ")", "{", "if", "(", "BundleContext", ".", "class", ".", "isAssignableFrom", "(", "field", ".", "getType", "(", ")", ")", ")", "{", "if", "(", "!", "field", ".", "isAccessible", "(", ")", ")", "{", "field", ".", "setAccessible", "(", "true", ")", ";", "}", "return", "(", "BundleContext", ")", "field", ".", "get", "(", "bundle", ")", ";", "}", "}", "}", "catch", "(", "Exception", "ignore", ")", "{", "// ignore", "}", "}", "// well, discovery failed", "return", "null", ";", "}" ]
Discovers the bundle context for a bundle. If the bundle is an 4.1.0 or greater bundle it should have a method that just returns the bundle context. Otherwise uses reflection to look for an internal bundle context. @param bundle the bundle from which the bundle context is needed @return corresponding bundle context or null if bundle context cannot be discovered
[ "Discovers", "the", "bundle", "context", "for", "a", "bundle", ".", "If", "the", "bundle", "is", "an", "4", ".", "1", ".", "0", "or", "greater", "bundle", "it", "should", "have", "a", "method", "that", "just", "returns", "the", "bundle", "context", ".", "Otherwise", "uses", "reflection", "to", "look", "for", "an", "internal", "bundle", "context", "." ]
00b0ee16cdbe8017984a4d7ba808b10d985c5b5c
https://github.com/ops4j/org.ops4j.pax.swissbox/blob/00b0ee16cdbe8017984a4d7ba808b10d985c5b5c/pax-swissbox-core/src/main/java/org/ops4j/pax/swissbox/core/BundleUtils.java#L46-L83
142,233
ops4j/org.ops4j.pax.swissbox
pax-swissbox-core/src/main/java/org/ops4j/pax/swissbox/core/BundleUtils.java
BundleUtils.getBundle
public static Bundle getBundle( BundleContext bc, String symbolicName ) { return getBundle( bc, symbolicName, null ); }
java
public static Bundle getBundle( BundleContext bc, String symbolicName ) { return getBundle( bc, symbolicName, null ); }
[ "public", "static", "Bundle", "getBundle", "(", "BundleContext", "bc", ",", "String", "symbolicName", ")", "{", "return", "getBundle", "(", "bc", ",", "symbolicName", ",", "null", ")", ";", "}" ]
Returns any bundle with the given symbolic name, or null if no such bundle exists. If there are multiple bundles with the same symbolic name and different version, this method returns the first bundle found. @param bc bundle context @param symbolicName bundle symbolic name @return matching bundle, or null
[ "Returns", "any", "bundle", "with", "the", "given", "symbolic", "name", "or", "null", "if", "no", "such", "bundle", "exists", ".", "If", "there", "are", "multiple", "bundles", "with", "the", "same", "symbolic", "name", "and", "different", "version", "this", "method", "returns", "the", "first", "bundle", "found", "." ]
00b0ee16cdbe8017984a4d7ba808b10d985c5b5c
https://github.com/ops4j/org.ops4j.pax.swissbox/blob/00b0ee16cdbe8017984a4d7ba808b10d985c5b5c/pax-swissbox-core/src/main/java/org/ops4j/pax/swissbox/core/BundleUtils.java#L94-L97
142,234
ops4j/org.ops4j.pax.swissbox
pax-swissbox-core/src/main/java/org/ops4j/pax/swissbox/core/BundleUtils.java
BundleUtils.getBundles
public static List<Bundle> getBundles( BundleContext bc, String symbolicName ) { List<Bundle> bundles = new ArrayList<Bundle>(); for( Bundle bundle : bc.getBundles() ) { if( bundle.getSymbolicName().equals( symbolicName ) ) { bundles.add( bundle ); } } return bundles; }
java
public static List<Bundle> getBundles( BundleContext bc, String symbolicName ) { List<Bundle> bundles = new ArrayList<Bundle>(); for( Bundle bundle : bc.getBundles() ) { if( bundle.getSymbolicName().equals( symbolicName ) ) { bundles.add( bundle ); } } return bundles; }
[ "public", "static", "List", "<", "Bundle", ">", "getBundles", "(", "BundleContext", "bc", ",", "String", "symbolicName", ")", "{", "List", "<", "Bundle", ">", "bundles", "=", "new", "ArrayList", "<", "Bundle", ">", "(", ")", ";", "for", "(", "Bundle", "bundle", ":", "bc", ".", "getBundles", "(", ")", ")", "{", "if", "(", "bundle", ".", "getSymbolicName", "(", ")", ".", "equals", "(", "symbolicName", ")", ")", "{", "bundles", ".", "add", "(", "bundle", ")", ";", "}", "}", "return", "bundles", ";", "}" ]
Returns a list of all bundles with the given symbolic name. @param bc bundle context @param symbolicName bundle symbolic name @return matching bundles. The list may be empty, but never null.
[ "Returns", "a", "list", "of", "all", "bundles", "with", "the", "given", "symbolic", "name", "." ]
00b0ee16cdbe8017984a4d7ba808b10d985c5b5c
https://github.com/ops4j/org.ops4j.pax.swissbox/blob/00b0ee16cdbe8017984a4d7ba808b10d985c5b5c/pax-swissbox-core/src/main/java/org/ops4j/pax/swissbox/core/BundleUtils.java#L106-L117
142,235
ops4j/org.ops4j.pax.swissbox
pax-swissbox-core/src/main/java/org/ops4j/pax/swissbox/core/BundleUtils.java
BundleUtils.getBundle
public static Bundle getBundle( BundleContext bc, String symbolicName, String version ) { for( Bundle bundle : bc.getBundles() ) { if( bundle.getSymbolicName().equals( symbolicName ) ) { if( version == null || version.equals( bundle.getVersion() ) ) { return bundle; } } } return null; }
java
public static Bundle getBundle( BundleContext bc, String symbolicName, String version ) { for( Bundle bundle : bc.getBundles() ) { if( bundle.getSymbolicName().equals( symbolicName ) ) { if( version == null || version.equals( bundle.getVersion() ) ) { return bundle; } } } return null; }
[ "public", "static", "Bundle", "getBundle", "(", "BundleContext", "bc", ",", "String", "symbolicName", ",", "String", "version", ")", "{", "for", "(", "Bundle", "bundle", ":", "bc", ".", "getBundles", "(", ")", ")", "{", "if", "(", "bundle", ".", "getSymbolicName", "(", ")", ".", "equals", "(", "symbolicName", ")", ")", "{", "if", "(", "version", "==", "null", "||", "version", ".", "equals", "(", "bundle", ".", "getVersion", "(", ")", ")", ")", "{", "return", "bundle", ";", "}", "}", "}", "return", "null", ";", "}" ]
Returns the bundle with the given symbolic name and the given version, or null if no such bundle exists @param bc bundle context @param symbolicName bundle symbolic name @param version bundle version @return matching bundle, or null
[ "Returns", "the", "bundle", "with", "the", "given", "symbolic", "name", "and", "the", "given", "version", "or", "null", "if", "no", "such", "bundle", "exists" ]
00b0ee16cdbe8017984a4d7ba808b10d985c5b5c
https://github.com/ops4j/org.ops4j.pax.swissbox/blob/00b0ee16cdbe8017984a4d7ba808b10d985c5b5c/pax-swissbox-core/src/main/java/org/ops4j/pax/swissbox/core/BundleUtils.java#L128-L141
142,236
petergeneric/stdlib
guice/common/src/main/java/com/peterphi/std/guice/restclient/jaxb/webquery/WQConstraint.java
WQConstraint.encodeValue
public String encodeValue() { switch (function) { case EQ: if (value != null && value.startsWith("_")) return function.getPrefix() + value; else return value; default: if (function.hasBinaryParam()) return function.getPrefix() + value + ".." + value2; else if (function.hasParam()) return function.getPrefix() + value; else return function.getPrefix(); } }
java
public String encodeValue() { switch (function) { case EQ: if (value != null && value.startsWith("_")) return function.getPrefix() + value; else return value; default: if (function.hasBinaryParam()) return function.getPrefix() + value + ".." + value2; else if (function.hasParam()) return function.getPrefix() + value; else return function.getPrefix(); } }
[ "public", "String", "encodeValue", "(", ")", "{", "switch", "(", "function", ")", "{", "case", "EQ", ":", "if", "(", "value", "!=", "null", "&&", "value", ".", "startsWith", "(", "\"_\"", ")", ")", "return", "function", ".", "getPrefix", "(", ")", "+", "value", ";", "else", "return", "value", ";", "default", ":", "if", "(", "function", ".", "hasBinaryParam", "(", ")", ")", "return", "function", ".", "getPrefix", "(", ")", "+", "value", "+", "\"..\"", "+", "value2", ";", "else", "if", "(", "function", ".", "hasParam", "(", ")", ")", "return", "function", ".", "getPrefix", "(", ")", "+", "value", ";", "else", "return", "function", ".", "getPrefix", "(", ")", ";", "}", "}" ]
Encode this constraint in the query string value format @return
[ "Encode", "this", "constraint", "in", "the", "query", "string", "value", "format" ]
d4025d2f881bc0542b1e004c5f65a1ccaf895836
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/guice/common/src/main/java/com/peterphi/std/guice/restclient/jaxb/webquery/WQConstraint.java#L92-L109
142,237
petergeneric/stdlib
guice/common/src/main/java/com/peterphi/std/guice/restclient/jaxb/webquery/WQConstraint.java
WQConstraint.decode
public static WQConstraint decode(final String field, final String rawValue) { final WQFunctionType function; final String value; if (StringUtils.equalsIgnoreCase(rawValue, WQFunctionType.IS_NULL.getPrefix())) return new WQConstraint(field, WQFunctionType.IS_NULL, null); else if (StringUtils.equalsIgnoreCase(rawValue, WQFunctionType.NOT_NULL.getPrefix())) return new WQConstraint(field, WQFunctionType.NOT_NULL, null); else if (rawValue.startsWith("_f_")) { function = WQFunctionType.getByPrefix(rawValue); if (function.hasParam()) { // Strip the function name from the value value = rawValue.substring(function.getPrefix().length()); if (function.hasBinaryParam()) { final String[] splitValues = StringUtils.split(value, "..", 2); final String left = splitValues[0]; final String right = splitValues[1]; return new WQConstraint(field, function, left, right); } } else { value = null; } } else { function = WQFunctionType.EQ; value = rawValue; } return new WQConstraint(field, function, value); }
java
public static WQConstraint decode(final String field, final String rawValue) { final WQFunctionType function; final String value; if (StringUtils.equalsIgnoreCase(rawValue, WQFunctionType.IS_NULL.getPrefix())) return new WQConstraint(field, WQFunctionType.IS_NULL, null); else if (StringUtils.equalsIgnoreCase(rawValue, WQFunctionType.NOT_NULL.getPrefix())) return new WQConstraint(field, WQFunctionType.NOT_NULL, null); else if (rawValue.startsWith("_f_")) { function = WQFunctionType.getByPrefix(rawValue); if (function.hasParam()) { // Strip the function name from the value value = rawValue.substring(function.getPrefix().length()); if (function.hasBinaryParam()) { final String[] splitValues = StringUtils.split(value, "..", 2); final String left = splitValues[0]; final String right = splitValues[1]; return new WQConstraint(field, function, left, right); } } else { value = null; } } else { function = WQFunctionType.EQ; value = rawValue; } return new WQConstraint(field, function, value); }
[ "public", "static", "WQConstraint", "decode", "(", "final", "String", "field", ",", "final", "String", "rawValue", ")", "{", "final", "WQFunctionType", "function", ";", "final", "String", "value", ";", "if", "(", "StringUtils", ".", "equalsIgnoreCase", "(", "rawValue", ",", "WQFunctionType", ".", "IS_NULL", ".", "getPrefix", "(", ")", ")", ")", "return", "new", "WQConstraint", "(", "field", ",", "WQFunctionType", ".", "IS_NULL", ",", "null", ")", ";", "else", "if", "(", "StringUtils", ".", "equalsIgnoreCase", "(", "rawValue", ",", "WQFunctionType", ".", "NOT_NULL", ".", "getPrefix", "(", ")", ")", ")", "return", "new", "WQConstraint", "(", "field", ",", "WQFunctionType", ".", "NOT_NULL", ",", "null", ")", ";", "else", "if", "(", "rawValue", ".", "startsWith", "(", "\"_f_\"", ")", ")", "{", "function", "=", "WQFunctionType", ".", "getByPrefix", "(", "rawValue", ")", ";", "if", "(", "function", ".", "hasParam", "(", ")", ")", "{", "// Strip the function name from the value", "value", "=", "rawValue", ".", "substring", "(", "function", ".", "getPrefix", "(", ")", ".", "length", "(", ")", ")", ";", "if", "(", "function", ".", "hasBinaryParam", "(", ")", ")", "{", "final", "String", "[", "]", "splitValues", "=", "StringUtils", ".", "split", "(", "value", ",", "\"..\"", ",", "2", ")", ";", "final", "String", "left", "=", "splitValues", "[", "0", "]", ";", "final", "String", "right", "=", "splitValues", "[", "1", "]", ";", "return", "new", "WQConstraint", "(", "field", ",", "function", ",", "left", ",", "right", ")", ";", "}", "}", "else", "{", "value", "=", "null", ";", "}", "}", "else", "{", "function", "=", "WQFunctionType", ".", "EQ", ";", "value", "=", "rawValue", ";", "}", "return", "new", "WQConstraint", "(", "field", ",", "function", ",", "value", ")", ";", "}" ]
Produce a WebQueryConstraint from a Query String format parameter @param field @param rawValue @return
[ "Produce", "a", "WebQueryConstraint", "from", "a", "Query", "String", "format", "parameter" ]
d4025d2f881bc0542b1e004c5f65a1ccaf895836
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/guice/common/src/main/java/com/peterphi/std/guice/restclient/jaxb/webquery/WQConstraint.java#L238-L278
142,238
ziccardi/jnrpe
jnrpe-plugins/src/main/java/it/jnrpe/plugin/mysql/CheckMysql.java
CheckMysql.checkSlave
private Metric checkSlave(final ICommandLine cl, final Mysql mysql, final Connection conn) throws MetricGatheringException { Metric metric = null; try { Map<String, Integer> status = getSlaveStatus(conn); if (status.isEmpty()) { mysql.closeConnection(conn); throw new MetricGatheringException("CHECK_MYSQL - WARNING: No slaves defined. ", Status.CRITICAL, null); } // check if slave is running int slaveIoRunning = status.get("Slave_IO_Running"); int slaveSqlRunning = status.get("Slave_SQL_Running"); int secondsBehindMaster = status.get("Seconds_Behind_Master"); if (slaveIoRunning == 0 || slaveSqlRunning == 0) { mysql.closeConnection(conn); throw new MetricGatheringException("CHECK_MYSQL - CRITICAL: Slave status unavailable. ", Status.CRITICAL, null); } String slaveResult = "Slave IO: " + slaveIoRunning + " Slave SQL: " + slaveSqlRunning + " Seconds Behind Master: " + secondsBehindMaster; metric = new Metric("secondsBehindMaster", slaveResult, new BigDecimal(secondsBehindMaster), null, null); } catch (SQLException e) { String message = e.getMessage(); LOG.warn(getContext(), "Error executing the CheckMysql plugin: " + message, e); throw new MetricGatheringException("CHECK_MYSQL - CRITICAL: Unable to check slave status: - " + message, Status.CRITICAL, e); } return metric; }
java
private Metric checkSlave(final ICommandLine cl, final Mysql mysql, final Connection conn) throws MetricGatheringException { Metric metric = null; try { Map<String, Integer> status = getSlaveStatus(conn); if (status.isEmpty()) { mysql.closeConnection(conn); throw new MetricGatheringException("CHECK_MYSQL - WARNING: No slaves defined. ", Status.CRITICAL, null); } // check if slave is running int slaveIoRunning = status.get("Slave_IO_Running"); int slaveSqlRunning = status.get("Slave_SQL_Running"); int secondsBehindMaster = status.get("Seconds_Behind_Master"); if (slaveIoRunning == 0 || slaveSqlRunning == 0) { mysql.closeConnection(conn); throw new MetricGatheringException("CHECK_MYSQL - CRITICAL: Slave status unavailable. ", Status.CRITICAL, null); } String slaveResult = "Slave IO: " + slaveIoRunning + " Slave SQL: " + slaveSqlRunning + " Seconds Behind Master: " + secondsBehindMaster; metric = new Metric("secondsBehindMaster", slaveResult, new BigDecimal(secondsBehindMaster), null, null); } catch (SQLException e) { String message = e.getMessage(); LOG.warn(getContext(), "Error executing the CheckMysql plugin: " + message, e); throw new MetricGatheringException("CHECK_MYSQL - CRITICAL: Unable to check slave status: - " + message, Status.CRITICAL, e); } return metric; }
[ "private", "Metric", "checkSlave", "(", "final", "ICommandLine", "cl", ",", "final", "Mysql", "mysql", ",", "final", "Connection", "conn", ")", "throws", "MetricGatheringException", "{", "Metric", "metric", "=", "null", ";", "try", "{", "Map", "<", "String", ",", "Integer", ">", "status", "=", "getSlaveStatus", "(", "conn", ")", ";", "if", "(", "status", ".", "isEmpty", "(", ")", ")", "{", "mysql", ".", "closeConnection", "(", "conn", ")", ";", "throw", "new", "MetricGatheringException", "(", "\"CHECK_MYSQL - WARNING: No slaves defined. \"", ",", "Status", ".", "CRITICAL", ",", "null", ")", ";", "}", "// check if slave is running", "int", "slaveIoRunning", "=", "status", ".", "get", "(", "\"Slave_IO_Running\"", ")", ";", "int", "slaveSqlRunning", "=", "status", ".", "get", "(", "\"Slave_SQL_Running\"", ")", ";", "int", "secondsBehindMaster", "=", "status", ".", "get", "(", "\"Seconds_Behind_Master\"", ")", ";", "if", "(", "slaveIoRunning", "==", "0", "||", "slaveSqlRunning", "==", "0", ")", "{", "mysql", ".", "closeConnection", "(", "conn", ")", ";", "throw", "new", "MetricGatheringException", "(", "\"CHECK_MYSQL - CRITICAL: Slave status unavailable. \"", ",", "Status", ".", "CRITICAL", ",", "null", ")", ";", "}", "String", "slaveResult", "=", "\"Slave IO: \"", "+", "slaveIoRunning", "+", "\" Slave SQL: \"", "+", "slaveSqlRunning", "+", "\" Seconds Behind Master: \"", "+", "secondsBehindMaster", ";", "metric", "=", "new", "Metric", "(", "\"secondsBehindMaster\"", ",", "slaveResult", ",", "new", "BigDecimal", "(", "secondsBehindMaster", ")", ",", "null", ",", "null", ")", ";", "}", "catch", "(", "SQLException", "e", ")", "{", "String", "message", "=", "e", ".", "getMessage", "(", ")", ";", "LOG", ".", "warn", "(", "getContext", "(", ")", ",", "\"Error executing the CheckMysql plugin: \"", "+", "message", ",", "e", ")", ";", "throw", "new", "MetricGatheringException", "(", "\"CHECK_MYSQL - CRITICAL: Unable to check slave status: - \"", "+", "message", ",", "Status", ".", "CRITICAL", ",", "e", ")", ";", "}", "return", "metric", ";", "}" ]
Check the status of mysql slave thread. @param cl The command line @param mysql MySQL connection mgr object @param conn The SQL connection @return ReturnValue - @throws MetricGatheringException -
[ "Check", "the", "status", "of", "mysql", "slave", "thread", "." ]
ac9046355851136994388442b01ba4063305f9c4
https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-plugins/src/main/java/it/jnrpe/plugin/mysql/CheckMysql.java#L117-L146
142,239
ziccardi/jnrpe
jnrpe-plugins/src/main/java/it/jnrpe/plugin/mysql/CheckMysql.java
CheckMysql.getSlaveStatus
private Map<String, Integer> getSlaveStatus(final Connection conn) throws SQLException { Map<String, Integer> map = new HashMap<String, Integer>(); String query = SLAVE_STATUS_QRY; Statement statement = null; ResultSet rs = null; try { if (conn != null) { statement = conn.createStatement(); rs = statement.executeQuery(query); while (rs.next()) { map.put("Slave_IO_Running", rs.getInt("Slave_IO_Running")); map.put("Slave_SQL_Running", rs.getInt("Slave_SQL_Running")); map.put("Seconds_Behind_Master", rs.getInt("Seconds_Behind_Master")); } } } finally { DBUtils.closeQuietly(rs); DBUtils.closeQuietly(statement); } return map; }
java
private Map<String, Integer> getSlaveStatus(final Connection conn) throws SQLException { Map<String, Integer> map = new HashMap<String, Integer>(); String query = SLAVE_STATUS_QRY; Statement statement = null; ResultSet rs = null; try { if (conn != null) { statement = conn.createStatement(); rs = statement.executeQuery(query); while (rs.next()) { map.put("Slave_IO_Running", rs.getInt("Slave_IO_Running")); map.put("Slave_SQL_Running", rs.getInt("Slave_SQL_Running")); map.put("Seconds_Behind_Master", rs.getInt("Seconds_Behind_Master")); } } } finally { DBUtils.closeQuietly(rs); DBUtils.closeQuietly(statement); } return map; }
[ "private", "Map", "<", "String", ",", "Integer", ">", "getSlaveStatus", "(", "final", "Connection", "conn", ")", "throws", "SQLException", "{", "Map", "<", "String", ",", "Integer", ">", "map", "=", "new", "HashMap", "<", "String", ",", "Integer", ">", "(", ")", ";", "String", "query", "=", "SLAVE_STATUS_QRY", ";", "Statement", "statement", "=", "null", ";", "ResultSet", "rs", "=", "null", ";", "try", "{", "if", "(", "conn", "!=", "null", ")", "{", "statement", "=", "conn", ".", "createStatement", "(", ")", ";", "rs", "=", "statement", ".", "executeQuery", "(", "query", ")", ";", "while", "(", "rs", ".", "next", "(", ")", ")", "{", "map", ".", "put", "(", "\"Slave_IO_Running\"", ",", "rs", ".", "getInt", "(", "\"Slave_IO_Running\"", ")", ")", ";", "map", ".", "put", "(", "\"Slave_SQL_Running\"", ",", "rs", ".", "getInt", "(", "\"Slave_SQL_Running\"", ")", ")", ";", "map", ".", "put", "(", "\"Seconds_Behind_Master\"", ",", "rs", ".", "getInt", "(", "\"Seconds_Behind_Master\"", ")", ")", ";", "}", "}", "}", "finally", "{", "DBUtils", ".", "closeQuietly", "(", "rs", ")", ";", "DBUtils", ".", "closeQuietly", "(", "statement", ")", ";", "}", "return", "map", ";", "}" ]
Get slave statuses. @param conn The database connection @return The slave status info @throws SQLException -
[ "Get", "slave", "statuses", "." ]
ac9046355851136994388442b01ba4063305f9c4
https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-plugins/src/main/java/it/jnrpe/plugin/mysql/CheckMysql.java#L157-L177
142,240
ziccardi/jnrpe
jnrpe-lib/src/main/java/it/jnrpe/net/packet/AbstractJNRPEProtocolPacket.java
AbstractJNRPEProtocolPacket.updateCRC
public void updateCRC() { this.crc32 = 0; CRC32 crcAlg = new CRC32(); crcAlg.update(this.toByteArray()); this.crc32 = (int) crcAlg.getValue(); }
java
public void updateCRC() { this.crc32 = 0; CRC32 crcAlg = new CRC32(); crcAlg.update(this.toByteArray()); this.crc32 = (int) crcAlg.getValue(); }
[ "public", "void", "updateCRC", "(", ")", "{", "this", ".", "crc32", "=", "0", ";", "CRC32", "crcAlg", "=", "new", "CRC32", "(", ")", ";", "crcAlg", ".", "update", "(", "this", ".", "toByteArray", "(", ")", ")", ";", "this", ".", "crc32", "=", "(", "int", ")", "crcAlg", ".", "getValue", "(", ")", ";", "}" ]
Updates the CRC value.
[ "Updates", "the", "CRC", "value", "." ]
ac9046355851136994388442b01ba4063305f9c4
https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-lib/src/main/java/it/jnrpe/net/packet/AbstractJNRPEProtocolPacket.java#L91-L97
142,241
ziccardi/jnrpe
jnrpe-lib/src/main/java/it/jnrpe/utils/thresholds/RangeStringParser.java
RangeStringParser.configureParser
private static Stage configureParser() { Stage startStage = new StartStage(); Stage negativeInfinityStage = new NegativeInfinityStage(); Stage positiveInfinityStage = new PositiveInfinityStage(); NegateStage negateStage = new NegateStage(); BracketStage.OpenBracketStage openBraceStage = new BracketStage.OpenBracketStage(); NumberBoundaryStage.LeftBoundaryStage startBoundaryStage = new NumberBoundaryStage.LeftBoundaryStage(); NumberBoundaryStage.RightBoundaryStage rightBoundaryStage = new NumberBoundaryStage.RightBoundaryStage(); SeparatorStage separatorStage = new SeparatorStage(); BracketStage.ClosedBracketStage closedBraketStage = new BracketStage.ClosedBracketStage(); startStage.addTransition(negateStage); startStage.addTransition(openBraceStage); startStage.addTransition(negativeInfinityStage); startStage.addTransition(startBoundaryStage); negateStage.addTransition(negativeInfinityStage); negateStage.addTransition(openBraceStage); negateStage.addTransition(startBoundaryStage); openBraceStage.addTransition(startBoundaryStage); startBoundaryStage.addTransition(separatorStage); negativeInfinityStage.addTransition(separatorStage); separatorStage.addTransition(positiveInfinityStage); separatorStage.addTransition(rightBoundaryStage); rightBoundaryStage.addTransition(closedBraketStage); return startStage; }
java
private static Stage configureParser() { Stage startStage = new StartStage(); Stage negativeInfinityStage = new NegativeInfinityStage(); Stage positiveInfinityStage = new PositiveInfinityStage(); NegateStage negateStage = new NegateStage(); BracketStage.OpenBracketStage openBraceStage = new BracketStage.OpenBracketStage(); NumberBoundaryStage.LeftBoundaryStage startBoundaryStage = new NumberBoundaryStage.LeftBoundaryStage(); NumberBoundaryStage.RightBoundaryStage rightBoundaryStage = new NumberBoundaryStage.RightBoundaryStage(); SeparatorStage separatorStage = new SeparatorStage(); BracketStage.ClosedBracketStage closedBraketStage = new BracketStage.ClosedBracketStage(); startStage.addTransition(negateStage); startStage.addTransition(openBraceStage); startStage.addTransition(negativeInfinityStage); startStage.addTransition(startBoundaryStage); negateStage.addTransition(negativeInfinityStage); negateStage.addTransition(openBraceStage); negateStage.addTransition(startBoundaryStage); openBraceStage.addTransition(startBoundaryStage); startBoundaryStage.addTransition(separatorStage); negativeInfinityStage.addTransition(separatorStage); separatorStage.addTransition(positiveInfinityStage); separatorStage.addTransition(rightBoundaryStage); rightBoundaryStage.addTransition(closedBraketStage); return startStage; }
[ "private", "static", "Stage", "configureParser", "(", ")", "{", "Stage", "startStage", "=", "new", "StartStage", "(", ")", ";", "Stage", "negativeInfinityStage", "=", "new", "NegativeInfinityStage", "(", ")", ";", "Stage", "positiveInfinityStage", "=", "new", "PositiveInfinityStage", "(", ")", ";", "NegateStage", "negateStage", "=", "new", "NegateStage", "(", ")", ";", "BracketStage", ".", "OpenBracketStage", "openBraceStage", "=", "new", "BracketStage", ".", "OpenBracketStage", "(", ")", ";", "NumberBoundaryStage", ".", "LeftBoundaryStage", "startBoundaryStage", "=", "new", "NumberBoundaryStage", ".", "LeftBoundaryStage", "(", ")", ";", "NumberBoundaryStage", ".", "RightBoundaryStage", "rightBoundaryStage", "=", "new", "NumberBoundaryStage", ".", "RightBoundaryStage", "(", ")", ";", "SeparatorStage", "separatorStage", "=", "new", "SeparatorStage", "(", ")", ";", "BracketStage", ".", "ClosedBracketStage", "closedBraketStage", "=", "new", "BracketStage", ".", "ClosedBracketStage", "(", ")", ";", "startStage", ".", "addTransition", "(", "negateStage", ")", ";", "startStage", ".", "addTransition", "(", "openBraceStage", ")", ";", "startStage", ".", "addTransition", "(", "negativeInfinityStage", ")", ";", "startStage", ".", "addTransition", "(", "startBoundaryStage", ")", ";", "negateStage", ".", "addTransition", "(", "negativeInfinityStage", ")", ";", "negateStage", ".", "addTransition", "(", "openBraceStage", ")", ";", "negateStage", ".", "addTransition", "(", "startBoundaryStage", ")", ";", "openBraceStage", ".", "addTransition", "(", "startBoundaryStage", ")", ";", "startBoundaryStage", ".", "addTransition", "(", "separatorStage", ")", ";", "negativeInfinityStage", ".", "addTransition", "(", "separatorStage", ")", ";", "separatorStage", ".", "addTransition", "(", "positiveInfinityStage", ")", ";", "separatorStage", ".", "addTransition", "(", "rightBoundaryStage", ")", ";", "rightBoundaryStage", ".", "addTransition", "(", "closedBraketStage", ")", ";", "return", "startStage", ";", "}" ]
Configures the state machine. @return The configured state machine.
[ "Configures", "the", "state", "machine", "." ]
ac9046355851136994388442b01ba4063305f9c4
https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-lib/src/main/java/it/jnrpe/utils/thresholds/RangeStringParser.java#L43-L73
142,242
ziccardi/jnrpe
jnrpe-lib/src/main/java/it/jnrpe/utils/thresholds/RangeStringParser.java
RangeStringParser.parse
public static void parse(final String range, final RangeConfig tc) throws RangeException { if (range == null) { throw new RangeException("Range can't be null"); } ROOT_STAGE.parse(range, tc); checkBoundaries(tc); }
java
public static void parse(final String range, final RangeConfig tc) throws RangeException { if (range == null) { throw new RangeException("Range can't be null"); } ROOT_STAGE.parse(range, tc); checkBoundaries(tc); }
[ "public", "static", "void", "parse", "(", "final", "String", "range", ",", "final", "RangeConfig", "tc", ")", "throws", "RangeException", "{", "if", "(", "range", "==", "null", ")", "{", "throw", "new", "RangeException", "(", "\"Range can't be null\"", ")", ";", "}", "ROOT_STAGE", ".", "parse", "(", "range", ",", "tc", ")", ";", "checkBoundaries", "(", "tc", ")", ";", "}" ]
Parses the threshold. @param range The threshold to be parsed @param tc The configuration @throws RangeException -
[ "Parses", "the", "threshold", "." ]
ac9046355851136994388442b01ba4063305f9c4
https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-lib/src/main/java/it/jnrpe/utils/thresholds/RangeStringParser.java#L85-L91
142,243
ziccardi/jnrpe
jnrpe-lib/src/main/java/it/jnrpe/utils/thresholds/RangeStringParser.java
RangeStringParser.checkBoundaries
private static void checkBoundaries(final RangeConfig rc) throws RangeException { if (rc.isNegativeInfinity()) { // No other checks necessary. Negative infinity is less than any // number return; } if (rc.isPositiveInfinity()) { // No other checks necessary. Positive infinity is greater than any // number return; } if (rc.getLeftBoundary().compareTo(rc.getRightBoundary()) > 0) { throw new RangeException("Left boundary must be less than right boundary (left:" + rc.getLeftBoundary() + ", right:" + rc.getRightBoundary() + ")"); } }
java
private static void checkBoundaries(final RangeConfig rc) throws RangeException { if (rc.isNegativeInfinity()) { // No other checks necessary. Negative infinity is less than any // number return; } if (rc.isPositiveInfinity()) { // No other checks necessary. Positive infinity is greater than any // number return; } if (rc.getLeftBoundary().compareTo(rc.getRightBoundary()) > 0) { throw new RangeException("Left boundary must be less than right boundary (left:" + rc.getLeftBoundary() + ", right:" + rc.getRightBoundary() + ")"); } }
[ "private", "static", "void", "checkBoundaries", "(", "final", "RangeConfig", "rc", ")", "throws", "RangeException", "{", "if", "(", "rc", ".", "isNegativeInfinity", "(", ")", ")", "{", "// No other checks necessary. Negative infinity is less than any", "// number", "return", ";", "}", "if", "(", "rc", ".", "isPositiveInfinity", "(", ")", ")", "{", "// No other checks necessary. Positive infinity is greater than any", "// number", "return", ";", "}", "if", "(", "rc", ".", "getLeftBoundary", "(", ")", ".", "compareTo", "(", "rc", ".", "getRightBoundary", "(", ")", ")", ">", "0", ")", "{", "throw", "new", "RangeException", "(", "\"Left boundary must be less than right boundary (left:\"", "+", "rc", ".", "getLeftBoundary", "(", ")", "+", "\", right:\"", "+", "rc", ".", "getRightBoundary", "(", ")", "+", "\")\"", ")", ";", "}", "}" ]
Checks that right boundary is greater than left boundary. @param rc The range configuration @throws RangeException If right < left
[ "Checks", "that", "right", "boundary", "is", "greater", "than", "left", "boundary", "." ]
ac9046355851136994388442b01ba4063305f9c4
https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-lib/src/main/java/it/jnrpe/utils/thresholds/RangeStringParser.java#L101-L118
142,244
petergeneric/stdlib
stdlib/src/main/java/com/peterphi/std/types/TimecodeBuilder.java
TimecodeBuilder.withTimecode
public TimecodeBuilder withTimecode(Timecode timecode) { return this .withNegative(timecode.isNegative()) .withDays(timecode.getDaysPart()) .withHours(timecode.getHoursPart()) .withMinutes(timecode.getMinutesPart()) .withSeconds(timecode.getSecondsPart()) .withFrames(timecode.getFramesPart()) .withDropFrame(timecode.isDropFrame()) .withRate(timecode.getTimebase()); }
java
public TimecodeBuilder withTimecode(Timecode timecode) { return this .withNegative(timecode.isNegative()) .withDays(timecode.getDaysPart()) .withHours(timecode.getHoursPart()) .withMinutes(timecode.getMinutesPart()) .withSeconds(timecode.getSecondsPart()) .withFrames(timecode.getFramesPart()) .withDropFrame(timecode.isDropFrame()) .withRate(timecode.getTimebase()); }
[ "public", "TimecodeBuilder", "withTimecode", "(", "Timecode", "timecode", ")", "{", "return", "this", ".", "withNegative", "(", "timecode", ".", "isNegative", "(", ")", ")", ".", "withDays", "(", "timecode", ".", "getDaysPart", "(", ")", ")", ".", "withHours", "(", "timecode", ".", "getHoursPart", "(", ")", ")", ".", "withMinutes", "(", "timecode", ".", "getMinutesPart", "(", ")", ")", ".", "withSeconds", "(", "timecode", ".", "getSecondsPart", "(", ")", ")", ".", "withFrames", "(", "timecode", ".", "getFramesPart", "(", ")", ")", ".", "withDropFrame", "(", "timecode", ".", "isDropFrame", "(", ")", ")", ".", "withRate", "(", "timecode", ".", "getTimebase", "(", ")", ")", ";", "}" ]
Reset this builder to the values in the provided Timecode @param timecode @return
[ "Reset", "this", "builder", "to", "the", "values", "in", "the", "provided", "Timecode" ]
d4025d2f881bc0542b1e004c5f65a1ccaf895836
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/stdlib/src/main/java/com/peterphi/std/types/TimecodeBuilder.java#L30-L41
142,245
petergeneric/stdlib
stdlib/src/main/java/com/peterphi/std/types/TimecodeBuilder.java
TimecodeBuilder.build
public Timecode build() { // If drop-frame is not specified (and timebase is drop frame capable) default to true final boolean dropFrame = (this.dropFrame != null) ? this.dropFrame.booleanValue() : getRate().canBeDropFrame(); return new Timecode(negative, days, hours, minutes, seconds, frames, rate, dropFrame); }
java
public Timecode build() { // If drop-frame is not specified (and timebase is drop frame capable) default to true final boolean dropFrame = (this.dropFrame != null) ? this.dropFrame.booleanValue() : getRate().canBeDropFrame(); return new Timecode(negative, days, hours, minutes, seconds, frames, rate, dropFrame); }
[ "public", "Timecode", "build", "(", ")", "{", "// If drop-frame is not specified (and timebase is drop frame capable) default to true", "final", "boolean", "dropFrame", "=", "(", "this", ".", "dropFrame", "!=", "null", ")", "?", "this", ".", "dropFrame", ".", "booleanValue", "(", ")", ":", "getRate", "(", ")", ".", "canBeDropFrame", "(", ")", ";", "return", "new", "Timecode", "(", "negative", ",", "days", ",", "hours", ",", "minutes", ",", "seconds", ",", "frames", ",", "rate", ",", "dropFrame", ")", ";", "}" ]
Constructs a Timecode instance with the fields defined in this builder @return @throws IllegalArgumentException if any of the fields are invalid/incompatible
[ "Constructs", "a", "Timecode", "instance", "with", "the", "fields", "defined", "in", "this", "builder" ]
d4025d2f881bc0542b1e004c5f65a1ccaf895836
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/stdlib/src/main/java/com/peterphi/std/types/TimecodeBuilder.java#L142-L148
142,246
petergeneric/stdlib
service-manager/configuration/src/main/java/com/peterphi/configuration/service/git/ConfigRepository.java
ConfigRepository.setAll
public void setAll(final String name, final String email, final Map<String, Map<String, ConfigPropertyValue>> data, final String message) { set(name, email, data, ConfigChangeMode.WIPE_ALL, message); }
java
public void setAll(final String name, final String email, final Map<String, Map<String, ConfigPropertyValue>> data, final String message) { set(name, email, data, ConfigChangeMode.WIPE_ALL, message); }
[ "public", "void", "setAll", "(", "final", "String", "name", ",", "final", "String", "email", ",", "final", "Map", "<", "String", ",", "Map", "<", "String", ",", "ConfigPropertyValue", ">", ">", "data", ",", "final", "String", "message", ")", "{", "set", "(", "name", ",", "email", ",", "data", ",", "ConfigChangeMode", ".", "WIPE_ALL", ",", "message", ")", ";", "}" ]
Create a new commit reflecting the provided properties, removing any property not mentioned here @param name @param email @param data @param message
[ "Create", "a", "new", "commit", "reflecting", "the", "provided", "properties", "removing", "any", "property", "not", "mentioned", "here" ]
d4025d2f881bc0542b1e004c5f65a1ccaf895836
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/service-manager/configuration/src/main/java/com/peterphi/configuration/service/git/ConfigRepository.java#L82-L88
142,247
petergeneric/stdlib
service-manager/configuration/src/main/java/com/peterphi/configuration/service/git/ConfigRepository.java
ConfigRepository.set
public void set(final String name, final String email, final Map<String, Map<String, ConfigPropertyValue>> data, final ConfigChangeMode changeMode, final String message) { try { RepoHelper.write(repo, name, email, data, changeMode, message); } catch (Exception e) { try { RepoHelper.reset(repo); } catch (Exception ee) { throw new RuntimeException("Error writing updated repository, then could not reset work tree", e); } throw new RuntimeException("Error writing updated repository, work tree reset", e); } // Push the changes to the remote if (hasRemote) { try { RepoHelper.push(repo, "origin", credentials); } catch (Throwable t) { throw new RuntimeException("Saved changes to the local repository but push to remote failed!", t); } } }
java
public void set(final String name, final String email, final Map<String, Map<String, ConfigPropertyValue>> data, final ConfigChangeMode changeMode, final String message) { try { RepoHelper.write(repo, name, email, data, changeMode, message); } catch (Exception e) { try { RepoHelper.reset(repo); } catch (Exception ee) { throw new RuntimeException("Error writing updated repository, then could not reset work tree", e); } throw new RuntimeException("Error writing updated repository, work tree reset", e); } // Push the changes to the remote if (hasRemote) { try { RepoHelper.push(repo, "origin", credentials); } catch (Throwable t) { throw new RuntimeException("Saved changes to the local repository but push to remote failed!", t); } } }
[ "public", "void", "set", "(", "final", "String", "name", ",", "final", "String", "email", ",", "final", "Map", "<", "String", ",", "Map", "<", "String", ",", "ConfigPropertyValue", ">", ">", "data", ",", "final", "ConfigChangeMode", "changeMode", ",", "final", "String", "message", ")", "{", "try", "{", "RepoHelper", ".", "write", "(", "repo", ",", "name", ",", "email", ",", "data", ",", "changeMode", ",", "message", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "try", "{", "RepoHelper", ".", "reset", "(", "repo", ")", ";", "}", "catch", "(", "Exception", "ee", ")", "{", "throw", "new", "RuntimeException", "(", "\"Error writing updated repository, then could not reset work tree\"", ",", "e", ")", ";", "}", "throw", "new", "RuntimeException", "(", "\"Error writing updated repository, work tree reset\"", ",", "e", ")", ";", "}", "// Push the changes to the remote", "if", "(", "hasRemote", ")", "{", "try", "{", "RepoHelper", ".", "push", "(", "repo", ",", "\"origin\"", ",", "credentials", ")", ";", "}", "catch", "(", "Throwable", "t", ")", "{", "throw", "new", "RuntimeException", "(", "\"Saved changes to the local repository but push to remote failed!\"", ",", "t", ")", ";", "}", "}", "}" ]
Create a new commit reflecting the provided properties @param name @param email @param data @param erase if true all existing properties will be erased @param message
[ "Create", "a", "new", "commit", "reflecting", "the", "provided", "properties" ]
d4025d2f881bc0542b1e004c5f65a1ccaf895836
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/service-manager/configuration/src/main/java/com/peterphi/configuration/service/git/ConfigRepository.java#L101-L137
142,248
petergeneric/stdlib
guice/webapp/src/main/java/com/peterphi/std/guice/web/HttpCallContext.java
HttpCallContext.get
public static HttpCallContext get() throws IllegalStateException { final HttpCallContext ctx = peek(); if (ctx != null) return ctx; else throw new IllegalStateException("Not in an HttpCallContext!"); }
java
public static HttpCallContext get() throws IllegalStateException { final HttpCallContext ctx = peek(); if (ctx != null) return ctx; else throw new IllegalStateException("Not in an HttpCallContext!"); }
[ "public", "static", "HttpCallContext", "get", "(", ")", "throws", "IllegalStateException", "{", "final", "HttpCallContext", "ctx", "=", "peek", "(", ")", ";", "if", "(", "ctx", "!=", "null", ")", "return", "ctx", ";", "else", "throw", "new", "IllegalStateException", "(", "\"Not in an HttpCallContext!\"", ")", ";", "}" ]
Retrieve the HttpCallContext associated with this Thread @return @throws IllegalStateException if not inside an http call
[ "Retrieve", "the", "HttpCallContext", "associated", "with", "this", "Thread" ]
d4025d2f881bc0542b1e004c5f65a1ccaf895836
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/guice/webapp/src/main/java/com/peterphi/std/guice/web/HttpCallContext.java#L31-L39
142,249
petergeneric/stdlib
guice/webapp/src/main/java/com/peterphi/std/guice/web/HttpCallContext.java
HttpCallContext.set
public static HttpCallContext set(HttpServletRequest request, HttpServletResponse response, ServletContext servletContext) { final HttpCallContext ctx = new HttpCallContext(generateTraceId(request), request, response, servletContext); contexts.set(ctx); return ctx; }
java
public static HttpCallContext set(HttpServletRequest request, HttpServletResponse response, ServletContext servletContext) { final HttpCallContext ctx = new HttpCallContext(generateTraceId(request), request, response, servletContext); contexts.set(ctx); return ctx; }
[ "public", "static", "HttpCallContext", "set", "(", "HttpServletRequest", "request", ",", "HttpServletResponse", "response", ",", "ServletContext", "servletContext", ")", "{", "final", "HttpCallContext", "ctx", "=", "new", "HttpCallContext", "(", "generateTraceId", "(", "request", ")", ",", "request", ",", "response", ",", "servletContext", ")", ";", "contexts", ".", "set", "(", "ctx", ")", ";", "return", "ctx", ";", "}" ]
Creates and associates an HttpCallContext with the current Thread @param request @param response @return
[ "Creates", "and", "associates", "an", "HttpCallContext", "with", "the", "current", "Thread" ]
d4025d2f881bc0542b1e004c5f65a1ccaf895836
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/guice/webapp/src/main/java/com/peterphi/std/guice/web/HttpCallContext.java#L70-L77
142,250
petergeneric/stdlib
stdlib/src/main/java/com/peterphi/std/crypto/openssl/OpenSSLPKCS12.java
OpenSSLPKCS12.filterP12
public static void filterP12(File p12, String p12Password) throws IOException { if (!p12.exists()) throw new IllegalArgumentException("p12 file does not exist: " + p12.getPath()); final File pem; if (USE_GENERIC_TEMP_DIRECTORY) pem = File.createTempFile(UUID.randomUUID().toString(), ""); else pem = new File(p12.getAbsolutePath() + ".pem.tmp"); final String pemPassword = UUID.randomUUID().toString(); try { P12toPEM(p12, p12Password, pem, pemPassword); PEMtoP12(pem, pemPassword, p12, p12Password); } finally { if (pem.exists()) if (!pem.delete()) log.warn("[OpenSSLPKCS12] {filterP12} Could not delete temporary PEM file " + pem); } }
java
public static void filterP12(File p12, String p12Password) throws IOException { if (!p12.exists()) throw new IllegalArgumentException("p12 file does not exist: " + p12.getPath()); final File pem; if (USE_GENERIC_TEMP_DIRECTORY) pem = File.createTempFile(UUID.randomUUID().toString(), ""); else pem = new File(p12.getAbsolutePath() + ".pem.tmp"); final String pemPassword = UUID.randomUUID().toString(); try { P12toPEM(p12, p12Password, pem, pemPassword); PEMtoP12(pem, pemPassword, p12, p12Password); } finally { if (pem.exists()) if (!pem.delete()) log.warn("[OpenSSLPKCS12] {filterP12} Could not delete temporary PEM file " + pem); } }
[ "public", "static", "void", "filterP12", "(", "File", "p12", ",", "String", "p12Password", ")", "throws", "IOException", "{", "if", "(", "!", "p12", ".", "exists", "(", ")", ")", "throw", "new", "IllegalArgumentException", "(", "\"p12 file does not exist: \"", "+", "p12", ".", "getPath", "(", ")", ")", ";", "final", "File", "pem", ";", "if", "(", "USE_GENERIC_TEMP_DIRECTORY", ")", "pem", "=", "File", ".", "createTempFile", "(", "UUID", ".", "randomUUID", "(", ")", ".", "toString", "(", ")", ",", "\"\"", ")", ";", "else", "pem", "=", "new", "File", "(", "p12", ".", "getAbsolutePath", "(", ")", "+", "\".pem.tmp\"", ")", ";", "final", "String", "pemPassword", "=", "UUID", ".", "randomUUID", "(", ")", ".", "toString", "(", ")", ";", "try", "{", "P12toPEM", "(", "p12", ",", "p12Password", ",", "pem", ",", "pemPassword", ")", ";", "PEMtoP12", "(", "pem", ",", "pemPassword", ",", "p12", ",", "p12Password", ")", ";", "}", "finally", "{", "if", "(", "pem", ".", "exists", "(", ")", ")", "if", "(", "!", "pem", ".", "delete", "(", ")", ")", "log", ".", "warn", "(", "\"[OpenSSLPKCS12] {filterP12} Could not delete temporary PEM file \"", "+", "pem", ")", ";", "}", "}" ]
Recreates a PKCS12 KeyStore using OpenSSL; this is a workaround a BouncyCastle-Firefox compatibility bug @param p12 The PKCS12 Keystore to filter @param p12Password The password for the keystore @throws IOException if a catastrophic unexpected failure occurs during execution @throws IllegalArgumentException if the PKCS12 keystore doesn't exist @throws IllegalStateException if openssl exits with a failure condition
[ "Recreates", "a", "PKCS12", "KeyStore", "using", "OpenSSL", ";", "this", "is", "a", "workaround", "a", "BouncyCastle", "-", "Firefox", "compatibility", "bug" ]
d4025d2f881bc0542b1e004c5f65a1ccaf895836
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/stdlib/src/main/java/com/peterphi/std/crypto/openssl/OpenSSLPKCS12.java#L34-L59
142,251
petergeneric/stdlib
guice/common/src/main/java/com/peterphi/std/guice/common/retry/retry/RetryManager.java
RetryManager.runUnchecked
public <T> T runUnchecked(Retryable<T> operation) throws RuntimeException { try { return run(operation); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException("Retryable " + operation + " failed: " + e.getMessage(), e); } }
java
public <T> T runUnchecked(Retryable<T> operation) throws RuntimeException { try { return run(operation); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException("Retryable " + operation + " failed: " + e.getMessage(), e); } }
[ "public", "<", "T", ">", "T", "runUnchecked", "(", "Retryable", "<", "T", ">", "operation", ")", "throws", "RuntimeException", "{", "try", "{", "return", "run", "(", "operation", ")", ";", "}", "catch", "(", "RuntimeException", "e", ")", "{", "throw", "e", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "RuntimeException", "(", "\"Retryable \"", "+", "operation", "+", "\" failed: \"", "+", "e", ".", "getMessage", "(", ")", ",", "e", ")", ";", "}", "}" ]
Run the operation, only throwing an unchecked exception on failure @param operation @param <T> @return @throws RuntimeException
[ "Run", "the", "operation", "only", "throwing", "an", "unchecked", "exception", "on", "failure" ]
d4025d2f881bc0542b1e004c5f65a1ccaf895836
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/guice/common/src/main/java/com/peterphi/std/guice/common/retry/retry/RetryManager.java#L131-L145
142,252
ziccardi/jnrpe
jnrpe-lib/src/main/java/it/jnrpe/JNRPELogger.java
JNRPELogger.trace
public void trace(final IJNRPEExecutionContext ctx, final String message) { postEvent(ctx, new LogEvent(source, LogEventType.TRACE, message)); }
java
public void trace(final IJNRPEExecutionContext ctx, final String message) { postEvent(ctx, new LogEvent(source, LogEventType.TRACE, message)); }
[ "public", "void", "trace", "(", "final", "IJNRPEExecutionContext", "ctx", ",", "final", "String", "message", ")", "{", "postEvent", "(", "ctx", ",", "new", "LogEvent", "(", "source", ",", "LogEventType", ".", "TRACE", ",", "message", ")", ")", ";", "}" ]
Sends trace level messages. @param ctx the JNRPE context @param message the message
[ "Sends", "trace", "level", "messages", "." ]
ac9046355851136994388442b01ba4063305f9c4
https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-lib/src/main/java/it/jnrpe/JNRPELogger.java#L49-L51
142,253
ziccardi/jnrpe
jnrpe-lib/src/main/java/it/jnrpe/JNRPELogger.java
JNRPELogger.debug
public void debug(final IJNRPEExecutionContext ctx, final String message) { postEvent(ctx, new LogEvent(source, LogEventType.DEBUG, message)); }
java
public void debug(final IJNRPEExecutionContext ctx, final String message) { postEvent(ctx, new LogEvent(source, LogEventType.DEBUG, message)); }
[ "public", "void", "debug", "(", "final", "IJNRPEExecutionContext", "ctx", ",", "final", "String", "message", ")", "{", "postEvent", "(", "ctx", ",", "new", "LogEvent", "(", "source", ",", "LogEventType", ".", "DEBUG", ",", "message", ")", ")", ";", "}" ]
Sends debug level messages. @param ctx the JNRPE context @param message the message
[ "Sends", "debug", "level", "messages", "." ]
ac9046355851136994388442b01ba4063305f9c4
https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-lib/src/main/java/it/jnrpe/JNRPELogger.java#L70-L72
142,254
ziccardi/jnrpe
jnrpe-lib/src/main/java/it/jnrpe/JNRPELogger.java
JNRPELogger.info
public void info(final IJNRPEExecutionContext ctx, final String message) { postEvent(ctx, new LogEvent(source, LogEventType.INFO, message)); }
java
public void info(final IJNRPEExecutionContext ctx, final String message) { postEvent(ctx, new LogEvent(source, LogEventType.INFO, message)); }
[ "public", "void", "info", "(", "final", "IJNRPEExecutionContext", "ctx", ",", "final", "String", "message", ")", "{", "postEvent", "(", "ctx", ",", "new", "LogEvent", "(", "source", ",", "LogEventType", ".", "INFO", ",", "message", ")", ")", ";", "}" ]
Sends info level messages. @param ctx the JNRPE context @param message the message
[ "Sends", "info", "level", "messages", "." ]
ac9046355851136994388442b01ba4063305f9c4
https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-lib/src/main/java/it/jnrpe/JNRPELogger.java#L91-L93
142,255
ziccardi/jnrpe
jnrpe-lib/src/main/java/it/jnrpe/JNRPELogger.java
JNRPELogger.warn
public void warn(final IJNRPEExecutionContext ctx, final String message) { postEvent(ctx, new LogEvent(source, LogEventType.WARNING, message)); }
java
public void warn(final IJNRPEExecutionContext ctx, final String message) { postEvent(ctx, new LogEvent(source, LogEventType.WARNING, message)); }
[ "public", "void", "warn", "(", "final", "IJNRPEExecutionContext", "ctx", ",", "final", "String", "message", ")", "{", "postEvent", "(", "ctx", ",", "new", "LogEvent", "(", "source", ",", "LogEventType", ".", "WARNING", ",", "message", ")", ")", ";", "}" ]
Sends warn level messages. @param ctx the JNRPE context @param message the message
[ "Sends", "warn", "level", "messages", "." ]
ac9046355851136994388442b01ba4063305f9c4
https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-lib/src/main/java/it/jnrpe/JNRPELogger.java#L112-L114
142,256
petergeneric/stdlib
rules/src/main/java/com/peterphi/rules/RulesEngineImpl.java
RulesEngineImpl.matching
@Override public Map<RuleSet, List<Rule>> matching(Rules rules, Map<String, Object> vars, boolean ignoreMethodErrors) throws OgnlException { Map<RuleSet, List<Rule>> ret = new HashMap<>(); for (RuleSet ruleSet : rules.ruleSets) { try { OgnlContext context = createContext(vars); List<Rule> matching = match(ruleSet, context); if (!matching.isEmpty()) { ret.put(ruleSet, matching); } } catch (MethodFailedException mfe) { if (!ignoreMethodErrors) { throw mfe; } log.warn("Method failed for ruleset " + ruleSet.id, mfe); } } return ret; }
java
@Override public Map<RuleSet, List<Rule>> matching(Rules rules, Map<String, Object> vars, boolean ignoreMethodErrors) throws OgnlException { Map<RuleSet, List<Rule>> ret = new HashMap<>(); for (RuleSet ruleSet : rules.ruleSets) { try { OgnlContext context = createContext(vars); List<Rule> matching = match(ruleSet, context); if (!matching.isEmpty()) { ret.put(ruleSet, matching); } } catch (MethodFailedException mfe) { if (!ignoreMethodErrors) { throw mfe; } log.warn("Method failed for ruleset " + ruleSet.id, mfe); } } return ret; }
[ "@", "Override", "public", "Map", "<", "RuleSet", ",", "List", "<", "Rule", ">", ">", "matching", "(", "Rules", "rules", ",", "Map", "<", "String", ",", "Object", ">", "vars", ",", "boolean", "ignoreMethodErrors", ")", "throws", "OgnlException", "{", "Map", "<", "RuleSet", ",", "List", "<", "Rule", ">", ">", "ret", "=", "new", "HashMap", "<>", "(", ")", ";", "for", "(", "RuleSet", "ruleSet", ":", "rules", ".", "ruleSets", ")", "{", "try", "{", "OgnlContext", "context", "=", "createContext", "(", "vars", ")", ";", "List", "<", "Rule", ">", "matching", "=", "match", "(", "ruleSet", ",", "context", ")", ";", "if", "(", "!", "matching", ".", "isEmpty", "(", ")", ")", "{", "ret", ".", "put", "(", "ruleSet", ",", "matching", ")", ";", "}", "}", "catch", "(", "MethodFailedException", "mfe", ")", "{", "if", "(", "!", "ignoreMethodErrors", ")", "{", "throw", "mfe", ";", "}", "log", ".", "warn", "(", "\"Method failed for ruleset \"", "+", "ruleSet", ".", "id", ",", "mfe", ")", ";", "}", "}", "return", "ret", ";", "}" ]
returns a list of the rules that match from the supplied Rules document @param rules @return
[ "returns", "a", "list", "of", "the", "rules", "that", "match", "from", "the", "supplied", "Rules", "document" ]
d4025d2f881bc0542b1e004c5f65a1ccaf895836
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/rules/src/main/java/com/peterphi/rules/RulesEngineImpl.java#L140-L173
142,257
petergeneric/stdlib
rules/src/main/java/com/peterphi/rules/RulesEngineImpl.java
RulesEngineImpl.match
private List<Rule> match(final RuleSet ruleSet, final OgnlContext ognlContext) throws OgnlException { log.debug("Assessing input for ruleset : " + ruleSet.id); //run the input commands ruleSet.runInput(ognlContext); final List<Rule> ret = new ArrayList<>(); //assess each rule against the input, return any that match for (Rule rule : ruleSet.rules) { Boolean bresult = rule.assessMatch(ognlContext); if (bresult) { log.debug(rule.condition.getOriginalExpression() + " matches"); ret.add(rule); } } return ret; }
java
private List<Rule> match(final RuleSet ruleSet, final OgnlContext ognlContext) throws OgnlException { log.debug("Assessing input for ruleset : " + ruleSet.id); //run the input commands ruleSet.runInput(ognlContext); final List<Rule> ret = new ArrayList<>(); //assess each rule against the input, return any that match for (Rule rule : ruleSet.rules) { Boolean bresult = rule.assessMatch(ognlContext); if (bresult) { log.debug(rule.condition.getOriginalExpression() + " matches"); ret.add(rule); } } return ret; }
[ "private", "List", "<", "Rule", ">", "match", "(", "final", "RuleSet", "ruleSet", ",", "final", "OgnlContext", "ognlContext", ")", "throws", "OgnlException", "{", "log", ".", "debug", "(", "\"Assessing input for ruleset : \"", "+", "ruleSet", ".", "id", ")", ";", "//run the input commands", "ruleSet", ".", "runInput", "(", "ognlContext", ")", ";", "final", "List", "<", "Rule", ">", "ret", "=", "new", "ArrayList", "<>", "(", ")", ";", "//assess each rule against the input, return any that match", "for", "(", "Rule", "rule", ":", "ruleSet", ".", "rules", ")", "{", "Boolean", "bresult", "=", "rule", ".", "assessMatch", "(", "ognlContext", ")", ";", "if", "(", "bresult", ")", "{", "log", ".", "debug", "(", "rule", ".", "condition", ".", "getOriginalExpression", "(", ")", "+", "\" matches\"", ")", ";", "ret", ".", "add", "(", "rule", ")", ";", "}", "}", "return", "ret", ";", "}" ]
returns a list of rules that match in the given rule set @param ruleSet @param ognlContext @return
[ "returns", "a", "list", "of", "rules", "that", "match", "in", "the", "given", "rule", "set" ]
d4025d2f881bc0542b1e004c5f65a1ccaf895836
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/rules/src/main/java/com/peterphi/rules/RulesEngineImpl.java#L273-L295
142,258
ziccardi/jnrpe
jnrpe-lib/src/main/java/it/jnrpe/JNRPEBuilder.java
JNRPEBuilder.build
public JNRPE build() { JNRPE jnrpe = new JNRPE(pluginRepository, commandRepository, charset, acceptParams, acceptedHosts, maxAcceptedConnections, readTimeout, writeTimeout); IJNRPEEventBus eventBus = jnrpe.getExecutionContext().getEventBus(); for (Object obj : eventListeners) { eventBus.register(obj); } return jnrpe; }
java
public JNRPE build() { JNRPE jnrpe = new JNRPE(pluginRepository, commandRepository, charset, acceptParams, acceptedHosts, maxAcceptedConnections, readTimeout, writeTimeout); IJNRPEEventBus eventBus = jnrpe.getExecutionContext().getEventBus(); for (Object obj : eventListeners) { eventBus.register(obj); } return jnrpe; }
[ "public", "JNRPE", "build", "(", ")", "{", "JNRPE", "jnrpe", "=", "new", "JNRPE", "(", "pluginRepository", ",", "commandRepository", ",", "charset", ",", "acceptParams", ",", "acceptedHosts", ",", "maxAcceptedConnections", ",", "readTimeout", ",", "writeTimeout", ")", ";", "IJNRPEEventBus", "eventBus", "=", "jnrpe", ".", "getExecutionContext", "(", ")", ".", "getEventBus", "(", ")", ";", "for", "(", "Object", "obj", ":", "eventListeners", ")", "{", "eventBus", ".", "register", "(", "obj", ")", ";", "}", "return", "jnrpe", ";", "}" ]
Builds the configured JNRPE instance. @return the configured JNRPE instance
[ "Builds", "the", "configured", "JNRPE", "instance", "." ]
ac9046355851136994388442b01ba4063305f9c4
https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-lib/src/main/java/it/jnrpe/JNRPEBuilder.java#L210-L221
142,259
petergeneric/stdlib
guice/common/src/main/java/com/peterphi/std/guice/restclient/resteasy/impl/ResteasyClientFactoryImpl.java
ResteasyClientFactoryImpl.getOrCreateClient
public ResteasyClient getOrCreateClient(final boolean fastFail, final AuthScope authScope, final Credentials credentials, final boolean preemptiveAuth, final boolean storeCookies, Consumer<HttpClientBuilder> customiser) { customiser = createHttpClientCustomiser(fastFail, authScope, credentials, preemptiveAuth, storeCookies, customiser); return getOrCreateClient(customiser, null); }
java
public ResteasyClient getOrCreateClient(final boolean fastFail, final AuthScope authScope, final Credentials credentials, final boolean preemptiveAuth, final boolean storeCookies, Consumer<HttpClientBuilder> customiser) { customiser = createHttpClientCustomiser(fastFail, authScope, credentials, preemptiveAuth, storeCookies, customiser); return getOrCreateClient(customiser, null); }
[ "public", "ResteasyClient", "getOrCreateClient", "(", "final", "boolean", "fastFail", ",", "final", "AuthScope", "authScope", ",", "final", "Credentials", "credentials", ",", "final", "boolean", "preemptiveAuth", ",", "final", "boolean", "storeCookies", ",", "Consumer", "<", "HttpClientBuilder", ">", "customiser", ")", "{", "customiser", "=", "createHttpClientCustomiser", "(", "fastFail", ",", "authScope", ",", "credentials", ",", "preemptiveAuth", ",", "storeCookies", ",", "customiser", ")", ";", "return", "getOrCreateClient", "(", "customiser", ",", "null", ")", ";", "}" ]
Build a new Resteasy Client, optionally with authentication credentials @param fastFail if true, use fast fail timeouts, otherwise false to use default timeouts @param authScope the auth scope to use - if null then defaults to <code>AuthScope.ANY</code> @param credentials the credentials to use (optional, e.g. {@link org.apache.http.auth.UsernamePasswordCredentials}) @param customiser optional HttpClientBuilder customiser. @return
[ "Build", "a", "new", "Resteasy", "Client", "optionally", "with", "authentication", "credentials" ]
d4025d2f881bc0542b1e004c5f65a1ccaf895836
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/guice/common/src/main/java/com/peterphi/std/guice/restclient/resteasy/impl/ResteasyClientFactoryImpl.java#L140-L151
142,260
petergeneric/stdlib
guice/common/src/main/java/com/peterphi/std/guice/restclient/resteasy/impl/ResteasyClientFactoryImpl.java
ResteasyClientFactoryImpl.createHttpClientCustomiser
public Consumer<HttpClientBuilder> createHttpClientCustomiser(final boolean fastFail, final AuthScope authScope, final Credentials credentials, final boolean preemptiveAuth, final boolean storeCookies, Consumer<HttpClientBuilder> customiser) { // Customise timeouts if fast fail mode is enabled if (fastFail) { customiser = concat(customiser, b -> { RequestConfig.Builder requestBuilder = RequestConfig.custom(); requestBuilder.setConnectTimeout((int) fastFailConnectionTimeout.getMilliseconds()) .setSocketTimeout((int) fastFailSocketTimeout.getMilliseconds()); b.setDefaultRequestConfig(requestBuilder.build()); }); } // If credentials were supplied then we should set them up if (credentials != null) { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); if (authScope != null) credentialsProvider.setCredentials(authScope, credentials); else credentialsProvider.setCredentials(AuthScope.ANY, credentials); // Set up bearer auth scheme provider if we're using bearer credentials if (credentials instanceof BearerCredentials) { customiser = concat(customiser, b -> { Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create().register( "Bearer", new BearerAuthSchemeProvider()).build(); b.setDefaultAuthSchemeRegistry(authSchemeRegistry); }); } // Set up the credentials customisation customiser = concat(customiser, b -> b.setDefaultCredentialsProvider(credentialsProvider)); if (preemptiveAuth && credentials instanceof BearerCredentials) customiser = concat(customiser, b -> b.addInterceptorFirst(new PreemptiveBearerAuthInterceptor())); else customiser = concat(customiser, b -> b.addInterceptorLast(new PreemptiveBasicAuthInterceptor())); } // If cookies are enabled then set up a cookie store if (storeCookies) customiser = concat(customiser, b -> b.setDefaultCookieStore(new BasicCookieStore())); return customiser; }
java
public Consumer<HttpClientBuilder> createHttpClientCustomiser(final boolean fastFail, final AuthScope authScope, final Credentials credentials, final boolean preemptiveAuth, final boolean storeCookies, Consumer<HttpClientBuilder> customiser) { // Customise timeouts if fast fail mode is enabled if (fastFail) { customiser = concat(customiser, b -> { RequestConfig.Builder requestBuilder = RequestConfig.custom(); requestBuilder.setConnectTimeout((int) fastFailConnectionTimeout.getMilliseconds()) .setSocketTimeout((int) fastFailSocketTimeout.getMilliseconds()); b.setDefaultRequestConfig(requestBuilder.build()); }); } // If credentials were supplied then we should set them up if (credentials != null) { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); if (authScope != null) credentialsProvider.setCredentials(authScope, credentials); else credentialsProvider.setCredentials(AuthScope.ANY, credentials); // Set up bearer auth scheme provider if we're using bearer credentials if (credentials instanceof BearerCredentials) { customiser = concat(customiser, b -> { Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create().register( "Bearer", new BearerAuthSchemeProvider()).build(); b.setDefaultAuthSchemeRegistry(authSchemeRegistry); }); } // Set up the credentials customisation customiser = concat(customiser, b -> b.setDefaultCredentialsProvider(credentialsProvider)); if (preemptiveAuth && credentials instanceof BearerCredentials) customiser = concat(customiser, b -> b.addInterceptorFirst(new PreemptiveBearerAuthInterceptor())); else customiser = concat(customiser, b -> b.addInterceptorLast(new PreemptiveBasicAuthInterceptor())); } // If cookies are enabled then set up a cookie store if (storeCookies) customiser = concat(customiser, b -> b.setDefaultCookieStore(new BasicCookieStore())); return customiser; }
[ "public", "Consumer", "<", "HttpClientBuilder", ">", "createHttpClientCustomiser", "(", "final", "boolean", "fastFail", ",", "final", "AuthScope", "authScope", ",", "final", "Credentials", "credentials", ",", "final", "boolean", "preemptiveAuth", ",", "final", "boolean", "storeCookies", ",", "Consumer", "<", "HttpClientBuilder", ">", "customiser", ")", "{", "// Customise timeouts if fast fail mode is enabled", "if", "(", "fastFail", ")", "{", "customiser", "=", "concat", "(", "customiser", ",", "b", "->", "{", "RequestConfig", ".", "Builder", "requestBuilder", "=", "RequestConfig", ".", "custom", "(", ")", ";", "requestBuilder", ".", "setConnectTimeout", "(", "(", "int", ")", "fastFailConnectionTimeout", ".", "getMilliseconds", "(", ")", ")", ".", "setSocketTimeout", "(", "(", "int", ")", "fastFailSocketTimeout", ".", "getMilliseconds", "(", ")", ")", ";", "b", ".", "setDefaultRequestConfig", "(", "requestBuilder", ".", "build", "(", ")", ")", ";", "}", ")", ";", "}", "// If credentials were supplied then we should set them up", "if", "(", "credentials", "!=", "null", ")", "{", "CredentialsProvider", "credentialsProvider", "=", "new", "BasicCredentialsProvider", "(", ")", ";", "if", "(", "authScope", "!=", "null", ")", "credentialsProvider", ".", "setCredentials", "(", "authScope", ",", "credentials", ")", ";", "else", "credentialsProvider", ".", "setCredentials", "(", "AuthScope", ".", "ANY", ",", "credentials", ")", ";", "// Set up bearer auth scheme provider if we're using bearer credentials", "if", "(", "credentials", "instanceof", "BearerCredentials", ")", "{", "customiser", "=", "concat", "(", "customiser", ",", "b", "->", "{", "Registry", "<", "AuthSchemeProvider", ">", "authSchemeRegistry", "=", "RegistryBuilder", ".", "<", "AuthSchemeProvider", ">", "create", "(", ")", ".", "register", "(", "\"Bearer\"", ",", "new", "BearerAuthSchemeProvider", "(", ")", ")", ".", "build", "(", ")", ";", "b", ".", "setDefaultAuthSchemeRegistry", "(", "authSchemeRegistry", ")", ";", "}", ")", ";", "}", "// Set up the credentials customisation", "customiser", "=", "concat", "(", "customiser", ",", "b", "->", "b", ".", "setDefaultCredentialsProvider", "(", "credentialsProvider", ")", ")", ";", "if", "(", "preemptiveAuth", "&&", "credentials", "instanceof", "BearerCredentials", ")", "customiser", "=", "concat", "(", "customiser", ",", "b", "->", "b", ".", "addInterceptorFirst", "(", "new", "PreemptiveBearerAuthInterceptor", "(", ")", ")", ")", ";", "else", "customiser", "=", "concat", "(", "customiser", ",", "b", "->", "b", ".", "addInterceptorLast", "(", "new", "PreemptiveBasicAuthInterceptor", "(", ")", ")", ")", ";", "}", "// If cookies are enabled then set up a cookie store", "if", "(", "storeCookies", ")", "customiser", "=", "concat", "(", "customiser", ",", "b", "->", "b", ".", "setDefaultCookieStore", "(", "new", "BasicCookieStore", "(", ")", ")", ")", ";", "return", "customiser", ";", "}" ]
N.B. This method signature may change in the future to add new parameters @param fastFail @param authScope @param credentials @param preemptiveAuth @param storeCookies @param customiser @return
[ "N", ".", "B", ".", "This", "method", "signature", "may", "change", "in", "the", "future", "to", "add", "new", "parameters" ]
d4025d2f881bc0542b1e004c5f65a1ccaf895836
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/guice/common/src/main/java/com/peterphi/std/guice/restclient/resteasy/impl/ResteasyClientFactoryImpl.java#L166-L223
142,261
petergeneric/stdlib
guice/common/src/main/java/com/peterphi/std/guice/restclient/resteasy/impl/ResteasyClientFactoryImpl.java
ResteasyClientFactoryImpl.createHttpClient
public CloseableHttpClient createHttpClient(final Consumer<HttpClientBuilder> customiser) { final HttpClientBuilder builder = HttpClientBuilder.create(); // By default set long call timeouts { RequestConfig.Builder requestBuilder = RequestConfig.custom(); requestBuilder.setConnectTimeout((int) connectionTimeout.getMilliseconds()) .setSocketTimeout((int) socketTimeout.getMilliseconds()); builder.setDefaultRequestConfig(requestBuilder.build()); } // Set the default keepalive setting if (noKeepalive) builder.setConnectionReuseStrategy(new NoConnectionReuseStrategy()); // By default share the common connection provider builder.setConnectionManager(connectionManager); // By default use the JRE default route planner for proxies builder.setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault())); // Allow customisation if (customiser != null) customiser.accept(builder); return builder.build(); }
java
public CloseableHttpClient createHttpClient(final Consumer<HttpClientBuilder> customiser) { final HttpClientBuilder builder = HttpClientBuilder.create(); // By default set long call timeouts { RequestConfig.Builder requestBuilder = RequestConfig.custom(); requestBuilder.setConnectTimeout((int) connectionTimeout.getMilliseconds()) .setSocketTimeout((int) socketTimeout.getMilliseconds()); builder.setDefaultRequestConfig(requestBuilder.build()); } // Set the default keepalive setting if (noKeepalive) builder.setConnectionReuseStrategy(new NoConnectionReuseStrategy()); // By default share the common connection provider builder.setConnectionManager(connectionManager); // By default use the JRE default route planner for proxies builder.setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault())); // Allow customisation if (customiser != null) customiser.accept(builder); return builder.build(); }
[ "public", "CloseableHttpClient", "createHttpClient", "(", "final", "Consumer", "<", "HttpClientBuilder", ">", "customiser", ")", "{", "final", "HttpClientBuilder", "builder", "=", "HttpClientBuilder", ".", "create", "(", ")", ";", "// By default set long call timeouts", "{", "RequestConfig", ".", "Builder", "requestBuilder", "=", "RequestConfig", ".", "custom", "(", ")", ";", "requestBuilder", ".", "setConnectTimeout", "(", "(", "int", ")", "connectionTimeout", ".", "getMilliseconds", "(", ")", ")", ".", "setSocketTimeout", "(", "(", "int", ")", "socketTimeout", ".", "getMilliseconds", "(", ")", ")", ";", "builder", ".", "setDefaultRequestConfig", "(", "requestBuilder", ".", "build", "(", ")", ")", ";", "}", "// Set the default keepalive setting", "if", "(", "noKeepalive", ")", "builder", ".", "setConnectionReuseStrategy", "(", "new", "NoConnectionReuseStrategy", "(", ")", ")", ";", "// By default share the common connection provider", "builder", ".", "setConnectionManager", "(", "connectionManager", ")", ";", "// By default use the JRE default route planner for proxies", "builder", ".", "setRoutePlanner", "(", "new", "SystemDefaultRoutePlanner", "(", "ProxySelector", ".", "getDefault", "(", ")", ")", ")", ";", "// Allow customisation", "if", "(", "customiser", "!=", "null", ")", "customiser", ".", "accept", "(", "builder", ")", ";", "return", "builder", ".", "build", "(", ")", ";", "}" ]
Build an HttpClient @param customiser @return
[ "Build", "an", "HttpClient" ]
d4025d2f881bc0542b1e004c5f65a1ccaf895836
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/guice/common/src/main/java/com/peterphi/std/guice/restclient/resteasy/impl/ResteasyClientFactoryImpl.java#L264-L293
142,262
petergeneric/stdlib
stdlib/src/main/java/com/peterphi/std/types/StorageSize.java
StorageSize.multiply
public StorageSize multiply(BigInteger by) { final BigInteger result = getBits().multiply(by); return new StorageSize(getUnit(), result); }
java
public StorageSize multiply(BigInteger by) { final BigInteger result = getBits().multiply(by); return new StorageSize(getUnit(), result); }
[ "public", "StorageSize", "multiply", "(", "BigInteger", "by", ")", "{", "final", "BigInteger", "result", "=", "getBits", "(", ")", ".", "multiply", "(", "by", ")", ";", "return", "new", "StorageSize", "(", "getUnit", "(", ")", ",", "result", ")", ";", "}" ]
Multiplies the storage size by a certain amount @param that @return
[ "Multiplies", "the", "storage", "size", "by", "a", "certain", "amount" ]
d4025d2f881bc0542b1e004c5f65a1ccaf895836
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/stdlib/src/main/java/com/peterphi/std/types/StorageSize.java#L378-L383
142,263
petergeneric/stdlib
stdlib/src/main/java/com/peterphi/std/types/StorageSize.java
StorageSize.subtract
public StorageSize subtract(StorageSize that) { StorageUnit smallestUnit = StorageUnit.smallest(this.getUnit(), that.getUnit()); final BigInteger a = this.getBits(); final BigInteger b = that.getBits(); final BigInteger result = a.subtract(b); return new StorageSize(smallestUnit, result); }
java
public StorageSize subtract(StorageSize that) { StorageUnit smallestUnit = StorageUnit.smallest(this.getUnit(), that.getUnit()); final BigInteger a = this.getBits(); final BigInteger b = that.getBits(); final BigInteger result = a.subtract(b); return new StorageSize(smallestUnit, result); }
[ "public", "StorageSize", "subtract", "(", "StorageSize", "that", ")", "{", "StorageUnit", "smallestUnit", "=", "StorageUnit", ".", "smallest", "(", "this", ".", "getUnit", "(", ")", ",", "that", ".", "getUnit", "(", ")", ")", ";", "final", "BigInteger", "a", "=", "this", ".", "getBits", "(", ")", ";", "final", "BigInteger", "b", "=", "that", ".", "getBits", "(", ")", ";", "final", "BigInteger", "result", "=", "a", ".", "subtract", "(", "b", ")", ";", "return", "new", "StorageSize", "(", "smallestUnit", ",", "result", ")", ";", "}" ]
Subtracts a storage size from the current object, using the smallest unit as the resulting StorageSize's unit @param storage @return
[ "Subtracts", "a", "storage", "size", "from", "the", "current", "object", "using", "the", "smallest", "unit", "as", "the", "resulting", "StorageSize", "s", "unit" ]
d4025d2f881bc0542b1e004c5f65a1ccaf895836
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/stdlib/src/main/java/com/peterphi/std/types/StorageSize.java#L393-L402
142,264
petergeneric/stdlib
guice/webapp/src/main/java/com/peterphi/std/guice/web/rest/auth/oauth2/RedirectToOAuthAccessRefuser.java
RedirectToOAuthAccessRefuser.isHtmlAcceptable
private boolean isHtmlAcceptable(HttpServletRequest request) { @SuppressWarnings("unchecked") final List<String> accepts = ListUtility.list(ListUtility.iterate(request.getHeaders( HttpHeaderNames.ACCEPT))); for (String accept : accepts) { if (StringUtils.startsWithIgnoreCase(accept, "text/html")) return true; } return false; }
java
private boolean isHtmlAcceptable(HttpServletRequest request) { @SuppressWarnings("unchecked") final List<String> accepts = ListUtility.list(ListUtility.iterate(request.getHeaders( HttpHeaderNames.ACCEPT))); for (String accept : accepts) { if (StringUtils.startsWithIgnoreCase(accept, "text/html")) return true; } return false; }
[ "private", "boolean", "isHtmlAcceptable", "(", "HttpServletRequest", "request", ")", "{", "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "final", "List", "<", "String", ">", "accepts", "=", "ListUtility", ".", "list", "(", "ListUtility", ".", "iterate", "(", "request", ".", "getHeaders", "(", "HttpHeaderNames", ".", "ACCEPT", ")", ")", ")", ";", "for", "(", "String", "accept", ":", "accepts", ")", "{", "if", "(", "StringUtils", ".", "startsWithIgnoreCase", "(", "accept", ",", "\"text/html\"", ")", ")", "return", "true", ";", "}", "return", "false", ";", "}" ]
Decides if an HTML response is acceptable to the client @param request @return
[ "Decides", "if", "an", "HTML", "response", "is", "acceptable", "to", "the", "client" ]
d4025d2f881bc0542b1e004c5f65a1ccaf895836
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/guice/webapp/src/main/java/com/peterphi/std/guice/web/rest/auth/oauth2/RedirectToOAuthAccessRefuser.java#L118-L130
142,265
petergeneric/stdlib
guice/common/src/main/java/com/peterphi/std/guice/apploader/impl/GuiceInjectorBootstrap.java
GuiceInjectorBootstrap.createInjector
public static Injector createInjector(final PropertyFile configuration, final GuiceSetup setup) { return new GuiceBuilder().withConfig(configuration).withSetup(setup).build(); }
java
public static Injector createInjector(final PropertyFile configuration, final GuiceSetup setup) { return new GuiceBuilder().withConfig(configuration).withSetup(setup).build(); }
[ "public", "static", "Injector", "createInjector", "(", "final", "PropertyFile", "configuration", ",", "final", "GuiceSetup", "setup", ")", "{", "return", "new", "GuiceBuilder", "(", ")", ".", "withConfig", "(", "configuration", ")", ".", "withSetup", "(", "setup", ")", ".", "build", "(", ")", ";", "}" ]
Creates an Injector by taking a preloaded service.properties and a pre-constructed GuiceSetup @param properties @param setup @return
[ "Creates", "an", "Injector", "by", "taking", "a", "preloaded", "service", ".", "properties", "and", "a", "pre", "-", "constructed", "GuiceSetup" ]
d4025d2f881bc0542b1e004c5f65a1ccaf895836
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/guice/common/src/main/java/com/peterphi/std/guice/apploader/impl/GuiceInjectorBootstrap.java#L57-L60
142,266
ziccardi/jnrpe
jnrpe-lib/src/main/java/it/jnrpe/ReturnValue.java
ReturnValue.getMessage
public String getMessage() { if (performanceDataList.isEmpty()) { return messageString; } StringBuilder res = new StringBuilder(messageString).append('|'); for (PerformanceData pd : performanceDataList) { res.append(pd.toPerformanceString()).append(' '); } return res.toString(); }
java
public String getMessage() { if (performanceDataList.isEmpty()) { return messageString; } StringBuilder res = new StringBuilder(messageString).append('|'); for (PerformanceData pd : performanceDataList) { res.append(pd.toPerformanceString()).append(' '); } return res.toString(); }
[ "public", "String", "getMessage", "(", ")", "{", "if", "(", "performanceDataList", ".", "isEmpty", "(", ")", ")", "{", "return", "messageString", ";", "}", "StringBuilder", "res", "=", "new", "StringBuilder", "(", "messageString", ")", ".", "append", "(", "'", "'", ")", ";", "for", "(", "PerformanceData", "pd", ":", "performanceDataList", ")", "{", "res", ".", "append", "(", "pd", ".", "toPerformanceString", "(", ")", ")", ".", "append", "(", "'", "'", ")", ";", "}", "return", "res", ".", "toString", "(", ")", ";", "}" ]
Returns the message. If the performance data has been passed in, they are attached at the end of the message accordingly to the Nagios specifications @return The message and optionally the performance data
[ "Returns", "the", "message", ".", "If", "the", "performance", "data", "has", "been", "passed", "in", "they", "are", "attached", "at", "the", "end", "of", "the", "message", "accordingly", "to", "the", "Nagios", "specifications" ]
ac9046355851136994388442b01ba4063305f9c4
https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-lib/src/main/java/it/jnrpe/ReturnValue.java#L211-L220
142,267
petergeneric/stdlib
service-manager/service-manager/src/main/java/com/peterphi/servicemanager/service/rest/resource/daemon/AzureInstanceActionDaemon.java
AzureInstanceActionDaemon.start
private void start(final ResourceInstanceEntity instance) { azure.start(instance.getProviderInstanceId()); instance.setState(ResourceInstanceState.PROVISIONING); }
java
private void start(final ResourceInstanceEntity instance) { azure.start(instance.getProviderInstanceId()); instance.setState(ResourceInstanceState.PROVISIONING); }
[ "private", "void", "start", "(", "final", "ResourceInstanceEntity", "instance", ")", "{", "azure", ".", "start", "(", "instance", ".", "getProviderInstanceId", "(", ")", ")", ";", "instance", ".", "setState", "(", "ResourceInstanceState", ".", "PROVISIONING", ")", ";", "}" ]
Start the instance
[ "Start", "the", "instance" ]
d4025d2f881bc0542b1e004c5f65a1ccaf895836
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/service-manager/service-manager/src/main/java/com/peterphi/servicemanager/service/rest/resource/daemon/AzureInstanceActionDaemon.java#L87-L92
142,268
petergeneric/stdlib
service-manager/service-manager/src/main/java/com/peterphi/servicemanager/service/rest/resource/daemon/AzureInstanceActionDaemon.java
AzureInstanceActionDaemon.stop
private void stop(final ResourceInstanceEntity instance) { azure.stop(instance); instance.setState(ResourceInstanceState.DISCARDING); }
java
private void stop(final ResourceInstanceEntity instance) { azure.stop(instance); instance.setState(ResourceInstanceState.DISCARDING); }
[ "private", "void", "stop", "(", "final", "ResourceInstanceEntity", "instance", ")", "{", "azure", ".", "stop", "(", "instance", ")", ";", "instance", ".", "setState", "(", "ResourceInstanceState", ".", "DISCARDING", ")", ";", "}" ]
Stop the instance
[ "Stop", "the", "instance" ]
d4025d2f881bc0542b1e004c5f65a1ccaf895836
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/service-manager/service-manager/src/main/java/com/peterphi/servicemanager/service/rest/resource/daemon/AzureInstanceActionDaemon.java#L96-L101
142,269
petergeneric/stdlib
service-manager/service-manager/src/main/java/com/peterphi/servicemanager/service/rest/resource/daemon/AzureInstanceActionDaemon.java
AzureInstanceActionDaemon.updateState
private void updateState(final ResourceInstanceEntity instance) { ResourceInstanceState actual = azure.determineState(instance); instance.setState(actual); }
java
private void updateState(final ResourceInstanceEntity instance) { ResourceInstanceState actual = azure.determineState(instance); instance.setState(actual); }
[ "private", "void", "updateState", "(", "final", "ResourceInstanceEntity", "instance", ")", "{", "ResourceInstanceState", "actual", "=", "azure", ".", "determineState", "(", "instance", ")", ";", "instance", ".", "setState", "(", "actual", ")", ";", "}" ]
Check in with Azure on the instance state
[ "Check", "in", "with", "Azure", "on", "the", "instance", "state" ]
d4025d2f881bc0542b1e004c5f65a1ccaf895836
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/service-manager/service-manager/src/main/java/com/peterphi/servicemanager/service/rest/resource/daemon/AzureInstanceActionDaemon.java#L105-L110
142,270
ziccardi/jnrpe
jnrpe-lib/src/main/java/it/jnrpe/net/JNRPEIdleStateHandler.java
JNRPEIdleStateHandler.userEventTriggered
@Override public void userEventTriggered(final ChannelHandlerContext ctx, final Object evt) { if (evt instanceof IdleStateEvent) { IdleStateEvent e = (IdleStateEvent) evt; if (e.state() == IdleState.READER_IDLE) { ctx.close(); LOG.warn(jnrpeContext, "Read Timeout"); //jnrpeContext.getEventBus().post(new LogEvent(this, LogEventType.INFO, "Read Timeout")); //EventsUtil.sendEvent(this.jnrpeContext, this, LogEvent.INFO, "Read Timeout"); } else if (e.state() == IdleState.WRITER_IDLE) { LOG.warn(jnrpeContext, "Write Timeout"); //jnrpeContext.getEventBus().post(new LogEvent(this, LogEventType.INFO, "Write Timeout")); //EventsUtil.sendEvent(jnrpeContext, this, LogEvent.INFO, "Write Timeout"); ctx.close(); } } }
java
@Override public void userEventTriggered(final ChannelHandlerContext ctx, final Object evt) { if (evt instanceof IdleStateEvent) { IdleStateEvent e = (IdleStateEvent) evt; if (e.state() == IdleState.READER_IDLE) { ctx.close(); LOG.warn(jnrpeContext, "Read Timeout"); //jnrpeContext.getEventBus().post(new LogEvent(this, LogEventType.INFO, "Read Timeout")); //EventsUtil.sendEvent(this.jnrpeContext, this, LogEvent.INFO, "Read Timeout"); } else if (e.state() == IdleState.WRITER_IDLE) { LOG.warn(jnrpeContext, "Write Timeout"); //jnrpeContext.getEventBus().post(new LogEvent(this, LogEventType.INFO, "Write Timeout")); //EventsUtil.sendEvent(jnrpeContext, this, LogEvent.INFO, "Write Timeout"); ctx.close(); } } }
[ "@", "Override", "public", "void", "userEventTriggered", "(", "final", "ChannelHandlerContext", "ctx", ",", "final", "Object", "evt", ")", "{", "if", "(", "evt", "instanceof", "IdleStateEvent", ")", "{", "IdleStateEvent", "e", "=", "(", "IdleStateEvent", ")", "evt", ";", "if", "(", "e", ".", "state", "(", ")", "==", "IdleState", ".", "READER_IDLE", ")", "{", "ctx", ".", "close", "(", ")", ";", "LOG", ".", "warn", "(", "jnrpeContext", ",", "\"Read Timeout\"", ")", ";", "//jnrpeContext.getEventBus().post(new LogEvent(this, LogEventType.INFO, \"Read Timeout\"));", "//EventsUtil.sendEvent(this.jnrpeContext, this, LogEvent.INFO, \"Read Timeout\");", "}", "else", "if", "(", "e", ".", "state", "(", ")", "==", "IdleState", ".", "WRITER_IDLE", ")", "{", "LOG", ".", "warn", "(", "jnrpeContext", ",", "\"Write Timeout\"", ")", ";", "//jnrpeContext.getEventBus().post(new LogEvent(this, LogEventType.INFO, \"Write Timeout\"));", "//EventsUtil.sendEvent(jnrpeContext, this, LogEvent.INFO, \"Write Timeout\");", "ctx", ".", "close", "(", ")", ";", "}", "}", "}" ]
Method userEventTriggered. @param ctx ChannelHandlerContext @param evt Object @see io.netty.channel.ChannelInboundHandler#userEventTriggered(ChannelHandlerContext, Object)
[ "Method", "userEventTriggered", "." ]
ac9046355851136994388442b01ba4063305f9c4
https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-lib/src/main/java/it/jnrpe/net/JNRPEIdleStateHandler.java#L59-L75
142,271
petergeneric/stdlib
guice/webapp/src/main/java/com/peterphi/std/guice/web/rest/service/servicedescription/freemarker/RestServiceInfo.java
RestServiceInfo.truncatePath
static String truncatePath(String path, String commonPrefix) { final int nextSlash = path.indexOf('/', commonPrefix.length()); final int nextOpenCurly = path.indexOf('{', commonPrefix.length()); if (nextSlash > 0) return path.substring(0, nextSlash); else if (nextOpenCurly > 0) return path.substring(0, nextOpenCurly); else return path; }
java
static String truncatePath(String path, String commonPrefix) { final int nextSlash = path.indexOf('/', commonPrefix.length()); final int nextOpenCurly = path.indexOf('{', commonPrefix.length()); if (nextSlash > 0) return path.substring(0, nextSlash); else if (nextOpenCurly > 0) return path.substring(0, nextOpenCurly); else return path; }
[ "static", "String", "truncatePath", "(", "String", "path", ",", "String", "commonPrefix", ")", "{", "final", "int", "nextSlash", "=", "path", ".", "indexOf", "(", "'", "'", ",", "commonPrefix", ".", "length", "(", ")", ")", ";", "final", "int", "nextOpenCurly", "=", "path", ".", "indexOf", "(", "'", "'", ",", "commonPrefix", ".", "length", "(", ")", ")", ";", "if", "(", "nextSlash", ">", "0", ")", "return", "path", ".", "substring", "(", "0", ",", "nextSlash", ")", ";", "else", "if", "(", "nextOpenCurly", ">", "0", ")", "return", "path", ".", "substring", "(", "0", ",", "nextOpenCurly", ")", ";", "else", "return", "path", ";", "}" ]
Truncate path to the completion of the segment ending with the common prefix @param path @param commonPrefix @return
[ "Truncate", "path", "to", "the", "completion", "of", "the", "segment", "ending", "with", "the", "common", "prefix" ]
d4025d2f881bc0542b1e004c5f65a1ccaf895836
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/guice/webapp/src/main/java/com/peterphi/std/guice/web/rest/service/servicedescription/freemarker/RestServiceInfo.java#L93-L104
142,272
petergeneric/stdlib
util/carbon-client/src/main/java/com/peterphi/carbon/type/mutable/CarbonSource.java
CarbonSource.setFilterGUIDs
public void setFilterGUIDs(List<String> filterGUIDs) { int i = 0; for (String filterGUID : filterGUIDs) { // Remove filters (we're replacing them) removeFilter("Filter_" + i); // Build a new Filter_0 element Element filter = buildFilterElement("Filter_" + i, filterGUID); element.addContent(filter); i++; } }
java
public void setFilterGUIDs(List<String> filterGUIDs) { int i = 0; for (String filterGUID : filterGUIDs) { // Remove filters (we're replacing them) removeFilter("Filter_" + i); // Build a new Filter_0 element Element filter = buildFilterElement("Filter_" + i, filterGUID); element.addContent(filter); i++; } }
[ "public", "void", "setFilterGUIDs", "(", "List", "<", "String", ">", "filterGUIDs", ")", "{", "int", "i", "=", "0", ";", "for", "(", "String", "filterGUID", ":", "filterGUIDs", ")", "{", "// Remove filters (we're replacing them)", "removeFilter", "(", "\"Filter_\"", "+", "i", ")", ";", "// Build a new Filter_0 element", "Element", "filter", "=", "buildFilterElement", "(", "\"Filter_\"", "+", "i", ",", "filterGUID", ")", ";", "element", ".", "addContent", "(", "filter", ")", ";", "i", "++", ";", "}", "}" ]
Set the filter GUID, replacing any filter that is currently defined @param filterGUIDs
[ "Set", "the", "filter", "GUID", "replacing", "any", "filter", "that", "is", "currently", "defined" ]
d4025d2f881bc0542b1e004c5f65a1ccaf895836
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/util/carbon-client/src/main/java/com/peterphi/carbon/type/mutable/CarbonSource.java#L126-L142
142,273
petergeneric/stdlib
guice/common/src/main/java/com/peterphi/std/guice/common/ognl/OgnlFactory.java
OgnlFactory.getInstance
public static OgnlEvaluator getInstance(final Object root, final String expression) { final OgnlEvaluatorCollection collection = INSTANCE.getEvaluators(getRootClass(root)); return collection.get(expression); }
java
public static OgnlEvaluator getInstance(final Object root, final String expression) { final OgnlEvaluatorCollection collection = INSTANCE.getEvaluators(getRootClass(root)); return collection.get(expression); }
[ "public", "static", "OgnlEvaluator", "getInstance", "(", "final", "Object", "root", ",", "final", "String", "expression", ")", "{", "final", "OgnlEvaluatorCollection", "collection", "=", "INSTANCE", ".", "getEvaluators", "(", "getRootClass", "(", "root", ")", ")", ";", "return", "collection", ".", "get", "(", "expression", ")", ";", "}" ]
Get an OGNL Evaluator for a particular expression with a given input @param root an example instance of the root object that will be passed to this OGNL evaluator @param expression the OGNL expression @return @see <a href="https://commons.apache.org/proper/commons-ognl/language-guide.html">OGNL Language Guide</a>
[ "Get", "an", "OGNL", "Evaluator", "for", "a", "particular", "expression", "with", "a", "given", "input" ]
d4025d2f881bc0542b1e004c5f65a1ccaf895836
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/guice/common/src/main/java/com/peterphi/std/guice/common/ognl/OgnlFactory.java#L61-L66
142,274
petergeneric/stdlib
stdlib/src/main/java/com/peterphi/std/io/PropertyFile.java
PropertyFile.find
public static PropertyFile find(final ClassLoader classloader, final String... fileNames) { URL resolvedResource = null; String resolvedFile = null; for (String fileName : fileNames) { if (fileName.charAt(0) == '/') { File file = new File(fileName); if (file.exists()) { try { return PropertyFile.readOnly(file); } catch (IOException e) { throw new IllegalArgumentException("Error loading property file: " + fileName + ". Error: " + e.getMessage(), e); } } } else { // Try to resolve the filename (for logging any errors) final URL resource = classloader.getResource(fileName); if (resource != null) { resolvedFile = fileName; resolvedResource = resource; break; } } } if (resolvedFile == null) { if (fileNames.length == 1) throw new IllegalArgumentException("Error finding property file in classpath: " + fileNames[0]); else throw new IllegalArgumentException("Error finding property files in classpath: " + Arrays.asList(fileNames)); } else if (log.isInfoEnabled()) log.info("{find} Loading properties from " + resolvedFile); return openResource(classloader, resolvedResource, resolvedFile); }
java
public static PropertyFile find(final ClassLoader classloader, final String... fileNames) { URL resolvedResource = null; String resolvedFile = null; for (String fileName : fileNames) { if (fileName.charAt(0) == '/') { File file = new File(fileName); if (file.exists()) { try { return PropertyFile.readOnly(file); } catch (IOException e) { throw new IllegalArgumentException("Error loading property file: " + fileName + ". Error: " + e.getMessage(), e); } } } else { // Try to resolve the filename (for logging any errors) final URL resource = classloader.getResource(fileName); if (resource != null) { resolvedFile = fileName; resolvedResource = resource; break; } } } if (resolvedFile == null) { if (fileNames.length == 1) throw new IllegalArgumentException("Error finding property file in classpath: " + fileNames[0]); else throw new IllegalArgumentException("Error finding property files in classpath: " + Arrays.asList(fileNames)); } else if (log.isInfoEnabled()) log.info("{find} Loading properties from " + resolvedFile); return openResource(classloader, resolvedResource, resolvedFile); }
[ "public", "static", "PropertyFile", "find", "(", "final", "ClassLoader", "classloader", ",", "final", "String", "...", "fileNames", ")", "{", "URL", "resolvedResource", "=", "null", ";", "String", "resolvedFile", "=", "null", ";", "for", "(", "String", "fileName", ":", "fileNames", ")", "{", "if", "(", "fileName", ".", "charAt", "(", "0", ")", "==", "'", "'", ")", "{", "File", "file", "=", "new", "File", "(", "fileName", ")", ";", "if", "(", "file", ".", "exists", "(", ")", ")", "{", "try", "{", "return", "PropertyFile", ".", "readOnly", "(", "file", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Error loading property file: \"", "+", "fileName", "+", "\". Error: \"", "+", "e", ".", "getMessage", "(", ")", ",", "e", ")", ";", "}", "}", "}", "else", "{", "// Try to resolve the filename (for logging any errors)", "final", "URL", "resource", "=", "classloader", ".", "getResource", "(", "fileName", ")", ";", "if", "(", "resource", "!=", "null", ")", "{", "resolvedFile", "=", "fileName", ";", "resolvedResource", "=", "resource", ";", "break", ";", "}", "}", "}", "if", "(", "resolvedFile", "==", "null", ")", "{", "if", "(", "fileNames", ".", "length", "==", "1", ")", "throw", "new", "IllegalArgumentException", "(", "\"Error finding property file in classpath: \"", "+", "fileNames", "[", "0", "]", ")", ";", "else", "throw", "new", "IllegalArgumentException", "(", "\"Error finding property files in classpath: \"", "+", "Arrays", ".", "asList", "(", "fileNames", ")", ")", ";", "}", "else", "if", "(", "log", ".", "isInfoEnabled", "(", ")", ")", "log", ".", "info", "(", "\"{find} Loading properties from \"", "+", "resolvedFile", ")", ";", "return", "openResource", "(", "classloader", ",", "resolvedResource", ",", "resolvedFile", ")", ";", "}" ]
Find a property file @param classloader @param fileName @return
[ "Find", "a", "property", "file" ]
d4025d2f881bc0542b1e004c5f65a1ccaf895836
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/stdlib/src/main/java/com/peterphi/std/io/PropertyFile.java#L92-L143
142,275
petergeneric/stdlib
guice/hibernate/src/main/java/com/peterphi/std/guice/hibernate/webquery/impl/jpa/JPAQueryBuilder.java
JPAQueryBuilder.getClassesByDiscriminators
private List<Class<?>> getClassesByDiscriminators(Collection<String> discriminators) { Map<String, Class<?>> entitiesByName = new HashMap<>(); // Prepare a Map of discriminator name -> entity class for (QEntity child : entity.getSubEntities()) { entitiesByName.put(child.getDiscriminatorValue(), child.getEntityClass()); } // If the root class isn't abstract then add it to the list of possible discriminators too if (!entity.isEntityClassAbstract()) entitiesByName.put(entity.getDiscriminatorValue(), entity.getEntityClass()); // Translate the discriminator string values to classes List<Class<?>> classes = new ArrayList<>(discriminators.size()); for (String discriminator : discriminators) { final Class<?> clazz = entitiesByName.get(discriminator); if (clazz != null) classes.add(clazz); else throw new IllegalArgumentException("Invalid class discriminator '" + discriminator + "', expected one of: " + entitiesByName.keySet()); } return classes; }
java
private List<Class<?>> getClassesByDiscriminators(Collection<String> discriminators) { Map<String, Class<?>> entitiesByName = new HashMap<>(); // Prepare a Map of discriminator name -> entity class for (QEntity child : entity.getSubEntities()) { entitiesByName.put(child.getDiscriminatorValue(), child.getEntityClass()); } // If the root class isn't abstract then add it to the list of possible discriminators too if (!entity.isEntityClassAbstract()) entitiesByName.put(entity.getDiscriminatorValue(), entity.getEntityClass()); // Translate the discriminator string values to classes List<Class<?>> classes = new ArrayList<>(discriminators.size()); for (String discriminator : discriminators) { final Class<?> clazz = entitiesByName.get(discriminator); if (clazz != null) classes.add(clazz); else throw new IllegalArgumentException("Invalid class discriminator '" + discriminator + "', expected one of: " + entitiesByName.keySet()); } return classes; }
[ "private", "List", "<", "Class", "<", "?", ">", ">", "getClassesByDiscriminators", "(", "Collection", "<", "String", ">", "discriminators", ")", "{", "Map", "<", "String", ",", "Class", "<", "?", ">", ">", "entitiesByName", "=", "new", "HashMap", "<>", "(", ")", ";", "// Prepare a Map of discriminator name -> entity class", "for", "(", "QEntity", "child", ":", "entity", ".", "getSubEntities", "(", ")", ")", "{", "entitiesByName", ".", "put", "(", "child", ".", "getDiscriminatorValue", "(", ")", ",", "child", ".", "getEntityClass", "(", ")", ")", ";", "}", "// If the root class isn't abstract then add it to the list of possible discriminators too", "if", "(", "!", "entity", ".", "isEntityClassAbstract", "(", ")", ")", "entitiesByName", ".", "put", "(", "entity", ".", "getDiscriminatorValue", "(", ")", ",", "entity", ".", "getEntityClass", "(", ")", ")", ";", "// Translate the discriminator string values to classes", "List", "<", "Class", "<", "?", ">", ">", "classes", "=", "new", "ArrayList", "<>", "(", "discriminators", ".", "size", "(", ")", ")", ";", "for", "(", "String", "discriminator", ":", "discriminators", ")", "{", "final", "Class", "<", "?", ">", "clazz", "=", "entitiesByName", ".", "get", "(", "discriminator", ")", ";", "if", "(", "clazz", "!=", "null", ")", "classes", ".", "add", "(", "clazz", ")", ";", "else", "throw", "new", "IllegalArgumentException", "(", "\"Invalid class discriminator '\"", "+", "discriminator", "+", "\"', expected one of: \"", "+", "entitiesByName", ".", "keySet", "(", ")", ")", ";", "}", "return", "classes", ";", "}" ]
Translates the set of string discriminators into entity classes @return
[ "Translates", "the", "set", "of", "string", "discriminators", "into", "entity", "classes" ]
d4025d2f881bc0542b1e004c5f65a1ccaf895836
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/guice/hibernate/src/main/java/com/peterphi/std/guice/hibernate/webquery/impl/jpa/JPAQueryBuilder.java#L110-L140
142,276
petergeneric/stdlib
guice/hibernate/src/main/java/com/peterphi/std/guice/hibernate/webquery/impl/jpa/JPAQueryBuilder.java
JPAQueryBuilder.getProperty
@Override public Expression<?> getProperty(final WQPath path) { final JPAJoin join = getOrCreateJoin(path.getTail()); return join.property(path.getHead().getPath()); }
java
@Override public Expression<?> getProperty(final WQPath path) { final JPAJoin join = getOrCreateJoin(path.getTail()); return join.property(path.getHead().getPath()); }
[ "@", "Override", "public", "Expression", "<", "?", ">", "getProperty", "(", "final", "WQPath", "path", ")", "{", "final", "JPAJoin", "join", "=", "getOrCreateJoin", "(", "path", ".", "getTail", "(", ")", ")", ";", "return", "join", ".", "property", "(", "path", ".", "getHead", "(", ")", ".", "getPath", "(", ")", ")", ";", "}" ]
Get a property, automatically creating any joins along the way as needed @param path @return
[ "Get", "a", "property", "automatically", "creating", "any", "joins", "along", "the", "way", "as", "needed" ]
d4025d2f881bc0542b1e004c5f65a1ccaf895836
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/guice/hibernate/src/main/java/com/peterphi/std/guice/hibernate/webquery/impl/jpa/JPAQueryBuilder.java#L180-L186
142,277
petergeneric/stdlib
guice/hibernate/src/main/java/com/peterphi/std/guice/hibernate/webquery/impl/jpa/JPAQueryBuilder.java
JPAQueryBuilder.getOrCreateJoin
@Override public JPAJoin getOrCreateJoin(final WQPath path) { if (path == null) return new JPAJoin(criteriaBuilder, entity, root, false); if (!joins.containsKey(path.getPath())) { final JPAJoin parent = getOrCreateJoin(path.getTail()); final JPAJoin join = parent.join(path.getHead().getPath()); joins.put(path.getPath(), join); return join; } else { return joins.get(path.getPath()); } }
java
@Override public JPAJoin getOrCreateJoin(final WQPath path) { if (path == null) return new JPAJoin(criteriaBuilder, entity, root, false); if (!joins.containsKey(path.getPath())) { final JPAJoin parent = getOrCreateJoin(path.getTail()); final JPAJoin join = parent.join(path.getHead().getPath()); joins.put(path.getPath(), join); return join; } else { return joins.get(path.getPath()); } }
[ "@", "Override", "public", "JPAJoin", "getOrCreateJoin", "(", "final", "WQPath", "path", ")", "{", "if", "(", "path", "==", "null", ")", "return", "new", "JPAJoin", "(", "criteriaBuilder", ",", "entity", ",", "root", ",", "false", ")", ";", "if", "(", "!", "joins", ".", "containsKey", "(", "path", ".", "getPath", "(", ")", ")", ")", "{", "final", "JPAJoin", "parent", "=", "getOrCreateJoin", "(", "path", ".", "getTail", "(", ")", ")", ";", "final", "JPAJoin", "join", "=", "parent", ".", "join", "(", "path", ".", "getHead", "(", ")", ".", "getPath", "(", ")", ")", ";", "joins", ".", "put", "(", "path", ".", "getPath", "(", ")", ",", "join", ")", ";", "return", "join", ";", "}", "else", "{", "return", "joins", ".", "get", "(", "path", ".", "getPath", "(", ")", ")", ";", "}", "}" ]
Ensure a join has been set up for a path @param path @return
[ "Ensure", "a", "join", "has", "been", "set", "up", "for", "a", "path" ]
d4025d2f881bc0542b1e004c5f65a1ccaf895836
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/guice/hibernate/src/main/java/com/peterphi/std/guice/hibernate/webquery/impl/jpa/JPAQueryBuilder.java#L196-L216
142,278
petergeneric/stdlib
guice/hibernate/src/main/java/com/peterphi/std/guice/hibernate/webquery/impl/jpa/JPAQueryBuilder.java
JPAQueryBuilder.hasCollectionFetch
public boolean hasCollectionFetch() { if (fetches != null) for (String fetch : fetches) { QEntity parent = entity; final String[] parts = StringUtils.split(fetch, '.'); for (int i = 0; i < parts.length; i++) { // If this is a fully supported relation then continue checking if (parent.hasRelation(parts[i])) { final QRelation relation = parent.getRelation(parts[i]); parent = relation.getEntity(); if (relation.isCollection()) { if (log.isTraceEnabled()) log.trace("Encountered fetch " + fetch + ". This resolves to " + relation + " which is a collection"); return true; } } // This covers partially-supported things like Map and other basic collections that don't have a QRelation description else if (parent.hasNonEntityRelation(parts[i])) { if (parent.isNonEntityRelationCollection(parts[i])) return true; } else { log.warn("Encountered relation " + parts[i] + " on " + parent.getName() + " as part of path " + fetch + ". Assuming QEntity simply does not know this relation. Assuming worst case scenario (collection join is involved)"); return true; } } } return false; }
java
public boolean hasCollectionFetch() { if (fetches != null) for (String fetch : fetches) { QEntity parent = entity; final String[] parts = StringUtils.split(fetch, '.'); for (int i = 0; i < parts.length; i++) { // If this is a fully supported relation then continue checking if (parent.hasRelation(parts[i])) { final QRelation relation = parent.getRelation(parts[i]); parent = relation.getEntity(); if (relation.isCollection()) { if (log.isTraceEnabled()) log.trace("Encountered fetch " + fetch + ". This resolves to " + relation + " which is a collection"); return true; } } // This covers partially-supported things like Map and other basic collections that don't have a QRelation description else if (parent.hasNonEntityRelation(parts[i])) { if (parent.isNonEntityRelationCollection(parts[i])) return true; } else { log.warn("Encountered relation " + parts[i] + " on " + parent.getName() + " as part of path " + fetch + ". Assuming QEntity simply does not know this relation. Assuming worst case scenario (collection join is involved)"); return true; } } } return false; }
[ "public", "boolean", "hasCollectionFetch", "(", ")", "{", "if", "(", "fetches", "!=", "null", ")", "for", "(", "String", "fetch", ":", "fetches", ")", "{", "QEntity", "parent", "=", "entity", ";", "final", "String", "[", "]", "parts", "=", "StringUtils", ".", "split", "(", "fetch", ",", "'", "'", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "parts", ".", "length", ";", "i", "++", ")", "{", "// If this is a fully supported relation then continue checking", "if", "(", "parent", ".", "hasRelation", "(", "parts", "[", "i", "]", ")", ")", "{", "final", "QRelation", "relation", "=", "parent", ".", "getRelation", "(", "parts", "[", "i", "]", ")", ";", "parent", "=", "relation", ".", "getEntity", "(", ")", ";", "if", "(", "relation", ".", "isCollection", "(", ")", ")", "{", "if", "(", "log", ".", "isTraceEnabled", "(", ")", ")", "log", ".", "trace", "(", "\"Encountered fetch \"", "+", "fetch", "+", "\". This resolves to \"", "+", "relation", "+", "\" which is a collection\"", ")", ";", "return", "true", ";", "}", "}", "// This covers partially-supported things like Map and other basic collections that don't have a QRelation description", "else", "if", "(", "parent", ".", "hasNonEntityRelation", "(", "parts", "[", "i", "]", ")", ")", "{", "if", "(", "parent", ".", "isNonEntityRelationCollection", "(", "parts", "[", "i", "]", ")", ")", "return", "true", ";", "}", "else", "{", "log", ".", "warn", "(", "\"Encountered relation \"", "+", "parts", "[", "i", "]", "+", "\" on \"", "+", "parent", ".", "getName", "(", ")", "+", "\" as part of path \"", "+", "fetch", "+", "\". Assuming QEntity simply does not know this relation. Assuming worst case scenario (collection join is involved)\"", ")", ";", "return", "true", ";", "}", "}", "}", "return", "false", ";", "}" ]
Returns true if one of the fetches specified will result in a collection being pulled back
[ "Returns", "true", "if", "one", "of", "the", "fetches", "specified", "will", "result", "in", "a", "collection", "being", "pulled", "back" ]
d4025d2f881bc0542b1e004c5f65a1ccaf895836
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/guice/hibernate/src/main/java/com/peterphi/std/guice/hibernate/webquery/impl/jpa/JPAQueryBuilder.java#L719-L770
142,279
petergeneric/stdlib
stdlib/src/main/java/com/peterphi/std/types/Timecode.java
Timecode.subtract
public Timecode subtract(SampleCount samples) { final SampleCount mySamples = getSampleCount(); final SampleCount result = mySamples.subtract(samples); return Timecode.getInstance(result, dropFrame); }
java
public Timecode subtract(SampleCount samples) { final SampleCount mySamples = getSampleCount(); final SampleCount result = mySamples.subtract(samples); return Timecode.getInstance(result, dropFrame); }
[ "public", "Timecode", "subtract", "(", "SampleCount", "samples", ")", "{", "final", "SampleCount", "mySamples", "=", "getSampleCount", "(", ")", ";", "final", "SampleCount", "result", "=", "mySamples", ".", "subtract", "(", "samples", ")", ";", "return", "Timecode", ".", "getInstance", "(", "result", ",", "dropFrame", ")", ";", "}" ]
Subtract some samples from this timecode @param samples @return
[ "Subtract", "some", "samples", "from", "this", "timecode" ]
d4025d2f881bc0542b1e004c5f65a1ccaf895836
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/stdlib/src/main/java/com/peterphi/std/types/Timecode.java#L428-L434
142,280
petergeneric/stdlib
stdlib/src/main/java/com/peterphi/std/types/Timecode.java
Timecode.add
public Timecode add(SampleCount samples) { final SampleCount mySamples = getSampleCount(); final SampleCount totalSamples = mySamples.add(samples); return TimecodeBuilder.fromSamples(totalSamples, dropFrame).build(); }
java
public Timecode add(SampleCount samples) { final SampleCount mySamples = getSampleCount(); final SampleCount totalSamples = mySamples.add(samples); return TimecodeBuilder.fromSamples(totalSamples, dropFrame).build(); }
[ "public", "Timecode", "add", "(", "SampleCount", "samples", ")", "{", "final", "SampleCount", "mySamples", "=", "getSampleCount", "(", ")", ";", "final", "SampleCount", "totalSamples", "=", "mySamples", ".", "add", "(", "samples", ")", ";", "return", "TimecodeBuilder", ".", "fromSamples", "(", "totalSamples", ",", "dropFrame", ")", ".", "build", "(", ")", ";", "}" ]
Add some samples to this timecode @param samples @return
[ "Add", "some", "samples", "to", "this", "timecode" ]
d4025d2f881bc0542b1e004c5f65a1ccaf895836
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/stdlib/src/main/java/com/peterphi/std/types/Timecode.java#L444-L450
142,281
petergeneric/stdlib
stdlib/src/main/java/com/peterphi/std/types/Timecode.java
Timecode.addPrecise
public Timecode addPrecise(SampleCount samples) throws ResamplingException { final SampleCount mySamples = getSampleCount(); final SampleCount totalSamples = mySamples.addPrecise(samples); return TimecodeBuilder.fromSamples(totalSamples, dropFrame).build(); }
java
public Timecode addPrecise(SampleCount samples) throws ResamplingException { final SampleCount mySamples = getSampleCount(); final SampleCount totalSamples = mySamples.addPrecise(samples); return TimecodeBuilder.fromSamples(totalSamples, dropFrame).build(); }
[ "public", "Timecode", "addPrecise", "(", "SampleCount", "samples", ")", "throws", "ResamplingException", "{", "final", "SampleCount", "mySamples", "=", "getSampleCount", "(", ")", ";", "final", "SampleCount", "totalSamples", "=", "mySamples", ".", "addPrecise", "(", "samples", ")", ";", "return", "TimecodeBuilder", ".", "fromSamples", "(", "totalSamples", ",", "dropFrame", ")", ".", "build", "(", ")", ";", "}" ]
Add some samples to this timecode, throwing an exception if precision would be lost @param samples @return @throws ResamplingException if the requested addition would result in a loss of accuracy due to resampling
[ "Add", "some", "samples", "to", "this", "timecode", "throwing", "an", "exception", "if", "precision", "would", "be", "lost" ]
d4025d2f881bc0542b1e004c5f65a1ccaf895836
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/stdlib/src/main/java/com/peterphi/std/types/Timecode.java#L463-L469
142,282
ziccardi/jnrpe
jnrpe-server/src/main/java/it/jnrpe/server/CommandsSection.java
CommandsSection.addCommand
public void addCommand(final String commandName, final String pluginName, final String commandLine) { commandsList.add(new Command(commandName, pluginName, commandLine)); }
java
public void addCommand(final String commandName, final String pluginName, final String commandLine) { commandsList.add(new Command(commandName, pluginName, commandLine)); }
[ "public", "void", "addCommand", "(", "final", "String", "commandName", ",", "final", "String", "pluginName", ",", "final", "String", "commandLine", ")", "{", "commandsList", ".", "add", "(", "new", "Command", "(", "commandName", ",", "pluginName", ",", "commandLine", ")", ")", ";", "}" ]
Adds a command to the section. @param commandName The command name @param pluginName The plugin name @param commandLine The command line
[ "Adds", "a", "command", "to", "the", "section", "." ]
ac9046355851136994388442b01ba4063305f9c4
https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-server/src/main/java/it/jnrpe/server/CommandsSection.java#L102-L104
142,283
ops4j/org.ops4j.pax.swissbox
pax-swissbox-extender/src/main/java/org/ops4j/pax/swissbox/extender/BundleManifestScanner.java
BundleManifestScanner.scan
public List<ManifestEntry> scan( final Bundle bundle ) { NullArgumentException.validateNotNull( bundle, "Bundle" ); final Dictionary bundleHeaders = bundle.getHeaders(); if( bundleHeaders != null && !bundleHeaders.isEmpty() ) { return asManifestEntryList( m_manifestFilter.match( dictionaryToMap( bundleHeaders ) ) ); } else { return Collections.emptyList(); } }
java
public List<ManifestEntry> scan( final Bundle bundle ) { NullArgumentException.validateNotNull( bundle, "Bundle" ); final Dictionary bundleHeaders = bundle.getHeaders(); if( bundleHeaders != null && !bundleHeaders.isEmpty() ) { return asManifestEntryList( m_manifestFilter.match( dictionaryToMap( bundleHeaders ) ) ); } else { return Collections.emptyList(); } }
[ "public", "List", "<", "ManifestEntry", ">", "scan", "(", "final", "Bundle", "bundle", ")", "{", "NullArgumentException", ".", "validateNotNull", "(", "bundle", ",", "\"Bundle\"", ")", ";", "final", "Dictionary", "bundleHeaders", "=", "bundle", ".", "getHeaders", "(", ")", ";", "if", "(", "bundleHeaders", "!=", "null", "&&", "!", "bundleHeaders", ".", "isEmpty", "(", ")", ")", "{", "return", "asManifestEntryList", "(", "m_manifestFilter", ".", "match", "(", "dictionaryToMap", "(", "bundleHeaders", ")", ")", ")", ";", "}", "else", "{", "return", "Collections", ".", "emptyList", "(", ")", ";", "}", "}" ]
Scans bundle manifest for matches against configured manifest headers. @param bundle bundle to be scanned @return list of matching manifest entries @see BundleScanner#scan(Bundle)
[ "Scans", "bundle", "manifest", "for", "matches", "against", "configured", "manifest", "headers", "." ]
00b0ee16cdbe8017984a4d7ba808b10d985c5b5c
https://github.com/ops4j/org.ops4j.pax.swissbox/blob/00b0ee16cdbe8017984a4d7ba808b10d985c5b5c/pax-swissbox-extender/src/main/java/org/ops4j/pax/swissbox/extender/BundleManifestScanner.java#L69-L82
142,284
petergeneric/stdlib
stdlib/src/main/java/com/peterphi/std/types/Timebase.java
Timebase.resample
public double resample(final double samples, final Timebase oldRate) { if (samples == 0) { return 0; } else if (!this.equals(oldRate)) { final double resampled = resample(samples, oldRate, this); return resampled; } else { return samples; } }
java
public double resample(final double samples, final Timebase oldRate) { if (samples == 0) { return 0; } else if (!this.equals(oldRate)) { final double resampled = resample(samples, oldRate, this); return resampled; } else { return samples; } }
[ "public", "double", "resample", "(", "final", "double", "samples", ",", "final", "Timebase", "oldRate", ")", "{", "if", "(", "samples", "==", "0", ")", "{", "return", "0", ";", "}", "else", "if", "(", "!", "this", ".", "equals", "(", "oldRate", ")", ")", "{", "final", "double", "resampled", "=", "resample", "(", "samples", ",", "oldRate", ",", "this", ")", ";", "return", "resampled", ";", "}", "else", "{", "return", "samples", ";", "}", "}" ]
Convert a sample count from one timebase to another @param samples @param oldRate @return
[ "Convert", "a", "sample", "count", "from", "one", "timebase", "to", "another" ]
d4025d2f881bc0542b1e004c5f65a1ccaf895836
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/stdlib/src/main/java/com/peterphi/std/types/Timebase.java#L247-L263
142,285
petergeneric/stdlib
guice/common/src/main/java/com/peterphi/std/guice/restclient/exception/RestExceptionFactory.java
RestExceptionFactory.buildKnown
private RestException buildKnown(Constructor<RestException> constructor, RestFailure failure) { try { return constructor.newInstance(failure.exception.detail, null); } catch (Exception e) { return buildUnknown(failure); } }
java
private RestException buildKnown(Constructor<RestException> constructor, RestFailure failure) { try { return constructor.newInstance(failure.exception.detail, null); } catch (Exception e) { return buildUnknown(failure); } }
[ "private", "RestException", "buildKnown", "(", "Constructor", "<", "RestException", ">", "constructor", ",", "RestFailure", "failure", ")", "{", "try", "{", "return", "constructor", ".", "newInstance", "(", "failure", ".", "exception", ".", "detail", ",", "null", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "return", "buildUnknown", "(", "failure", ")", ";", "}", "}" ]
Build an exception for a known exception type @param constructor @param failure @return
[ "Build", "an", "exception", "for", "a", "known", "exception", "type" ]
d4025d2f881bc0542b1e004c5f65a1ccaf895836
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/guice/common/src/main/java/com/peterphi/std/guice/restclient/exception/RestExceptionFactory.java#L70-L80
142,286
petergeneric/stdlib
guice/common/src/main/java/com/peterphi/std/guice/restclient/exception/RestExceptionFactory.java
RestExceptionFactory.buildUnknown
private UnboundRestException buildUnknown(RestFailure failure) { // We need to build up exception detail that reasonably accurately describes the source exception final String msg = failure.exception.shortName + ": " + failure.exception.detail + " (" + failure.id + ")"; return new UnboundRestException(msg); }
java
private UnboundRestException buildUnknown(RestFailure failure) { // We need to build up exception detail that reasonably accurately describes the source exception final String msg = failure.exception.shortName + ": " + failure.exception.detail + " (" + failure.id + ")"; return new UnboundRestException(msg); }
[ "private", "UnboundRestException", "buildUnknown", "(", "RestFailure", "failure", ")", "{", "// We need to build up exception detail that reasonably accurately describes the source exception", "final", "String", "msg", "=", "failure", ".", "exception", ".", "shortName", "+", "\": \"", "+", "failure", ".", "exception", ".", "detail", "+", "\" (\"", "+", "failure", ".", "id", "+", "\")\"", ";", "return", "new", "UnboundRestException", "(", "msg", ")", ";", "}" ]
Build an exception to represent an unknown or problematic exception type @param failure @return
[ "Build", "an", "exception", "to", "represent", "an", "unknown", "or", "problematic", "exception", "type" ]
d4025d2f881bc0542b1e004c5f65a1ccaf895836
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/guice/common/src/main/java/com/peterphi/std/guice/restclient/exception/RestExceptionFactory.java#L89-L95
142,287
petergeneric/stdlib
stdlib/src/main/java/com/peterphi/std/io/nio/NIOHelper.java
NIOHelper.blockingRead
public static ByteBuffer blockingRead(SocketChannel so, long timeout, byte[] bytes) throws IOException { ByteBuffer b = ByteBuffer.wrap(bytes); if (bytes.length == 0) return b; final long timeoutTime = (timeout > 0) ? (System.currentTimeMillis() + timeout) : (Long.MAX_VALUE); while (b.remaining() != 0 && System.currentTimeMillis() < timeoutTime) { if (!so.isConnected()) throw new IOException("Socket closed during read operation!"); so.read(b); if (b.remaining() != 0) { // sleep for a short time try { Thread.sleep(20); } catch (InterruptedException e) { } } } if (System.currentTimeMillis() >= timeoutTime) { return null; } b.rewind(); // make it easy for the caller to read from the buffer (if they're interested) return b; }
java
public static ByteBuffer blockingRead(SocketChannel so, long timeout, byte[] bytes) throws IOException { ByteBuffer b = ByteBuffer.wrap(bytes); if (bytes.length == 0) return b; final long timeoutTime = (timeout > 0) ? (System.currentTimeMillis() + timeout) : (Long.MAX_VALUE); while (b.remaining() != 0 && System.currentTimeMillis() < timeoutTime) { if (!so.isConnected()) throw new IOException("Socket closed during read operation!"); so.read(b); if (b.remaining() != 0) { // sleep for a short time try { Thread.sleep(20); } catch (InterruptedException e) { } } } if (System.currentTimeMillis() >= timeoutTime) { return null; } b.rewind(); // make it easy for the caller to read from the buffer (if they're interested) return b; }
[ "public", "static", "ByteBuffer", "blockingRead", "(", "SocketChannel", "so", ",", "long", "timeout", ",", "byte", "[", "]", "bytes", ")", "throws", "IOException", "{", "ByteBuffer", "b", "=", "ByteBuffer", ".", "wrap", "(", "bytes", ")", ";", "if", "(", "bytes", ".", "length", "==", "0", ")", "return", "b", ";", "final", "long", "timeoutTime", "=", "(", "timeout", ">", "0", ")", "?", "(", "System", ".", "currentTimeMillis", "(", ")", "+", "timeout", ")", ":", "(", "Long", ".", "MAX_VALUE", ")", ";", "while", "(", "b", ".", "remaining", "(", ")", "!=", "0", "&&", "System", ".", "currentTimeMillis", "(", ")", "<", "timeoutTime", ")", "{", "if", "(", "!", "so", ".", "isConnected", "(", ")", ")", "throw", "new", "IOException", "(", "\"Socket closed during read operation!\"", ")", ";", "so", ".", "read", "(", "b", ")", ";", "if", "(", "b", ".", "remaining", "(", ")", "!=", "0", ")", "{", "// sleep for a short time", "try", "{", "Thread", ".", "sleep", "(", "20", ")", ";", "}", "catch", "(", "InterruptedException", "e", ")", "{", "}", "}", "}", "if", "(", "System", ".", "currentTimeMillis", "(", ")", ">=", "timeoutTime", ")", "{", "return", "null", ";", "}", "b", ".", "rewind", "(", ")", ";", "// make it easy for the caller to read from the buffer (if they're interested)", "return", "b", ";", "}" ]
Read a number of bytes from a socket, terminating when complete, after timeout milliseconds or if an error occurs
[ "Read", "a", "number", "of", "bytes", "from", "a", "socket", "terminating", "when", "complete", "after", "timeout", "milliseconds", "or", "if", "an", "error", "occurs" ]
d4025d2f881bc0542b1e004c5f65a1ccaf895836
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/stdlib/src/main/java/com/peterphi/std/io/nio/NIOHelper.java#L103-L140
142,288
petergeneric/stdlib
stdlib/src/main/java/com/peterphi/std/util/jaxb/JAXBSerialiser.java
JAXBSerialiser.deserialise
public <T> T deserialise(final Class<T> clazz, final InputSource source) { final Object obj = deserialise(source); if (clazz.isInstance(obj)) return clazz.cast(obj); else throw new JAXBRuntimeException("XML deserialised to " + obj.getClass() + ", could not cast to the expected " + clazz); }
java
public <T> T deserialise(final Class<T> clazz, final InputSource source) { final Object obj = deserialise(source); if (clazz.isInstance(obj)) return clazz.cast(obj); else throw new JAXBRuntimeException("XML deserialised to " + obj.getClass() + ", could not cast to the expected " + clazz); }
[ "public", "<", "T", ">", "T", "deserialise", "(", "final", "Class", "<", "T", ">", "clazz", ",", "final", "InputSource", "source", ")", "{", "final", "Object", "obj", "=", "deserialise", "(", "source", ")", ";", "if", "(", "clazz", ".", "isInstance", "(", "obj", ")", ")", "return", "clazz", ".", "cast", "(", "obj", ")", ";", "else", "throw", "new", "JAXBRuntimeException", "(", "\"XML deserialised to \"", "+", "obj", ".", "getClass", "(", ")", "+", "\", could not cast to the expected \"", "+", "clazz", ")", ";", "}" ]
Deserialise an input and cast to a particular type @param clazz @param source @return
[ "Deserialise", "an", "input", "and", "cast", "to", "a", "particular", "type" ]
d4025d2f881bc0542b1e004c5f65a1ccaf895836
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/stdlib/src/main/java/com/peterphi/std/util/jaxb/JAXBSerialiser.java#L322-L330
142,289
petergeneric/stdlib
stdlib/src/main/java/com/peterphi/std/util/jaxb/JAXBSerialiser.java
JAXBSerialiser.deserialise
public <T> T deserialise(final Class<T> clazz, final String xml) { final Object obj = deserialise(new InputSource(new StringReader(xml))); if (clazz.isInstance(obj)) return clazz.cast(obj); else throw new JAXBRuntimeException("XML deserialised to " + obj.getClass() + ", could not cast to the expected " + clazz); }
java
public <T> T deserialise(final Class<T> clazz, final String xml) { final Object obj = deserialise(new InputSource(new StringReader(xml))); if (clazz.isInstance(obj)) return clazz.cast(obj); else throw new JAXBRuntimeException("XML deserialised to " + obj.getClass() + ", could not cast to the expected " + clazz); }
[ "public", "<", "T", ">", "T", "deserialise", "(", "final", "Class", "<", "T", ">", "clazz", ",", "final", "String", "xml", ")", "{", "final", "Object", "obj", "=", "deserialise", "(", "new", "InputSource", "(", "new", "StringReader", "(", "xml", ")", ")", ")", ";", "if", "(", "clazz", ".", "isInstance", "(", "obj", ")", ")", "return", "clazz", ".", "cast", "(", "obj", ")", ";", "else", "throw", "new", "JAXBRuntimeException", "(", "\"XML deserialised to \"", "+", "obj", ".", "getClass", "(", ")", "+", "\", could not cast to the expected \"", "+", "clazz", ")", ";", "}" ]
Deserialise and cast to a particular type @param clazz @param xml a String of XML @return
[ "Deserialise", "and", "cast", "to", "a", "particular", "type" ]
d4025d2f881bc0542b1e004c5f65a1ccaf895836
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/stdlib/src/main/java/com/peterphi/std/util/jaxb/JAXBSerialiser.java#L342-L350
142,290
petergeneric/stdlib
stdlib/src/main/java/com/peterphi/std/util/jaxb/JAXBSerialiser.java
JAXBSerialiser.serialiseToDocument
public Document serialiseToDocument(final Object obj) { final Document document = DOMUtils.createDocumentBuilder().newDocument(); serialise(obj, document); return document; }
java
public Document serialiseToDocument(final Object obj) { final Document document = DOMUtils.createDocumentBuilder().newDocument(); serialise(obj, document); return document; }
[ "public", "Document", "serialiseToDocument", "(", "final", "Object", "obj", ")", "{", "final", "Document", "document", "=", "DOMUtils", ".", "createDocumentBuilder", "(", ")", ".", "newDocument", "(", ")", ";", "serialise", "(", "obj", ",", "document", ")", ";", "return", "document", ";", "}" ]
Helper method to serialise an Object to an org.w3c.dom.Document @param obj the object to serialise @return a new Document containing the serialised form of the provided Object
[ "Helper", "method", "to", "serialise", "an", "Object", "to", "an", "org", ".", "w3c", ".", "dom", ".", "Document" ]
d4025d2f881bc0542b1e004c5f65a1ccaf895836
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/stdlib/src/main/java/com/peterphi/std/util/jaxb/JAXBSerialiser.java#L486-L493
142,291
petergeneric/stdlib
service-manager/host-agent/src/main/java/com/peterphi/servicemanager/hostagent/webapp/service/NginxService.java
NginxService.reload
public void reload() { try { final Execed process = Exec.rootUtility(new File(binPath, "nginx-reload").getAbsolutePath()); process.waitForExit(new Timeout(30, TimeUnit.SECONDS).start(), 0); } catch (IOException e) { throw new RuntimeException("Error executing nginx-reload command", e); } }
java
public void reload() { try { final Execed process = Exec.rootUtility(new File(binPath, "nginx-reload").getAbsolutePath()); process.waitForExit(new Timeout(30, TimeUnit.SECONDS).start(), 0); } catch (IOException e) { throw new RuntimeException("Error executing nginx-reload command", e); } }
[ "public", "void", "reload", "(", ")", "{", "try", "{", "final", "Execed", "process", "=", "Exec", ".", "rootUtility", "(", "new", "File", "(", "binPath", ",", "\"nginx-reload\"", ")", ".", "getAbsolutePath", "(", ")", ")", ";", "process", ".", "waitForExit", "(", "new", "Timeout", "(", "30", ",", "TimeUnit", ".", "SECONDS", ")", ".", "start", "(", ")", ",", "0", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "\"Error executing nginx-reload command\"", ",", "e", ")", ";", "}", "}" ]
Reload the nginx configuration
[ "Reload", "the", "nginx", "configuration" ]
d4025d2f881bc0542b1e004c5f65a1ccaf895836
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/service-manager/host-agent/src/main/java/com/peterphi/servicemanager/hostagent/webapp/service/NginxService.java#L25-L36
142,292
petergeneric/stdlib
service-manager/host-agent/src/main/java/com/peterphi/servicemanager/hostagent/webapp/service/NginxService.java
NginxService.reconfigure
public void reconfigure(final String config) { try { final File tempFile = File.createTempFile("nginx", ".conf"); try { FileHelper.write(tempFile, config); final Execed process = Exec.rootUtility(new File(binPath, "nginx-reconfigure").getAbsolutePath(), tempFile.getAbsolutePath()); process.waitForExit(new Timeout(30, TimeUnit.SECONDS).start(), 0); } finally { FileUtils.deleteQuietly(tempFile); } } catch (IOException e) { throw new RuntimeException("Error executing nginx-reload command", e); } reload(); }
java
public void reconfigure(final String config) { try { final File tempFile = File.createTempFile("nginx", ".conf"); try { FileHelper.write(tempFile, config); final Execed process = Exec.rootUtility(new File(binPath, "nginx-reconfigure").getAbsolutePath(), tempFile.getAbsolutePath()); process.waitForExit(new Timeout(30, TimeUnit.SECONDS).start(), 0); } finally { FileUtils.deleteQuietly(tempFile); } } catch (IOException e) { throw new RuntimeException("Error executing nginx-reload command", e); } reload(); }
[ "public", "void", "reconfigure", "(", "final", "String", "config", ")", "{", "try", "{", "final", "File", "tempFile", "=", "File", ".", "createTempFile", "(", "\"nginx\"", ",", "\".conf\"", ")", ";", "try", "{", "FileHelper", ".", "write", "(", "tempFile", ",", "config", ")", ";", "final", "Execed", "process", "=", "Exec", ".", "rootUtility", "(", "new", "File", "(", "binPath", ",", "\"nginx-reconfigure\"", ")", ".", "getAbsolutePath", "(", ")", ",", "tempFile", ".", "getAbsolutePath", "(", ")", ")", ";", "process", ".", "waitForExit", "(", "new", "Timeout", "(", "30", ",", "TimeUnit", ".", "SECONDS", ")", ".", "start", "(", ")", ",", "0", ")", ";", "}", "finally", "{", "FileUtils", ".", "deleteQuietly", "(", "tempFile", ")", ";", "}", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "\"Error executing nginx-reload command\"", ",", "e", ")", ";", "}", "reload", "(", ")", ";", "}" ]
Rewrite the nginx site configuration and reload @param config the nginx site configuration
[ "Rewrite", "the", "nginx", "site", "configuration", "and", "reload" ]
d4025d2f881bc0542b1e004c5f65a1ccaf895836
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/service-manager/host-agent/src/main/java/com/peterphi/servicemanager/hostagent/webapp/service/NginxService.java#L45-L70
142,293
petergeneric/stdlib
service-manager/host-agent/src/main/java/com/peterphi/servicemanager/hostagent/webapp/service/NginxService.java
NginxService.installCertificates
public void installCertificates(final String key, final String cert, final String chain) { try { final File keyFile = File.createTempFile("key", ".pem"); final File certFile = File.createTempFile("cert", ".pem"); final File chainFile = File.createTempFile("chain", ".pem"); try { FileHelper.write(keyFile, key); FileHelper.write(certFile, cert); FileHelper.write(chainFile, chain); final Execed process = Exec.rootUtility(new File(binPath, "cert-update").getAbsolutePath(), keyFile.getAbsolutePath(), certFile.getAbsolutePath(), chainFile.getAbsolutePath()); process.waitForExit(new Timeout(30, TimeUnit.SECONDS).start(), 0); } finally { FileUtils.deleteQuietly(keyFile); FileUtils.deleteQuietly(certFile); FileUtils.deleteQuietly(chainFile); } } catch (IOException e) { throw new RuntimeException("Error executing cert-update command", e); } }
java
public void installCertificates(final String key, final String cert, final String chain) { try { final File keyFile = File.createTempFile("key", ".pem"); final File certFile = File.createTempFile("cert", ".pem"); final File chainFile = File.createTempFile("chain", ".pem"); try { FileHelper.write(keyFile, key); FileHelper.write(certFile, cert); FileHelper.write(chainFile, chain); final Execed process = Exec.rootUtility(new File(binPath, "cert-update").getAbsolutePath(), keyFile.getAbsolutePath(), certFile.getAbsolutePath(), chainFile.getAbsolutePath()); process.waitForExit(new Timeout(30, TimeUnit.SECONDS).start(), 0); } finally { FileUtils.deleteQuietly(keyFile); FileUtils.deleteQuietly(certFile); FileUtils.deleteQuietly(chainFile); } } catch (IOException e) { throw new RuntimeException("Error executing cert-update command", e); } }
[ "public", "void", "installCertificates", "(", "final", "String", "key", ",", "final", "String", "cert", ",", "final", "String", "chain", ")", "{", "try", "{", "final", "File", "keyFile", "=", "File", ".", "createTempFile", "(", "\"key\"", ",", "\".pem\"", ")", ";", "final", "File", "certFile", "=", "File", ".", "createTempFile", "(", "\"cert\"", ",", "\".pem\"", ")", ";", "final", "File", "chainFile", "=", "File", ".", "createTempFile", "(", "\"chain\"", ",", "\".pem\"", ")", ";", "try", "{", "FileHelper", ".", "write", "(", "keyFile", ",", "key", ")", ";", "FileHelper", ".", "write", "(", "certFile", ",", "cert", ")", ";", "FileHelper", ".", "write", "(", "chainFile", ",", "chain", ")", ";", "final", "Execed", "process", "=", "Exec", ".", "rootUtility", "(", "new", "File", "(", "binPath", ",", "\"cert-update\"", ")", ".", "getAbsolutePath", "(", ")", ",", "keyFile", ".", "getAbsolutePath", "(", ")", ",", "certFile", ".", "getAbsolutePath", "(", ")", ",", "chainFile", ".", "getAbsolutePath", "(", ")", ")", ";", "process", ".", "waitForExit", "(", "new", "Timeout", "(", "30", ",", "TimeUnit", ".", "SECONDS", ")", ".", "start", "(", ")", ",", "0", ")", ";", "}", "finally", "{", "FileUtils", ".", "deleteQuietly", "(", "keyFile", ")", ";", "FileUtils", ".", "deleteQuietly", "(", "certFile", ")", ";", "FileUtils", ".", "deleteQuietly", "(", "chainFile", ")", ";", "}", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "\"Error executing cert-update command\"", ",", "e", ")", ";", "}", "}" ]
Install new SSL Certificates for the host @param key @param cert @param chain
[ "Install", "new", "SSL", "Certificates", "for", "the", "host" ]
d4025d2f881bc0542b1e004c5f65a1ccaf895836
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/service-manager/host-agent/src/main/java/com/peterphi/servicemanager/hostagent/webapp/service/NginxService.java#L80-L112
142,294
petergeneric/stdlib
stdlib/src/main/java/com/peterphi/std/util/ClassManifestLocator.java
ClassManifestLocator.get
public static PropertyFile get(Class<?> clazz) { try { // If we get a guice-enhanced class then we should go up one level to get the class name from the user's code if (clazz.getName().contains("$$EnhancerByGuice$$")) clazz = clazz.getSuperclass(); final String classFileName = clazz.getSimpleName() + ".class"; final String classFilePathAndName = clazz.getName().replace('.', '/') + ".class"; URL url = clazz.getResource(classFileName); if (log.isTraceEnabled()) log.trace("getResource(" + classFileName + ") = " + url); if (url == null) { return null; } else { String classesUrl = url.toString(); // Get the classes base classesUrl = classesUrl.replace(classFilePathAndName, ""); // Special-case: classes in a webapp are at /WEB-INF/classes/ rather than / if (classesUrl.endsWith("WEB-INF/classes/")) { classesUrl = classesUrl.replace("WEB-INF/classes/", ""); } final URL manifestURL = new URL(classesUrl + "META-INF/MANIFEST.MF"); try { final InputStream is = manifestURL.openStream(); try { final PropertyFile props = new PropertyFile(); final Manifest manifest = new Manifest(is); for (Object key : manifest.getMainAttributes().keySet()) { final Object value = manifest.getMainAttributes().get(key); props.set(key.toString(), value.toString()); } return props; } finally { IOUtils.closeQuietly(is); } } catch (FileNotFoundException e) { log.warn("Could not find: " + manifestURL, e); return null; } } } catch (Throwable t) { log.warn("Error acquiring MANIFEST.MF for " + clazz, t); return null; } }
java
public static PropertyFile get(Class<?> clazz) { try { // If we get a guice-enhanced class then we should go up one level to get the class name from the user's code if (clazz.getName().contains("$$EnhancerByGuice$$")) clazz = clazz.getSuperclass(); final String classFileName = clazz.getSimpleName() + ".class"; final String classFilePathAndName = clazz.getName().replace('.', '/') + ".class"; URL url = clazz.getResource(classFileName); if (log.isTraceEnabled()) log.trace("getResource(" + classFileName + ") = " + url); if (url == null) { return null; } else { String classesUrl = url.toString(); // Get the classes base classesUrl = classesUrl.replace(classFilePathAndName, ""); // Special-case: classes in a webapp are at /WEB-INF/classes/ rather than / if (classesUrl.endsWith("WEB-INF/classes/")) { classesUrl = classesUrl.replace("WEB-INF/classes/", ""); } final URL manifestURL = new URL(classesUrl + "META-INF/MANIFEST.MF"); try { final InputStream is = manifestURL.openStream(); try { final PropertyFile props = new PropertyFile(); final Manifest manifest = new Manifest(is); for (Object key : manifest.getMainAttributes().keySet()) { final Object value = manifest.getMainAttributes().get(key); props.set(key.toString(), value.toString()); } return props; } finally { IOUtils.closeQuietly(is); } } catch (FileNotFoundException e) { log.warn("Could not find: " + manifestURL, e); return null; } } } catch (Throwable t) { log.warn("Error acquiring MANIFEST.MF for " + clazz, t); return null; } }
[ "public", "static", "PropertyFile", "get", "(", "Class", "<", "?", ">", "clazz", ")", "{", "try", "{", "// If we get a guice-enhanced class then we should go up one level to get the class name from the user's code", "if", "(", "clazz", ".", "getName", "(", ")", ".", "contains", "(", "\"$$EnhancerByGuice$$\"", ")", ")", "clazz", "=", "clazz", ".", "getSuperclass", "(", ")", ";", "final", "String", "classFileName", "=", "clazz", ".", "getSimpleName", "(", ")", "+", "\".class\"", ";", "final", "String", "classFilePathAndName", "=", "clazz", ".", "getName", "(", ")", ".", "replace", "(", "'", "'", ",", "'", "'", ")", "+", "\".class\"", ";", "URL", "url", "=", "clazz", ".", "getResource", "(", "classFileName", ")", ";", "if", "(", "log", ".", "isTraceEnabled", "(", ")", ")", "log", ".", "trace", "(", "\"getResource(\"", "+", "classFileName", "+", "\") = \"", "+", "url", ")", ";", "if", "(", "url", "==", "null", ")", "{", "return", "null", ";", "}", "else", "{", "String", "classesUrl", "=", "url", ".", "toString", "(", ")", ";", "// Get the classes base", "classesUrl", "=", "classesUrl", ".", "replace", "(", "classFilePathAndName", ",", "\"\"", ")", ";", "// Special-case: classes in a webapp are at /WEB-INF/classes/ rather than /", "if", "(", "classesUrl", ".", "endsWith", "(", "\"WEB-INF/classes/\"", ")", ")", "{", "classesUrl", "=", "classesUrl", ".", "replace", "(", "\"WEB-INF/classes/\"", ",", "\"\"", ")", ";", "}", "final", "URL", "manifestURL", "=", "new", "URL", "(", "classesUrl", "+", "\"META-INF/MANIFEST.MF\"", ")", ";", "try", "{", "final", "InputStream", "is", "=", "manifestURL", ".", "openStream", "(", ")", ";", "try", "{", "final", "PropertyFile", "props", "=", "new", "PropertyFile", "(", ")", ";", "final", "Manifest", "manifest", "=", "new", "Manifest", "(", "is", ")", ";", "for", "(", "Object", "key", ":", "manifest", ".", "getMainAttributes", "(", ")", ".", "keySet", "(", ")", ")", "{", "final", "Object", "value", "=", "manifest", ".", "getMainAttributes", "(", ")", ".", "get", "(", "key", ")", ";", "props", ".", "set", "(", "key", ".", "toString", "(", ")", ",", "value", ".", "toString", "(", ")", ")", ";", "}", "return", "props", ";", "}", "finally", "{", "IOUtils", ".", "closeQuietly", "(", "is", ")", ";", "}", "}", "catch", "(", "FileNotFoundException", "e", ")", "{", "log", ".", "warn", "(", "\"Could not find: \"", "+", "manifestURL", ",", "e", ")", ";", "return", "null", ";", "}", "}", "}", "catch", "(", "Throwable", "t", ")", "{", "log", ".", "warn", "(", "\"Error acquiring MANIFEST.MF for \"", "+", "clazz", ",", "t", ")", ";", "return", "null", ";", "}", "}" ]
Attempt to find the MANIFEST.MF associated with a particular class @param clazz The class whose jar/war should be searched for a MANIFEST.MF @return a PropertyFile version of the main manifest attributes if found, otherwise null
[ "Attempt", "to", "find", "the", "MANIFEST", ".", "MF", "associated", "with", "a", "particular", "class" ]
d4025d2f881bc0542b1e004c5f65a1ccaf895836
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/stdlib/src/main/java/com/peterphi/std/util/ClassManifestLocator.java#L28-L100
142,295
ziccardi/jnrpe
jnrpe-lib/src/main/java/it/jnrpe/utils/LoadedClassCache.java
LoadedClassCache.saveClass
private static void saveClass(final ClassLoader cl, final Class c) { if (LOADED_PLUGINS.get(cl) == null) { LOADED_PLUGINS.put(cl, new ClassesData()); } ClassesData cd = LOADED_PLUGINS.get(cl); cd.addClass(c); }
java
private static void saveClass(final ClassLoader cl, final Class c) { if (LOADED_PLUGINS.get(cl) == null) { LOADED_PLUGINS.put(cl, new ClassesData()); } ClassesData cd = LOADED_PLUGINS.get(cl); cd.addClass(c); }
[ "private", "static", "void", "saveClass", "(", "final", "ClassLoader", "cl", ",", "final", "Class", "c", ")", "{", "if", "(", "LOADED_PLUGINS", ".", "get", "(", "cl", ")", "==", "null", ")", "{", "LOADED_PLUGINS", ".", "put", "(", "cl", ",", "new", "ClassesData", "(", ")", ")", ";", "}", "ClassesData", "cd", "=", "LOADED_PLUGINS", ".", "get", "(", "cl", ")", ";", "cd", ".", "addClass", "(", "c", ")", ";", "}" ]
Stores a class in the cache. @param cl The classloader @param c the class to be stored
[ "Stores", "a", "class", "in", "the", "cache", "." ]
ac9046355851136994388442b01ba4063305f9c4
https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-lib/src/main/java/it/jnrpe/utils/LoadedClassCache.java#L118-L125
142,296
ziccardi/jnrpe
jnrpe-lib/src/main/java/it/jnrpe/utils/LoadedClassCache.java
LoadedClassCache.getClass
public static Class getClass(final ClassLoader cl, final String className) throws ClassNotFoundException { if (LOADED_PLUGINS.get(cl) == null) { LOADED_PLUGINS.put(cl, new ClassesData()); } ClassesData cd = LOADED_PLUGINS.get(cl); Class clazz = cd.getClass(className); if (clazz == null) { clazz = cl.loadClass(className); saveClass(cl, clazz); } return clazz; }
java
public static Class getClass(final ClassLoader cl, final String className) throws ClassNotFoundException { if (LOADED_PLUGINS.get(cl) == null) { LOADED_PLUGINS.put(cl, new ClassesData()); } ClassesData cd = LOADED_PLUGINS.get(cl); Class clazz = cd.getClass(className); if (clazz == null) { clazz = cl.loadClass(className); saveClass(cl, clazz); } return clazz; }
[ "public", "static", "Class", "getClass", "(", "final", "ClassLoader", "cl", ",", "final", "String", "className", ")", "throws", "ClassNotFoundException", "{", "if", "(", "LOADED_PLUGINS", ".", "get", "(", "cl", ")", "==", "null", ")", "{", "LOADED_PLUGINS", ".", "put", "(", "cl", ",", "new", "ClassesData", "(", ")", ")", ";", "}", "ClassesData", "cd", "=", "LOADED_PLUGINS", ".", "get", "(", "cl", ")", ";", "Class", "clazz", "=", "cd", ".", "getClass", "(", "className", ")", ";", "if", "(", "clazz", "==", "null", ")", "{", "clazz", "=", "cl", ".", "loadClass", "(", "className", ")", ";", "saveClass", "(", "cl", ",", "clazz", ")", ";", "}", "return", "clazz", ";", "}" ]
Returns a class object. If the class is new, a new Class object is created, otherwise the cached object is returned. @param cl the classloader @param className the class name @return the class object associated to the given class name * @throws ClassNotFoundException if the class can't be loaded
[ "Returns", "a", "class", "object", ".", "If", "the", "class", "is", "new", "a", "new", "Class", "object", "is", "created", "otherwise", "the", "cached", "object", "is", "returned", "." ]
ac9046355851136994388442b01ba4063305f9c4
https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-lib/src/main/java/it/jnrpe/utils/LoadedClassCache.java#L139-L152
142,297
ziccardi/jnrpe
jnrpe-lib/src/main/java/it/jnrpe/utils/thresholds/ThresholdsEvaluator.java
ThresholdsEvaluator.evaluate
final Status evaluate(final Metric metric) { if (metric == null || metric.getMetricValue() == null) { throw new NullPointerException("Metric value can't be null"); } IThreshold thr = thresholdsMap.get(metric.getMetricName()); if (thr == null) { return Status.OK; } return thr.evaluate(metric); }
java
final Status evaluate(final Metric metric) { if (metric == null || metric.getMetricValue() == null) { throw new NullPointerException("Metric value can't be null"); } IThreshold thr = thresholdsMap.get(metric.getMetricName()); if (thr == null) { return Status.OK; } return thr.evaluate(metric); }
[ "final", "Status", "evaluate", "(", "final", "Metric", "metric", ")", "{", "if", "(", "metric", "==", "null", "||", "metric", ".", "getMetricValue", "(", ")", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", "\"Metric value can't be null\"", ")", ";", "}", "IThreshold", "thr", "=", "thresholdsMap", ".", "get", "(", "metric", ".", "getMetricName", "(", ")", ")", ";", "if", "(", "thr", "==", "null", ")", "{", "return", "Status", ".", "OK", ";", "}", "return", "thr", ".", "evaluate", "(", "metric", ")", ";", "}" ]
Evaluates the passed in metric against the threshold configured inside this evaluator. If the threshold do not refer the passed in metric, then it is ignored and the next threshold is checked. @param metric The metric to be checked @return The status computed according to the rules specified for {@link IThreshold#evaluate(Metric)}
[ "Evaluates", "the", "passed", "in", "metric", "against", "the", "threshold", "configured", "inside", "this", "evaluator", ".", "If", "the", "threshold", "do", "not", "refer", "the", "passed", "in", "metric", "then", "it", "is", "ignored", "and", "the", "next", "threshold", "is", "checked", "." ]
ac9046355851136994388442b01ba4063305f9c4
https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-lib/src/main/java/it/jnrpe/utils/thresholds/ThresholdsEvaluator.java#L90-L102
142,298
ziccardi/jnrpe
jnrpe-plugins/src/main/java/it/jnrpe/plugin/utils/Shell.java
Shell.executeSystemCommandAndGetOutput
public final String executeSystemCommandAndGetOutput(final String[] command, final String encoding) throws IOException { Process p = Runtime.getRuntime().exec(command); StreamManager sm = new StreamManager(); try { InputStream input = sm.handle(p.getInputStream()); StringBuffer lines = new StringBuffer(); String line; BufferedReader in = (BufferedReader) sm.handle(new BufferedReader(new InputStreamReader(input, encoding))); while ((line = in.readLine()) != null) { lines.append(line).append('\n'); } return lines.toString(); } finally { sm.closeAll(); } }
java
public final String executeSystemCommandAndGetOutput(final String[] command, final String encoding) throws IOException { Process p = Runtime.getRuntime().exec(command); StreamManager sm = new StreamManager(); try { InputStream input = sm.handle(p.getInputStream()); StringBuffer lines = new StringBuffer(); String line; BufferedReader in = (BufferedReader) sm.handle(new BufferedReader(new InputStreamReader(input, encoding))); while ((line = in.readLine()) != null) { lines.append(line).append('\n'); } return lines.toString(); } finally { sm.closeAll(); } }
[ "public", "final", "String", "executeSystemCommandAndGetOutput", "(", "final", "String", "[", "]", "command", ",", "final", "String", "encoding", ")", "throws", "IOException", "{", "Process", "p", "=", "Runtime", ".", "getRuntime", "(", ")", ".", "exec", "(", "command", ")", ";", "StreamManager", "sm", "=", "new", "StreamManager", "(", ")", ";", "try", "{", "InputStream", "input", "=", "sm", ".", "handle", "(", "p", ".", "getInputStream", "(", ")", ")", ";", "StringBuffer", "lines", "=", "new", "StringBuffer", "(", ")", ";", "String", "line", ";", "BufferedReader", "in", "=", "(", "BufferedReader", ")", "sm", ".", "handle", "(", "new", "BufferedReader", "(", "new", "InputStreamReader", "(", "input", ",", "encoding", ")", ")", ")", ";", "while", "(", "(", "line", "=", "in", ".", "readLine", "(", ")", ")", "!=", "null", ")", "{", "lines", ".", "append", "(", "line", ")", ".", "append", "(", "'", "'", ")", ";", "}", "return", "lines", ".", "toString", "(", ")", ";", "}", "finally", "{", "sm", ".", "closeAll", "(", ")", ";", "}", "}" ]
Executes a system command with arguments and returns the output. @param command command to be executed @param encoding encoding to be used @return command output @throws IOException on any error
[ "Executes", "a", "system", "command", "with", "arguments", "and", "returns", "the", "output", "." ]
ac9046355851136994388442b01ba4063305f9c4
https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-plugins/src/main/java/it/jnrpe/plugin/utils/Shell.java#L55-L72
142,299
petergeneric/stdlib
stdlib/src/main/java/com/peterphi/std/threading/Daemon.java
Daemon.startThread
public synchronized Thread startThread(String name) throws IllegalThreadStateException { if (!running) { log.info("[Daemon] {startThread} Starting thread " + name); this.running = true; thisThread = new Thread(this, name); thisThread.setDaemon(shouldStartAsDaemon()); // Set whether we're a daemon thread (false by default) thisThread.start(); return thisThread; } else { throw new IllegalThreadStateException("Daemon must be stopped before it may be started"); } }
java
public synchronized Thread startThread(String name) throws IllegalThreadStateException { if (!running) { log.info("[Daemon] {startThread} Starting thread " + name); this.running = true; thisThread = new Thread(this, name); thisThread.setDaemon(shouldStartAsDaemon()); // Set whether we're a daemon thread (false by default) thisThread.start(); return thisThread; } else { throw new IllegalThreadStateException("Daemon must be stopped before it may be started"); } }
[ "public", "synchronized", "Thread", "startThread", "(", "String", "name", ")", "throws", "IllegalThreadStateException", "{", "if", "(", "!", "running", ")", "{", "log", ".", "info", "(", "\"[Daemon] {startThread} Starting thread \"", "+", "name", ")", ";", "this", ".", "running", "=", "true", ";", "thisThread", "=", "new", "Thread", "(", "this", ",", "name", ")", ";", "thisThread", ".", "setDaemon", "(", "shouldStartAsDaemon", "(", ")", ")", ";", "// Set whether we're a daemon thread (false by default)", "thisThread", ".", "start", "(", ")", ";", "return", "thisThread", ";", "}", "else", "{", "throw", "new", "IllegalThreadStateException", "(", "\"Daemon must be stopped before it may be started\"", ")", ";", "}", "}" ]
Starts this daemon, creating a new thread for it @param name String The name for the thread @return Thread The daemon's thread @throws IllegalThreadStateException If the daemon is still running
[ "Starts", "this", "daemon", "creating", "a", "new", "thread", "for", "it" ]
d4025d2f881bc0542b1e004c5f65a1ccaf895836
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/stdlib/src/main/java/com/peterphi/std/threading/Daemon.java#L75-L90