repo stringlengths 7 58 | path stringlengths 12 218 | func_name stringlengths 3 140 | original_string stringlengths 73 34.1k | language stringclasses 1
value | code stringlengths 73 34.1k | code_tokens list | docstring stringlengths 3 16k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 105 339 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
petergeneric/stdlib | guice/common/src/main/java/com/peterphi/std/guice/common/logging/appender/ServiceManagerLogForwardDaemon.java | ServiceManagerLogForwardDaemon.shutdown | @Override
public void shutdown()
{
// Stop the appender from delivering new messages to us
ServiceManagerAppender.shutdown();
// Before shutting down synchronously transfer all the pending logs
try
{
final LinkedList<LogLine> copy;
synchronized (incoming)
{
if (!incoming.isEmpty())
{
// Take all the logs as they stand currently and forward them synchronously before shutdown
copy = new LinkedList<>(incoming);
incoming.clear();
}
else
{
copy = null;
}
}
if (copy != null)
{
// Keep forwarding logs until we encounter an error (or run out of logs to forward)
while (!copy.isEmpty() && (forwardLogs(copy) > 0))
;
if (!copy.isEmpty())
log.warn(
"Shutdown called but failed to transfer all pending logs at time of shutdown to Service Manager: there are " +
copy.size() +
" remaining");
}
}
catch (Throwable t)
{
log.warn("Logging system encountered a problem during shutdown", t);
}
super.shutdown();
} | java | @Override
public void shutdown()
{
// Stop the appender from delivering new messages to us
ServiceManagerAppender.shutdown();
// Before shutting down synchronously transfer all the pending logs
try
{
final LinkedList<LogLine> copy;
synchronized (incoming)
{
if (!incoming.isEmpty())
{
// Take all the logs as they stand currently and forward them synchronously before shutdown
copy = new LinkedList<>(incoming);
incoming.clear();
}
else
{
copy = null;
}
}
if (copy != null)
{
// Keep forwarding logs until we encounter an error (or run out of logs to forward)
while (!copy.isEmpty() && (forwardLogs(copy) > 0))
;
if (!copy.isEmpty())
log.warn(
"Shutdown called but failed to transfer all pending logs at time of shutdown to Service Manager: there are " +
copy.size() +
" remaining");
}
}
catch (Throwable t)
{
log.warn("Logging system encountered a problem during shutdown", t);
}
super.shutdown();
} | [
"@",
"Override",
"public",
"void",
"shutdown",
"(",
")",
"{",
"// Stop the appender from delivering new messages to us",
"ServiceManagerAppender",
".",
"shutdown",
"(",
")",
";",
"// Before shutting down synchronously transfer all the pending logs",
"try",
"{",
"final",
"Linked... | Shuts down the log forwarding | [
"Shuts",
"down",
"the",
"log",
"forwarding"
] | d4025d2f881bc0542b1e004c5f65a1ccaf895836 | https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/guice/common/src/main/java/com/peterphi/std/guice/common/logging/appender/ServiceManagerLogForwardDaemon.java#L245-L288 | train |
petergeneric/stdlib | util/carbon-client/src/main/java/com/peterphi/carbon/type/immutable/CarbonReply.java | CarbonReply.getProfileList | public List<CarbonProfile> getProfileList()
{
final List<CarbonProfile> profiles = new ArrayList<CarbonProfile>();
Element profileList = element.getChild("ProfileList");
if (profileList != null)
{
for (Element profileElement : profileList.getChildren())
{
CarbonProfile profile = new CarbonProfile(profileElement);
profiles.add(profile);
}
}
return profiles;
} | java | public List<CarbonProfile> getProfileList()
{
final List<CarbonProfile> profiles = new ArrayList<CarbonProfile>();
Element profileList = element.getChild("ProfileList");
if (profileList != null)
{
for (Element profileElement : profileList.getChildren())
{
CarbonProfile profile = new CarbonProfile(profileElement);
profiles.add(profile);
}
}
return profiles;
} | [
"public",
"List",
"<",
"CarbonProfile",
">",
"getProfileList",
"(",
")",
"{",
"final",
"List",
"<",
"CarbonProfile",
">",
"profiles",
"=",
"new",
"ArrayList",
"<",
"CarbonProfile",
">",
"(",
")",
";",
"Element",
"profileList",
"=",
"element",
".",
"getChild"... | Return the list of profiles contained within the response
@return | [
"Return",
"the",
"list",
"of",
"profiles",
"contained",
"within",
"the",
"response"
] | d4025d2f881bc0542b1e004c5f65a1ccaf895836 | https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/util/carbon-client/src/main/java/com/peterphi/carbon/type/immutable/CarbonReply.java#L127-L144 | train |
petergeneric/stdlib | guice/common/src/main/java/com/peterphi/std/guice/common/ognl/OgnlEvaluator.java | OgnlEvaluator.compile | Node compile(final Object root)
{
if (compiled == null)
{
compiled = compileExpression(root, this.expr);
parsed = null;
if (this.notifyOnCompiled != null)
this.notifyOnCompiled.accept(this.expr, this);
}
return compiled;
} | java | Node compile(final Object root)
{
if (compiled == null)
{
compiled = compileExpression(root, this.expr);
parsed = null;
if (this.notifyOnCompiled != null)
this.notifyOnCompiled.accept(this.expr, this);
}
return compiled;
} | [
"Node",
"compile",
"(",
"final",
"Object",
"root",
")",
"{",
"if",
"(",
"compiled",
"==",
"null",
")",
"{",
"compiled",
"=",
"compileExpression",
"(",
"root",
",",
"this",
".",
"expr",
")",
";",
"parsed",
"=",
"null",
";",
"if",
"(",
"this",
".",
"... | Eagerly compile this OGNL expression
@param root
@return | [
"Eagerly",
"compile",
"this",
"OGNL",
"expression"
] | d4025d2f881bc0542b1e004c5f65a1ccaf895836 | https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/guice/common/src/main/java/com/peterphi/std/guice/common/ognl/OgnlEvaluator.java#L85-L97 | train |
ziccardi/jnrpe | jcheck_nrpe/src/main/java/it/jnrpe/client/JNRPEClient.java | JNRPEClient.sendCommand | public final ReturnValue sendCommand(final String sCommandName, final String... arguments) throws JNRPEClientException {
return sendRequest(new JNRPERequest(sCommandName, arguments));
} | java | public final ReturnValue sendCommand(final String sCommandName, final String... arguments) throws JNRPEClientException {
return sendRequest(new JNRPERequest(sCommandName, arguments));
} | [
"public",
"final",
"ReturnValue",
"sendCommand",
"(",
"final",
"String",
"sCommandName",
",",
"final",
"String",
"...",
"arguments",
")",
"throws",
"JNRPEClientException",
"{",
"return",
"sendRequest",
"(",
"new",
"JNRPERequest",
"(",
"sCommandName",
",",
"arguments... | Inovoke a command installed in JNRPE.
@param sCommandName
The name of the command to be invoked
@param arguments
The arguments to pass to the command (will substitute the
$ARGSx$ parameters)
@return The value returned by the server
@throws JNRPEClientException
Thrown on any communication error. | [
"Inovoke",
"a",
"command",
"installed",
"in",
"JNRPE",
"."
] | ac9046355851136994388442b01ba4063305f9c4 | https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jcheck_nrpe/src/main/java/it/jnrpe/client/JNRPEClient.java#L226-L228 | train |
ziccardi/jnrpe | jcheck_nrpe/src/main/java/it/jnrpe/client/JNRPEClient.java | JNRPEClient.printVersion | private static void printVersion() {
System.out.println("jcheck_nrpe version " + JNRPEClient.class.getPackage().getImplementationVersion());
System.out.println("Copyright (c) 2013 Massimiliano Ziccardi");
System.out.println("Licensed under the Apache License, Version 2.0");
System.out.println();
} | java | private static void printVersion() {
System.out.println("jcheck_nrpe version " + JNRPEClient.class.getPackage().getImplementationVersion());
System.out.println("Copyright (c) 2013 Massimiliano Ziccardi");
System.out.println("Licensed under the Apache License, Version 2.0");
System.out.println();
} | [
"private",
"static",
"void",
"printVersion",
"(",
")",
"{",
"System",
".",
"out",
".",
"println",
"(",
"\"jcheck_nrpe version \"",
"+",
"JNRPEClient",
".",
"class",
".",
"getPackage",
"(",
")",
".",
"getImplementationVersion",
"(",
")",
")",
";",
"System",
"... | Prints the application version. | [
"Prints",
"the",
"application",
"version",
"."
] | ac9046355851136994388442b01ba4063305f9c4 | https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jcheck_nrpe/src/main/java/it/jnrpe/client/JNRPEClient.java#L330-L336 | train |
ziccardi/jnrpe | jcheck_nrpe/src/main/java/it/jnrpe/client/JNRPEClient.java | JNRPEClient.printUsage | @SuppressWarnings("unchecked")
private static void printUsage(final Exception e) {
printVersion();
StringBuilder sbDivider = new StringBuilder("=");
if (e != null) {
System.out.println(e.getMessage() + "\n");
}
HelpFormatter hf = new HelpFormatter();
while (sbDivider.length() < hf.getPageWidth()) {
sbDivider.append('=');
}
// DISPLAY SETTING
Set displaySettings = hf.getDisplaySettings();
displaySettings.clear();
displaySettings.add(DisplaySetting.DISPLAY_GROUP_EXPANDED);
displaySettings.add(DisplaySetting.DISPLAY_PARENT_CHILDREN);
// USAGE SETTING
Set usageSettings = hf.getFullUsageSettings();
usageSettings.clear();
usageSettings.add(DisplaySetting.DISPLAY_PARENT_ARGUMENT);
usageSettings.add(DisplaySetting.DISPLAY_ARGUMENT_BRACKETED);
usageSettings.add(DisplaySetting.DISPLAY_PARENT_CHILDREN);
usageSettings.add(DisplaySetting.DISPLAY_GROUP_EXPANDED);
hf.setDivider(sbDivider.toString());
hf.setGroup(configureCommandLine());
hf.print();
} | java | @SuppressWarnings("unchecked")
private static void printUsage(final Exception e) {
printVersion();
StringBuilder sbDivider = new StringBuilder("=");
if (e != null) {
System.out.println(e.getMessage() + "\n");
}
HelpFormatter hf = new HelpFormatter();
while (sbDivider.length() < hf.getPageWidth()) {
sbDivider.append('=');
}
// DISPLAY SETTING
Set displaySettings = hf.getDisplaySettings();
displaySettings.clear();
displaySettings.add(DisplaySetting.DISPLAY_GROUP_EXPANDED);
displaySettings.add(DisplaySetting.DISPLAY_PARENT_CHILDREN);
// USAGE SETTING
Set usageSettings = hf.getFullUsageSettings();
usageSettings.clear();
usageSettings.add(DisplaySetting.DISPLAY_PARENT_ARGUMENT);
usageSettings.add(DisplaySetting.DISPLAY_ARGUMENT_BRACKETED);
usageSettings.add(DisplaySetting.DISPLAY_PARENT_CHILDREN);
usageSettings.add(DisplaySetting.DISPLAY_GROUP_EXPANDED);
hf.setDivider(sbDivider.toString());
hf.setGroup(configureCommandLine());
hf.print();
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"private",
"static",
"void",
"printUsage",
"(",
"final",
"Exception",
"e",
")",
"{",
"printVersion",
"(",
")",
";",
"StringBuilder",
"sbDivider",
"=",
"new",
"StringBuilder",
"(",
"\"=\"",
")",
";",
"if",
"... | Prints usage instrunctions and, eventually, an error message about the
latest execution.
@param e
The exception error | [
"Prints",
"usage",
"instrunctions",
"and",
"eventually",
"an",
"error",
"message",
"about",
"the",
"latest",
"execution",
"."
] | ac9046355851136994388442b01ba4063305f9c4 | https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jcheck_nrpe/src/main/java/it/jnrpe/client/JNRPEClient.java#L345-L379 | train |
petergeneric/stdlib | stdlib/src/main/java/com/peterphi/std/system/exec/AbstractProcessTracker.java | AbstractProcessTracker.isFinished | public boolean isFinished()
{
if (finished)
return true;
try
{
final int code = exitCode();
finished(code);
return true;
}
catch (IllegalThreadStateException e)
{
return false;
}
} | java | public boolean isFinished()
{
if (finished)
return true;
try
{
final int code = exitCode();
finished(code);
return true;
}
catch (IllegalThreadStateException e)
{
return false;
}
} | [
"public",
"boolean",
"isFinished",
"(",
")",
"{",
"if",
"(",
"finished",
")",
"return",
"true",
";",
"try",
"{",
"final",
"int",
"code",
"=",
"exitCode",
"(",
")",
";",
"finished",
"(",
"code",
")",
";",
"return",
"true",
";",
"}",
"catch",
"(",
"I... | Determines if the application has completed yet
@return true if the process has terminated, otherwise false | [
"Determines",
"if",
"the",
"application",
"has",
"completed",
"yet"
] | d4025d2f881bc0542b1e004c5f65a1ccaf895836 | https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/stdlib/src/main/java/com/peterphi/std/system/exec/AbstractProcessTracker.java#L59-L76 | train |
petergeneric/stdlib | stdlib/src/main/java/com/peterphi/std/system/exec/AbstractProcessTracker.java | AbstractProcessTracker.copy | protected Thread copy(final InputStream in, final Writer out)
{
Runnable r = () -> {
try
{
StreamUtil.streamCopy(in, out);
}
catch (IOException e)
{
try
{
out.flush();
}
catch (Throwable t)
{
}
unexpectedFailure(e);
}
};
Thread t = new Thread(r);
t.setName(this + " - IOCopy " + in + " to " + out);
t.setDaemon(true);
t.start();
return t;
} | java | protected Thread copy(final InputStream in, final Writer out)
{
Runnable r = () -> {
try
{
StreamUtil.streamCopy(in, out);
}
catch (IOException e)
{
try
{
out.flush();
}
catch (Throwable t)
{
}
unexpectedFailure(e);
}
};
Thread t = new Thread(r);
t.setName(this + " - IOCopy " + in + " to " + out);
t.setDaemon(true);
t.start();
return t;
} | [
"protected",
"Thread",
"copy",
"(",
"final",
"InputStream",
"in",
",",
"final",
"Writer",
"out",
")",
"{",
"Runnable",
"r",
"=",
"(",
")",
"->",
"{",
"try",
"{",
"StreamUtil",
".",
"streamCopy",
"(",
"in",
",",
"out",
")",
";",
"}",
"catch",
"(",
"... | Commence a background copy | [
"Commence",
"a",
"background",
"copy"
] | d4025d2f881bc0542b1e004c5f65a1ccaf895836 | https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/stdlib/src/main/java/com/peterphi/std/system/exec/AbstractProcessTracker.java#L253-L280 | train |
petergeneric/stdlib | guice/webapp/src/main/java/com/peterphi/std/guice/web/rest/resteasy/GuicedResteasy.java | GuicedResteasy.configure | protected void configure(ServletContainerDispatcher dispatcher) throws ServletException
{
// Make sure we are registered with the Guice registry
registry.register(this, true);
// Configure the dispatcher
final Registry resteasyRegistry;
final ResteasyProviderFactory providerFactory;
{
final ResteasyRequestResponseFactory converter = new ResteasyRequestResponseFactory(dispatcher);
dispatcher.init(context, bootstrap, converter, converter);
if (filterConfig != null)
dispatcher.getDispatcher().getDefaultContextObjects().put(FilterConfig.class, filterConfig);
if (servletConfig != null)
dispatcher.getDispatcher().getDefaultContextObjects().put(ServletConfig.class, servletConfig);
resteasyRegistry = dispatcher.getDispatcher().getRegistry();
providerFactory = dispatcher.getDispatcher().getProviderFactory();
}
// Register the REST provider classes
for (Class<?> providerClass : ResteasyProviderRegistry.getClasses())
{
log.debug("Registering REST providers: " + providerClass.getName());
providerFactory.registerProvider(providerClass);
}
// Register the REST provider singletons
for (Object provider : ResteasyProviderRegistry.getSingletons())
{
log.debug("Registering REST provider singleton: " + provider);
providerFactory.registerProviderInstance(provider);
}
providerFactory.registerProviderInstance(new LogReportMessageBodyReader());
// Register the JAXBContext provider
providerFactory.registerProviderInstance(jaxbContextResolver);
// Register the exception mapper
{
// Register the ExceptionMapper for ApplicationException
providerFactory.register(this.exceptionMapper);
log.trace("ExceptionMapper registered for ApplicationException");
}
// Register the REST resources
for (RestResource resource : RestResourceRegistry.getResources())
{
log.debug("Registering REST resource: " + resource.getResourceClass().getName());
resteasyRegistry.addResourceFactory(new ResteasyGuiceResource(injector, resource.getResourceClass()));
}
} | java | protected void configure(ServletContainerDispatcher dispatcher) throws ServletException
{
// Make sure we are registered with the Guice registry
registry.register(this, true);
// Configure the dispatcher
final Registry resteasyRegistry;
final ResteasyProviderFactory providerFactory;
{
final ResteasyRequestResponseFactory converter = new ResteasyRequestResponseFactory(dispatcher);
dispatcher.init(context, bootstrap, converter, converter);
if (filterConfig != null)
dispatcher.getDispatcher().getDefaultContextObjects().put(FilterConfig.class, filterConfig);
if (servletConfig != null)
dispatcher.getDispatcher().getDefaultContextObjects().put(ServletConfig.class, servletConfig);
resteasyRegistry = dispatcher.getDispatcher().getRegistry();
providerFactory = dispatcher.getDispatcher().getProviderFactory();
}
// Register the REST provider classes
for (Class<?> providerClass : ResteasyProviderRegistry.getClasses())
{
log.debug("Registering REST providers: " + providerClass.getName());
providerFactory.registerProvider(providerClass);
}
// Register the REST provider singletons
for (Object provider : ResteasyProviderRegistry.getSingletons())
{
log.debug("Registering REST provider singleton: " + provider);
providerFactory.registerProviderInstance(provider);
}
providerFactory.registerProviderInstance(new LogReportMessageBodyReader());
// Register the JAXBContext provider
providerFactory.registerProviderInstance(jaxbContextResolver);
// Register the exception mapper
{
// Register the ExceptionMapper for ApplicationException
providerFactory.register(this.exceptionMapper);
log.trace("ExceptionMapper registered for ApplicationException");
}
// Register the REST resources
for (RestResource resource : RestResourceRegistry.getResources())
{
log.debug("Registering REST resource: " + resource.getResourceClass().getName());
resteasyRegistry.addResourceFactory(new ResteasyGuiceResource(injector, resource.getResourceClass()));
}
} | [
"protected",
"void",
"configure",
"(",
"ServletContainerDispatcher",
"dispatcher",
")",
"throws",
"ServletException",
"{",
"// Make sure we are registered with the Guice registry",
"registry",
".",
"register",
"(",
"this",
",",
"true",
")",
";",
"// Configure the dispatcher",... | Try to initialise a ServletContainerDispatcher with the connection to the Guice REST services | [
"Try",
"to",
"initialise",
"a",
"ServletContainerDispatcher",
"with",
"the",
"connection",
"to",
"the",
"Guice",
"REST",
"services"
] | d4025d2f881bc0542b1e004c5f65a1ccaf895836 | https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/guice/webapp/src/main/java/com/peterphi/std/guice/web/rest/resteasy/GuicedResteasy.java#L330-L386 | train |
ziccardi/jnrpe | jnrpe-lib/src/main/java/it/jnrpe/utils/thresholds/RangeException.java | RangeException.parseExpecting | private static String parseExpecting(final Stage stage) {
StringBuilder expected = new StringBuilder();
for (String key : stage.getTransitionNames()) {
expected.append(',').append(stage.getTransition(key).expects());
}
return expected.substring(1);
} | java | private static String parseExpecting(final Stage stage) {
StringBuilder expected = new StringBuilder();
for (String key : stage.getTransitionNames()) {
expected.append(',').append(stage.getTransition(key).expects());
}
return expected.substring(1);
} | [
"private",
"static",
"String",
"parseExpecting",
"(",
"final",
"Stage",
"stage",
")",
"{",
"StringBuilder",
"expected",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"for",
"(",
"String",
"key",
":",
"stage",
".",
"getTransitionNames",
"(",
")",
")",
"{",
"e... | Utility method for error messages.
@param stage
the stage to ask for expected tokens.
@return The list of expected tokens | [
"Utility",
"method",
"for",
"error",
"messages",
"."
] | ac9046355851136994388442b01ba4063305f9c4 | https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-lib/src/main/java/it/jnrpe/utils/thresholds/RangeException.java#L123-L131 | train |
petergeneric/stdlib | stdlib/src/main/java/com/peterphi/std/io/FileHelper.java | FileHelper.createTempFile | public static File createTempFile(final String prefix, final String suffix)
{
try
{
File tempFile = File.createTempFile(prefix, suffix);
if (tempFile.exists())
{
if (!tempFile.delete())
throw new RuntimeException("Could not delete new temp file: " + tempFile);
}
return tempFile;
}
catch (IOException e)
{
log.error("[FileHelper] {createTempFile} Error creating temp file: " + e.getMessage(), e);
return null;
}
} | java | public static File createTempFile(final String prefix, final String suffix)
{
try
{
File tempFile = File.createTempFile(prefix, suffix);
if (tempFile.exists())
{
if (!tempFile.delete())
throw new RuntimeException("Could not delete new temp file: " + tempFile);
}
return tempFile;
}
catch (IOException e)
{
log.error("[FileHelper] {createTempFile} Error creating temp file: " + e.getMessage(), e);
return null;
}
} | [
"public",
"static",
"File",
"createTempFile",
"(",
"final",
"String",
"prefix",
",",
"final",
"String",
"suffix",
")",
"{",
"try",
"{",
"File",
"tempFile",
"=",
"File",
".",
"createTempFile",
"(",
"prefix",
",",
"suffix",
")",
";",
"if",
"(",
"tempFile",
... | Creates a temporary file name
@return File | [
"Creates",
"a",
"temporary",
"file",
"name"
] | d4025d2f881bc0542b1e004c5f65a1ccaf895836 | https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/stdlib/src/main/java/com/peterphi/std/io/FileHelper.java#L55-L73 | train |
petergeneric/stdlib | stdlib/src/main/java/com/peterphi/std/io/FileHelper.java | FileHelper.safeMove | @Deprecated
public static boolean safeMove(File src, File dest) throws SecurityException
{
assert (src.exists());
final boolean createDestIfNotExist = true;
try
{
if (src.isFile())
FileUtils.moveFile(src, dest);
else
FileUtils.moveDirectoryToDirectory(src, dest, createDestIfNotExist);
return true;
}
catch (IOException e)
{
log.error("{safeMove} Error during move operation: " + e.getMessage(), e);
return false;
}
} | java | @Deprecated
public static boolean safeMove(File src, File dest) throws SecurityException
{
assert (src.exists());
final boolean createDestIfNotExist = true;
try
{
if (src.isFile())
FileUtils.moveFile(src, dest);
else
FileUtils.moveDirectoryToDirectory(src, dest, createDestIfNotExist);
return true;
}
catch (IOException e)
{
log.error("{safeMove} Error during move operation: " + e.getMessage(), e);
return false;
}
} | [
"@",
"Deprecated",
"public",
"static",
"boolean",
"safeMove",
"(",
"File",
"src",
",",
"File",
"dest",
")",
"throws",
"SecurityException",
"{",
"assert",
"(",
"src",
".",
"exists",
"(",
")",
")",
";",
"final",
"boolean",
"createDestIfNotExist",
"=",
"true",
... | Safely moves a file from one place to another, ensuring the filesystem is left in a consistent state
@param src
File The source file
@param dest
File The destination file
@return boolean True if the file has been completely moved to the new location, false if it is still in the original
location
@throws java.lang.SecurityException
MAY BE THROWN if permission is denied to src or dest
@deprecated use commons file utils FileUtils.moveDirectoryToDirectory instead | [
"Safely",
"moves",
"a",
"file",
"from",
"one",
"place",
"to",
"another",
"ensuring",
"the",
"filesystem",
"is",
"left",
"in",
"a",
"consistent",
"state"
] | d4025d2f881bc0542b1e004c5f65a1ccaf895836 | https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/stdlib/src/main/java/com/peterphi/std/io/FileHelper.java#L335-L356 | train |
petergeneric/stdlib | stdlib/src/main/java/com/peterphi/std/io/FileHelper.java | FileHelper.delete | public static boolean delete(File f) throws IOException
{
assert (f.exists());
if (f.isDirectory())
{
FileUtils.deleteDirectory(f);
return true;
}
else
{
return f.delete();
}
} | java | public static boolean delete(File f) throws IOException
{
assert (f.exists());
if (f.isDirectory())
{
FileUtils.deleteDirectory(f);
return true;
}
else
{
return f.delete();
}
} | [
"public",
"static",
"boolean",
"delete",
"(",
"File",
"f",
")",
"throws",
"IOException",
"{",
"assert",
"(",
"f",
".",
"exists",
"(",
")",
")",
";",
"if",
"(",
"f",
".",
"isDirectory",
"(",
")",
")",
"{",
"FileUtils",
".",
"deleteDirectory",
"(",
"f"... | Deletes a local file or directory from the filesystem
@param f
File The file/directory to delete
@return boolean True if the deletion was a success, otherwise false | [
"Deletes",
"a",
"local",
"file",
"or",
"directory",
"from",
"the",
"filesystem"
] | d4025d2f881bc0542b1e004c5f65a1ccaf895836 | https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/stdlib/src/main/java/com/peterphi/std/io/FileHelper.java#L367-L380 | train |
petergeneric/stdlib | stdlib/src/main/java/com/peterphi/std/io/FileHelper.java | FileHelper.smartEquals | public static boolean smartEquals(File one, File two, boolean checkName) throws IOException
{
if (checkName)
{
if (!one.getName().equals(two.getName()))
{
return false;
}
}
if (one.isDirectory() == two.isDirectory())
{
if (one.isDirectory())
{
File[] filesOne = one.listFiles();
File[] filesTwo = two.listFiles();
if (filesOne.length == filesTwo.length)
{
if (filesOne.length > 0)
{
for (int i = 0; i < filesOne.length; i++)
{
if (!smartEquals(filesOne[i], filesTwo[i], checkName))
{
return false;
}
}
return true; // all subfiles are equal
}
else
{
return true;
}
}
else
{
return false;
}
} // Otherwise, the File objects are Files
else if (one.isFile() && two.isFile())
{
if (one.length() == two.length())
{
return FileUtils.contentEquals(one, two);
}
else
{
return false;
}
}
else
{
throw new IOException("I don't know how to handle a non-file non-directory File: one=" + one + " two=" + two);
}
} // One is a directory and the other is not
else
{
return false;
}
} | java | public static boolean smartEquals(File one, File two, boolean checkName) throws IOException
{
if (checkName)
{
if (!one.getName().equals(two.getName()))
{
return false;
}
}
if (one.isDirectory() == two.isDirectory())
{
if (one.isDirectory())
{
File[] filesOne = one.listFiles();
File[] filesTwo = two.listFiles();
if (filesOne.length == filesTwo.length)
{
if (filesOne.length > 0)
{
for (int i = 0; i < filesOne.length; i++)
{
if (!smartEquals(filesOne[i], filesTwo[i], checkName))
{
return false;
}
}
return true; // all subfiles are equal
}
else
{
return true;
}
}
else
{
return false;
}
} // Otherwise, the File objects are Files
else if (one.isFile() && two.isFile())
{
if (one.length() == two.length())
{
return FileUtils.contentEquals(one, two);
}
else
{
return false;
}
}
else
{
throw new IOException("I don't know how to handle a non-file non-directory File: one=" + one + " two=" + two);
}
} // One is a directory and the other is not
else
{
return false;
}
} | [
"public",
"static",
"boolean",
"smartEquals",
"(",
"File",
"one",
",",
"File",
"two",
",",
"boolean",
"checkName",
")",
"throws",
"IOException",
"{",
"if",
"(",
"checkName",
")",
"{",
"if",
"(",
"!",
"one",
".",
"getName",
"(",
")",
".",
"equals",
"(",... | Determines if 2 files or directories are equivalent by looking inside them
@param one
File The first file/directory
@param two
File The second file/directory
@param checkName
boolean Whether names should be identical also
@return boolean True if the files/directories are equivalent, otherwise false
@throws IOException
On an unhandleable error or a non-file, non-directory input | [
"Determines",
"if",
"2",
"files",
"or",
"directories",
"are",
"equivalent",
"by",
"looking",
"inside",
"them"
] | d4025d2f881bc0542b1e004c5f65a1ccaf895836 | https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/stdlib/src/main/java/com/peterphi/std/io/FileHelper.java#L398-L458 | train |
petergeneric/stdlib | util/carbon-client/src/main/java/com/peterphi/carbon/CarbonClientImpl.java | CarbonClientImpl.send | public CarbonReply send(Element element) throws CarbonException
{
try
{
final String responseXml = send(serialise(element));
return new CarbonReply(deserialise(responseXml));
}
catch (CarbonException e)
{
throw e;
}
catch (Exception e)
{
throw new CarbonException(e);
}
} | java | public CarbonReply send(Element element) throws CarbonException
{
try
{
final String responseXml = send(serialise(element));
return new CarbonReply(deserialise(responseXml));
}
catch (CarbonException e)
{
throw e;
}
catch (Exception e)
{
throw new CarbonException(e);
}
} | [
"public",
"CarbonReply",
"send",
"(",
"Element",
"element",
")",
"throws",
"CarbonException",
"{",
"try",
"{",
"final",
"String",
"responseXml",
"=",
"send",
"(",
"serialise",
"(",
"element",
")",
")",
";",
"return",
"new",
"CarbonReply",
"(",
"deserialise",
... | Send some XML
@param doc
@return
@throws CarbonException | [
"Send",
"some",
"XML"
] | d4025d2f881bc0542b1e004c5f65a1ccaf895836 | https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/util/carbon-client/src/main/java/com/peterphi/carbon/CarbonClientImpl.java#L103-L119 | train |
ops4j/org.ops4j.pax.swissbox | pax-swissbox-tracker/src/main/java/org/ops4j/pax/swissbox/tracker/ReplaceableService.java | ReplaceableService.setService | private synchronized void setService( final T newService )
{
if( m_service != newService )
{
LOG.debug( "Service changed [" + m_service + "] -> [" + newService + "]" );
final T oldService = m_service;
m_service = newService;
if( m_serviceListener != null )
{
m_serviceListener.serviceChanged( oldService, m_service );
}
}
} | java | private synchronized void setService( final T newService )
{
if( m_service != newService )
{
LOG.debug( "Service changed [" + m_service + "] -> [" + newService + "]" );
final T oldService = m_service;
m_service = newService;
if( m_serviceListener != null )
{
m_serviceListener.serviceChanged( oldService, m_service );
}
}
} | [
"private",
"synchronized",
"void",
"setService",
"(",
"final",
"T",
"newService",
")",
"{",
"if",
"(",
"m_service",
"!=",
"newService",
")",
"{",
"LOG",
".",
"debug",
"(",
"\"Service changed [\"",
"+",
"m_service",
"+",
"\"] -> [\"",
"+",
"newService",
"+",
... | Sets the new service and notifies the listener that the service was changed.
@param newService the new service | [
"Sets",
"the",
"new",
"service",
"and",
"notifies",
"the",
"listener",
"that",
"the",
"service",
"was",
"changed",
"."
] | 00b0ee16cdbe8017984a4d7ba808b10d985c5b5c | https://github.com/ops4j/org.ops4j.pax.swissbox/blob/00b0ee16cdbe8017984a4d7ba808b10d985c5b5c/pax-swissbox-tracker/src/main/java/org/ops4j/pax/swissbox/tracker/ReplaceableService.java#L106-L118 | train |
ops4j/org.ops4j.pax.swissbox | pax-swissbox-tracker/src/main/java/org/ops4j/pax/swissbox/tracker/ReplaceableService.java | ReplaceableService.resolveService | private synchronized void resolveService()
{
T newService = null;
final Iterator<T> it = m_serviceCollection.iterator();
while( newService == null && it.hasNext() )
{
final T candidateService = it.next();
if( !candidateService.equals( getService() ) )
{
newService = candidateService;
}
}
setService( newService );
} | java | private synchronized void resolveService()
{
T newService = null;
final Iterator<T> it = m_serviceCollection.iterator();
while( newService == null && it.hasNext() )
{
final T candidateService = it.next();
if( !candidateService.equals( getService() ) )
{
newService = candidateService;
}
}
setService( newService );
} | [
"private",
"synchronized",
"void",
"resolveService",
"(",
")",
"{",
"T",
"newService",
"=",
"null",
";",
"final",
"Iterator",
"<",
"T",
">",
"it",
"=",
"m_serviceCollection",
".",
"iterator",
"(",
")",
";",
"while",
"(",
"newService",
"==",
"null",
"&&",
... | Resolves a new service by serching the services collection for first available service. | [
"Resolves",
"a",
"new",
"service",
"by",
"serching",
"the",
"services",
"collection",
"for",
"first",
"available",
"service",
"."
] | 00b0ee16cdbe8017984a4d7ba808b10d985c5b5c | https://github.com/ops4j/org.ops4j.pax.swissbox/blob/00b0ee16cdbe8017984a4d7ba808b10d985c5b5c/pax-swissbox-tracker/src/main/java/org/ops4j/pax/swissbox/tracker/ReplaceableService.java#L123-L136 | train |
ops4j/org.ops4j.pax.swissbox | pax-swissbox-tracker/src/main/java/org/ops4j/pax/swissbox/tracker/ReplaceableService.java | ReplaceableService.onStart | @Override
protected void onStart()
{
m_serviceCollection = new ServiceCollection<T>( m_context, m_serviceClass, new CollectionListener() );
m_serviceCollection.start();
} | java | @Override
protected void onStart()
{
m_serviceCollection = new ServiceCollection<T>( m_context, m_serviceClass, new CollectionListener() );
m_serviceCollection.start();
} | [
"@",
"Override",
"protected",
"void",
"onStart",
"(",
")",
"{",
"m_serviceCollection",
"=",
"new",
"ServiceCollection",
"<",
"T",
">",
"(",
"m_context",
",",
"m_serviceClass",
",",
"new",
"CollectionListener",
"(",
")",
")",
";",
"m_serviceCollection",
".",
"s... | Creates a service collection and starts it.
@see AbstractLifecycle#onStart | [
"Creates",
"a",
"service",
"collection",
"and",
"starts",
"it",
"."
] | 00b0ee16cdbe8017984a4d7ba808b10d985c5b5c | https://github.com/ops4j/org.ops4j.pax.swissbox/blob/00b0ee16cdbe8017984a4d7ba808b10d985c5b5c/pax-swissbox-tracker/src/main/java/org/ops4j/pax/swissbox/tracker/ReplaceableService.java#L143-L148 | train |
ops4j/org.ops4j.pax.swissbox | pax-swissbox-tracker/src/main/java/org/ops4j/pax/swissbox/tracker/ReplaceableService.java | ReplaceableService.onStop | @Override
protected void onStop()
{
if( m_serviceCollection != null )
{
m_serviceCollection.stop();
m_serviceCollection = null;
}
setService( null );
} | java | @Override
protected void onStop()
{
if( m_serviceCollection != null )
{
m_serviceCollection.stop();
m_serviceCollection = null;
}
setService( null );
} | [
"@",
"Override",
"protected",
"void",
"onStop",
"(",
")",
"{",
"if",
"(",
"m_serviceCollection",
"!=",
"null",
")",
"{",
"m_serviceCollection",
".",
"stop",
"(",
")",
";",
"m_serviceCollection",
"=",
"null",
";",
"}",
"setService",
"(",
"null",
")",
";",
... | Stops the service collection and releases resources.
@see AbstractLifecycle#onStop | [
"Stops",
"the",
"service",
"collection",
"and",
"releases",
"resources",
"."
] | 00b0ee16cdbe8017984a4d7ba808b10d985c5b5c | https://github.com/ops4j/org.ops4j.pax.swissbox/blob/00b0ee16cdbe8017984a4d7ba808b10d985c5b5c/pax-swissbox-tracker/src/main/java/org/ops4j/pax/swissbox/tracker/ReplaceableService.java#L155-L164 | train |
petergeneric/stdlib | stdlib/src/main/java/com/peterphi/std/system/exec/Exec.java | Exec.getProcessBuilder | public ProcessBuilder getProcessBuilder()
{
if (spawned)
return builder; // throw new IllegalStateException("Cannot call spawn twice!");
if (runAs != null)
{
String command = cmd.get(0);
if (command.charAt(0) == '-' && !SudoFeature.hasArgumentsEnd())
throw new IllegalArgumentException("Command to runAs starts with - but this version of sudo does not support the -- argument end token: this command cannot, therefore, be executed securely. Command was: '" +
command + "'");
// Pass the environment in through an "env" command:
if (this.environment.size() > 0)
{
for (final String key : this.environment.keySet())
{
final String value = this.environment.get(key);
final String var = key + "=" + value;
addToCmd(0, var);
}
// cmd.add(0,"env");
addToCmd(0, "env");
}
// cmd.add(0, "--"); // doesn't work everywhere
// cmd.add(0, runAs);
// cmd.add(0, "-u");
// cmd.add(0, "-n"); // Never prompt for a password: we simply cannot provide one
// cmd.add(0, "sudo");
if (SudoFeature.hasArgumentsEnd())
addToCmd(0, "--");
// If possible tell sudo to run non-interactively
String noninteractive = SudoFeature.hasNonInteractive() ? "-n" : null;
if (this.runAs.equals(SUPERUSER_IDENTIFIER))
{
addToCmd(0, "sudo", noninteractive);
}
else
addToCmd(0, "sudo", noninteractive, "-u", runAs);
}
else
{
builder.environment().putAll(this.environment);
}
spawned = true;
if (log.isInfoEnabled())
{
log.info("ProcessBuilder created for command: " + join(" ", cmd));
}
return builder;
} | java | public ProcessBuilder getProcessBuilder()
{
if (spawned)
return builder; // throw new IllegalStateException("Cannot call spawn twice!");
if (runAs != null)
{
String command = cmd.get(0);
if (command.charAt(0) == '-' && !SudoFeature.hasArgumentsEnd())
throw new IllegalArgumentException("Command to runAs starts with - but this version of sudo does not support the -- argument end token: this command cannot, therefore, be executed securely. Command was: '" +
command + "'");
// Pass the environment in through an "env" command:
if (this.environment.size() > 0)
{
for (final String key : this.environment.keySet())
{
final String value = this.environment.get(key);
final String var = key + "=" + value;
addToCmd(0, var);
}
// cmd.add(0,"env");
addToCmd(0, "env");
}
// cmd.add(0, "--"); // doesn't work everywhere
// cmd.add(0, runAs);
// cmd.add(0, "-u");
// cmd.add(0, "-n"); // Never prompt for a password: we simply cannot provide one
// cmd.add(0, "sudo");
if (SudoFeature.hasArgumentsEnd())
addToCmd(0, "--");
// If possible tell sudo to run non-interactively
String noninteractive = SudoFeature.hasNonInteractive() ? "-n" : null;
if (this.runAs.equals(SUPERUSER_IDENTIFIER))
{
addToCmd(0, "sudo", noninteractive);
}
else
addToCmd(0, "sudo", noninteractive, "-u", runAs);
}
else
{
builder.environment().putAll(this.environment);
}
spawned = true;
if (log.isInfoEnabled())
{
log.info("ProcessBuilder created for command: " + join(" ", cmd));
}
return builder;
} | [
"public",
"ProcessBuilder",
"getProcessBuilder",
"(",
")",
"{",
"if",
"(",
"spawned",
")",
"return",
"builder",
";",
"// throw new IllegalStateException(\"Cannot call spawn twice!\");",
"if",
"(",
"runAs",
"!=",
"null",
")",
"{",
"String",
"command",
"=",
"cmd",
"."... | Returns a ProcessBuilder for use in a manual launching
@return | [
"Returns",
"a",
"ProcessBuilder",
"for",
"use",
"in",
"a",
"manual",
"launching"
] | d4025d2f881bc0542b1e004c5f65a1ccaf895836 | https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/stdlib/src/main/java/com/peterphi/std/system/exec/Exec.java#L160-L221 | train |
ziccardi/jnrpe | jnrpe-plugins/src/main/java/it/jnrpe/plugin/CheckDisk.java | CheckDisk.percent | private int percent(final long val, final long total) {
if (total == 0) {
return 100;
}
if (val == 0) {
return 0;
}
double dVal = (double) val;
double dTotal = (double) total;
return (int) (dVal / dTotal * 100);
} | java | private int percent(final long val, final long total) {
if (total == 0) {
return 100;
}
if (val == 0) {
return 0;
}
double dVal = (double) val;
double dTotal = (double) total;
return (int) (dVal / dTotal * 100);
} | [
"private",
"int",
"percent",
"(",
"final",
"long",
"val",
",",
"final",
"long",
"total",
")",
"{",
"if",
"(",
"total",
"==",
"0",
")",
"{",
"return",
"100",
";",
"}",
"if",
"(",
"val",
"==",
"0",
")",
"{",
"return",
"0",
";",
"}",
"double",
"dV... | Compute the percent values.
@param val
The value to be represented in percent
@param total
The total value
@return The percent of val/total | [
"Compute",
"the",
"percent",
"values",
"."
] | ac9046355851136994388442b01ba4063305f9c4 | https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-plugins/src/main/java/it/jnrpe/plugin/CheckDisk.java#L58-L71 | train |
ziccardi/jnrpe | jnrpe-plugins/src/main/java/it/jnrpe/plugin/CheckDisk.java | CheckDisk.format | private String format(final long bytes) {
if (bytes > MB) {
return String.valueOf(bytes / MB) + " MB";
}
return String.valueOf(bytes / KB) + " KB";
} | java | private String format(final long bytes) {
if (bytes > MB) {
return String.valueOf(bytes / MB) + " MB";
}
return String.valueOf(bytes / KB) + " KB";
} | [
"private",
"String",
"format",
"(",
"final",
"long",
"bytes",
")",
"{",
"if",
"(",
"bytes",
">",
"MB",
")",
"{",
"return",
"String",
".",
"valueOf",
"(",
"bytes",
"/",
"MB",
")",
"+",
"\" MB\"",
";",
"}",
"return",
"String",
".",
"valueOf",
"(",
"b... | Format the size returning it as MB or KB.
@param bytes
The size to be formatted
@return The formatted size | [
"Format",
"the",
"size",
"returning",
"it",
"as",
"MB",
"or",
"KB",
"."
] | ac9046355851136994388442b01ba4063305f9c4 | https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-plugins/src/main/java/it/jnrpe/plugin/CheckDisk.java#L124-L129 | train |
petergeneric/stdlib | guice/webapp/src/main/java/com/peterphi/std/guice/web/rest/auth/interceptor/AuthConstraintMethodInterceptor.java | AuthConstraintMethodInterceptor.passes | private boolean passes(final AuthScope scope, final AuthConstraint constraint, final CurrentUser user)
{
if (scope.getSkip(constraint))
{
if (log.isTraceEnabled())
log.trace("Allowing method invocation (skip=true).");
return true;
}
else
{
final boolean pass = user.hasRole(scope.getRole(constraint));
if (log.isTraceEnabled())
if (pass)
log.trace("Allow method invocation: user " + user + " has role " + scope.getRole(constraint));
else
log.trace("Deny method invocation: user " + user + " does not have role " + scope.getRole(constraint));
return pass;
}
} | java | private boolean passes(final AuthScope scope, final AuthConstraint constraint, final CurrentUser user)
{
if (scope.getSkip(constraint))
{
if (log.isTraceEnabled())
log.trace("Allowing method invocation (skip=true).");
return true;
}
else
{
final boolean pass = user.hasRole(scope.getRole(constraint));
if (log.isTraceEnabled())
if (pass)
log.trace("Allow method invocation: user " + user + " has role " + scope.getRole(constraint));
else
log.trace("Deny method invocation: user " + user + " does not have role " + scope.getRole(constraint));
return pass;
}
} | [
"private",
"boolean",
"passes",
"(",
"final",
"AuthScope",
"scope",
",",
"final",
"AuthConstraint",
"constraint",
",",
"final",
"CurrentUser",
"user",
")",
"{",
"if",
"(",
"scope",
".",
"getSkip",
"(",
"constraint",
")",
")",
"{",
"if",
"(",
"log",
".",
... | Determines whether a given user has the necessary role to pass a constraint
@param constraint
the constraint to use to test the user
@param user
the current user
@return true if the user passes, otherwise false | [
"Determines",
"whether",
"a",
"given",
"user",
"has",
"the",
"necessary",
"role",
"to",
"pass",
"a",
"constraint"
] | d4025d2f881bc0542b1e004c5f65a1ccaf895836 | https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/guice/webapp/src/main/java/com/peterphi/std/guice/web/rest/auth/interceptor/AuthConstraintMethodInterceptor.java#L121-L142 | train |
petergeneric/stdlib | guice/common/src/main/java/com/peterphi/std/guice/common/serviceprops/ConfigurationPropertyRegistry.java | ConfigurationPropertyRegistry.addInstance | void addInstance(final Class<?> discoveredType, final Object newlyConstructed)
{
WeakHashMap<Object, Void> map;
synchronized (instances)
{
map = instances.get(discoveredType);
if (map == null)
{
map = new WeakHashMap<>();
instances.put(discoveredType, map);
}
}
synchronized (map)
{
map.put(newlyConstructed, null);
}
} | java | void addInstance(final Class<?> discoveredType, final Object newlyConstructed)
{
WeakHashMap<Object, Void> map;
synchronized (instances)
{
map = instances.get(discoveredType);
if (map == null)
{
map = new WeakHashMap<>();
instances.put(discoveredType, map);
}
}
synchronized (map)
{
map.put(newlyConstructed, null);
}
} | [
"void",
"addInstance",
"(",
"final",
"Class",
"<",
"?",
">",
"discoveredType",
",",
"final",
"Object",
"newlyConstructed",
")",
"{",
"WeakHashMap",
"<",
"Object",
",",
"Void",
">",
"map",
";",
"synchronized",
"(",
"instances",
")",
"{",
"map",
"=",
"instan... | Register an instance of a property-consuming type; the registry will use a weak reference to hold on to this instance, so
that it can be discarded if it has a short lifespan
@param discoveredType
@param newlyConstructed | [
"Register",
"an",
"instance",
"of",
"a",
"property",
"-",
"consuming",
"type",
";",
"the",
"registry",
"will",
"use",
"a",
"weak",
"reference",
"to",
"hold",
"on",
"to",
"this",
"instance",
"so",
"that",
"it",
"can",
"be",
"discarded",
"if",
"it",
"has",... | d4025d2f881bc0542b1e004c5f65a1ccaf895836 | https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/guice/common/src/main/java/com/peterphi/std/guice/common/serviceprops/ConfigurationPropertyRegistry.java#L112-L131 | train |
ziccardi/jnrpe | jnrpe-plugins/src/main/java/it/jnrpe/plugin/utils/HttpUtils.java | HttpUtils.doGET | public static String doGET(final URL url, final Properties requestProps, final Integer timeout, boolean includeHeaders, boolean ignoreBody)
throws Exception {
return doRequest(url, requestProps, timeout, includeHeaders, ignoreBody, "GET");
} | java | public static String doGET(final URL url, final Properties requestProps, final Integer timeout, boolean includeHeaders, boolean ignoreBody)
throws Exception {
return doRequest(url, requestProps, timeout, includeHeaders, ignoreBody, "GET");
} | [
"public",
"static",
"String",
"doGET",
"(",
"final",
"URL",
"url",
",",
"final",
"Properties",
"requestProps",
",",
"final",
"Integer",
"timeout",
",",
"boolean",
"includeHeaders",
",",
"boolean",
"ignoreBody",
")",
"throws",
"Exception",
"{",
"return",
"doReque... | Do a http get request and return response
@param url target url
@param requestProps props to be requested
@param timeout connection timeout
@param includeHeaders whether to include headers or not
@param ignoreBody whether to ignore body content or not
@return server answer
@throws Exception on any connection | [
"Do",
"a",
"http",
"get",
"request",
"and",
"return",
"response"
] | ac9046355851136994388442b01ba4063305f9c4 | https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-plugins/src/main/java/it/jnrpe/plugin/utils/HttpUtils.java#L48-L51 | train |
ziccardi/jnrpe | jnrpe-plugins/src/main/java/it/jnrpe/plugin/utils/HttpUtils.java | HttpUtils.doPOST | public static String doPOST(final URL url, final Properties requestProps, final Integer timeout, final String encodedData,
boolean includeHeaders, boolean ignoreBody) throws IOException {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
setRequestProperties(requestProps, conn, timeout);
sendPostData(conn, encodedData);
return parseHttpResponse(conn, includeHeaders, ignoreBody);
} | java | public static String doPOST(final URL url, final Properties requestProps, final Integer timeout, final String encodedData,
boolean includeHeaders, boolean ignoreBody) throws IOException {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
setRequestProperties(requestProps, conn, timeout);
sendPostData(conn, encodedData);
return parseHttpResponse(conn, includeHeaders, ignoreBody);
} | [
"public",
"static",
"String",
"doPOST",
"(",
"final",
"URL",
"url",
",",
"final",
"Properties",
"requestProps",
",",
"final",
"Integer",
"timeout",
",",
"final",
"String",
"encodedData",
",",
"boolean",
"includeHeaders",
",",
"boolean",
"ignoreBody",
")",
"throw... | Do a http post request and return response
@param url target url
@param requestProps props to be requested
@param timeout connection timeout
@param includeHeaders whether to include headers or not
@param ignoreBody whether to ignore body content or not
@return server answer
@throws IOException on any connection | [
"Do",
"a",
"http",
"post",
"request",
"and",
"return",
"response"
] | ac9046355851136994388442b01ba4063305f9c4 | https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-plugins/src/main/java/it/jnrpe/plugin/utils/HttpUtils.java#L80-L86 | train |
ziccardi/jnrpe | jnrpe-plugins/src/main/java/it/jnrpe/plugin/utils/HttpUtils.java | HttpUtils.sendPostData | public static void sendPostData(HttpURLConnection conn, String encodedData) throws IOException {
StreamManager sm = new StreamManager();
try {
conn.setDoOutput(true);
conn.setRequestMethod("POST");
if (conn.getRequestProperty("Content-Type") == null) {
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
}
if (encodedData != null) {
if (conn.getRequestProperty("Content-Length") == null) {
conn.setRequestProperty("Content-Length", String.valueOf(encodedData.getBytes("UTF-8").length));
}
DataOutputStream out = new DataOutputStream(sm.handle(conn.getOutputStream()));
out.write(encodedData.getBytes());
out.close();
}
} finally {
sm.closeAll();
}
} | java | public static void sendPostData(HttpURLConnection conn, String encodedData) throws IOException {
StreamManager sm = new StreamManager();
try {
conn.setDoOutput(true);
conn.setRequestMethod("POST");
if (conn.getRequestProperty("Content-Type") == null) {
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
}
if (encodedData != null) {
if (conn.getRequestProperty("Content-Length") == null) {
conn.setRequestProperty("Content-Length", String.valueOf(encodedData.getBytes("UTF-8").length));
}
DataOutputStream out = new DataOutputStream(sm.handle(conn.getOutputStream()));
out.write(encodedData.getBytes());
out.close();
}
} finally {
sm.closeAll();
}
} | [
"public",
"static",
"void",
"sendPostData",
"(",
"HttpURLConnection",
"conn",
",",
"String",
"encodedData",
")",
"throws",
"IOException",
"{",
"StreamManager",
"sm",
"=",
"new",
"StreamManager",
"(",
")",
";",
"try",
"{",
"conn",
".",
"setDoOutput",
"(",
"true... | Submits http post data to an HttpURLConnection.
@param conn teh connection
@param encodedData the encoded data to be sent
@throws IOException on any connection | [
"Submits",
"http",
"post",
"data",
"to",
"an",
"HttpURLConnection",
"."
] | ac9046355851136994388442b01ba4063305f9c4 | https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-plugins/src/main/java/it/jnrpe/plugin/utils/HttpUtils.java#L95-L117 | train |
ziccardi/jnrpe | jnrpe-plugins/src/main/java/it/jnrpe/plugin/utils/HttpUtils.java | HttpUtils.setRequestProperties | public static void setRequestProperties(final Properties props, HttpURLConnection conn, Integer timeout) {
if (props != null) {
if (props.get("User-Agent") == null) {
conn.setRequestProperty("User-Agent", "Java");
}
for (Entry entry : props.entrySet()) {
conn.setRequestProperty(String.valueOf(entry.getKey()), String.valueOf(entry.getValue()));
}
}
if (timeout != null) {
conn.setConnectTimeout(timeout * 1000);
}
} | java | public static void setRequestProperties(final Properties props, HttpURLConnection conn, Integer timeout) {
if (props != null) {
if (props.get("User-Agent") == null) {
conn.setRequestProperty("User-Agent", "Java");
}
for (Entry entry : props.entrySet()) {
conn.setRequestProperty(String.valueOf(entry.getKey()), String.valueOf(entry.getValue()));
}
}
if (timeout != null) {
conn.setConnectTimeout(timeout * 1000);
}
} | [
"public",
"static",
"void",
"setRequestProperties",
"(",
"final",
"Properties",
"props",
",",
"HttpURLConnection",
"conn",
",",
"Integer",
"timeout",
")",
"{",
"if",
"(",
"props",
"!=",
"null",
")",
"{",
"if",
"(",
"props",
".",
"get",
"(",
"\"User-Agent\"",... | Sets request headers for an http connection
@param props properties to be sent
@param conn the connection
@param timeout the connection timeout | [
"Sets",
"request",
"headers",
"for",
"an",
"http",
"connection"
] | ac9046355851136994388442b01ba4063305f9c4 | https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-plugins/src/main/java/it/jnrpe/plugin/utils/HttpUtils.java#L137-L152 | train |
ziccardi/jnrpe | jnrpe-plugins/src/main/java/it/jnrpe/plugin/utils/HttpUtils.java | HttpUtils.parseHttpResponse | public static String parseHttpResponse(HttpURLConnection conn, boolean includeHeaders, boolean ignoreBody) throws IOException {
StringBuilder buff = new StringBuilder();
if (includeHeaders) {
buff.append(conn.getResponseCode()).append(' ').append(conn.getResponseMessage()).append('\n');
int idx = (conn.getHeaderFieldKey(0) == null) ? 1 : 0;
while (true) {
String key = conn.getHeaderFieldKey(idx);
if (key == null) {
break;
}
buff.append(key).append(": ").append(conn.getHeaderField(idx)).append('\n');
++idx;
}
}
StreamManager sm = new StreamManager();
try {
if (!ignoreBody) {
BufferedReader in = (BufferedReader) sm.handle(new BufferedReader(new InputStreamReader(conn.getInputStream())));
String inputLine;
while ((inputLine = in.readLine()) != null) {
buff.append(inputLine);
}
in.close();
}
} finally {
sm.closeAll();
}
return buff.toString();
} | java | public static String parseHttpResponse(HttpURLConnection conn, boolean includeHeaders, boolean ignoreBody) throws IOException {
StringBuilder buff = new StringBuilder();
if (includeHeaders) {
buff.append(conn.getResponseCode()).append(' ').append(conn.getResponseMessage()).append('\n');
int idx = (conn.getHeaderFieldKey(0) == null) ? 1 : 0;
while (true) {
String key = conn.getHeaderFieldKey(idx);
if (key == null) {
break;
}
buff.append(key).append(": ").append(conn.getHeaderField(idx)).append('\n');
++idx;
}
}
StreamManager sm = new StreamManager();
try {
if (!ignoreBody) {
BufferedReader in = (BufferedReader) sm.handle(new BufferedReader(new InputStreamReader(conn.getInputStream())));
String inputLine;
while ((inputLine = in.readLine()) != null) {
buff.append(inputLine);
}
in.close();
}
} finally {
sm.closeAll();
}
return buff.toString();
} | [
"public",
"static",
"String",
"parseHttpResponse",
"(",
"HttpURLConnection",
"conn",
",",
"boolean",
"includeHeaders",
",",
"boolean",
"ignoreBody",
")",
"throws",
"IOException",
"{",
"StringBuilder",
"buff",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"if",
"(",
... | Parses an http request response
@param conn the connection
@param includeHeaders if include headers ot not
@param ignoreBody if ignore body or not
@return a string representing the received answer
@throws IOException on any connection | [
"Parses",
"an",
"http",
"request",
"response"
] | ac9046355851136994388442b01ba4063305f9c4 | https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-plugins/src/main/java/it/jnrpe/plugin/utils/HttpUtils.java#L163-L193 | train |
ziccardi/jnrpe | jnrpe-plugins/src/main/java/it/jnrpe/plugin/CCheckOracle.java | CCheckOracle.checkAlive | private List<Metric> checkAlive(final Connection c, final ICommandLine cl) throws BadThresholdException, SQLException {
List<Metric> metricList = new ArrayList<Metric>();
Statement stmt = null;
ResultSet rs = null;
long lStart = System.currentTimeMillis();
try {
stmt = c.createStatement();
rs = stmt.executeQuery(QRY_CHECK_ALIVE);
if (!rs.next()) {
// Should never happen...
throw new SQLException("Unable to execute a 'SELECT SYSDATE FROM DUAL' query");
}
long elapsed = (System.currentTimeMillis() - lStart) / 1000L;
metricList.add(new Metric("conn", "Connection time : " + elapsed + "s", new BigDecimal(elapsed), new BigDecimal(0), null));
return metricList;
} finally {
DBUtils.closeQuietly(rs);
DBUtils.closeQuietly(stmt);
}
} | java | private List<Metric> checkAlive(final Connection c, final ICommandLine cl) throws BadThresholdException, SQLException {
List<Metric> metricList = new ArrayList<Metric>();
Statement stmt = null;
ResultSet rs = null;
long lStart = System.currentTimeMillis();
try {
stmt = c.createStatement();
rs = stmt.executeQuery(QRY_CHECK_ALIVE);
if (!rs.next()) {
// Should never happen...
throw new SQLException("Unable to execute a 'SELECT SYSDATE FROM DUAL' query");
}
long elapsed = (System.currentTimeMillis() - lStart) / 1000L;
metricList.add(new Metric("conn", "Connection time : " + elapsed + "s", new BigDecimal(elapsed), new BigDecimal(0), null));
return metricList;
} finally {
DBUtils.closeQuietly(rs);
DBUtils.closeQuietly(stmt);
}
} | [
"private",
"List",
"<",
"Metric",
">",
"checkAlive",
"(",
"final",
"Connection",
"c",
",",
"final",
"ICommandLine",
"cl",
")",
"throws",
"BadThresholdException",
",",
"SQLException",
"{",
"List",
"<",
"Metric",
">",
"metricList",
"=",
"new",
"ArrayList",
"<",
... | Checks if the database is reacheble.
@param c
The connection to the database
@param cl
The command line as received from JNRPE
@return The plugin result
@throws BadThresholdException
-
@throws SQLException | [
"Checks",
"if",
"the",
"database",
"is",
"reacheble",
"."
] | ac9046355851136994388442b01ba4063305f9c4 | https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-plugins/src/main/java/it/jnrpe/plugin/CCheckOracle.java#L96-L123 | train |
ziccardi/jnrpe | jnrpe-plugins/src/main/java/it/jnrpe/plugin/CCheckOracle.java | CCheckOracle.checkTablespace | private List<Metric> checkTablespace(final Connection c, final ICommandLine cl) throws BadThresholdException, SQLException {
// Metric : tblspace_usage
List<Metric> metricList = new ArrayList<Metric>();
String sTablespace = cl.getOptionValue("tablespace").toUpperCase();
// FIXME : a prepared satement should be used
final String sQry = String.format(QRY_CHECK_TBLSPACE_PATTERN, sTablespace);
Statement stmt = null;
ResultSet rs = null;
try {
stmt = c.createStatement();
rs = stmt.executeQuery(sQry);
boolean bFound = rs.next();
if (!bFound) {
throw new SQLException("Tablespace " + cl.getOptionValue("tablespace") + " not found.");
}
BigDecimal tsFree = rs.getBigDecimal(1);
BigDecimal tsTotal = rs.getBigDecimal(2);
BigDecimal tsPct = rs.getBigDecimal(3);
//
metricList.add(new Metric("tblspace_freepct", cl.getOptionValue("tablespace") + " : " + tsPct + "% free", tsPct, new BigDecimal(0),
new BigDecimal(100)));
metricList.add(new Metric("tblspace_free", cl.getOptionValue("tablespace") + " : " + tsFree + "MB free", tsPct, new BigDecimal(0),
tsTotal));
return metricList;
} finally {
DBUtils.closeQuietly(rs);
DBUtils.closeQuietly(stmt);
}
} | java | private List<Metric> checkTablespace(final Connection c, final ICommandLine cl) throws BadThresholdException, SQLException {
// Metric : tblspace_usage
List<Metric> metricList = new ArrayList<Metric>();
String sTablespace = cl.getOptionValue("tablespace").toUpperCase();
// FIXME : a prepared satement should be used
final String sQry = String.format(QRY_CHECK_TBLSPACE_PATTERN, sTablespace);
Statement stmt = null;
ResultSet rs = null;
try {
stmt = c.createStatement();
rs = stmt.executeQuery(sQry);
boolean bFound = rs.next();
if (!bFound) {
throw new SQLException("Tablespace " + cl.getOptionValue("tablespace") + " not found.");
}
BigDecimal tsFree = rs.getBigDecimal(1);
BigDecimal tsTotal = rs.getBigDecimal(2);
BigDecimal tsPct = rs.getBigDecimal(3);
//
metricList.add(new Metric("tblspace_freepct", cl.getOptionValue("tablespace") + " : " + tsPct + "% free", tsPct, new BigDecimal(0),
new BigDecimal(100)));
metricList.add(new Metric("tblspace_free", cl.getOptionValue("tablespace") + " : " + tsFree + "MB free", tsPct, new BigDecimal(0),
tsTotal));
return metricList;
} finally {
DBUtils.closeQuietly(rs);
DBUtils.closeQuietly(stmt);
}
} | [
"private",
"List",
"<",
"Metric",
">",
"checkTablespace",
"(",
"final",
"Connection",
"c",
",",
"final",
"ICommandLine",
"cl",
")",
"throws",
"BadThresholdException",
",",
"SQLException",
"{",
"// Metric : tblspace_usage",
"List",
"<",
"Metric",
">",
"metricList",
... | Checks database usage.
@param c
The connection to the database
@param cl
The command line as received from JNRPE
@return The plugin result
@throws BadThresholdException
- | [
"Checks",
"database",
"usage",
"."
] | ac9046355851136994388442b01ba4063305f9c4 | https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-plugins/src/main/java/it/jnrpe/plugin/CCheckOracle.java#L136-L177 | train |
ziccardi/jnrpe | jnrpe-plugins/src/main/java/it/jnrpe/plugin/CCheckOracle.java | CCheckOracle.checkCache | private List<Metric> checkCache(final Connection c, final ICommandLine cl) throws BadThresholdException, SQLException {
List<Metric> metricList = new ArrayList<Metric>();
// Metrics cache_buf, cache_lib
String sQry1 = "select (1-(pr.value/(dbg.value+cg.value)))*100" + " from v$sysstat pr, v$sysstat dbg, v$sysstat cg"
+ " where pr.name='physical reads'" + " and dbg.name='db block gets'" + " and cg.name='consistent gets'";
String sQry2 = "select sum(lc.pins)/(sum(lc.pins)" + "+sum(lc.reloads))*100 from v$librarycache lc";
Statement stmt = null;
ResultSet rs = null;
try {
stmt = c.createStatement();
rs = stmt.executeQuery(sQry1);
rs.next();
BigDecimal buf_hr = rs.getBigDecimal(1);
rs = stmt.executeQuery(sQry2);
rs.next();
BigDecimal lib_hr = rs.getBigDecimal(1);
String libHitRate = "Cache Hit Rate {1,number,0.#}% Lib";
String buffHitRate = "Cache Hit Rate {1,number,0.#}% Buff";
metricList.add(new Metric("cache_buf", MessageFormat.format(buffHitRate, buf_hr), buf_hr, new BigDecimal(0), new BigDecimal(100)));
metricList.add(new Metric("cache_lib", MessageFormat.format(libHitRate, lib_hr), lib_hr, new BigDecimal(0), new BigDecimal(100)));
return metricList;
} finally {
DBUtils.closeQuietly(rs);
DBUtils.closeQuietly(stmt);
}
} | java | private List<Metric> checkCache(final Connection c, final ICommandLine cl) throws BadThresholdException, SQLException {
List<Metric> metricList = new ArrayList<Metric>();
// Metrics cache_buf, cache_lib
String sQry1 = "select (1-(pr.value/(dbg.value+cg.value)))*100" + " from v$sysstat pr, v$sysstat dbg, v$sysstat cg"
+ " where pr.name='physical reads'" + " and dbg.name='db block gets'" + " and cg.name='consistent gets'";
String sQry2 = "select sum(lc.pins)/(sum(lc.pins)" + "+sum(lc.reloads))*100 from v$librarycache lc";
Statement stmt = null;
ResultSet rs = null;
try {
stmt = c.createStatement();
rs = stmt.executeQuery(sQry1);
rs.next();
BigDecimal buf_hr = rs.getBigDecimal(1);
rs = stmt.executeQuery(sQry2);
rs.next();
BigDecimal lib_hr = rs.getBigDecimal(1);
String libHitRate = "Cache Hit Rate {1,number,0.#}% Lib";
String buffHitRate = "Cache Hit Rate {1,number,0.#}% Buff";
metricList.add(new Metric("cache_buf", MessageFormat.format(buffHitRate, buf_hr), buf_hr, new BigDecimal(0), new BigDecimal(100)));
metricList.add(new Metric("cache_lib", MessageFormat.format(libHitRate, lib_hr), lib_hr, new BigDecimal(0), new BigDecimal(100)));
return metricList;
} finally {
DBUtils.closeQuietly(rs);
DBUtils.closeQuietly(stmt);
}
} | [
"private",
"List",
"<",
"Metric",
">",
"checkCache",
"(",
"final",
"Connection",
"c",
",",
"final",
"ICommandLine",
"cl",
")",
"throws",
"BadThresholdException",
",",
"SQLException",
"{",
"List",
"<",
"Metric",
">",
"metricList",
"=",
"new",
"ArrayList",
"<",
... | Checks cache hit rates.
@param c
The connection to the database
@param cl
The command line as received from JNRPE
@return The result of the plugin
@throws BadThresholdException
- | [
"Checks",
"cache",
"hit",
"rates",
"."
] | ac9046355851136994388442b01ba4063305f9c4 | https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-plugins/src/main/java/it/jnrpe/plugin/CCheckOracle.java#L190-L228 | train |
petergeneric/stdlib | user-manager/service/src/main/java/com/peterphi/usermanager/db/dao/hibernate/UserDaoImpl.java | UserDaoImpl.rotateUserAccessKey | @Transactional
public void rotateUserAccessKey(final int id)
{
final UserEntity account = getById(id);
if (account != null)
{
// Set the secondary token to the old primary token
account.setAccessKeySecondary(account.getAccessKey());
// Now regenerate the primary token
account.setAccessKey(SimpleId.alphanumeric(UserManagerBearerToken.PREFIX, 100));
update(account);
}
else
{
throw new IllegalArgumentException("No such user: " + id);
}
} | java | @Transactional
public void rotateUserAccessKey(final int id)
{
final UserEntity account = getById(id);
if (account != null)
{
// Set the secondary token to the old primary token
account.setAccessKeySecondary(account.getAccessKey());
// Now regenerate the primary token
account.setAccessKey(SimpleId.alphanumeric(UserManagerBearerToken.PREFIX, 100));
update(account);
}
else
{
throw new IllegalArgumentException("No such user: " + id);
}
} | [
"@",
"Transactional",
"public",
"void",
"rotateUserAccessKey",
"(",
"final",
"int",
"id",
")",
"{",
"final",
"UserEntity",
"account",
"=",
"getById",
"(",
"id",
")",
";",
"if",
"(",
"account",
"!=",
"null",
")",
"{",
"// Set the secondary token to the old primar... | Rotate the primary access key -> secondary access key, dropping the old secondary access key and generating a new primary access key
@param id | [
"Rotate",
"the",
"primary",
"access",
"key",
"-",
">",
"secondary",
"access",
"key",
"dropping",
"the",
"old",
"secondary",
"access",
"key",
"and",
"generating",
"a",
"new",
"primary",
"access",
"key"
] | d4025d2f881bc0542b1e004c5f65a1ccaf895836 | https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/user-manager/service/src/main/java/com/peterphi/usermanager/db/dao/hibernate/UserDaoImpl.java#L56-L75 | train |
petergeneric/stdlib | user-manager/service/src/main/java/com/peterphi/usermanager/db/dao/hibernate/UserDaoImpl.java | UserDaoImpl.hashPassword | private String hashPassword(String password)
{
return BCrypt.hash(password.toCharArray(), BCrypt.DEFAULT_COST);
} | java | private String hashPassword(String password)
{
return BCrypt.hash(password.toCharArray(), BCrypt.DEFAULT_COST);
} | [
"private",
"String",
"hashPassword",
"(",
"String",
"password",
")",
"{",
"return",
"BCrypt",
".",
"hash",
"(",
"password",
".",
"toCharArray",
"(",
")",
",",
"BCrypt",
".",
"DEFAULT_COST",
")",
";",
"}"
] | Creates a BCrypted hash for a password
@param password
@return | [
"Creates",
"a",
"BCrypted",
"hash",
"for",
"a",
"password"
] | d4025d2f881bc0542b1e004c5f65a1ccaf895836 | https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/user-manager/service/src/main/java/com/peterphi/usermanager/db/dao/hibernate/UserDaoImpl.java#L119-L122 | train |
ziccardi/jnrpe | jnrpe-plugins/src/main/java/it/jnrpe/plugin/utils/Utils.java | Utils.formatSize | public static String formatSize(final long value) {
double size = value;
DecimalFormat df = new DecimalFormat("#.##");
if (size >= GB) {
return df.format(size / GB) + " GB";
}
if (size >= MB) {
return df.format(size / MB) + " MB";
}
if (size >= KB) {
return df.format(size / KB) + " KB";
}
return String.valueOf((int) size) + " bytes";
} | java | public static String formatSize(final long value) {
double size = value;
DecimalFormat df = new DecimalFormat("#.##");
if (size >= GB) {
return df.format(size / GB) + " GB";
}
if (size >= MB) {
return df.format(size / MB) + " MB";
}
if (size >= KB) {
return df.format(size / KB) + " KB";
}
return String.valueOf((int) size) + " bytes";
} | [
"public",
"static",
"String",
"formatSize",
"(",
"final",
"long",
"value",
")",
"{",
"double",
"size",
"=",
"value",
";",
"DecimalFormat",
"df",
"=",
"new",
"DecimalFormat",
"(",
"\"#.##\"",
")",
";",
"if",
"(",
"size",
">=",
"GB",
")",
"{",
"return",
... | Returns formatted size of a file size.
@param value
The value
@return String | [
"Returns",
"formatted",
"size",
"of",
"a",
"file",
"size",
"."
] | ac9046355851136994388442b01ba4063305f9c4 | https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-plugins/src/main/java/it/jnrpe/plugin/utils/Utils.java#L92-L105 | train |
petergeneric/stdlib | stdlib/src/main/java/com/peterphi/std/io/ArchiveHelper.java | ArchiveHelper.extractArchive | public static boolean extractArchive(File tarFile, File extractTo)
{
try
{
TarArchive ta = getArchive(tarFile);
try
{
if (!extractTo.exists())
if (!extractTo.mkdir())
throw new RuntimeException("Could not create extract dir: " + extractTo);
ta.extractContents(extractTo);
}
finally
{
ta.closeArchive();
}
return true;
}
catch (FileNotFoundException e)
{
log.error("File not found exception: " + e.getMessage(), e);
return false;
}
catch (Exception e)
{
log.error("Exception while extracting archive: " + e.getMessage(), e);
return false;
}
} | java | public static boolean extractArchive(File tarFile, File extractTo)
{
try
{
TarArchive ta = getArchive(tarFile);
try
{
if (!extractTo.exists())
if (!extractTo.mkdir())
throw new RuntimeException("Could not create extract dir: " + extractTo);
ta.extractContents(extractTo);
}
finally
{
ta.closeArchive();
}
return true;
}
catch (FileNotFoundException e)
{
log.error("File not found exception: " + e.getMessage(), e);
return false;
}
catch (Exception e)
{
log.error("Exception while extracting archive: " + e.getMessage(), e);
return false;
}
} | [
"public",
"static",
"boolean",
"extractArchive",
"(",
"File",
"tarFile",
",",
"File",
"extractTo",
")",
"{",
"try",
"{",
"TarArchive",
"ta",
"=",
"getArchive",
"(",
"tarFile",
")",
";",
"try",
"{",
"if",
"(",
"!",
"extractTo",
".",
"exists",
"(",
")",
... | Extracts a .tar or .tar.gz archive to a given folder
@param tarFile
File The archive file
@param extractTo
File The folder to extract the contents of this archive to
@return boolean True if the archive was successfully extracted, otherwise false | [
"Extracts",
"a",
".",
"tar",
"or",
".",
"tar",
".",
"gz",
"archive",
"to",
"a",
"given",
"folder"
] | d4025d2f881bc0542b1e004c5f65a1ccaf895836 | https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/stdlib/src/main/java/com/peterphi/std/io/ArchiveHelper.java#L78-L107 | train |
petergeneric/stdlib | stdlib/src/main/java/com/peterphi/std/io/ArchiveHelper.java | ArchiveHelper.addFilesToExistingJar | public static boolean addFilesToExistingJar(File jarFile,
String basePathWithinJar,
Map<String, File> files,
ActionOnConflict action) throws IOException
{
// get a temp file
File tempFile = FileHelper.createTempFile(jarFile.getName(), null);
boolean renamed = jarFile.renameTo(tempFile);
if (!renamed)
{
throw new RuntimeException("[ArchiveHelper] {addFilesToExistingJar} " + "Could not rename the file " +
jarFile.getAbsolutePath() + " to " + tempFile.getAbsolutePath());
}
ZipInputStream jarInput = new ZipInputStream(new FileInputStream(tempFile));
ZipOutputStream jarOutput = new ZipOutputStream(new FileOutputStream(jarFile));
try
{
switch (action)
{
case OVERWRITE:
overwriteFiles(jarInput, jarOutput, basePathWithinJar, files);
break;
case CONFLICT:
conflictFiles(jarInput, jarOutput, basePathWithinJar, files);
break;
default:
// This should never happen with validation of action taking place in WarDriver class
throw new IOException("An invalid ActionOnConflict action was received");
}
}
finally
{
if (!tempFile.delete())
log.warn("Could not delete temp file " + tempFile);
}
return true;
} | java | public static boolean addFilesToExistingJar(File jarFile,
String basePathWithinJar,
Map<String, File> files,
ActionOnConflict action) throws IOException
{
// get a temp file
File tempFile = FileHelper.createTempFile(jarFile.getName(), null);
boolean renamed = jarFile.renameTo(tempFile);
if (!renamed)
{
throw new RuntimeException("[ArchiveHelper] {addFilesToExistingJar} " + "Could not rename the file " +
jarFile.getAbsolutePath() + " to " + tempFile.getAbsolutePath());
}
ZipInputStream jarInput = new ZipInputStream(new FileInputStream(tempFile));
ZipOutputStream jarOutput = new ZipOutputStream(new FileOutputStream(jarFile));
try
{
switch (action)
{
case OVERWRITE:
overwriteFiles(jarInput, jarOutput, basePathWithinJar, files);
break;
case CONFLICT:
conflictFiles(jarInput, jarOutput, basePathWithinJar, files);
break;
default:
// This should never happen with validation of action taking place in WarDriver class
throw new IOException("An invalid ActionOnConflict action was received");
}
}
finally
{
if (!tempFile.delete())
log.warn("Could not delete temp file " + tempFile);
}
return true;
} | [
"public",
"static",
"boolean",
"addFilesToExistingJar",
"(",
"File",
"jarFile",
",",
"String",
"basePathWithinJar",
",",
"Map",
"<",
"String",
",",
"File",
">",
"files",
",",
"ActionOnConflict",
"action",
")",
"throws",
"IOException",
"{",
"// get a temp file",
"F... | Adds a file or files to a jar file, replacing the original one
@param jarFile
File the jar file
@param basePathWithinJar
String the base path to put the files within the Jar
@param files
File[] The files. The files will be placed in basePathWithinJar
@throws Exception
@since 2007-06-07 uses createTempFile instead of Java's createTempFile, increased buffer from 1k to 4k | [
"Adds",
"a",
"file",
"or",
"files",
"to",
"a",
"jar",
"file",
"replacing",
"the",
"original",
"one"
] | d4025d2f881bc0542b1e004c5f65a1ccaf895836 | https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/stdlib/src/main/java/com/peterphi/std/io/ArchiveHelper.java#L123-L163 | train |
petergeneric/stdlib | stdlib/src/main/java/com/peterphi/std/util/ListUtility.java | ListUtility.list | public static <T> List<T> list(Iterable<T> iterable)
{
List<T> list = new ArrayList<T>();
for (T item : iterable)
{
list.add(item);
}
return list;
} | java | public static <T> List<T> list(Iterable<T> iterable)
{
List<T> list = new ArrayList<T>();
for (T item : iterable)
{
list.add(item);
}
return list;
} | [
"public",
"static",
"<",
"T",
">",
"List",
"<",
"T",
">",
"list",
"(",
"Iterable",
"<",
"T",
">",
"iterable",
")",
"{",
"List",
"<",
"T",
">",
"list",
"=",
"new",
"ArrayList",
"<",
"T",
">",
"(",
")",
";",
"for",
"(",
"T",
"item",
":",
"itera... | Converts an Iterable into a List
@param iterable
@return | [
"Converts",
"an",
"Iterable",
"into",
"a",
"List"
] | d4025d2f881bc0542b1e004c5f65a1ccaf895836 | https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/stdlib/src/main/java/com/peterphi/std/util/ListUtility.java#L38-L47 | train |
petergeneric/stdlib | stdlib/src/main/java/com/peterphi/std/util/ListUtility.java | ListUtility.last | public static <T> List<T> last(final List<T> src, int count)
{
if (count >= src.size())
{
return new ArrayList<T>(src);
}
else
{
final List<T> dest = new ArrayList<T>(count);
final int size = src.size();
for (int i = size - count; i < size; i++)
{
dest.add(src.get(i));
}
return dest;
}
} | java | public static <T> List<T> last(final List<T> src, int count)
{
if (count >= src.size())
{
return new ArrayList<T>(src);
}
else
{
final List<T> dest = new ArrayList<T>(count);
final int size = src.size();
for (int i = size - count; i < size; i++)
{
dest.add(src.get(i));
}
return dest;
}
} | [
"public",
"static",
"<",
"T",
">",
"List",
"<",
"T",
">",
"last",
"(",
"final",
"List",
"<",
"T",
">",
"src",
",",
"int",
"count",
")",
"{",
"if",
"(",
"count",
">=",
"src",
".",
"size",
"(",
")",
")",
"{",
"return",
"new",
"ArrayList",
"<",
... | Return, at most, the last n items from the source list
@param <T>
the list type
@param src
the source list
@param count
the maximum number of items
@return the last n items from the src list; if the list is not of size n, the original list is copied and returned | [
"Return",
"at",
"most",
"the",
"last",
"n",
"items",
"from",
"the",
"source",
"list"
] | d4025d2f881bc0542b1e004c5f65a1ccaf895836 | https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/stdlib/src/main/java/com/peterphi/std/util/ListUtility.java#L73-L91 | train |
petergeneric/stdlib | stdlib/src/main/java/com/peterphi/std/util/ListUtility.java | ListUtility.tail | public static <T> List<T> tail(List<T> list)
{
if (list.isEmpty())
return Collections.emptyList();
else
return list.subList(1, list.size());
} | java | public static <T> List<T> tail(List<T> list)
{
if (list.isEmpty())
return Collections.emptyList();
else
return list.subList(1, list.size());
} | [
"public",
"static",
"<",
"T",
">",
"List",
"<",
"T",
">",
"tail",
"(",
"List",
"<",
"T",
">",
"list",
")",
"{",
"if",
"(",
"list",
".",
"isEmpty",
"(",
")",
")",
"return",
"Collections",
".",
"emptyList",
"(",
")",
";",
"else",
"return",
"list",
... | Returns a sublist containing all the items in the list after the first
@param list
@return | [
"Returns",
"a",
"sublist",
"containing",
"all",
"the",
"items",
"in",
"the",
"list",
"after",
"the",
"first"
] | d4025d2f881bc0542b1e004c5f65a1ccaf895836 | https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/stdlib/src/main/java/com/peterphi/std/util/ListUtility.java#L117-L123 | train |
petergeneric/stdlib | stdlib/src/main/java/com/peterphi/std/util/ListUtility.java | ListUtility.flip | public static int[] flip(int[] src, int[] dest, final int start, final int length)
{
if (dest == null || dest.length < length)
dest = new int[length];
int srcIndex = start + length;
for (int i = 0; i < length; i++)
{
dest[i] = src[--srcIndex];
}
return dest;
} | java | public static int[] flip(int[] src, int[] dest, final int start, final int length)
{
if (dest == null || dest.length < length)
dest = new int[length];
int srcIndex = start + length;
for (int i = 0; i < length; i++)
{
dest[i] = src[--srcIndex];
}
return dest;
} | [
"public",
"static",
"int",
"[",
"]",
"flip",
"(",
"int",
"[",
"]",
"src",
",",
"int",
"[",
"]",
"dest",
",",
"final",
"int",
"start",
",",
"final",
"int",
"length",
")",
"{",
"if",
"(",
"dest",
"==",
"null",
"||",
"dest",
".",
"length",
"<",
"l... | Reverses an integer array
@param src
@param dest
@param start
@param length
@return | [
"Reverses",
"an",
"integer",
"array"
] | d4025d2f881bc0542b1e004c5f65a1ccaf895836 | https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/stdlib/src/main/java/com/peterphi/std/util/ListUtility.java#L225-L237 | train |
petergeneric/stdlib | stdlib/src/main/java/com/peterphi/std/util/ListUtility.java | ListUtility.concat | public static <T> List<T> concat(final Collection<? extends T>... lists)
{
ArrayList<T> al = new ArrayList<T>();
for (Collection<? extends T> list : lists)
if (list != null)
al.addAll(list);
return al;
} | java | public static <T> List<T> concat(final Collection<? extends T>... lists)
{
ArrayList<T> al = new ArrayList<T>();
for (Collection<? extends T> list : lists)
if (list != null)
al.addAll(list);
return al;
} | [
"public",
"static",
"<",
"T",
">",
"List",
"<",
"T",
">",
"concat",
"(",
"final",
"Collection",
"<",
"?",
"extends",
"T",
">",
"...",
"lists",
")",
"{",
"ArrayList",
"<",
"T",
">",
"al",
"=",
"new",
"ArrayList",
"<",
"T",
">",
"(",
")",
";",
"f... | Concatenates a number of Collections into a single List
@param <T>
@param lists
@return | [
"Concatenates",
"a",
"number",
"of",
"Collections",
"into",
"a",
"single",
"List"
] | d4025d2f881bc0542b1e004c5f65a1ccaf895836 | https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/stdlib/src/main/java/com/peterphi/std/util/ListUtility.java#L348-L357 | train |
petergeneric/stdlib | stdlib/src/main/java/com/peterphi/std/util/ListUtility.java | ListUtility.union | public static <T> Set<T> union(final Collection<? extends T>... lists)
{
Set<T> s = new HashSet<T>();
for (Collection<? extends T> list : lists)
if (list != null)
s.addAll(list);
return s;
} | java | public static <T> Set<T> union(final Collection<? extends T>... lists)
{
Set<T> s = new HashSet<T>();
for (Collection<? extends T> list : lists)
if (list != null)
s.addAll(list);
return s;
} | [
"public",
"static",
"<",
"T",
">",
"Set",
"<",
"T",
">",
"union",
"(",
"final",
"Collection",
"<",
"?",
"extends",
"T",
">",
"...",
"lists",
")",
"{",
"Set",
"<",
"T",
">",
"s",
"=",
"new",
"HashSet",
"<",
"T",
">",
"(",
")",
";",
"for",
"(",... | Concatenates a number of Collections into a single Set
@param <T>
@param lists
@return | [
"Concatenates",
"a",
"number",
"of",
"Collections",
"into",
"a",
"single",
"Set"
] | d4025d2f881bc0542b1e004c5f65a1ccaf895836 | https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/stdlib/src/main/java/com/peterphi/std/util/ListUtility.java#L368-L377 | train |
petergeneric/stdlib | guice/webapp/src/main/java/com/peterphi/std/guice/web/rest/templating/thymeleaf/GuiceCoreTemplater.java | GuiceCoreTemplater.getOrCreateTemplater | private ThymeleafTemplater getOrCreateTemplater()
{
ThymeleafTemplater templater = this.templater.get();
// Lazy-create a ThymeleafTemplater
if (templater == null)
{
final TemplateEngine engine = getOrCreateEngine();
templater = new ThymeleafTemplater(engine, configuration, metrics, userProvider);
templater.set("coreRestPrefix", coreRestPrefix);
templater.set("coreRestEndpoint", coreRestEndpoint.toString());
templater.set("coreServices", services);
templater.set("currentUser", new ThymeleafCurrentUserUtils(userProvider));
this.templater = new WeakReference<>(templater);
}
return templater;
} | java | private ThymeleafTemplater getOrCreateTemplater()
{
ThymeleafTemplater templater = this.templater.get();
// Lazy-create a ThymeleafTemplater
if (templater == null)
{
final TemplateEngine engine = getOrCreateEngine();
templater = new ThymeleafTemplater(engine, configuration, metrics, userProvider);
templater.set("coreRestPrefix", coreRestPrefix);
templater.set("coreRestEndpoint", coreRestEndpoint.toString());
templater.set("coreServices", services);
templater.set("currentUser", new ThymeleafCurrentUserUtils(userProvider));
this.templater = new WeakReference<>(templater);
}
return templater;
} | [
"private",
"ThymeleafTemplater",
"getOrCreateTemplater",
"(",
")",
"{",
"ThymeleafTemplater",
"templater",
"=",
"this",
".",
"templater",
".",
"get",
"(",
")",
";",
"// Lazy-create a ThymeleafTemplater",
"if",
"(",
"templater",
"==",
"null",
")",
"{",
"final",
"Te... | Retrieve or build a Thymeleaf templater
@return | [
"Retrieve",
"or",
"build",
"a",
"Thymeleaf",
"templater"
] | d4025d2f881bc0542b1e004c5f65a1ccaf895836 | https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/guice/webapp/src/main/java/com/peterphi/std/guice/web/rest/templating/thymeleaf/GuiceCoreTemplater.java#L61-L81 | train |
petergeneric/stdlib | guice/common/src/main/java/com/peterphi/std/guice/restclient/jaxb/webquery/WQProjectionField.java | WQProjectionField.isPrimitive | public static boolean isPrimitive(final Object value)
{
return (value == null ||
value instanceof String ||
value instanceof Number ||
value instanceof Boolean ||
value instanceof DateTime ||
value instanceof Date ||
value instanceof SampleCount ||
value instanceof Timecode ||
value.getClass().isEnum() ||
value.getClass().isPrimitive());
} | java | public static boolean isPrimitive(final Object value)
{
return (value == null ||
value instanceof String ||
value instanceof Number ||
value instanceof Boolean ||
value instanceof DateTime ||
value instanceof Date ||
value instanceof SampleCount ||
value instanceof Timecode ||
value.getClass().isEnum() ||
value.getClass().isPrimitive());
} | [
"public",
"static",
"boolean",
"isPrimitive",
"(",
"final",
"Object",
"value",
")",
"{",
"return",
"(",
"value",
"==",
"null",
"||",
"value",
"instanceof",
"String",
"||",
"value",
"instanceof",
"Number",
"||",
"value",
"instanceof",
"Boolean",
"||",
"value",
... | Helper method that returns True if the provided value should be represented as a String
@param value
@return | [
"Helper",
"method",
"that",
"returns",
"True",
"if",
"the",
"provided",
"value",
"should",
"be",
"represented",
"as",
"a",
"String"
] | d4025d2f881bc0542b1e004c5f65a1ccaf895836 | https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/guice/common/src/main/java/com/peterphi/std/guice/restclient/jaxb/webquery/WQProjectionField.java#L58-L70 | train |
ziccardi/jnrpe | jnrpe-lib/src/main/java/it/jnrpe/PerformanceData.java | PerformanceData.toPerformanceString | public String toPerformanceString() {
final StringBuilder res =
new StringBuilder()
.append(
quote(metric.getMetricName()))
.append('=')
.append((metric.getMetricValue(prefix)).toPrettyPrintedString());
if (unitOfMeasure != null) {
switch (unitOfMeasure) {
case milliseconds:
res.append("ms");
break;
case microseconds:
res.append("us");
break;
case seconds:
res.append('s');
break;
case bytes:
res.append('B');
break;
case kilobytes:
res.append("KB");
break;
case megabytes:
res.append("MB");
break;
case gigabytes:
res.append("GB");
break;
case terabytes:
res.append("TB");
break;
case percentage:
res.append('%');
break;
case counter:
res.append('c');
break;
default:
}
}
if (unit != null) {
res.append(unit);
}
res.append(';');
if (warningRange != null) {
res.append(warningRange);
}
res.append(';');
if (criticalRange != null) {
res.append(criticalRange);
}
res.append(';');
if (metric.getMinValue() != null) {
res.append(metric.getMinValue(prefix).toPrettyPrintedString());
}
res.append(';');
if (metric.getMaxValue() != null) {
res.append(metric.getMaxValue(prefix).toPrettyPrintedString());
}
while (res.charAt(res.length() - 1) == ';') {
res.deleteCharAt(res.length() - 1);
}
return res.toString();
} | java | public String toPerformanceString() {
final StringBuilder res =
new StringBuilder()
.append(
quote(metric.getMetricName()))
.append('=')
.append((metric.getMetricValue(prefix)).toPrettyPrintedString());
if (unitOfMeasure != null) {
switch (unitOfMeasure) {
case milliseconds:
res.append("ms");
break;
case microseconds:
res.append("us");
break;
case seconds:
res.append('s');
break;
case bytes:
res.append('B');
break;
case kilobytes:
res.append("KB");
break;
case megabytes:
res.append("MB");
break;
case gigabytes:
res.append("GB");
break;
case terabytes:
res.append("TB");
break;
case percentage:
res.append('%');
break;
case counter:
res.append('c');
break;
default:
}
}
if (unit != null) {
res.append(unit);
}
res.append(';');
if (warningRange != null) {
res.append(warningRange);
}
res.append(';');
if (criticalRange != null) {
res.append(criticalRange);
}
res.append(';');
if (metric.getMinValue() != null) {
res.append(metric.getMinValue(prefix).toPrettyPrintedString());
}
res.append(';');
if (metric.getMaxValue() != null) {
res.append(metric.getMaxValue(prefix).toPrettyPrintedString());
}
while (res.charAt(res.length() - 1) == ';') {
res.deleteCharAt(res.length() - 1);
}
return res.toString();
} | [
"public",
"String",
"toPerformanceString",
"(",
")",
"{",
"final",
"StringBuilder",
"res",
"=",
"new",
"StringBuilder",
"(",
")",
".",
"append",
"(",
"quote",
"(",
"metric",
".",
"getMetricName",
"(",
")",
")",
")",
".",
"append",
"(",
"'",
"'",
")",
"... | Produce a performance string according to Nagios specification based on
the value of this performance data object.
@return a string that can be returned to Nagios | [
"Produce",
"a",
"performance",
"string",
"according",
"to",
"Nagios",
"specification",
"based",
"on",
"the",
"value",
"of",
"this",
"performance",
"data",
"object",
"."
] | ac9046355851136994388442b01ba4063305f9c4 | https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-lib/src/main/java/it/jnrpe/PerformanceData.java#L116-L186 | train |
ziccardi/jnrpe | jnrpe-lib/src/main/java/it/jnrpe/PerformanceData.java | PerformanceData.quote | private String quote(final String lbl) {
if (lbl.indexOf(' ') == -1) {
return lbl;
}
return new StringBuffer("'").append(lbl).append('\'').toString();
} | java | private String quote(final String lbl) {
if (lbl.indexOf(' ') == -1) {
return lbl;
}
return new StringBuffer("'").append(lbl).append('\'').toString();
} | [
"private",
"String",
"quote",
"(",
"final",
"String",
"lbl",
")",
"{",
"if",
"(",
"lbl",
".",
"indexOf",
"(",
"'",
"'",
")",
"==",
"-",
"1",
")",
"{",
"return",
"lbl",
";",
"}",
"return",
"new",
"StringBuffer",
"(",
"\"'\"",
")",
".",
"append",
"... | Quotes the label if required.
@param lbl
The label to be quoted
@return The quoted label or the original label if quoting is not
required. | [
"Quotes",
"the",
"label",
"if",
"required",
"."
] | ac9046355851136994388442b01ba4063305f9c4 | https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-lib/src/main/java/it/jnrpe/PerformanceData.java#L196-L202 | train |
petergeneric/stdlib | guice/webapp/src/main/java/com/peterphi/std/guice/web/rest/service/servicedescription/freemarker/SchemaGenerateUtil.java | SchemaGenerateUtil.getSchema | public String getSchema(Class<?> clazz)
{
if (clazz == Integer.class || clazz == Integer.TYPE)
{
return "integer [" + Integer.MIN_VALUE + " to " + Integer.MAX_VALUE + "]";
}
else if (clazz == Long.class || clazz == Long.TYPE)
{
return "long [" + Long.MIN_VALUE + " to " + Long.MAX_VALUE + "]";
}
else if (clazz == Double.class || clazz == Double.TYPE)
{
return "double [" + Double.MIN_VALUE + " to " + Double.MAX_VALUE + "]";
}
else if (clazz == Boolean.class || clazz == Boolean.TYPE)
{
return "boolean [true, false]";
}
else if (clazz == Void.class)
{
return "void";
}
else if (clazz == Byte[].class || clazz == byte[].class)
{
return "binary stream";
}
else if (clazz.isEnum())
{
return "enum " + Arrays.asList(clazz.getEnumConstants());
}
else if (clazz.isAnnotationPresent(XmlRootElement.class))
{
try
{
final JAXBSerialiser serialiser = JAXBSerialiser.getMoxy(clazz);
return generate(serialiser);
}
catch (Exception e)
{
// Ignore
return "error generating schema for " + clazz + ": " + e.getMessage();
}
}
else if (clazz.isAnnotationPresent(XmlType.class) || clazz.isAnnotationPresent(XmlEnum.class))
{
// Class generated by JAXB XSD To Java (as a result we have to emit the entire schema rather than being able to provide a specific sub-schema for the type in question because XmlRootElement is not specified)
try
{
final JAXBSerialiser serialiser = JAXBSerialiser.getMoxy(clazz.getPackage().getName());
return generate(serialiser);
}
catch (Exception e)
{
// Ignore
return "error generating schema for XSD-To-Java package schema for class " + clazz + ": " + e.getMessage();
}
}
else
{
return clazz.toString();
}
} | java | public String getSchema(Class<?> clazz)
{
if (clazz == Integer.class || clazz == Integer.TYPE)
{
return "integer [" + Integer.MIN_VALUE + " to " + Integer.MAX_VALUE + "]";
}
else if (clazz == Long.class || clazz == Long.TYPE)
{
return "long [" + Long.MIN_VALUE + " to " + Long.MAX_VALUE + "]";
}
else if (clazz == Double.class || clazz == Double.TYPE)
{
return "double [" + Double.MIN_VALUE + " to " + Double.MAX_VALUE + "]";
}
else if (clazz == Boolean.class || clazz == Boolean.TYPE)
{
return "boolean [true, false]";
}
else if (clazz == Void.class)
{
return "void";
}
else if (clazz == Byte[].class || clazz == byte[].class)
{
return "binary stream";
}
else if (clazz.isEnum())
{
return "enum " + Arrays.asList(clazz.getEnumConstants());
}
else if (clazz.isAnnotationPresent(XmlRootElement.class))
{
try
{
final JAXBSerialiser serialiser = JAXBSerialiser.getMoxy(clazz);
return generate(serialiser);
}
catch (Exception e)
{
// Ignore
return "error generating schema for " + clazz + ": " + e.getMessage();
}
}
else if (clazz.isAnnotationPresent(XmlType.class) || clazz.isAnnotationPresent(XmlEnum.class))
{
// Class generated by JAXB XSD To Java (as a result we have to emit the entire schema rather than being able to provide a specific sub-schema for the type in question because XmlRootElement is not specified)
try
{
final JAXBSerialiser serialiser = JAXBSerialiser.getMoxy(clazz.getPackage().getName());
return generate(serialiser);
}
catch (Exception e)
{
// Ignore
return "error generating schema for XSD-To-Java package schema for class " + clazz + ": " + e.getMessage();
}
}
else
{
return clazz.toString();
}
} | [
"public",
"String",
"getSchema",
"(",
"Class",
"<",
"?",
">",
"clazz",
")",
"{",
"if",
"(",
"clazz",
"==",
"Integer",
".",
"class",
"||",
"clazz",
"==",
"Integer",
".",
"TYPE",
")",
"{",
"return",
"\"integer [\"",
"+",
"Integer",
".",
"MIN_VALUE",
"+",... | Retrieve a schema description for a type
@param clazz
@return | [
"Retrieve",
"a",
"schema",
"description",
"for",
"a",
"type"
] | d4025d2f881bc0542b1e004c5f65a1ccaf895836 | https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/guice/webapp/src/main/java/com/peterphi/std/guice/web/rest/service/servicedescription/freemarker/SchemaGenerateUtil.java#L40-L103 | train |
ziccardi/jnrpe | jnrpe-lib/src/main/java/it/jnrpe/plugins/MetricBuilder.java | MetricBuilder.withValue | public MetricBuilder withValue(Number value, String prettyPrintFormat) {
current = new MetricValue(value.toString(), prettyPrintFormat);
return this;
} | java | public MetricBuilder withValue(Number value, String prettyPrintFormat) {
current = new MetricValue(value.toString(), prettyPrintFormat);
return this;
} | [
"public",
"MetricBuilder",
"withValue",
"(",
"Number",
"value",
",",
"String",
"prettyPrintFormat",
")",
"{",
"current",
"=",
"new",
"MetricValue",
"(",
"value",
".",
"toString",
"(",
")",
",",
"prettyPrintFormat",
")",
";",
"return",
"this",
";",
"}"
] | Sets the value of the metric to be built.
@param value the value of the metric
@param prettyPrintFormat the format of the output (@see {@link DecimalFormat})
@return this | [
"Sets",
"the",
"value",
"of",
"the",
"metric",
"to",
"be",
"built",
"."
] | ac9046355851136994388442b01ba4063305f9c4 | https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-lib/src/main/java/it/jnrpe/plugins/MetricBuilder.java#L81-L84 | train |
ziccardi/jnrpe | jnrpe-lib/src/main/java/it/jnrpe/plugins/MetricBuilder.java | MetricBuilder.withMinValue | public MetricBuilder withMinValue(Number value, String prettyPrintFormat) {
min = new MetricValue(value.toString(), prettyPrintFormat);
return this;
} | java | public MetricBuilder withMinValue(Number value, String prettyPrintFormat) {
min = new MetricValue(value.toString(), prettyPrintFormat);
return this;
} | [
"public",
"MetricBuilder",
"withMinValue",
"(",
"Number",
"value",
",",
"String",
"prettyPrintFormat",
")",
"{",
"min",
"=",
"new",
"MetricValue",
"(",
"value",
".",
"toString",
"(",
")",
",",
"prettyPrintFormat",
")",
";",
"return",
"this",
";",
"}"
] | Sets the minimum value of the metric to be built.
@param value the minimum value of the metric
@param prettyPrintFormat the format of the output (@see {@link DecimalFormat})
@return this | [
"Sets",
"the",
"minimum",
"value",
"of",
"the",
"metric",
"to",
"be",
"built",
"."
] | ac9046355851136994388442b01ba4063305f9c4 | https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-lib/src/main/java/it/jnrpe/plugins/MetricBuilder.java#L104-L107 | train |
ziccardi/jnrpe | jnrpe-lib/src/main/java/it/jnrpe/plugins/MetricBuilder.java | MetricBuilder.withMaxValue | public MetricBuilder withMaxValue(Number value, String prettyPrintFormat) {
max = new MetricValue(value.toString(), prettyPrintFormat);
return this;
} | java | public MetricBuilder withMaxValue(Number value, String prettyPrintFormat) {
max = new MetricValue(value.toString(), prettyPrintFormat);
return this;
} | [
"public",
"MetricBuilder",
"withMaxValue",
"(",
"Number",
"value",
",",
"String",
"prettyPrintFormat",
")",
"{",
"max",
"=",
"new",
"MetricValue",
"(",
"value",
".",
"toString",
"(",
")",
",",
"prettyPrintFormat",
")",
";",
"return",
"this",
";",
"}"
] | Sets the maximum value of the metric to be built.
@param value the maximum value of the metric
@param prettyPrintFormat the format of the output (@see {@link DecimalFormat})
@return this | [
"Sets",
"the",
"maximum",
"value",
"of",
"the",
"metric",
"to",
"be",
"built",
"."
] | ac9046355851136994388442b01ba4063305f9c4 | https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-lib/src/main/java/it/jnrpe/plugins/MetricBuilder.java#L127-L130 | train |
ziccardi/jnrpe | jnrpe-lib/src/main/java/it/jnrpe/plugins/MetricBuilder.java | MetricBuilder.withMessage | public MetricBuilder withMessage(String messagePattern, Object ...params) {
this.metricMessage = MessageFormat.format(messagePattern, params);
return this;
} | java | public MetricBuilder withMessage(String messagePattern, Object ...params) {
this.metricMessage = MessageFormat.format(messagePattern, params);
return this;
} | [
"public",
"MetricBuilder",
"withMessage",
"(",
"String",
"messagePattern",
",",
"Object",
"...",
"params",
")",
"{",
"this",
".",
"metricMessage",
"=",
"MessageFormat",
".",
"format",
"(",
"messagePattern",
",",
"params",
")",
";",
"return",
"this",
";",
"}"
] | Sets the message to be associated with this metric.
@param messagePattern the message pattern to be associated with this metric
@param params the parameter to pass to {@link MessageFormat} to
create the complete message
@return this | [
"Sets",
"the",
"message",
"to",
"be",
"associated",
"with",
"this",
"metric",
"."
] | ac9046355851136994388442b01ba4063305f9c4 | https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-lib/src/main/java/it/jnrpe/plugins/MetricBuilder.java#L162-L165 | train |
petergeneric/stdlib | guice/hibernate/src/main/java/com/peterphi/std/guice/hibernate/webquery/ResultSetConstraintBuilderFactory.java | ResultSetConstraintBuilderFactory.build | @Deprecated
public ResultSetConstraint build(Map<String, List<String>> constraints)
{
return builder(constraints).build();
} | java | @Deprecated
public ResultSetConstraint build(Map<String, List<String>> constraints)
{
return builder(constraints).build();
} | [
"@",
"Deprecated",
"public",
"ResultSetConstraint",
"build",
"(",
"Map",
"<",
"String",
",",
"List",
"<",
"String",
">",
">",
"constraints",
")",
"{",
"return",
"builder",
"(",
"constraints",
")",
".",
"build",
"(",
")",
";",
"}"
] | Convenience method to build based on a Map of constraints quickly
@param constraints
@return
@deprecated use {@link #builder(Map)} and then call {@link ResultSetConstraintBuilder#buildQuery()} | [
"Convenience",
"method",
"to",
"build",
"based",
"on",
"a",
"Map",
"of",
"constraints",
"quickly"
] | d4025d2f881bc0542b1e004c5f65a1ccaf895836 | https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/guice/hibernate/src/main/java/com/peterphi/std/guice/hibernate/webquery/ResultSetConstraintBuilderFactory.java#L35-L39 | train |
petergeneric/stdlib | guice/hibernate/src/main/java/com/peterphi/std/guice/hibernate/dao/HibernateDao.java | HibernateDao.setTypeLiteral | @Inject
@SuppressWarnings("unchecked")
public void setTypeLiteral(TypeLiteral<T> clazz)
{
if (clazz == null)
throw new IllegalArgumentException("Cannot set null TypeLiteral on " + this);
if (this.clazz != null && !this.clazz.equals(clazz.getRawType()))
throw new IllegalStateException("Cannot call setTypeLiteral twice! Already has value " +
this.clazz +
", will not overwrite with " +
clazz.getRawType());
// Guice sets a Class<? super T> but we know we can cast to Class<T> by convention
this.clazz = (Class<T>) clazz.getRawType();
isLargeTable = this.clazz.isAnnotationPresent(LargeTable.class);
} | java | @Inject
@SuppressWarnings("unchecked")
public void setTypeLiteral(TypeLiteral<T> clazz)
{
if (clazz == null)
throw new IllegalArgumentException("Cannot set null TypeLiteral on " + this);
if (this.clazz != null && !this.clazz.equals(clazz.getRawType()))
throw new IllegalStateException("Cannot call setTypeLiteral twice! Already has value " +
this.clazz +
", will not overwrite with " +
clazz.getRawType());
// Guice sets a Class<? super T> but we know we can cast to Class<T> by convention
this.clazz = (Class<T>) clazz.getRawType();
isLargeTable = this.clazz.isAnnotationPresent(LargeTable.class);
} | [
"@",
"Inject",
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"void",
"setTypeLiteral",
"(",
"TypeLiteral",
"<",
"T",
">",
"clazz",
")",
"{",
"if",
"(",
"clazz",
"==",
"null",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Cannot set n... | Called by guice to provide the Class associated with T
@param clazz
The TypeLiteral associated with T (the entity type) | [
"Called",
"by",
"guice",
"to",
"provide",
"the",
"Class",
"associated",
"with",
"T"
] | d4025d2f881bc0542b1e004c5f65a1ccaf895836 | https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/guice/hibernate/src/main/java/com/peterphi/std/guice/hibernate/dao/HibernateDao.java#L85-L101 | train |
petergeneric/stdlib | guice/hibernate/src/main/java/com/peterphi/std/guice/hibernate/dao/HibernateDao.java | HibernateDao.getIds | public Collection<ID> getIds(final WebQuery constraints)
{
return (Collection<ID>) find(constraints, JPASearchStrategy.ID).getList();
} | java | public Collection<ID> getIds(final WebQuery constraints)
{
return (Collection<ID>) find(constraints, JPASearchStrategy.ID).getList();
} | [
"public",
"Collection",
"<",
"ID",
">",
"getIds",
"(",
"final",
"WebQuery",
"constraints",
")",
"{",
"return",
"(",
"Collection",
"<",
"ID",
">",
")",
"find",
"(",
"constraints",
",",
"JPASearchStrategy",
".",
"ID",
")",
".",
"getList",
"(",
")",
";",
... | Get a list of IDs matching a WebQuery
@param constraints
@return | [
"Get",
"a",
"list",
"of",
"IDs",
"matching",
"a",
"WebQuery"
] | d4025d2f881bc0542b1e004c5f65a1ccaf895836 | https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/guice/hibernate/src/main/java/com/peterphi/std/guice/hibernate/dao/HibernateDao.java#L563-L566 | train |
ziccardi/jnrpe | jnrpe-lib/src/main/java/it/jnrpe/JNRPE.java | JNRPE.getSSLEngine | private SSLEngine getSSLEngine() throws KeyStoreException,
CertificateException,
IOException,
UnrecoverableKeyException,
KeyManagementException {
// Open the KeyStore Stream
final StreamManager streamManager = new StreamManager();
SSLContext ctx;
KeyManagerFactory kmf;
try {
final InputStream ksStream = getClass().getClassLoader().getResourceAsStream(KEYSTORE_NAME);
streamManager.handle(ksStream);
ctx = SSLContext.getInstance("SSLv3");
kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
final KeyStore ks = KeyStore.getInstance("JKS");
char[] passphrase = KEYSTORE_PWD.toCharArray();
ks.load(ksStream, passphrase);
kmf.init(ks, passphrase);
ctx.init(kmf.getKeyManagers(), null, new java.security.SecureRandom());
} catch (NoSuchAlgorithmException e) {
throw new SSLException("Unable to initialize SSLSocketFactory" + e.getMessage(), e);
} finally {
streamManager.closeAll();
}
return ctx.createSSLEngine();
} | java | private SSLEngine getSSLEngine() throws KeyStoreException,
CertificateException,
IOException,
UnrecoverableKeyException,
KeyManagementException {
// Open the KeyStore Stream
final StreamManager streamManager = new StreamManager();
SSLContext ctx;
KeyManagerFactory kmf;
try {
final InputStream ksStream = getClass().getClassLoader().getResourceAsStream(KEYSTORE_NAME);
streamManager.handle(ksStream);
ctx = SSLContext.getInstance("SSLv3");
kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
final KeyStore ks = KeyStore.getInstance("JKS");
char[] passphrase = KEYSTORE_PWD.toCharArray();
ks.load(ksStream, passphrase);
kmf.init(ks, passphrase);
ctx.init(kmf.getKeyManagers(), null, new java.security.SecureRandom());
} catch (NoSuchAlgorithmException e) {
throw new SSLException("Unable to initialize SSLSocketFactory" + e.getMessage(), e);
} finally {
streamManager.closeAll();
}
return ctx.createSSLEngine();
} | [
"private",
"SSLEngine",
"getSSLEngine",
"(",
")",
"throws",
"KeyStoreException",
",",
"CertificateException",
",",
"IOException",
",",
"UnrecoverableKeyException",
",",
"KeyManagementException",
"{",
"// Open the KeyStore Stream",
"final",
"StreamManager",
"streamManager",
"=... | Creates, configures and returns the SSL engine.
@return the SSL Engine * @throws KeyStoreException
on keystore errorss * @throws CertificateException
on certificate errors * @throws IOException
on I/O errors * @throws UnrecoverableKeyException
if key is unrecoverable * @throws KeyManagementException
key management error | [
"Creates",
"configures",
"and",
"returns",
"the",
"SSL",
"engine",
"."
] | ac9046355851136994388442b01ba4063305f9c4 | https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-lib/src/main/java/it/jnrpe/JNRPE.java#L284-L316 | train |
ziccardi/jnrpe | jnrpe-lib/src/main/java/it/jnrpe/JNRPE.java | JNRPE.getServerBootstrap | private ServerBootstrap getServerBootstrap(final boolean useSSL) {
final CommandInvoker invoker = new CommandInvoker(pluginRepository, commandRepository, acceptParams, getExecutionContext());
final ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(final SocketChannel ch) throws Exception {
if (useSSL) {
final SSLEngine engine = getSSLEngine();
engine.setEnabledCipherSuites(engine.getSupportedCipherSuites());
engine.setUseClientMode(false);
engine.setNeedClientAuth(false);
ch.pipeline().addLast("ssl", new SslHandler(engine));
}
ch.pipeline()
.addLast(new JNRPERequestDecoder(), new JNRPEResponseEncoder(), new JNRPEServerHandler(invoker, context))
.addLast("idleStateHandler", new IdleStateHandler(readTimeout, writeTimeout, 0))
.addLast(
"jnrpeIdleStateHandler",
new JNRPEIdleStateHandler(context));
}
}).option(ChannelOption.SO_BACKLOG, maxAcceptedConnections).childOption(ChannelOption.SO_KEEPALIVE, Boolean.TRUE);
return serverBootstrap;
} | java | private ServerBootstrap getServerBootstrap(final boolean useSSL) {
final CommandInvoker invoker = new CommandInvoker(pluginRepository, commandRepository, acceptParams, getExecutionContext());
final ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(final SocketChannel ch) throws Exception {
if (useSSL) {
final SSLEngine engine = getSSLEngine();
engine.setEnabledCipherSuites(engine.getSupportedCipherSuites());
engine.setUseClientMode(false);
engine.setNeedClientAuth(false);
ch.pipeline().addLast("ssl", new SslHandler(engine));
}
ch.pipeline()
.addLast(new JNRPERequestDecoder(), new JNRPEResponseEncoder(), new JNRPEServerHandler(invoker, context))
.addLast("idleStateHandler", new IdleStateHandler(readTimeout, writeTimeout, 0))
.addLast(
"jnrpeIdleStateHandler",
new JNRPEIdleStateHandler(context));
}
}).option(ChannelOption.SO_BACKLOG, maxAcceptedConnections).childOption(ChannelOption.SO_KEEPALIVE, Boolean.TRUE);
return serverBootstrap;
} | [
"private",
"ServerBootstrap",
"getServerBootstrap",
"(",
"final",
"boolean",
"useSSL",
")",
"{",
"final",
"CommandInvoker",
"invoker",
"=",
"new",
"CommandInvoker",
"(",
"pluginRepository",
",",
"commandRepository",
",",
"acceptParams",
",",
"getExecutionContext",
"(",
... | Creates and returns a configured NETTY ServerBootstrap object.
@param useSSL
<code>true</code> if SSL must be used.
@return the server bootstrap object | [
"Creates",
"and",
"returns",
"a",
"configured",
"NETTY",
"ServerBootstrap",
"object",
"."
] | ac9046355851136994388442b01ba4063305f9c4 | https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-lib/src/main/java/it/jnrpe/JNRPE.java#L325-L352 | train |
petergeneric/stdlib | stdlib/src/main/java/com/peterphi/std/types/SampleCount.java | SampleCount.resample | public SampleCount resample(Timebase newRate)
{
if (!this.rate.equals(newRate))
{
final long newSamples = getSamples(newRate);
return new SampleCount(newSamples, newRate);
}
else
{
// Same rate, no need to resample
return this;
}
} | java | public SampleCount resample(Timebase newRate)
{
if (!this.rate.equals(newRate))
{
final long newSamples = getSamples(newRate);
return new SampleCount(newSamples, newRate);
}
else
{
// Same rate, no need to resample
return this;
}
} | [
"public",
"SampleCount",
"resample",
"(",
"Timebase",
"newRate",
")",
"{",
"if",
"(",
"!",
"this",
".",
"rate",
".",
"equals",
"(",
"newRate",
")",
")",
"{",
"final",
"long",
"newSamples",
"=",
"getSamples",
"(",
"newRate",
")",
";",
"return",
"new",
"... | Resample this sample count to another rate
@param newRate
@return | [
"Resample",
"this",
"sample",
"count",
"to",
"another",
"rate"
] | d4025d2f881bc0542b1e004c5f65a1ccaf895836 | https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/stdlib/src/main/java/com/peterphi/std/types/SampleCount.java#L29-L42 | train |
ops4j/org.ops4j.pax.swissbox | pax-swissbox-extender/src/main/java/org/ops4j/pax/swissbox/extender/SynchronousBundleWatcher.java | SynchronousBundleWatcher.onStart | @Override
protected void onStart()
{
m_mappings = new HashMap<Bundle, List<T>>();
// listen to bundles events
m_context.addBundleListener( m_bundleListener = new SynchronousBundleListener()
{
public void bundleChanged( final BundleEvent bundleEvent )
{
switch( bundleEvent.getType() )
{
case BundleEvent.STARTED:
register( bundleEvent.getBundle() );
break;
case BundleEvent.STOPPED:
unregister( bundleEvent.getBundle() );
break;
}
}
}
);
// scan already started bundles
Bundle[] bundles = m_context.getBundles();
if( bundles != null )
{
for( Bundle bundle : bundles )
{
if( bundle.getState() == Bundle.ACTIVE )
{
register( bundle );
}
}
}
} | java | @Override
protected void onStart()
{
m_mappings = new HashMap<Bundle, List<T>>();
// listen to bundles events
m_context.addBundleListener( m_bundleListener = new SynchronousBundleListener()
{
public void bundleChanged( final BundleEvent bundleEvent )
{
switch( bundleEvent.getType() )
{
case BundleEvent.STARTED:
register( bundleEvent.getBundle() );
break;
case BundleEvent.STOPPED:
unregister( bundleEvent.getBundle() );
break;
}
}
}
);
// scan already started bundles
Bundle[] bundles = m_context.getBundles();
if( bundles != null )
{
for( Bundle bundle : bundles )
{
if( bundle.getState() == Bundle.ACTIVE )
{
register( bundle );
}
}
}
} | [
"@",
"Override",
"protected",
"void",
"onStart",
"(",
")",
"{",
"m_mappings",
"=",
"new",
"HashMap",
"<",
"Bundle",
",",
"List",
"<",
"T",
">",
">",
"(",
")",
";",
"// listen to bundles events\r",
"m_context",
".",
"addBundleListener",
"(",
"m_bundleListener",... | Registers a listener for bundle events and scans already active bundles. | [
"Registers",
"a",
"listener",
"for",
"bundle",
"events",
"and",
"scans",
"already",
"active",
"bundles",
"."
] | 00b0ee16cdbe8017984a4d7ba808b10d985c5b5c | https://github.com/ops4j/org.ops4j.pax.swissbox/blob/00b0ee16cdbe8017984a4d7ba808b10d985c5b5c/pax-swissbox-extender/src/main/java/org/ops4j/pax/swissbox/extender/SynchronousBundleWatcher.java#L119-L155 | train |
ops4j/org.ops4j.pax.swissbox | pax-swissbox-extender/src/main/java/org/ops4j/pax/swissbox/extender/SynchronousBundleWatcher.java | SynchronousBundleWatcher.onStop | @Override
protected void onStop()
{
m_context.removeBundleListener( m_bundleListener );
final Bundle[] toBeRemoved =
m_mappings.keySet().toArray( new Bundle[m_mappings.keySet().size()] );
for( Bundle bundle : toBeRemoved )
{
unregister( bundle );
}
m_bundleListener = null;
m_mappings = null;
} | java | @Override
protected void onStop()
{
m_context.removeBundleListener( m_bundleListener );
final Bundle[] toBeRemoved =
m_mappings.keySet().toArray( new Bundle[m_mappings.keySet().size()] );
for( Bundle bundle : toBeRemoved )
{
unregister( bundle );
}
m_bundleListener = null;
m_mappings = null;
} | [
"@",
"Override",
"protected",
"void",
"onStop",
"(",
")",
"{",
"m_context",
".",
"removeBundleListener",
"(",
"m_bundleListener",
")",
";",
"final",
"Bundle",
"[",
"]",
"toBeRemoved",
"=",
"m_mappings",
".",
"keySet",
"(",
")",
".",
"toArray",
"(",
"new",
... | Un-register the bundle listener, releases resources | [
"Un",
"-",
"register",
"the",
"bundle",
"listener",
"releases",
"resources"
] | 00b0ee16cdbe8017984a4d7ba808b10d985c5b5c | https://github.com/ops4j/org.ops4j.pax.swissbox/blob/00b0ee16cdbe8017984a4d7ba808b10d985c5b5c/pax-swissbox-extender/src/main/java/org/ops4j/pax/swissbox/extender/SynchronousBundleWatcher.java#L160-L173 | train |
ziccardi/jnrpe | jnrpe-server/src/main/java/it/jnrpe/server/JNRPEConfiguration.java | JNRPEConfiguration.createCommandRepository | public final CommandRepository createCommandRepository() {
CommandRepository cr = new CommandRepository();
for (Command c : commandSection.getAllCommands()) {
CommandDefinition cd = new CommandDefinition(c.getName(), c.getPlugin());
cd.setArgs(c.getCommandLine());
cr.addCommandDefinition(cd);
}
return cr;
} | java | public final CommandRepository createCommandRepository() {
CommandRepository cr = new CommandRepository();
for (Command c : commandSection.getAllCommands()) {
CommandDefinition cd = new CommandDefinition(c.getName(), c.getPlugin());
cd.setArgs(c.getCommandLine());
cr.addCommandDefinition(cd);
}
return cr;
} | [
"public",
"final",
"CommandRepository",
"createCommandRepository",
"(",
")",
"{",
"CommandRepository",
"cr",
"=",
"new",
"CommandRepository",
"(",
")",
";",
"for",
"(",
"Command",
"c",
":",
"commandSection",
".",
"getAllCommands",
"(",
")",
")",
"{",
"CommandDef... | Returns a command repository containing all the commands configured
inside the configuration file.
@return The command repository | [
"Returns",
"a",
"command",
"repository",
"containing",
"all",
"the",
"commands",
"configured",
"inside",
"the",
"configuration",
"file",
"."
] | ac9046355851136994388442b01ba4063305f9c4 | https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-server/src/main/java/it/jnrpe/server/JNRPEConfiguration.java#L77-L88 | train |
ziccardi/jnrpe | jnrpe-lib/src/main/java/it/jnrpe/net/JNRPERequest.java | JNRPERequest.init | private void init(final String commandName, final String... arguments) {
if (arguments != null) {
if (arguments.length == 1) {
init(commandName, arguments[0]);
return;
}
String[] ary = new String[arguments.length];
for (int i = 0; i < arguments.length; i++) {
if (arguments[i].indexOf('!') == -1) {
ary[i] = arguments[i];
} else {
ary[i] = "'" + arguments[i] + "'";
}
}
// sCommandBytes = StringUtils.join(ary, '!');
init(commandName, StringUtils.join(ary, '!'));
} else {
init(commandName, (String) null);
}
} | java | private void init(final String commandName, final String... arguments) {
if (arguments != null) {
if (arguments.length == 1) {
init(commandName, arguments[0]);
return;
}
String[] ary = new String[arguments.length];
for (int i = 0; i < arguments.length; i++) {
if (arguments[i].indexOf('!') == -1) {
ary[i] = arguments[i];
} else {
ary[i] = "'" + arguments[i] + "'";
}
}
// sCommandBytes = StringUtils.join(ary, '!');
init(commandName, StringUtils.join(ary, '!'));
} else {
init(commandName, (String) null);
}
} | [
"private",
"void",
"init",
"(",
"final",
"String",
"commandName",
",",
"final",
"String",
"...",
"arguments",
")",
"{",
"if",
"(",
"arguments",
"!=",
"null",
")",
"{",
"if",
"(",
"arguments",
".",
"length",
"==",
"1",
")",
"{",
"init",
"(",
"commandNam... | Initializes the object with the given command and the given arguments.
The arguments gets quoted if they contains '!' and are then joined using
the '!' as separator.
@param commandName
The command
@param arguments
The arguments | [
"Initializes",
"the",
"object",
"with",
"the",
"given",
"command",
"and",
"the",
"given",
"arguments",
"."
] | ac9046355851136994388442b01ba4063305f9c4 | https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-lib/src/main/java/it/jnrpe/net/JNRPERequest.java#L75-L96 | train |
ziccardi/jnrpe | jnrpe-lib/src/main/java/it/jnrpe/net/JNRPERequest.java | JNRPERequest.init | private void init(final String commandName, final String argumentsString) {
String fullCommandString;
String tmpArgumentsString = argumentsString;
if (tmpArgumentsString != null && !tmpArgumentsString.isEmpty() && tmpArgumentsString.charAt(0) == '!') {
tmpArgumentsString = tmpArgumentsString.substring(1);
}
if (!StringUtils.isBlank(tmpArgumentsString)) {
fullCommandString = commandName + "!" + tmpArgumentsString;
} else {
fullCommandString = commandName;
}
this.packet.setType(PacketType.QUERY);
this.packet.setBuffer(fullCommandString);
// updateCRC();
} | java | private void init(final String commandName, final String argumentsString) {
String fullCommandString;
String tmpArgumentsString = argumentsString;
if (tmpArgumentsString != null && !tmpArgumentsString.isEmpty() && tmpArgumentsString.charAt(0) == '!') {
tmpArgumentsString = tmpArgumentsString.substring(1);
}
if (!StringUtils.isBlank(tmpArgumentsString)) {
fullCommandString = commandName + "!" + tmpArgumentsString;
} else {
fullCommandString = commandName;
}
this.packet.setType(PacketType.QUERY);
this.packet.setBuffer(fullCommandString);
// updateCRC();
} | [
"private",
"void",
"init",
"(",
"final",
"String",
"commandName",
",",
"final",
"String",
"argumentsString",
")",
"{",
"String",
"fullCommandString",
";",
"String",
"tmpArgumentsString",
"=",
"argumentsString",
";",
"if",
"(",
"tmpArgumentsString",
"!=",
"null",
"... | Initializes the object with the given command and the given list of '!'
separated list of arguments.
@param commandName
The command
@param argumentsString
The arguments | [
"Initializes",
"the",
"object",
"with",
"the",
"given",
"command",
"and",
"the",
"given",
"list",
"of",
"!",
"separated",
"list",
"of",
"arguments",
"."
] | ac9046355851136994388442b01ba4063305f9c4 | https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-lib/src/main/java/it/jnrpe/net/JNRPERequest.java#L107-L125 | train |
ziccardi/jnrpe | jnrpe-lib/src/main/java/it/jnrpe/net/JNRPERequest.java | JNRPERequest.getArguments | public final String[] getArguments() {
// extracting params
String[] partsAry = split(this.packet.getBufferAsString());
String[] argsAry = new String[partsAry.length - 1];
System.arraycopy(partsAry, 1, argsAry, 0, argsAry.length);
return argsAry;
} | java | public final String[] getArguments() {
// extracting params
String[] partsAry = split(this.packet.getBufferAsString());
String[] argsAry = new String[partsAry.length - 1];
System.arraycopy(partsAry, 1, argsAry, 0, argsAry.length);
return argsAry;
} | [
"public",
"final",
"String",
"[",
"]",
"getArguments",
"(",
")",
"{",
"// extracting params",
"String",
"[",
"]",
"partsAry",
"=",
"split",
"(",
"this",
".",
"packet",
".",
"getBufferAsString",
"(",
")",
")",
";",
"String",
"[",
"]",
"argsAry",
"=",
"new... | Returns the command arguments.
@return the command arguments | [
"Returns",
"the",
"command",
"arguments",
"."
] | ac9046355851136994388442b01ba4063305f9c4 | https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-lib/src/main/java/it/jnrpe/net/JNRPERequest.java#L144-L152 | train |
ziccardi/jnrpe | jnrpe-lib/src/main/java/it/jnrpe/net/JNRPERequest.java | JNRPERequest.split | private String[] split(final String sCommandLine) {
return it.jnrpe.utils.StringUtils.split(sCommandLine, '!', false);
} | java | private String[] split(final String sCommandLine) {
return it.jnrpe.utils.StringUtils.split(sCommandLine, '!', false);
} | [
"private",
"String",
"[",
"]",
"split",
"(",
"final",
"String",
"sCommandLine",
")",
"{",
"return",
"it",
".",
"jnrpe",
".",
"utils",
".",
"StringUtils",
".",
"split",
"(",
"sCommandLine",
",",
"'",
"'",
",",
"false",
")",
";",
"}"
] | Utility method that splits using the '!' character and handling quoting
by "'" and '"'.
@param sCommandLine
The command line string
@return The splitted string | [
"Utility",
"method",
"that",
"splits",
"using",
"the",
"!",
"character",
"and",
"handling",
"quoting",
"by",
"and",
"."
] | ac9046355851136994388442b01ba4063305f9c4 | https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-lib/src/main/java/it/jnrpe/net/JNRPERequest.java#L162-L164 | train |
petergeneric/stdlib | user-manager/service/src/main/java/com/peterphi/usermanager/guice/authentication/db/InternalUserAuthenticationServiceImpl.java | InternalUserAuthenticationServiceImpl.ensureRolesFetched | private UserEntity ensureRolesFetched(final UserEntity user)
{
if (user != null)
user.getRoles().stream().map(r -> r.getId()).collect(Collectors.toList());
return user;
} | java | private UserEntity ensureRolesFetched(final UserEntity user)
{
if (user != null)
user.getRoles().stream().map(r -> r.getId()).collect(Collectors.toList());
return user;
} | [
"private",
"UserEntity",
"ensureRolesFetched",
"(",
"final",
"UserEntity",
"user",
")",
"{",
"if",
"(",
"user",
"!=",
"null",
")",
"user",
".",
"getRoles",
"(",
")",
".",
"stream",
"(",
")",
".",
"map",
"(",
"r",
"->",
"r",
".",
"getId",
"(",
")",
... | Make sure the roles have been fetched from the database
@param user
@return | [
"Make",
"sure",
"the",
"roles",
"have",
"been",
"fetched",
"from",
"the",
"database"
] | d4025d2f881bc0542b1e004c5f65a1ccaf895836 | https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/user-manager/service/src/main/java/com/peterphi/usermanager/guice/authentication/db/InternalUserAuthenticationServiceImpl.java#L43-L49 | train |
petergeneric/stdlib | user-manager/service/src/main/java/com/peterphi/usermanager/guice/authentication/UserLoginProvider.java | UserLoginProvider.tryBasicAuthLogin | private UserLogin tryBasicAuthLogin(UserLogin login, UserAuthenticationService authService, HttpServletRequest request)
{
final String header = request.getHeader(HttpHeaderNames.AUTHORIZATION);
if (header != null)
{
final String[] credentials = BasicAuthHelper.parseHeader(header);
if (credentials != null)
{
final String username = credentials[0];
final String password = credentials[1];
final Future<UserEntity> future = asynchService.get().submit(() -> tryLogin(authService,
username,
password,
true));
try
{
UserEntity user = LOGIN_TIMEOUT.start().resolveFuture(future, true);
login.reload(user);
}
catch (Exception e)
{
throw new RuntimeException("Error attempting asynchronous BASIC auth login: " + e.getMessage(), e);
}
}
}
// No authorisation (or unsupported authorisation type)
return null;
} | java | private UserLogin tryBasicAuthLogin(UserLogin login, UserAuthenticationService authService, HttpServletRequest request)
{
final String header = request.getHeader(HttpHeaderNames.AUTHORIZATION);
if (header != null)
{
final String[] credentials = BasicAuthHelper.parseHeader(header);
if (credentials != null)
{
final String username = credentials[0];
final String password = credentials[1];
final Future<UserEntity> future = asynchService.get().submit(() -> tryLogin(authService,
username,
password,
true));
try
{
UserEntity user = LOGIN_TIMEOUT.start().resolveFuture(future, true);
login.reload(user);
}
catch (Exception e)
{
throw new RuntimeException("Error attempting asynchronous BASIC auth login: " + e.getMessage(), e);
}
}
}
// No authorisation (or unsupported authorisation type)
return null;
} | [
"private",
"UserLogin",
"tryBasicAuthLogin",
"(",
"UserLogin",
"login",
",",
"UserAuthenticationService",
"authService",
",",
"HttpServletRequest",
"request",
")",
"{",
"final",
"String",
"header",
"=",
"request",
".",
"getHeader",
"(",
"HttpHeaderNames",
".",
"AUTHOR... | Support proactive HTTP BASIC authentication
@param authService
the user authentication service
@param request
the HTTP request
@return a UserLogin for the appropriate user if valid credentials were presented, otherwise null | [
"Support",
"proactive",
"HTTP",
"BASIC",
"authentication"
] | d4025d2f881bc0542b1e004c5f65a1ccaf895836 | https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/user-manager/service/src/main/java/com/peterphi/usermanager/guice/authentication/UserLoginProvider.java#L121-L154 | train |
petergeneric/stdlib | stdlib/src/main/java/com/peterphi/std/util/jaxb/JAXBSerialiserFactory.java | JAXBSerialiserFactory.prune | private void prune()
{
if (useSoftReferences)
{
Iterator<Map.Entry<String, Object>> it = cache.entrySet().iterator();
while (it.hasNext())
{
final Map.Entry<String, Object> entry = it.next();
if (dereference(entry.getValue()) == null)
it.remove();
}
}
} | java | private void prune()
{
if (useSoftReferences)
{
Iterator<Map.Entry<String, Object>> it = cache.entrySet().iterator();
while (it.hasNext())
{
final Map.Entry<String, Object> entry = it.next();
if (dereference(entry.getValue()) == null)
it.remove();
}
}
} | [
"private",
"void",
"prune",
"(",
")",
"{",
"if",
"(",
"useSoftReferences",
")",
"{",
"Iterator",
"<",
"Map",
".",
"Entry",
"<",
"String",
",",
"Object",
">",
">",
"it",
"=",
"cache",
".",
"entrySet",
"(",
")",
".",
"iterator",
"(",
")",
";",
"while... | Finds stale entries in the map | [
"Finds",
"stale",
"entries",
"in",
"the",
"map"
] | d4025d2f881bc0542b1e004c5f65a1ccaf895836 | https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/stdlib/src/main/java/com/peterphi/std/util/jaxb/JAXBSerialiserFactory.java#L96-L110 | train |
ziccardi/jnrpe | jnrpe-lib/src/main/java/it/jnrpe/utils/thresholds/ThresholdsEvaluatorBuilder.java | ThresholdsEvaluatorBuilder.withLegacyThreshold | public final ThresholdsEvaluatorBuilder withLegacyThreshold(final String metric, final String okRange, final String warnRange,
final String critRange) throws BadThresholdException {
LegacyRange ok = null, warn = null, crit = null;
if (okRange != null) {
ok = new LegacyRange(okRange);
}
if (warnRange != null) {
warn = new LegacyRange(warnRange);
}
if (critRange != null) {
crit = new LegacyRange(critRange);
}
thresholds.addThreshold(new LegacyThreshold(metric, ok, warn, crit));
return this;
} | java | public final ThresholdsEvaluatorBuilder withLegacyThreshold(final String metric, final String okRange, final String warnRange,
final String critRange) throws BadThresholdException {
LegacyRange ok = null, warn = null, crit = null;
if (okRange != null) {
ok = new LegacyRange(okRange);
}
if (warnRange != null) {
warn = new LegacyRange(warnRange);
}
if (critRange != null) {
crit = new LegacyRange(critRange);
}
thresholds.addThreshold(new LegacyThreshold(metric, ok, warn, crit));
return this;
} | [
"public",
"final",
"ThresholdsEvaluatorBuilder",
"withLegacyThreshold",
"(",
"final",
"String",
"metric",
",",
"final",
"String",
"okRange",
",",
"final",
"String",
"warnRange",
",",
"final",
"String",
"critRange",
")",
"throws",
"BadThresholdException",
"{",
"LegacyR... | This method allows to specify thresholds using the old format.
@param metric
The metric for which this threshold must be configured
@param okRange
The ok range (can be null)
@param warnRange
The warning range (can be null)
@param critRange
The critical range (can be null).
@return this
@throws BadThresholdException If the threshold can't be
parsed. | [
"This",
"method",
"allows",
"to",
"specify",
"thresholds",
"using",
"the",
"old",
"format",
"."
] | ac9046355851136994388442b01ba4063305f9c4 | https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-lib/src/main/java/it/jnrpe/utils/thresholds/ThresholdsEvaluatorBuilder.java#L71-L87 | train |
petergeneric/stdlib | guice/webapp/src/main/java/com/peterphi/std/guice/web/rest/resteasy/ResteasyProviderRegistry.java | ResteasyProviderRegistry.register | public static synchronized void register(Class<?> clazz)
{
if (clazz.isAnnotationPresent(javax.ws.rs.ext.Provider.class))
{
classes.add(clazz);
revision++;
}
else
{
throw new RuntimeException("Class " + clazz.getName() + " is not annotated with javax.ws.rs.ext.Provider");
}
} | java | public static synchronized void register(Class<?> clazz)
{
if (clazz.isAnnotationPresent(javax.ws.rs.ext.Provider.class))
{
classes.add(clazz);
revision++;
}
else
{
throw new RuntimeException("Class " + clazz.getName() + " is not annotated with javax.ws.rs.ext.Provider");
}
} | [
"public",
"static",
"synchronized",
"void",
"register",
"(",
"Class",
"<",
"?",
">",
"clazz",
")",
"{",
"if",
"(",
"clazz",
".",
"isAnnotationPresent",
"(",
"javax",
".",
"ws",
".",
"rs",
".",
"ext",
".",
"Provider",
".",
"class",
")",
")",
"{",
"cla... | Register a provider class
@param clazz | [
"Register",
"a",
"provider",
"class"
] | d4025d2f881bc0542b1e004c5f65a1ccaf895836 | https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/guice/webapp/src/main/java/com/peterphi/std/guice/web/rest/resteasy/ResteasyProviderRegistry.java#L24-L35 | train |
ops4j/org.ops4j.pax.swissbox | pax-swissbox-bnd/src/main/java/org/ops4j/pax/swissbox/bnd/BndUtils.java | BndUtils.createInputStream | private static PipedInputStream createInputStream( final Jar jar )
throws IOException
{
final CloseAwarePipedInputStream pin = new CloseAwarePipedInputStream();
final PipedOutputStream pout = new PipedOutputStream( pin );
new Thread()
{
public void run()
{
try
{
jar.write( pout );
}
catch( Exception e )
{
if (pin.closed)
{
// logging the message at DEBUG logging instead
// -- reading thread probably stopped reading
LOG.debug( "Bundle cannot be generated, pipe closed by reader", e );
}
else {
LOG.warn( "Bundle cannot be generated", e );
}
}
finally
{
try
{
jar.close();
pout.close();
}
catch( IOException ignore )
{
// if we get here something is very wrong
LOG.error( "Bundle cannot be generated", ignore );
}
}
}
}.start();
return pin;
} | java | private static PipedInputStream createInputStream( final Jar jar )
throws IOException
{
final CloseAwarePipedInputStream pin = new CloseAwarePipedInputStream();
final PipedOutputStream pout = new PipedOutputStream( pin );
new Thread()
{
public void run()
{
try
{
jar.write( pout );
}
catch( Exception e )
{
if (pin.closed)
{
// logging the message at DEBUG logging instead
// -- reading thread probably stopped reading
LOG.debug( "Bundle cannot be generated, pipe closed by reader", e );
}
else {
LOG.warn( "Bundle cannot be generated", e );
}
}
finally
{
try
{
jar.close();
pout.close();
}
catch( IOException ignore )
{
// if we get here something is very wrong
LOG.error( "Bundle cannot be generated", ignore );
}
}
}
}.start();
return pin;
} | [
"private",
"static",
"PipedInputStream",
"createInputStream",
"(",
"final",
"Jar",
"jar",
")",
"throws",
"IOException",
"{",
"final",
"CloseAwarePipedInputStream",
"pin",
"=",
"new",
"CloseAwarePipedInputStream",
"(",
")",
";",
"final",
"PipedOutputStream",
"pout",
"=... | Creates an piped input stream for the wrapped jar.
This is done in a thread so we can return quickly.
@param jar the wrapped jar
@return an input stream for the wrapped jar
@throws java.io.IOException re-thrown | [
"Creates",
"an",
"piped",
"input",
"stream",
"for",
"the",
"wrapped",
"jar",
".",
"This",
"is",
"done",
"in",
"a",
"thread",
"so",
"we",
"can",
"return",
"quickly",
"."
] | 00b0ee16cdbe8017984a4d7ba808b10d985c5b5c | https://github.com/ops4j/org.ops4j.pax.swissbox/blob/00b0ee16cdbe8017984a4d7ba808b10d985c5b5c/pax-swissbox-bnd/src/main/java/org/ops4j/pax/swissbox/bnd/BndUtils.java#L184-L227 | train |
ops4j/org.ops4j.pax.swissbox | pax-swissbox-bnd/src/main/java/org/ops4j/pax/swissbox/bnd/BndUtils.java | BndUtils.checkMandatoryProperties | private static void checkMandatoryProperties( final Analyzer analyzer,
final Jar jar,
final String symbolicName )
{
final String importPackage = analyzer.getProperty( Analyzer.IMPORT_PACKAGE );
if( importPackage == null || importPackage.trim().length() == 0 )
{
analyzer.setProperty( Analyzer.IMPORT_PACKAGE, "*;resolution:=optional" );
}
final String exportPackage = analyzer.getProperty( Analyzer.EXPORT_PACKAGE );
if( exportPackage == null || exportPackage.trim().length() == 0 )
{
analyzer.setProperty( Analyzer.EXPORT_PACKAGE, "*" );
}
final String localSymbolicName = analyzer.getProperty( Analyzer.BUNDLE_SYMBOLICNAME, symbolicName );
analyzer.setProperty( Analyzer.BUNDLE_SYMBOLICNAME, generateSymbolicName( localSymbolicName ) );
} | java | private static void checkMandatoryProperties( final Analyzer analyzer,
final Jar jar,
final String symbolicName )
{
final String importPackage = analyzer.getProperty( Analyzer.IMPORT_PACKAGE );
if( importPackage == null || importPackage.trim().length() == 0 )
{
analyzer.setProperty( Analyzer.IMPORT_PACKAGE, "*;resolution:=optional" );
}
final String exportPackage = analyzer.getProperty( Analyzer.EXPORT_PACKAGE );
if( exportPackage == null || exportPackage.trim().length() == 0 )
{
analyzer.setProperty( Analyzer.EXPORT_PACKAGE, "*" );
}
final String localSymbolicName = analyzer.getProperty( Analyzer.BUNDLE_SYMBOLICNAME, symbolicName );
analyzer.setProperty( Analyzer.BUNDLE_SYMBOLICNAME, generateSymbolicName( localSymbolicName ) );
} | [
"private",
"static",
"void",
"checkMandatoryProperties",
"(",
"final",
"Analyzer",
"analyzer",
",",
"final",
"Jar",
"jar",
",",
"final",
"String",
"symbolicName",
")",
"{",
"final",
"String",
"importPackage",
"=",
"analyzer",
".",
"getProperty",
"(",
"Analyzer",
... | Check if manadatory properties are present, otherwise generate default.
@param analyzer bnd analyzer
@param jar bnd jar
@param symbolicName bundle symbolic name | [
"Check",
"if",
"manadatory",
"properties",
"are",
"present",
"otherwise",
"generate",
"default",
"."
] | 00b0ee16cdbe8017984a4d7ba808b10d985c5b5c | https://github.com/ops4j/org.ops4j.pax.swissbox/blob/00b0ee16cdbe8017984a4d7ba808b10d985c5b5c/pax-swissbox-bnd/src/main/java/org/ops4j/pax/swissbox/bnd/BndUtils.java#L236-L252 | train |
ops4j/org.ops4j.pax.swissbox | pax-swissbox-bnd/src/main/java/org/ops4j/pax/swissbox/bnd/BndUtils.java | BndUtils.parseInstructions | public static Properties parseInstructions( final String query )
throws MalformedURLException
{
final Properties instructions = new Properties();
if( query != null )
{
try
{
// just ignore for the moment and try out if we have valid properties separated by "&"
final String segments[] = query.split( "&" );
for( String segment : segments )
{
// do not parse empty strings
if( segment.trim().length() > 0 )
{
final Matcher matcher = INSTRUCTIONS_PATTERN.matcher( segment );
if( matcher.matches() )
{
String key = matcher.group( 1 );
String val = matcher.group( 2 );
instructions.setProperty(
verifyKey(key),
val != null ? URLDecoder.decode( val, "UTF-8" ) : ""
);
}
else
{
throw new MalformedURLException( "Invalid syntax for instruction [" + segment
+ "]. Take a look at http://www.aqute.biz/Code/Bnd."
);
}
}
}
}
catch( UnsupportedEncodingException e )
{
// thrown by URLDecoder but it should never happen
throwAsMalformedURLException( "Could not retrieve the instructions from [" + query + "]", e );
}
}
return instructions;
} | java | public static Properties parseInstructions( final String query )
throws MalformedURLException
{
final Properties instructions = new Properties();
if( query != null )
{
try
{
// just ignore for the moment and try out if we have valid properties separated by "&"
final String segments[] = query.split( "&" );
for( String segment : segments )
{
// do not parse empty strings
if( segment.trim().length() > 0 )
{
final Matcher matcher = INSTRUCTIONS_PATTERN.matcher( segment );
if( matcher.matches() )
{
String key = matcher.group( 1 );
String val = matcher.group( 2 );
instructions.setProperty(
verifyKey(key),
val != null ? URLDecoder.decode( val, "UTF-8" ) : ""
);
}
else
{
throw new MalformedURLException( "Invalid syntax for instruction [" + segment
+ "]. Take a look at http://www.aqute.biz/Code/Bnd."
);
}
}
}
}
catch( UnsupportedEncodingException e )
{
// thrown by URLDecoder but it should never happen
throwAsMalformedURLException( "Could not retrieve the instructions from [" + query + "]", e );
}
}
return instructions;
} | [
"public",
"static",
"Properties",
"parseInstructions",
"(",
"final",
"String",
"query",
")",
"throws",
"MalformedURLException",
"{",
"final",
"Properties",
"instructions",
"=",
"new",
"Properties",
"(",
")",
";",
"if",
"(",
"query",
"!=",
"null",
")",
"{",
"tr... | Parses bnd instructions out of an url query string.
@param query query part of an url.
@return parsed instructions as properties
@throws java.net.MalformedURLException if provided path does not comply to syntax. | [
"Parses",
"bnd",
"instructions",
"out",
"of",
"an",
"url",
"query",
"string",
"."
] | 00b0ee16cdbe8017984a4d7ba808b10d985c5b5c | https://github.com/ops4j/org.ops4j.pax.swissbox/blob/00b0ee16cdbe8017984a4d7ba808b10d985c5b5c/pax-swissbox-bnd/src/main/java/org/ops4j/pax/swissbox/bnd/BndUtils.java#L275-L316 | train |
ops4j/org.ops4j.pax.swissbox | pax-swissbox-bnd/src/main/java/org/ops4j/pax/swissbox/bnd/BndUtils.java | BndUtils.throwAsMalformedURLException | private static void throwAsMalformedURLException( final String message, final Exception cause )
throws MalformedURLException
{
final MalformedURLException exception = new MalformedURLException( message );
exception.initCause( cause );
throw exception;
} | java | private static void throwAsMalformedURLException( final String message, final Exception cause )
throws MalformedURLException
{
final MalformedURLException exception = new MalformedURLException( message );
exception.initCause( cause );
throw exception;
} | [
"private",
"static",
"void",
"throwAsMalformedURLException",
"(",
"final",
"String",
"message",
",",
"final",
"Exception",
"cause",
")",
"throws",
"MalformedURLException",
"{",
"final",
"MalformedURLException",
"exception",
"=",
"new",
"MalformedURLException",
"(",
"mes... | Creates an MalformedURLException with a message and a cause.
@param message exception message
@param cause exception cause
@throws MalformedURLException the created MalformedURLException | [
"Creates",
"an",
"MalformedURLException",
"with",
"a",
"message",
"and",
"a",
"cause",
"."
] | 00b0ee16cdbe8017984a4d7ba808b10d985c5b5c | https://github.com/ops4j/org.ops4j.pax.swissbox/blob/00b0ee16cdbe8017984a4d7ba808b10d985c5b5c/pax-swissbox-bnd/src/main/java/org/ops4j/pax/swissbox/bnd/BndUtils.java#L350-L356 | train |
petergeneric/stdlib | guice/hibernate/src/main/java/com/peterphi/std/guice/hibernate/module/HibernateModule.java | HibernateModule.validateHibernateProperties | private void validateHibernateProperties(final GuiceConfig configuration, final Properties hibernateProperties)
{
final boolean allowCreateSchema = configuration.getBoolean(GuiceProperties.HIBERNATE_ALLOW_HBM2DDL_CREATE, false);
if (!allowCreateSchema)
{
// Check that hbm2ddl is not set to a prohibited value, throwing an exception if it is
final String hbm2ddl = hibernateProperties.getProperty("hibernate.hbm2ddl.auto");
if (hbm2ddl != null && (hbm2ddl.equalsIgnoreCase("create") || hbm2ddl.equalsIgnoreCase("create-drop")))
{
throw new IllegalArgumentException("Value '" +
hbm2ddl +
"' is not permitted for hibernate property 'hibernate.hbm2ddl.auto' under the current configuration, consider using 'update' instead. If you must use the value 'create' then set configuration parameter '" +
GuiceProperties.HIBERNATE_ALLOW_HBM2DDL_CREATE +
"' to 'true'");
}
}
} | java | private void validateHibernateProperties(final GuiceConfig configuration, final Properties hibernateProperties)
{
final boolean allowCreateSchema = configuration.getBoolean(GuiceProperties.HIBERNATE_ALLOW_HBM2DDL_CREATE, false);
if (!allowCreateSchema)
{
// Check that hbm2ddl is not set to a prohibited value, throwing an exception if it is
final String hbm2ddl = hibernateProperties.getProperty("hibernate.hbm2ddl.auto");
if (hbm2ddl != null && (hbm2ddl.equalsIgnoreCase("create") || hbm2ddl.equalsIgnoreCase("create-drop")))
{
throw new IllegalArgumentException("Value '" +
hbm2ddl +
"' is not permitted for hibernate property 'hibernate.hbm2ddl.auto' under the current configuration, consider using 'update' instead. If you must use the value 'create' then set configuration parameter '" +
GuiceProperties.HIBERNATE_ALLOW_HBM2DDL_CREATE +
"' to 'true'");
}
}
} | [
"private",
"void",
"validateHibernateProperties",
"(",
"final",
"GuiceConfig",
"configuration",
",",
"final",
"Properties",
"hibernateProperties",
")",
"{",
"final",
"boolean",
"allowCreateSchema",
"=",
"configuration",
".",
"getBoolean",
"(",
"GuiceProperties",
".",
"H... | Checks whether hbm2ddl is set to a prohibited value, throwing an exception if it is
@param configuration
the global app config
@param hibernateProperties
the hibernate-specific config
@throws IllegalArgumentException
if the hibernate.hbm2ddl.auto property is set to a prohibited value | [
"Checks",
"whether",
"hbm2ddl",
"is",
"set",
"to",
"a",
"prohibited",
"value",
"throwing",
"an",
"exception",
"if",
"it",
"is"
] | d4025d2f881bc0542b1e004c5f65a1ccaf895836 | https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/guice/hibernate/src/main/java/com/peterphi/std/guice/hibernate/module/HibernateModule.java#L171-L189 | train |
ziccardi/jnrpe | jnrpe-lib/src/main/java/it/jnrpe/utils/thresholds/ReturnValueBuilder.java | ReturnValueBuilder.forPlugin | public static ReturnValueBuilder forPlugin(final String name, final ThresholdsEvaluator thr) {
if (thr != null) {
return new ReturnValueBuilder(name, thr);
}
return new ReturnValueBuilder(name, new ThresholdsEvaluatorBuilder().create());
} | java | public static ReturnValueBuilder forPlugin(final String name, final ThresholdsEvaluator thr) {
if (thr != null) {
return new ReturnValueBuilder(name, thr);
}
return new ReturnValueBuilder(name, new ThresholdsEvaluatorBuilder().create());
} | [
"public",
"static",
"ReturnValueBuilder",
"forPlugin",
"(",
"final",
"String",
"name",
",",
"final",
"ThresholdsEvaluator",
"thr",
")",
"{",
"if",
"(",
"thr",
"!=",
"null",
")",
"{",
"return",
"new",
"ReturnValueBuilder",
"(",
"name",
",",
"thr",
")",
";",
... | Constructs the object with the given threshold evaluator.
@param name
The name of the plugin that is creating this result
@param thr
The threshold evaluator.
@return the newly created instance. | [
"Constructs",
"the",
"object",
"with",
"the",
"given",
"threshold",
"evaluator",
"."
] | ac9046355851136994388442b01ba4063305f9c4 | https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-lib/src/main/java/it/jnrpe/utils/thresholds/ReturnValueBuilder.java#L97-L102 | train |
ziccardi/jnrpe | jnrpe-lib/src/main/java/it/jnrpe/utils/thresholds/ReturnValueBuilder.java | ReturnValueBuilder.formatResultMessage | private void formatResultMessage(final Metric pluginMetric) {
if (StringUtils.isEmpty(pluginMetric.getMessage())) {
return;
}
if (StringUtils.isEmpty(retValMessage)) {
retValMessage = pluginMetric.getMessage();
return;
}
retValMessage += " " + pluginMetric.getMessage();
} | java | private void formatResultMessage(final Metric pluginMetric) {
if (StringUtils.isEmpty(pluginMetric.getMessage())) {
return;
}
if (StringUtils.isEmpty(retValMessage)) {
retValMessage = pluginMetric.getMessage();
return;
}
retValMessage += " " + pluginMetric.getMessage();
} | [
"private",
"void",
"formatResultMessage",
"(",
"final",
"Metric",
"pluginMetric",
")",
"{",
"if",
"(",
"StringUtils",
".",
"isEmpty",
"(",
"pluginMetric",
".",
"getMessage",
"(",
")",
")",
")",
"{",
"return",
";",
"}",
"if",
"(",
"StringUtils",
".",
"isEmp... | Formats the message to return to Nagios according to the specifications
contained inside the pluginMetric object.
@param pluginMetric
The metric. | [
"Formats",
"the",
"message",
"to",
"return",
"to",
"Nagios",
"according",
"to",
"the",
"specifications",
"contained",
"inside",
"the",
"pluginMetric",
"object",
"."
] | ac9046355851136994388442b01ba4063305f9c4 | https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-lib/src/main/java/it/jnrpe/utils/thresholds/ReturnValueBuilder.java#L135-L145 | train |
petergeneric/stdlib | stdlib/src/main/java/com/peterphi/std/net/IpHelper.java | IpHelper.getLocalhost | public static String getLocalhost() throws RuntimeException
{
String hostname = null;
try
{
InetAddress addr = InetAddress.getLocalHost();
hostname = addr.getHostName();
}
catch (UnknownHostException e)
{
throw new RuntimeException("[FileHelper] {getLocalhost}: Can't get local hostname");
}
return hostname;
} | java | public static String getLocalhost() throws RuntimeException
{
String hostname = null;
try
{
InetAddress addr = InetAddress.getLocalHost();
hostname = addr.getHostName();
}
catch (UnknownHostException e)
{
throw new RuntimeException("[FileHelper] {getLocalhost}: Can't get local hostname");
}
return hostname;
} | [
"public",
"static",
"String",
"getLocalhost",
"(",
")",
"throws",
"RuntimeException",
"{",
"String",
"hostname",
"=",
"null",
";",
"try",
"{",
"InetAddress",
"addr",
"=",
"InetAddress",
".",
"getLocalHost",
"(",
")",
";",
"hostname",
"=",
"addr",
".",
"getHo... | Gets the hostname of localhost
@return String
@throws RuntimeException
When we cannot determine the local machine's hostname | [
"Gets",
"the",
"hostname",
"of",
"localhost"
] | d4025d2f881bc0542b1e004c5f65a1ccaf895836 | https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/stdlib/src/main/java/com/peterphi/std/net/IpHelper.java#L62-L78 | train |
petergeneric/stdlib | stdlib/src/main/java/com/peterphi/std/net/IpHelper.java | IpHelper.getLocalIp | public static String getLocalIp() throws RuntimeException
{
try
{
InetAddress addr = getLocalIpAddress();
return addr.getHostAddress();
}
catch (RuntimeException e)
{
throw new RuntimeException("[FileHelper] {getLocalIp}: Unable to find the local machine", e);
}
} | java | public static String getLocalIp() throws RuntimeException
{
try
{
InetAddress addr = getLocalIpAddress();
return addr.getHostAddress();
}
catch (RuntimeException e)
{
throw new RuntimeException("[FileHelper] {getLocalIp}: Unable to find the local machine", e);
}
} | [
"public",
"static",
"String",
"getLocalIp",
"(",
")",
"throws",
"RuntimeException",
"{",
"try",
"{",
"InetAddress",
"addr",
"=",
"getLocalIpAddress",
"(",
")",
";",
"return",
"addr",
".",
"getHostAddress",
"(",
")",
";",
"}",
"catch",
"(",
"RuntimeException",
... | Gets the local IP address
@return String the local ip address's HostAddress
@throws RuntimeException
On error (eg. when the local host cannot be determined) | [
"Gets",
"the",
"local",
"IP",
"address"
] | d4025d2f881bc0542b1e004c5f65a1ccaf895836 | https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/stdlib/src/main/java/com/peterphi/std/net/IpHelper.java#L89-L101 | train |
petergeneric/stdlib | stdlib/src/main/java/com/peterphi/std/net/IpHelper.java | IpHelper.getLocalIpAddress | public static InetAddress getLocalIpAddress() throws RuntimeException
{
try
{
List<InetAddress> ips = getLocalIpAddresses(false, true);
for (InetAddress ip : ips)
{
log.debug("[IpHelper] {getLocalIpAddress} Considering locality of " + ip.getHostAddress());
if (!ip.isAnyLocalAddress() && (ip instanceof Inet4Address))
{
// Ubuntu sets the unix hostname to resolve to 127.0.1.1; this is annoying so treat it as a loopback
if (!ip.getHostAddress().startsWith("127.0."))
{
log.debug("[IpHelper] {getLocalIpAddress} Found nonloopback IP: " + ip.getHostAddress());
return ip;
}
}
}
log.trace("[IpHelper] {getLocalIpAddress} Couldn't find a public IP in the ip (size " + ips.size() + ")");
return InetAddress.getLocalHost();
}
catch (UnknownHostException e)
{
throw new RuntimeException("[FileHelper] {getLocalIp}: Unable to acquire the current machine's InetAddress", e);
}
} | java | public static InetAddress getLocalIpAddress() throws RuntimeException
{
try
{
List<InetAddress> ips = getLocalIpAddresses(false, true);
for (InetAddress ip : ips)
{
log.debug("[IpHelper] {getLocalIpAddress} Considering locality of " + ip.getHostAddress());
if (!ip.isAnyLocalAddress() && (ip instanceof Inet4Address))
{
// Ubuntu sets the unix hostname to resolve to 127.0.1.1; this is annoying so treat it as a loopback
if (!ip.getHostAddress().startsWith("127.0."))
{
log.debug("[IpHelper] {getLocalIpAddress} Found nonloopback IP: " + ip.getHostAddress());
return ip;
}
}
}
log.trace("[IpHelper] {getLocalIpAddress} Couldn't find a public IP in the ip (size " + ips.size() + ")");
return InetAddress.getLocalHost();
}
catch (UnknownHostException e)
{
throw new RuntimeException("[FileHelper] {getLocalIp}: Unable to acquire the current machine's InetAddress", e);
}
} | [
"public",
"static",
"InetAddress",
"getLocalIpAddress",
"(",
")",
"throws",
"RuntimeException",
"{",
"try",
"{",
"List",
"<",
"InetAddress",
">",
"ips",
"=",
"getLocalIpAddresses",
"(",
"false",
",",
"true",
")",
";",
"for",
"(",
"InetAddress",
"ip",
":",
"i... | Returns the primary InetAddress of localhost
@return InetAddress The InetAddress of the local host
@throws RuntimeException
On any error
@since 1.0 | [
"Returns",
"the",
"primary",
"InetAddress",
"of",
"localhost"
] | d4025d2f881bc0542b1e004c5f65a1ccaf895836 | https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/stdlib/src/main/java/com/peterphi/std/net/IpHelper.java#L113-L140 | train |
petergeneric/stdlib | stdlib/src/main/java/com/peterphi/std/net/IpHelper.java | IpHelper.getLocalIpAddress | public static InetAddress getLocalIpAddress(String iface) throws RuntimeException
{
try
{
NetworkInterface nic = NetworkInterface.getByName(iface);
Enumeration<InetAddress> ips = nic.getInetAddresses();
InetAddress firstIP = null;
while (ips != null && ips.hasMoreElements())
{
InetAddress ip = ips.nextElement();
if (firstIP == null)
firstIP = ip;
if (log.isDebugEnabled())
log.debug("[IpHelper] {getLocalIpAddress} Considering locality: " + ip.getHostAddress());
if (!ip.isAnyLocalAddress())
{
return ip;
}
}
// Return the first IP (or null if no IPs were returned)
return firstIP;
}
catch (SocketException e)
{
throw new RuntimeException("[IpHelper] {getLocalIpAddress}: Unable to acquire an IP", e);
}
} | java | public static InetAddress getLocalIpAddress(String iface) throws RuntimeException
{
try
{
NetworkInterface nic = NetworkInterface.getByName(iface);
Enumeration<InetAddress> ips = nic.getInetAddresses();
InetAddress firstIP = null;
while (ips != null && ips.hasMoreElements())
{
InetAddress ip = ips.nextElement();
if (firstIP == null)
firstIP = ip;
if (log.isDebugEnabled())
log.debug("[IpHelper] {getLocalIpAddress} Considering locality: " + ip.getHostAddress());
if (!ip.isAnyLocalAddress())
{
return ip;
}
}
// Return the first IP (or null if no IPs were returned)
return firstIP;
}
catch (SocketException e)
{
throw new RuntimeException("[IpHelper] {getLocalIpAddress}: Unable to acquire an IP", e);
}
} | [
"public",
"static",
"InetAddress",
"getLocalIpAddress",
"(",
"String",
"iface",
")",
"throws",
"RuntimeException",
"{",
"try",
"{",
"NetworkInterface",
"nic",
"=",
"NetworkInterface",
".",
"getByName",
"(",
"iface",
")",
";",
"Enumeration",
"<",
"InetAddress",
">"... | Returns the IP address associated with iface
@param iface
The interface name
@return InetAddress The InetAddress of the interface (or null if none found)
@throws RuntimeException
On any error
@since 1.0 | [
"Returns",
"the",
"IP",
"address",
"associated",
"with",
"iface"
] | d4025d2f881bc0542b1e004c5f65a1ccaf895836 | https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/stdlib/src/main/java/com/peterphi/std/net/IpHelper.java#L155-L186 | train |
petergeneric/stdlib | stdlib/src/main/java/com/peterphi/std/net/IpHelper.java | IpHelper.getLocalIpAddresses | public static List<InetAddress> getLocalIpAddresses(boolean pruneSiteLocal, boolean pruneDown) throws RuntimeException
{
try
{
Enumeration<NetworkInterface> nics = NetworkInterface.getNetworkInterfaces();
List<InetAddress> addresses = new Vector<InetAddress>();
while (nics.hasMoreElements())
{
NetworkInterface iface = nics.nextElement();
Enumeration<InetAddress> addrs = iface.getInetAddresses();
if (!pruneDown || iface.isUp())
{
while (addrs.hasMoreElements())
{
InetAddress addr = addrs.nextElement();
if (!addr.isLoopbackAddress() && !addr.isLinkLocalAddress())
{
if (!pruneSiteLocal || (pruneSiteLocal && !addr.isSiteLocalAddress()))
{
addresses.add(addr);
}
}
}
}
}
return addresses;
}
catch (SocketException e)
{
throw new RuntimeException(e.getMessage(), e);
}
} | java | public static List<InetAddress> getLocalIpAddresses(boolean pruneSiteLocal, boolean pruneDown) throws RuntimeException
{
try
{
Enumeration<NetworkInterface> nics = NetworkInterface.getNetworkInterfaces();
List<InetAddress> addresses = new Vector<InetAddress>();
while (nics.hasMoreElements())
{
NetworkInterface iface = nics.nextElement();
Enumeration<InetAddress> addrs = iface.getInetAddresses();
if (!pruneDown || iface.isUp())
{
while (addrs.hasMoreElements())
{
InetAddress addr = addrs.nextElement();
if (!addr.isLoopbackAddress() && !addr.isLinkLocalAddress())
{
if (!pruneSiteLocal || (pruneSiteLocal && !addr.isSiteLocalAddress()))
{
addresses.add(addr);
}
}
}
}
}
return addresses;
}
catch (SocketException e)
{
throw new RuntimeException(e.getMessage(), e);
}
} | [
"public",
"static",
"List",
"<",
"InetAddress",
">",
"getLocalIpAddresses",
"(",
"boolean",
"pruneSiteLocal",
",",
"boolean",
"pruneDown",
")",
"throws",
"RuntimeException",
"{",
"try",
"{",
"Enumeration",
"<",
"NetworkInterface",
">",
"nics",
"=",
"NetworkInterface... | Returns a list of local InetAddresses for this machine
@param pruneSiteLocal
boolean Set to true if site local (10/8, for example) addresses should be pruned
@param pruneDown
boolean Set to true to prune out interfaces whose .isUp() return false
@return List[InetAddress] The list of addresses
@throws RuntimeException
If there is an error retrieving the InetAddresses
@since IpHelper.java 2007-11-22 | [
"Returns",
"a",
"list",
"of",
"local",
"InetAddresses",
"for",
"this",
"machine"
] | d4025d2f881bc0542b1e004c5f65a1ccaf895836 | https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/stdlib/src/main/java/com/peterphi/std/net/IpHelper.java#L236-L271 | train |
petergeneric/stdlib | stdlib/src/main/java/com/peterphi/std/net/IpHelper.java | IpHelper.getMacFor | public static String getMacFor(NetworkInterface iface) throws SocketException, NoMacAddressException
{
assert (iface != null);
byte[] hwaddr = iface.getHardwareAddress();
if (hwaddr == null || hwaddr.length == 0)
{
throw new NoMacAddressException("Interface " + iface.getName() + " has no physical address specified.");
}
else
{
return physicalAddressToString(hwaddr);
}
} | java | public static String getMacFor(NetworkInterface iface) throws SocketException, NoMacAddressException
{
assert (iface != null);
byte[] hwaddr = iface.getHardwareAddress();
if (hwaddr == null || hwaddr.length == 0)
{
throw new NoMacAddressException("Interface " + iface.getName() + " has no physical address specified.");
}
else
{
return physicalAddressToString(hwaddr);
}
} | [
"public",
"static",
"String",
"getMacFor",
"(",
"NetworkInterface",
"iface",
")",
"throws",
"SocketException",
",",
"NoMacAddressException",
"{",
"assert",
"(",
"iface",
"!=",
"null",
")",
";",
"byte",
"[",
"]",
"hwaddr",
"=",
"iface",
".",
"getHardwareAddress",... | Given a network interface, determines its mac address
@param iface
the interface
@return The MAC address formatted in lower-case colon-delimited hexidecimal bytes (aa:ab:ac)
@throws SocketException
@throws NoMacAddressException
If the interface doesn't have a mac address | [
"Given",
"a",
"network",
"interface",
"determines",
"its",
"mac",
"address"
] | d4025d2f881bc0542b1e004c5f65a1ccaf895836 | https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/stdlib/src/main/java/com/peterphi/std/net/IpHelper.java#L305-L319 | train |
petergeneric/stdlib | stdlib/src/main/java/com/peterphi/std/net/IpHelper.java | IpHelper.getInterfaceForLocalIp | public static NetworkInterface getInterfaceForLocalIp(InetAddress addr) throws SocketException, NoInterfaceException
{
assert (getLocalIpAddresses(false).contains(addr)) : "IP is not local";
NetworkInterface iface = NetworkInterface.getByInetAddress(addr);
if (iface != null)
return iface;
else
throw new NoInterfaceException("No network interface for IP: " + addr.toString());
} | java | public static NetworkInterface getInterfaceForLocalIp(InetAddress addr) throws SocketException, NoInterfaceException
{
assert (getLocalIpAddresses(false).contains(addr)) : "IP is not local";
NetworkInterface iface = NetworkInterface.getByInetAddress(addr);
if (iface != null)
return iface;
else
throw new NoInterfaceException("No network interface for IP: " + addr.toString());
} | [
"public",
"static",
"NetworkInterface",
"getInterfaceForLocalIp",
"(",
"InetAddress",
"addr",
")",
"throws",
"SocketException",
",",
"NoInterfaceException",
"{",
"assert",
"(",
"getLocalIpAddresses",
"(",
"false",
")",
".",
"contains",
"(",
"addr",
")",
")",
":",
... | Given a local IP address, returns the Interface it corresponds to
@param addr
The address
@return The interface, or null if no interface corresponds to that address
@throws SocketException
@throws NoInterfaceException
If there's no corresponding interface for the given IP | [
"Given",
"a",
"local",
"IP",
"address",
"returns",
"the",
"Interface",
"it",
"corresponds",
"to"
] | d4025d2f881bc0542b1e004c5f65a1ccaf895836 | https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/stdlib/src/main/java/com/peterphi/std/net/IpHelper.java#L334-L344 | train |
petergeneric/stdlib | stdlib/src/main/java/com/peterphi/std/net/IpHelper.java | IpHelper.ntoa | public static InetAddress ntoa(final int address)
{
try
{
final byte[] addr = new byte[4];
addr[0] = (byte) ((address >>> 24) & 0xFF);
addr[1] = (byte) ((address >>> 16) & 0xFF);
addr[2] = (byte) ((address >>> 8) & 0xFF);
addr[3] = (byte) (address & 0xFF);
return InetAddress.getByAddress(addr);
}
catch (UnknownHostException e)
{
// will never be thrown
throw new Error(e);
}
} | java | public static InetAddress ntoa(final int address)
{
try
{
final byte[] addr = new byte[4];
addr[0] = (byte) ((address >>> 24) & 0xFF);
addr[1] = (byte) ((address >>> 16) & 0xFF);
addr[2] = (byte) ((address >>> 8) & 0xFF);
addr[3] = (byte) (address & 0xFF);
return InetAddress.getByAddress(addr);
}
catch (UnknownHostException e)
{
// will never be thrown
throw new Error(e);
}
} | [
"public",
"static",
"InetAddress",
"ntoa",
"(",
"final",
"int",
"address",
")",
"{",
"try",
"{",
"final",
"byte",
"[",
"]",
"addr",
"=",
"new",
"byte",
"[",
"4",
"]",
";",
"addr",
"[",
"0",
"]",
"=",
"(",
"byte",
")",
"(",
"(",
"address",
">>>",
... | Converts numeric address to an InetAddress
@param address
@return | [
"Converts",
"numeric",
"address",
"to",
"an",
"InetAddress"
] | d4025d2f881bc0542b1e004c5f65a1ccaf895836 | https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/stdlib/src/main/java/com/peterphi/std/net/IpHelper.java#L796-L814 | train |
petergeneric/stdlib | stdlib/src/main/java/com/peterphi/std/net/IpHelper.java | IpHelper.isPubliclyRoutable | public static boolean isPubliclyRoutable(final InetAddress addrIP)
{
if (addrIP == null)
throw new NullPointerException("isPubliclyRoutable requires an IP address be passed to it!");
return !addrIP.isSiteLocalAddress() && !addrIP.isLinkLocalAddress() && !addrIP.isLoopbackAddress();
} | java | public static boolean isPubliclyRoutable(final InetAddress addrIP)
{
if (addrIP == null)
throw new NullPointerException("isPubliclyRoutable requires an IP address be passed to it!");
return !addrIP.isSiteLocalAddress() && !addrIP.isLinkLocalAddress() && !addrIP.isLoopbackAddress();
} | [
"public",
"static",
"boolean",
"isPubliclyRoutable",
"(",
"final",
"InetAddress",
"addrIP",
")",
"{",
"if",
"(",
"addrIP",
"==",
"null",
")",
"throw",
"new",
"NullPointerException",
"(",
"\"isPubliclyRoutable requires an IP address be passed to it!\"",
")",
";",
"return... | Determines whether a particular IP address is publicly routable on the internet
@param addrIP
@return | [
"Determines",
"whether",
"a",
"particular",
"IP",
"address",
"is",
"publicly",
"routable",
"on",
"the",
"internet"
] | d4025d2f881bc0542b1e004c5f65a1ccaf895836 | https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/stdlib/src/main/java/com/peterphi/std/net/IpHelper.java#L865-L870 | train |
petergeneric/stdlib | guice/hibernate/src/main/java/com/peterphi/std/guice/hibernate/webquery/ResultSetConstraintBuilder.java | ResultSetConstraintBuilder.buildQuery | public WebQuery buildQuery()
{
Map<String, List<String>> map = new HashMap<>(constraints);
applyDefault(WQUriControlField.FETCH, map, defaultFetch);
applyDefault(WQUriControlField.EXPAND, map, defaultExpand);
applyDefault(WQUriControlField.ORDER, map, defaultOrder);
applyDefault(WQUriControlField.OFFSET, map, "0");
applyDefault(WQUriControlField.LIMIT, map, Integer.toString(defaultLimit));
return new WebQuery().decode(map);
} | java | public WebQuery buildQuery()
{
Map<String, List<String>> map = new HashMap<>(constraints);
applyDefault(WQUriControlField.FETCH, map, defaultFetch);
applyDefault(WQUriControlField.EXPAND, map, defaultExpand);
applyDefault(WQUriControlField.ORDER, map, defaultOrder);
applyDefault(WQUriControlField.OFFSET, map, "0");
applyDefault(WQUriControlField.LIMIT, map, Integer.toString(defaultLimit));
return new WebQuery().decode(map);
} | [
"public",
"WebQuery",
"buildQuery",
"(",
")",
"{",
"Map",
"<",
"String",
",",
"List",
"<",
"String",
">",
">",
"map",
"=",
"new",
"HashMap",
"<>",
"(",
"constraints",
")",
";",
"applyDefault",
"(",
"WQUriControlField",
".",
"FETCH",
",",
"map",
",",
"d... | Construct a WebQueryDefinition from this, applying the web query semantics
@return | [
"Construct",
"a",
"WebQueryDefinition",
"from",
"this",
"applying",
"the",
"web",
"query",
"semantics"
] | d4025d2f881bc0542b1e004c5f65a1ccaf895836 | https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/guice/hibernate/src/main/java/com/peterphi/std/guice/hibernate/webquery/ResultSetConstraintBuilder.java#L200-L211 | train |
ziccardi/jnrpe | jnrpe-server/src/main/java/it/jnrpe/server/plugins/DynaPluginRepository.java | DynaPluginRepository.configurePlugins | private void configurePlugins(final File fDir) throws PluginConfigurationException {
LOG.trace("READING PLUGIN CONFIGURATION FROM DIRECTORY {}", fDir.getName());
StreamManager streamMgr = new StreamManager();
File[] vfJars = fDir.listFiles(JAR_FILE_FILTER);
if (vfJars == null || vfJars.length == 0) {
return;
}
// Initializing classloader
List<URL> vUrls = new ArrayList<URL>(vfJars.length);
ClassLoader ul = null;
for (int j = 0; j < vfJars.length; j++) {
try {
vUrls.add(vfJars[j].toURI().toURL());
} catch (MalformedURLException e) {
// should never happen
throw new IllegalStateException(e.getMessage(), e);
}
}
ul = new JNRPEClassLoader(vUrls);
try {
for (File file : vfJars) {
JarFile jarFile = null;
try {
jarFile = new JarFile(file);
JarEntry entry = jarFile.getJarEntry("plugin.xml");
if (entry == null) {
entry = jarFile.getJarEntry("jnrpe_plugins.xml");
}
if (entry == null) {
// The jar do not contain a jnrpe_plugins.xml nor a
// plugin.xml file...
continue;
}
InputStream in = streamMgr.handle(jarFile.getInputStream(entry));
PluginRepositoryUtil.loadFromXmlPluginPackageDefinitions(this, ul, in);
in.close();
} catch (Exception e) {
LOG.error("Skipping plugin package contained in file '{}' because of the following error : {}",
new String[] { file.getName(), e.getMessage() }, e);
} finally {
try {
jarFile.close();
} catch (Exception e) {
// Intentionally ignored...
LOG.warn("An error has occurred closing jar file '{}'",file.getName(), e);
}
}
}
} finally {
streamMgr.closeAll();
}
} | java | private void configurePlugins(final File fDir) throws PluginConfigurationException {
LOG.trace("READING PLUGIN CONFIGURATION FROM DIRECTORY {}", fDir.getName());
StreamManager streamMgr = new StreamManager();
File[] vfJars = fDir.listFiles(JAR_FILE_FILTER);
if (vfJars == null || vfJars.length == 0) {
return;
}
// Initializing classloader
List<URL> vUrls = new ArrayList<URL>(vfJars.length);
ClassLoader ul = null;
for (int j = 0; j < vfJars.length; j++) {
try {
vUrls.add(vfJars[j].toURI().toURL());
} catch (MalformedURLException e) {
// should never happen
throw new IllegalStateException(e.getMessage(), e);
}
}
ul = new JNRPEClassLoader(vUrls);
try {
for (File file : vfJars) {
JarFile jarFile = null;
try {
jarFile = new JarFile(file);
JarEntry entry = jarFile.getJarEntry("plugin.xml");
if (entry == null) {
entry = jarFile.getJarEntry("jnrpe_plugins.xml");
}
if (entry == null) {
// The jar do not contain a jnrpe_plugins.xml nor a
// plugin.xml file...
continue;
}
InputStream in = streamMgr.handle(jarFile.getInputStream(entry));
PluginRepositoryUtil.loadFromXmlPluginPackageDefinitions(this, ul, in);
in.close();
} catch (Exception e) {
LOG.error("Skipping plugin package contained in file '{}' because of the following error : {}",
new String[] { file.getName(), e.getMessage() }, e);
} finally {
try {
jarFile.close();
} catch (Exception e) {
// Intentionally ignored...
LOG.warn("An error has occurred closing jar file '{}'",file.getName(), e);
}
}
}
} finally {
streamMgr.closeAll();
}
} | [
"private",
"void",
"configurePlugins",
"(",
"final",
"File",
"fDir",
")",
"throws",
"PluginConfigurationException",
"{",
"LOG",
".",
"trace",
"(",
"\"READING PLUGIN CONFIGURATION FROM DIRECTORY {}\"",
",",
"fDir",
".",
"getName",
"(",
")",
")",
";",
"StreamManager",
... | Loads all the plugins definitions from the given directory.
@param fDir
The plugin package directory.
@throws PluginConfigurationException
- | [
"Loads",
"all",
"the",
"plugins",
"definitions",
"from",
"the",
"given",
"directory",
"."
] | ac9046355851136994388442b01ba4063305f9c4 | https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-server/src/main/java/it/jnrpe/server/plugins/DynaPluginRepository.java#L83-L145 | train |
ziccardi/jnrpe | jnrpe-server/src/main/java/it/jnrpe/server/plugins/DynaPluginRepository.java | DynaPluginRepository.load | public final void load(final File fDirectory) throws PluginConfigurationException {
File[] vFiles = fDirectory.listFiles();
if (vFiles != null) {
for (File f : vFiles) {
if (f.isDirectory()) {
configurePlugins(f);
}
}
}
} | java | public final void load(final File fDirectory) throws PluginConfigurationException {
File[] vFiles = fDirectory.listFiles();
if (vFiles != null) {
for (File f : vFiles) {
if (f.isDirectory()) {
configurePlugins(f);
}
}
}
} | [
"public",
"final",
"void",
"load",
"(",
"final",
"File",
"fDirectory",
")",
"throws",
"PluginConfigurationException",
"{",
"File",
"[",
"]",
"vFiles",
"=",
"fDirectory",
".",
"listFiles",
"(",
")",
";",
"if",
"(",
"vFiles",
"!=",
"null",
")",
"{",
"for",
... | Loops through all the directories present inside the JNRPE plugin
directory.
@param fDirectory
The JNRPE plugins directory
@throws PluginConfigurationException
- | [
"Loops",
"through",
"all",
"the",
"directories",
"present",
"inside",
"the",
"JNRPE",
"plugin",
"directory",
"."
] | ac9046355851136994388442b01ba4063305f9c4 | https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-server/src/main/java/it/jnrpe/server/plugins/DynaPluginRepository.java#L156-L165 | train |
ziccardi/jnrpe | jnrpe-plugins/src/main/java/it/jnrpe/plugin/utils/SshUtils.java | SshUtils.getSession | public static Session getSession(final ICommandLine cl) throws Exception {
JSch jsch = new JSch();
Session session = null;
int timeout = DEFAULT_TIMEOUT;
int port = cl.hasOption("port") ? Integer.parseInt(cl.getOptionValue("port")) : +DEFAULT_PORT;
String hostname = cl.getOptionValue("hostname");
String username = cl.getOptionValue("username");
String password = cl.getOptionValue("password");
String key = cl.getOptionValue("key");
if (cl.hasOption("timeout")) {
try {
timeout = Integer.parseInt(cl.getOptionValue("timeout"));
} catch (NumberFormatException e) {
throw new MetricGatheringException("Invalid numeric value for timeout.", Status.CRITICAL, e);
}
}
session = jsch.getSession(username, hostname, port);
if (key == null) {
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword(password);
} else {
jsch.addIdentity(key);
}
session.connect(timeout * 1000);
return session;
} | java | public static Session getSession(final ICommandLine cl) throws Exception {
JSch jsch = new JSch();
Session session = null;
int timeout = DEFAULT_TIMEOUT;
int port = cl.hasOption("port") ? Integer.parseInt(cl.getOptionValue("port")) : +DEFAULT_PORT;
String hostname = cl.getOptionValue("hostname");
String username = cl.getOptionValue("username");
String password = cl.getOptionValue("password");
String key = cl.getOptionValue("key");
if (cl.hasOption("timeout")) {
try {
timeout = Integer.parseInt(cl.getOptionValue("timeout"));
} catch (NumberFormatException e) {
throw new MetricGatheringException("Invalid numeric value for timeout.", Status.CRITICAL, e);
}
}
session = jsch.getSession(username, hostname, port);
if (key == null) {
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword(password);
} else {
jsch.addIdentity(key);
}
session.connect(timeout * 1000);
return session;
} | [
"public",
"static",
"Session",
"getSession",
"(",
"final",
"ICommandLine",
"cl",
")",
"throws",
"Exception",
"{",
"JSch",
"jsch",
"=",
"new",
"JSch",
"(",
")",
";",
"Session",
"session",
"=",
"null",
";",
"int",
"timeout",
"=",
"DEFAULT_TIMEOUT",
";",
"int... | Starts an ssh session
@param cl the command line object
@return an ssh session
@throws Exception on any error | [
"Starts",
"an",
"ssh",
"session"
] | ac9046355851136994388442b01ba4063305f9c4 | https://github.com/ziccardi/jnrpe/blob/ac9046355851136994388442b01ba4063305f9c4/jnrpe-plugins/src/main/java/it/jnrpe/plugin/utils/SshUtils.java#L51-L76 | train |
petergeneric/stdlib | stdlib/src/main/java/com/peterphi/std/threading/Deadline.java | Deadline.getTimeoutLeft | public Timeout getTimeoutLeft()
{
final long left = getTimeLeft();
if (left != 0)
return new Timeout(left, TimeUnit.MILLISECONDS);
else
return Timeout.ZERO;
} | java | public Timeout getTimeoutLeft()
{
final long left = getTimeLeft();
if (left != 0)
return new Timeout(left, TimeUnit.MILLISECONDS);
else
return Timeout.ZERO;
} | [
"public",
"Timeout",
"getTimeoutLeft",
"(",
")",
"{",
"final",
"long",
"left",
"=",
"getTimeLeft",
"(",
")",
";",
"if",
"(",
"left",
"!=",
"0",
")",
"return",
"new",
"Timeout",
"(",
"left",
",",
"TimeUnit",
".",
"MILLISECONDS",
")",
";",
"else",
"retur... | Determines the amount of time leftuntil the deadline and returns it as a timeout
@return a timeout representing the amount of time remaining until this deadline expires | [
"Determines",
"the",
"amount",
"of",
"time",
"leftuntil",
"the",
"deadline",
"and",
"returns",
"it",
"as",
"a",
"timeout"
] | d4025d2f881bc0542b1e004c5f65a1ccaf895836 | https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/stdlib/src/main/java/com/peterphi/std/threading/Deadline.java#L120-L128 | train |
petergeneric/stdlib | stdlib/src/main/java/com/peterphi/std/threading/Deadline.java | Deadline.soonest | public static Deadline soonest(Deadline... deadlines)
{
Deadline min = null;
if (deadlines != null)
for (Deadline deadline : deadlines)
{
if (deadline != null)
{
if (min == null)
min = deadline;
else if (deadline.getTimeLeft() < min.getTimeLeft())
{
min = deadline;
}
}
}
return min;
} | java | public static Deadline soonest(Deadline... deadlines)
{
Deadline min = null;
if (deadlines != null)
for (Deadline deadline : deadlines)
{
if (deadline != null)
{
if (min == null)
min = deadline;
else if (deadline.getTimeLeft() < min.getTimeLeft())
{
min = deadline;
}
}
}
return min;
} | [
"public",
"static",
"Deadline",
"soonest",
"(",
"Deadline",
"...",
"deadlines",
")",
"{",
"Deadline",
"min",
"=",
"null",
";",
"if",
"(",
"deadlines",
"!=",
"null",
")",
"for",
"(",
"Deadline",
"deadline",
":",
"deadlines",
")",
"{",
"if",
"(",
"deadline... | Retrieve the deadline with the least time remaining until it expires
@param deadlines
@return | [
"Retrieve",
"the",
"deadline",
"with",
"the",
"least",
"time",
"remaining",
"until",
"it",
"expires"
] | d4025d2f881bc0542b1e004c5f65a1ccaf895836 | https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/stdlib/src/main/java/com/peterphi/std/threading/Deadline.java#L380-L399 | train |
petergeneric/stdlib | guice/webapp/src/main/java/com/peterphi/std/guice/web/rest/jaxrs/exception/RestFailureMarshaller.java | RestFailureMarshaller.renderFailure | public RestFailure renderFailure(Throwable e)
{
// Strip away ApplicationException wrappers
if (e.getCause() != null && (e instanceof ApplicationException))
{
return renderFailure(e.getCause());
}
RestFailure failure = new RestFailure();
failure.id = getOrGenerateFailureId();
failure.date = new Date();
if (e instanceof RestException)
{
RestException re = (RestException) e;
failure.httpCode = re.getHttpCode();
failure.exception = renderThrowable(e);
}
else
{
failure.httpCode = 500; // by default
failure.exception = renderThrowable(e);
}
return failure;
} | java | public RestFailure renderFailure(Throwable e)
{
// Strip away ApplicationException wrappers
if (e.getCause() != null && (e instanceof ApplicationException))
{
return renderFailure(e.getCause());
}
RestFailure failure = new RestFailure();
failure.id = getOrGenerateFailureId();
failure.date = new Date();
if (e instanceof RestException)
{
RestException re = (RestException) e;
failure.httpCode = re.getHttpCode();
failure.exception = renderThrowable(e);
}
else
{
failure.httpCode = 500; // by default
failure.exception = renderThrowable(e);
}
return failure;
} | [
"public",
"RestFailure",
"renderFailure",
"(",
"Throwable",
"e",
")",
"{",
"// Strip away ApplicationException wrappers",
"if",
"(",
"e",
".",
"getCause",
"(",
")",
"!=",
"null",
"&&",
"(",
"e",
"instanceof",
"ApplicationException",
")",
")",
"{",
"return",
"ren... | Render a Throwable as a RestFailure
@param e
@return | [
"Render",
"a",
"Throwable",
"as",
"a",
"RestFailure"
] | d4025d2f881bc0542b1e004c5f65a1ccaf895836 | https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/guice/webapp/src/main/java/com/peterphi/std/guice/web/rest/jaxrs/exception/RestFailureMarshaller.java#L43-L67 | train |
petergeneric/stdlib | guice/hibernate/src/main/java/com/peterphi/std/guice/hibernate/module/TransactionHelper.java | TransactionHelper.start | public HibernateTransaction start()
{
final Session session = sessionProvider.get();
final Transaction tx = session.beginTransaction();
return new HibernateTransaction(tx);
} | java | public HibernateTransaction start()
{
final Session session = sessionProvider.get();
final Transaction tx = session.beginTransaction();
return new HibernateTransaction(tx);
} | [
"public",
"HibernateTransaction",
"start",
"(",
")",
"{",
"final",
"Session",
"session",
"=",
"sessionProvider",
".",
"get",
"(",
")",
";",
"final",
"Transaction",
"tx",
"=",
"session",
".",
"beginTransaction",
"(",
")",
";",
"return",
"new",
"HibernateTransac... | Starts a new Hibernate transaction. Note that the caller accepts responsibility for closing the transaction
@return | [
"Starts",
"a",
"new",
"Hibernate",
"transaction",
".",
"Note",
"that",
"the",
"caller",
"accepts",
"responsibility",
"for",
"closing",
"the",
"transaction"
] | d4025d2f881bc0542b1e004c5f65a1ccaf895836 | https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/guice/hibernate/src/main/java/com/peterphi/std/guice/hibernate/module/TransactionHelper.java#L50-L56 | train |
petergeneric/stdlib | guice/hibernate/src/main/java/com/peterphi/std/guice/hibernate/module/TransactionHelper.java | TransactionHelper.execute | public void execute(Runnable statements)
{
try (HibernateTransaction tx = start().withAutoRollback())
{
statements.run();
// Success, perform a TX commit
tx.commit();
}
} | java | public void execute(Runnable statements)
{
try (HibernateTransaction tx = start().withAutoRollback())
{
statements.run();
// Success, perform a TX commit
tx.commit();
}
} | [
"public",
"void",
"execute",
"(",
"Runnable",
"statements",
")",
"{",
"try",
"(",
"HibernateTransaction",
"tx",
"=",
"start",
"(",
")",
".",
"withAutoRollback",
"(",
")",
")",
"{",
"statements",
".",
"run",
"(",
")",
";",
"// Success, perform a TX commit",
"... | Execute the provided Runnable within a transaction, committing if no exceptions are thrown
@param statements | [
"Execute",
"the",
"provided",
"Runnable",
"within",
"a",
"transaction",
"committing",
"if",
"no",
"exceptions",
"are",
"thrown"
] | d4025d2f881bc0542b1e004c5f65a1ccaf895836 | https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/guice/hibernate/src/main/java/com/peterphi/std/guice/hibernate/module/TransactionHelper.java#L89-L98 | train |
petergeneric/stdlib | guice/hibernate/src/main/java/com/peterphi/std/guice/hibernate/module/TransactionHelper.java | TransactionHelper.addCommitAction | public void addCommitAction(final Runnable action) throws HibernateException
{
if (action == null)
return; // ignore null actions
addAction(new BaseSessionEventListener()
{
@Override
public void transactionCompletion(final boolean successful)
{
if (successful)
action.run();
}
});
} | java | public void addCommitAction(final Runnable action) throws HibernateException
{
if (action == null)
return; // ignore null actions
addAction(new BaseSessionEventListener()
{
@Override
public void transactionCompletion(final boolean successful)
{
if (successful)
action.run();
}
});
} | [
"public",
"void",
"addCommitAction",
"(",
"final",
"Runnable",
"action",
")",
"throws",
"HibernateException",
"{",
"if",
"(",
"action",
"==",
"null",
")",
"return",
";",
"// ignore null actions",
"addAction",
"(",
"new",
"BaseSessionEventListener",
"(",
")",
"{",
... | Register an action to run on the successful commit of the transaction
@param action
@throws HibernateException | [
"Register",
"an",
"action",
"to",
"run",
"on",
"the",
"successful",
"commit",
"of",
"the",
"transaction"
] | d4025d2f881bc0542b1e004c5f65a1ccaf895836 | https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/guice/hibernate/src/main/java/com/peterphi/std/guice/hibernate/module/TransactionHelper.java#L119-L133 | train |
petergeneric/stdlib | guice/hibernate/src/main/java/com/peterphi/std/guice/hibernate/module/TransactionHelper.java | TransactionHelper.deleteOnRollback | public void deleteOnRollback(final Collection<File> files)
{
addRollbackAction(new Runnable()
{
@Override
public void run()
{
for (File file : files)
{
if (log.isTraceEnabled())
log.trace("Delete file on transaction rollback: " + file);
final boolean success = FileUtils.deleteQuietly(file);
if (!success)
log.warn("Failed to delete file on transaction rollback: " + file);
}
}
});
} | java | public void deleteOnRollback(final Collection<File> files)
{
addRollbackAction(new Runnable()
{
@Override
public void run()
{
for (File file : files)
{
if (log.isTraceEnabled())
log.trace("Delete file on transaction rollback: " + file);
final boolean success = FileUtils.deleteQuietly(file);
if (!success)
log.warn("Failed to delete file on transaction rollback: " + file);
}
}
});
} | [
"public",
"void",
"deleteOnRollback",
"(",
"final",
"Collection",
"<",
"File",
">",
"files",
")",
"{",
"addRollbackAction",
"(",
"new",
"Runnable",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"run",
"(",
")",
"{",
"for",
"(",
"File",
"file",
":",
... | Adds an action to the transaction to delete a set of files once rollback completes
@param files | [
"Adds",
"an",
"action",
"to",
"the",
"transaction",
"to",
"delete",
"a",
"set",
"of",
"files",
"once",
"rollback",
"completes"
] | d4025d2f881bc0542b1e004c5f65a1ccaf895836 | https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/guice/hibernate/src/main/java/com/peterphi/std/guice/hibernate/module/TransactionHelper.java#L165-L184 | train |
petergeneric/stdlib | guice/hibernate/src/main/java/com/peterphi/std/guice/hibernate/webquery/impl/QEntity.java | QEntity.newInstanceWithId | public Object newInstanceWithId(final Object id)
{
try
{
final Object o = clazz.newInstance();
idProperty.set(o, id);
return o;
}
catch (Throwable e)
{
throw new RuntimeException("Cannot create new instance of " +
clazz +
" with ID " +
id +
" (of type " +
id.getClass() +
") populated!", e);
}
} | java | public Object newInstanceWithId(final Object id)
{
try
{
final Object o = clazz.newInstance();
idProperty.set(o, id);
return o;
}
catch (Throwable e)
{
throw new RuntimeException("Cannot create new instance of " +
clazz +
" with ID " +
id +
" (of type " +
id.getClass() +
") populated!", e);
}
} | [
"public",
"Object",
"newInstanceWithId",
"(",
"final",
"Object",
"id",
")",
"{",
"try",
"{",
"final",
"Object",
"o",
"=",
"clazz",
".",
"newInstance",
"(",
")",
";",
"idProperty",
".",
"set",
"(",
"o",
",",
"id",
")",
";",
"return",
"o",
";",
"}",
... | Create a new instance of this entity, setting only the ID field
@param id
@return | [
"Create",
"a",
"new",
"instance",
"of",
"this",
"entity",
"setting",
"only",
"the",
"ID",
"field"
] | d4025d2f881bc0542b1e004c5f65a1ccaf895836 | https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/guice/hibernate/src/main/java/com/peterphi/std/guice/hibernate/webquery/impl/QEntity.java#L517-L537 | train |
petergeneric/stdlib | guice/hibernate/src/main/java/com/peterphi/std/guice/hibernate/webquery/impl/QEntity.java | QEntity.getDefaultGraph | public EntityGraph getDefaultGraph(final Session session)
{
if (this.defaultExpandGraph == null)
{
final EntityGraph<?> graph = session.createEntityGraph(clazz);
populateGraph(graph, getEagerFetch());
this.defaultExpandGraph = graph;
return graph;
}
else
{
return this.defaultExpandGraph;
}
} | java | public EntityGraph getDefaultGraph(final Session session)
{
if (this.defaultExpandGraph == null)
{
final EntityGraph<?> graph = session.createEntityGraph(clazz);
populateGraph(graph, getEagerFetch());
this.defaultExpandGraph = graph;
return graph;
}
else
{
return this.defaultExpandGraph;
}
} | [
"public",
"EntityGraph",
"getDefaultGraph",
"(",
"final",
"Session",
"session",
")",
"{",
"if",
"(",
"this",
".",
"defaultExpandGraph",
"==",
"null",
")",
"{",
"final",
"EntityGraph",
"<",
"?",
">",
"graph",
"=",
"session",
".",
"createEntityGraph",
"(",
"cl... | Build or return the default Entity Graph that represents defaultExpand
@param session
@return | [
"Build",
"or",
"return",
"the",
"default",
"Entity",
"Graph",
"that",
"represents",
"defaultExpand"
] | d4025d2f881bc0542b1e004c5f65a1ccaf895836 | https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/guice/hibernate/src/main/java/com/peterphi/std/guice/hibernate/webquery/impl/QEntity.java#L672-L688 | train |
petergeneric/stdlib | guice/hibernate/src/main/java/com/peterphi/std/guice/hibernate/webquery/impl/QEntity.java | QEntity.populateGraph | private void populateGraph(final EntityGraph<?> graph, final Set<String> fetches)
{
Map<String, Subgraph<?>> created = new HashMap<>();
for (String fetch : fetches)
{
final String[] parts = StringUtils.split(fetch, '.');
// Starts of null (meaning parent is the root graph), updated as we go through path segments to refer to the last path segment
Subgraph<?> parent = null;
// Iterate over the path segments, adding attributes subgraphs
for (int i = 0; i < parts.length; i++)
{
final String path = StringUtils.join(parts, '.', 0, i + 1);
final boolean isLeaf = (i == parts.length - 1);
final Subgraph<?> existing = created.get(path);
if (existing == null)
{
if (parent == null)
{
try
{
// Relation under root
graph.addAttributeNodes(parts[i]);
// Only set up a subgraph if this is not a leaf node
// This prevents us trying to add a Subgraph for a List of Embeddable
if (!isLeaf)
parent = graph.addSubgraph(parts[i]);
}
catch (IllegalArgumentException e)
{
throw new IllegalArgumentException("Error adding graph member " +
parts[i] +
" with isLeaf=" +
isLeaf +
" to root as part of " +
fetch, e);
}
}
else
{
try
{
// Relation under parent
parent.addAttributeNodes(parts[i]);
// Only set up a subgraph if this is not a leaf node
// This prevents us trying to add a Subgraph for a List of Embeddable
if (!isLeaf)
parent = parent.addSubgraph(parts[i]);
}
catch (IllegalArgumentException e)
{
throw new IllegalArgumentException("Error adding graph member " +
parts[i] +
" with isLeaf=" +
isLeaf +
" as part of " +
fetch +
" with parent.class=" +
parent.getClassType(), e);
}
}
if (!isLeaf)
created.put(path, parent);
}
else
{
// Already seen this graph node before
parent = existing;
}
}
}
} | java | private void populateGraph(final EntityGraph<?> graph, final Set<String> fetches)
{
Map<String, Subgraph<?>> created = new HashMap<>();
for (String fetch : fetches)
{
final String[] parts = StringUtils.split(fetch, '.');
// Starts of null (meaning parent is the root graph), updated as we go through path segments to refer to the last path segment
Subgraph<?> parent = null;
// Iterate over the path segments, adding attributes subgraphs
for (int i = 0; i < parts.length; i++)
{
final String path = StringUtils.join(parts, '.', 0, i + 1);
final boolean isLeaf = (i == parts.length - 1);
final Subgraph<?> existing = created.get(path);
if (existing == null)
{
if (parent == null)
{
try
{
// Relation under root
graph.addAttributeNodes(parts[i]);
// Only set up a subgraph if this is not a leaf node
// This prevents us trying to add a Subgraph for a List of Embeddable
if (!isLeaf)
parent = graph.addSubgraph(parts[i]);
}
catch (IllegalArgumentException e)
{
throw new IllegalArgumentException("Error adding graph member " +
parts[i] +
" with isLeaf=" +
isLeaf +
" to root as part of " +
fetch, e);
}
}
else
{
try
{
// Relation under parent
parent.addAttributeNodes(parts[i]);
// Only set up a subgraph if this is not a leaf node
// This prevents us trying to add a Subgraph for a List of Embeddable
if (!isLeaf)
parent = parent.addSubgraph(parts[i]);
}
catch (IllegalArgumentException e)
{
throw new IllegalArgumentException("Error adding graph member " +
parts[i] +
" with isLeaf=" +
isLeaf +
" as part of " +
fetch +
" with parent.class=" +
parent.getClassType(), e);
}
}
if (!isLeaf)
created.put(path, parent);
}
else
{
// Already seen this graph node before
parent = existing;
}
}
}
} | [
"private",
"void",
"populateGraph",
"(",
"final",
"EntityGraph",
"<",
"?",
">",
"graph",
",",
"final",
"Set",
"<",
"String",
">",
"fetches",
")",
"{",
"Map",
"<",
"String",
",",
"Subgraph",
"<",
"?",
">",
">",
"created",
"=",
"new",
"HashMap",
"<>",
... | Creates an EntityGraph representing the
@param graph
@param fetches | [
"Creates",
"an",
"EntityGraph",
"representing",
"the"
] | d4025d2f881bc0542b1e004c5f65a1ccaf895836 | https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/guice/hibernate/src/main/java/com/peterphi/std/guice/hibernate/webquery/impl/QEntity.java#L697-L775 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.