id
int32
0
165k
repo
stringlengths
7
58
path
stringlengths
12
218
func_name
stringlengths
3
140
original_string
stringlengths
73
34.1k
language
stringclasses
1 value
code
stringlengths
73
34.1k
code_tokens
sequence
docstring
stringlengths
3
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
105
339
900
khuxtable/seaglass
src/main/java/com/seaglasslookandfeel/painter/TitlePaneMaximizeButtonPainter.java
TitlePaneMaximizeButtonPainter.paintMaximizePressed
private void paintMaximizePressed(Graphics2D g, JComponent c, int width, int height) { maximizePainter.paintPressed(g, c, width, height); }
java
private void paintMaximizePressed(Graphics2D g, JComponent c, int width, int height) { maximizePainter.paintPressed(g, c, width, height); }
[ "private", "void", "paintMaximizePressed", "(", "Graphics2D", "g", ",", "JComponent", "c", ",", "int", "width", ",", "int", "height", ")", "{", "maximizePainter", ".", "paintPressed", "(", "g", ",", "c", ",", "width", ",", "height", ")", ";", "}" ]
Paint the foreground maximize button pressed state. @param g the Graphics2D context to paint with. @param c the component. @param width the width of the component. @param height the height of the component.
[ "Paint", "the", "foreground", "maximize", "button", "pressed", "state", "." ]
f25ecba622923d7b29b64cb7d6068dd8005989b3
https://github.com/khuxtable/seaglass/blob/f25ecba622923d7b29b64cb7d6068dd8005989b3/src/main/java/com/seaglasslookandfeel/painter/TitlePaneMaximizeButtonPainter.java#L197-L199
901
khuxtable/seaglass
src/main/java/com/seaglasslookandfeel/component/SeaGlassIcon.java
SeaGlassIcon.paintIcon
@SuppressWarnings("unchecked") @Override public void paintIcon(Component c, Graphics g, int x, int y) { SeaGlassPainter painter = (SeaGlassPainter) UIManager.get(prefix + "[Enabled]." + key); if (painter != null) { JComponent jc = (c instanceof JComponent) ? (JComponent) c : null; Graphics2D gfx = (Graphics2D) g; gfx.translate(x, y); painter.paint(gfx, jc, width, height); gfx.translate(-x, -y); } }
java
@SuppressWarnings("unchecked") @Override public void paintIcon(Component c, Graphics g, int x, int y) { SeaGlassPainter painter = (SeaGlassPainter) UIManager.get(prefix + "[Enabled]." + key); if (painter != null) { JComponent jc = (c instanceof JComponent) ? (JComponent) c : null; Graphics2D gfx = (Graphics2D) g; gfx.translate(x, y); painter.paint(gfx, jc, width, height); gfx.translate(-x, -y); } }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "@", "Override", "public", "void", "paintIcon", "(", "Component", "c", ",", "Graphics", "g", ",", "int", "x", ",", "int", "y", ")", "{", "SeaGlassPainter", "painter", "=", "(", "SeaGlassPainter", ")", "UIManager", ".", "get", "(", "prefix", "+", "\"[Enabled].\"", "+", "key", ")", ";", "if", "(", "painter", "!=", "null", ")", "{", "JComponent", "jc", "=", "(", "c", "instanceof", "JComponent", ")", "?", "(", "JComponent", ")", "c", ":", "null", ";", "Graphics2D", "gfx", "=", "(", "Graphics2D", ")", "g", ";", "gfx", ".", "translate", "(", "x", ",", "y", ")", ";", "painter", ".", "paint", "(", "gfx", ",", "jc", ",", "width", ",", "height", ")", ";", "gfx", ".", "translate", "(", "-", "x", ",", "-", "y", ")", ";", "}", "}" ]
Implements the standard Icon interface's paintIcon method as the standard synth stub passes null for the context and this will cause us to not paint any thing, so we override here so that we can paint the enabled state if no synth context is available @param c the component to paint. @param g the Graphics context to paint with. @param x the x coordinate of the upper-left corner of the icon. @param y the y coordinate of the upper-left corner of the icon.
[ "Implements", "the", "standard", "Icon", "interface", "s", "paintIcon", "method", "as", "the", "standard", "synth", "stub", "passes", "null", "for", "the", "context", "and", "this", "will", "cause", "us", "to", "not", "paint", "any", "thing", "so", "we", "override", "here", "so", "that", "we", "can", "paint", "the", "enabled", "state", "if", "no", "synth", "context", "is", "available" ]
f25ecba622923d7b29b64cb7d6068dd8005989b3
https://github.com/khuxtable/seaglass/blob/f25ecba622923d7b29b64cb7d6068dd8005989b3/src/main/java/com/seaglasslookandfeel/component/SeaGlassIcon.java#L186-L199
902
khuxtable/seaglass
src/main/java/com/seaglasslookandfeel/component/SeaGlassIcon.java
SeaGlassIcon.scale
private int scale(SynthContext context, int size) { if (context == null || context.getComponent() == null) { return size; } // The key "JComponent.sizeVariant" is used to match Apple's LAF String scaleKey = SeaGlassStyle.getSizeVariant(context.getComponent()); if (scaleKey != null) { if (SeaGlassStyle.LARGE_KEY.equals(scaleKey)) { size *= SeaGlassStyle.LARGE_SCALE; } else if (SeaGlassStyle.SMALL_KEY.equals(scaleKey)) { size *= SeaGlassStyle.SMALL_SCALE; } else if (SeaGlassStyle.MINI_KEY.equals(scaleKey)) { // mini is not quite as small for icons as full mini is // just too tiny size *= SeaGlassStyle.MINI_SCALE + 0.07; } } return size; }
java
private int scale(SynthContext context, int size) { if (context == null || context.getComponent() == null) { return size; } // The key "JComponent.sizeVariant" is used to match Apple's LAF String scaleKey = SeaGlassStyle.getSizeVariant(context.getComponent()); if (scaleKey != null) { if (SeaGlassStyle.LARGE_KEY.equals(scaleKey)) { size *= SeaGlassStyle.LARGE_SCALE; } else if (SeaGlassStyle.SMALL_KEY.equals(scaleKey)) { size *= SeaGlassStyle.SMALL_SCALE; } else if (SeaGlassStyle.MINI_KEY.equals(scaleKey)) { // mini is not quite as small for icons as full mini is // just too tiny size *= SeaGlassStyle.MINI_SCALE + 0.07; } } return size; }
[ "private", "int", "scale", "(", "SynthContext", "context", ",", "int", "size", ")", "{", "if", "(", "context", "==", "null", "||", "context", ".", "getComponent", "(", ")", "==", "null", ")", "{", "return", "size", ";", "}", "// The key \"JComponent.sizeVariant\" is used to match Apple's LAF", "String", "scaleKey", "=", "SeaGlassStyle", ".", "getSizeVariant", "(", "context", ".", "getComponent", "(", ")", ")", ";", "if", "(", "scaleKey", "!=", "null", ")", "{", "if", "(", "SeaGlassStyle", ".", "LARGE_KEY", ".", "equals", "(", "scaleKey", ")", ")", "{", "size", "*=", "SeaGlassStyle", ".", "LARGE_SCALE", ";", "}", "else", "if", "(", "SeaGlassStyle", ".", "SMALL_KEY", ".", "equals", "(", "scaleKey", ")", ")", "{", "size", "*=", "SeaGlassStyle", ".", "SMALL_SCALE", ";", "}", "else", "if", "(", "SeaGlassStyle", ".", "MINI_KEY", ".", "equals", "(", "scaleKey", ")", ")", "{", "// mini is not quite as small for icons as full mini is", "// just too tiny", "size", "*=", "SeaGlassStyle", ".", "MINI_SCALE", "+", "0.07", ";", "}", "}", "return", "size", ";", "}" ]
Scale a size based on the "JComponent.sizeVariant" client property of the component that is using this icon @param context The synthContext to get the component from @param size The size to scale @return The scaled size or original if "JComponent.sizeVariant" is not set
[ "Scale", "a", "size", "based", "on", "the", "JComponent", ".", "sizeVariant", "client", "property", "of", "the", "component", "that", "is", "using", "this", "icon" ]
f25ecba622923d7b29b64cb7d6068dd8005989b3
https://github.com/khuxtable/seaglass/blob/f25ecba622923d7b29b64cb7d6068dd8005989b3/src/main/java/com/seaglasslookandfeel/component/SeaGlassIcon.java#L279-L300
903
jhalterman/lyra
src/main/java/net/jodah/lyra/internal/util/Exceptions.java
Exceptions.isConnectionClosure
public static boolean isConnectionClosure(ShutdownSignalException e) { return e instanceof AlreadyClosedException ? e.getReference() instanceof Connection : e.isHardError(); }
java
public static boolean isConnectionClosure(ShutdownSignalException e) { return e instanceof AlreadyClosedException ? e.getReference() instanceof Connection : e.isHardError(); }
[ "public", "static", "boolean", "isConnectionClosure", "(", "ShutdownSignalException", "e", ")", "{", "return", "e", "instanceof", "AlreadyClosedException", "?", "e", ".", "getReference", "(", ")", "instanceof", "Connection", ":", "e", ".", "isHardError", "(", ")", ";", "}" ]
Reliably returns whether the shutdown signal represents a connection closure.
[ "Reliably", "returns", "whether", "the", "shutdown", "signal", "represents", "a", "connection", "closure", "." ]
ce347a69357fef1b34e92d92a4f9e68792d81255
https://github.com/jhalterman/lyra/blob/ce347a69357fef1b34e92d92a4f9e68792d81255/src/main/java/net/jodah/lyra/internal/util/Exceptions.java#L36-L39
904
jhalterman/lyra
src/main/java/net/jodah/lyra/internal/RecurringPolicy.java
RecurringPolicy.withMaxDuration
@SuppressWarnings("unchecked") public T withMaxDuration(Duration maxDuration) { Assert.notNull(maxDuration, "maxDuration"); this.maxDuration = maxDuration; return (T) this; }
java
@SuppressWarnings("unchecked") public T withMaxDuration(Duration maxDuration) { Assert.notNull(maxDuration, "maxDuration"); this.maxDuration = maxDuration; return (T) this; }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "T", "withMaxDuration", "(", "Duration", "maxDuration", ")", "{", "Assert", ".", "notNull", "(", "maxDuration", ",", "\"maxDuration\"", ")", ";", "this", ".", "maxDuration", "=", "maxDuration", ";", "return", "(", "T", ")", "this", ";", "}" ]
Sets the max duration to perform attempts for. @throws NullPointerException if {@code maxDuration} is null
[ "Sets", "the", "max", "duration", "to", "perform", "attempts", "for", "." ]
ce347a69357fef1b34e92d92a4f9e68792d81255
https://github.com/jhalterman/lyra/blob/ce347a69357fef1b34e92d92a4f9e68792d81255/src/main/java/net/jodah/lyra/internal/RecurringPolicy.java#L145-L150
905
jhalterman/lyra
src/main/java/net/jodah/lyra/internal/RetryableResource.java
RetryableResource.handleCommonMethods
boolean handleCommonMethods(Object delegate, Method method, Object[] args) throws Throwable { if ("abort".equals(method.getName()) || "close".equals(method.getName())) { try { Reflection.invoke(delegate, method, args); return true; } finally { closed = true; afterClosure(); interruptWaiters(); } } else if ("addShutdownListener".equals(method.getName()) && args[0] != null) shutdownListeners.add((ShutdownListener) args[0]); else if ("removeShutdownListener".equals(method.getName()) && args[0] != null) shutdownListeners.remove((ShutdownListener) args[0]); return false; }
java
boolean handleCommonMethods(Object delegate, Method method, Object[] args) throws Throwable { if ("abort".equals(method.getName()) || "close".equals(method.getName())) { try { Reflection.invoke(delegate, method, args); return true; } finally { closed = true; afterClosure(); interruptWaiters(); } } else if ("addShutdownListener".equals(method.getName()) && args[0] != null) shutdownListeners.add((ShutdownListener) args[0]); else if ("removeShutdownListener".equals(method.getName()) && args[0] != null) shutdownListeners.remove((ShutdownListener) args[0]); return false; }
[ "boolean", "handleCommonMethods", "(", "Object", "delegate", ",", "Method", "method", ",", "Object", "[", "]", "args", ")", "throws", "Throwable", "{", "if", "(", "\"abort\"", ".", "equals", "(", "method", ".", "getName", "(", ")", ")", "||", "\"close\"", ".", "equals", "(", "method", ".", "getName", "(", ")", ")", ")", "{", "try", "{", "Reflection", ".", "invoke", "(", "delegate", ",", "method", ",", "args", ")", ";", "return", "true", ";", "}", "finally", "{", "closed", "=", "true", ";", "afterClosure", "(", ")", ";", "interruptWaiters", "(", ")", ";", "}", "}", "else", "if", "(", "\"addShutdownListener\"", ".", "equals", "(", "method", ".", "getName", "(", ")", ")", "&&", "args", "[", "0", "]", "!=", "null", ")", "shutdownListeners", ".", "add", "(", "(", "ShutdownListener", ")", "args", "[", "0", "]", ")", ";", "else", "if", "(", "\"removeShutdownListener\"", ".", "equals", "(", "method", ".", "getName", "(", ")", ")", "&&", "args", "[", "0", "]", "!=", "null", ")", "shutdownListeners", ".", "remove", "(", "(", "ShutdownListener", ")", "args", "[", "0", "]", ")", ";", "return", "false", ";", "}" ]
Handles common method invocations.
[ "Handles", "common", "method", "invocations", "." ]
ce347a69357fef1b34e92d92a4f9e68792d81255
https://github.com/jhalterman/lyra/blob/ce347a69357fef1b34e92d92a4f9e68792d81255/src/main/java/net/jodah/lyra/internal/RetryableResource.java#L105-L120
906
jhalterman/lyra
src/main/java/net/jodah/lyra/internal/RecurringStats.java
RecurringStats.isPolicyExceeded
public boolean isPolicyExceeded() { boolean withinMaxRetries = maxAttempts == -1 || attemptCount < maxAttempts; boolean withinMaxDuration = maxDuration == -1 || System.nanoTime() - startTime < maxDuration; return !withinMaxRetries || !withinMaxDuration; }
java
public boolean isPolicyExceeded() { boolean withinMaxRetries = maxAttempts == -1 || attemptCount < maxAttempts; boolean withinMaxDuration = maxDuration == -1 || System.nanoTime() - startTime < maxDuration; return !withinMaxRetries || !withinMaxDuration; }
[ "public", "boolean", "isPolicyExceeded", "(", ")", "{", "boolean", "withinMaxRetries", "=", "maxAttempts", "==", "-", "1", "||", "attemptCount", "<", "maxAttempts", ";", "boolean", "withinMaxDuration", "=", "maxDuration", "==", "-", "1", "||", "System", ".", "nanoTime", "(", ")", "-", "startTime", "<", "maxDuration", ";", "return", "!", "withinMaxRetries", "||", "!", "withinMaxDuration", ";", "}" ]
Returns true if the max attempts or max duration for the recurring policy have been exceeded else false.
[ "Returns", "true", "if", "the", "max", "attempts", "or", "max", "duration", "for", "the", "recurring", "policy", "have", "been", "exceeded", "else", "false", "." ]
ce347a69357fef1b34e92d92a4f9e68792d81255
https://github.com/jhalterman/lyra/blob/ce347a69357fef1b34e92d92a4f9e68792d81255/src/main/java/net/jodah/lyra/internal/RecurringStats.java#L91-L95
907
jhalterman/lyra
src/main/java/net/jodah/lyra/internal/util/ArrayListMultiMap.java
ArrayListMultiMap.values
public Iterable<V> values() { return new Iterable<V>() { @Override public Iterator<V> iterator() { return new Iterator<V>() { final Iterator<List<V>> valuesIterator = map.values().iterator(); Iterator<V> current; { if (valuesIterator.hasNext()) current = valuesIterator.next().iterator(); } @Override public boolean hasNext() { return current != null && current.hasNext(); } @Override public V next() { V value = current.next(); while (!current.hasNext() && valuesIterator.hasNext()) current = valuesIterator.next().iterator(); return value; } @Override public void remove() { throw new UnsupportedOperationException(); } }; } }; }
java
public Iterable<V> values() { return new Iterable<V>() { @Override public Iterator<V> iterator() { return new Iterator<V>() { final Iterator<List<V>> valuesIterator = map.values().iterator(); Iterator<V> current; { if (valuesIterator.hasNext()) current = valuesIterator.next().iterator(); } @Override public boolean hasNext() { return current != null && current.hasNext(); } @Override public V next() { V value = current.next(); while (!current.hasNext() && valuesIterator.hasNext()) current = valuesIterator.next().iterator(); return value; } @Override public void remove() { throw new UnsupportedOperationException(); } }; } }; }
[ "public", "Iterable", "<", "V", ">", "values", "(", ")", "{", "return", "new", "Iterable", "<", "V", ">", "(", ")", "{", "@", "Override", "public", "Iterator", "<", "V", ">", "iterator", "(", ")", "{", "return", "new", "Iterator", "<", "V", ">", "(", ")", "{", "final", "Iterator", "<", "List", "<", "V", ">", ">", "valuesIterator", "=", "map", ".", "values", "(", ")", ".", "iterator", "(", ")", ";", "Iterator", "<", "V", ">", "current", ";", "{", "if", "(", "valuesIterator", ".", "hasNext", "(", ")", ")", "current", "=", "valuesIterator", ".", "next", "(", ")", ".", "iterator", "(", ")", ";", "}", "@", "Override", "public", "boolean", "hasNext", "(", ")", "{", "return", "current", "!=", "null", "&&", "current", ".", "hasNext", "(", ")", ";", "}", "@", "Override", "public", "V", "next", "(", ")", "{", "V", "value", "=", "current", ".", "next", "(", ")", ";", "while", "(", "!", "current", ".", "hasNext", "(", ")", "&&", "valuesIterator", ".", "hasNext", "(", ")", ")", "current", "=", "valuesIterator", ".", "next", "(", ")", ".", "iterator", "(", ")", ";", "return", "value", ";", "}", "@", "Override", "public", "void", "remove", "(", ")", "{", "throw", "new", "UnsupportedOperationException", "(", ")", ";", "}", "}", ";", "}", "}", ";", "}" ]
Returns an iterable over the multimap's values. Unsafe for concurrent modification.
[ "Returns", "an", "iterable", "over", "the", "multimap", "s", "values", ".", "Unsafe", "for", "concurrent", "modification", "." ]
ce347a69357fef1b34e92d92a4f9e68792d81255
https://github.com/jhalterman/lyra/blob/ce347a69357fef1b34e92d92a4f9e68792d81255/src/main/java/net/jodah/lyra/internal/util/ArrayListMultiMap.java#L81-L114
908
jhalterman/lyra
src/main/java/net/jodah/lyra/internal/ChannelHandler.java
ChannelHandler.recoverChannel
synchronized void recoverChannel(boolean viaConnectionRecovery) throws Exception { recoveryPending.set(false); if (circuit.isClosed()) return; if (recoveryStats == null) { recoveryConsumers = consumerDeclarations.isEmpty() ? null : new LinkedHashMap<String, ConsumerDeclaration>(consumerDeclarations); recoveryStats = new RecurringStats(config.getChannelRecoveryPolicy()); recoveryStats.incrementTime(); } else if (recoveryStats.isPolicyExceeded()) { recoveryFailed(lastShutdownSignal); if (!viaConnectionRecovery) return; } try { notifyRecoveryStarted(); delegate = callWithRetries(new Callable<Channel>() { @Override public Channel call() throws Exception { log.info("Recovering {}", ChannelHandler.this); previousMaxDeliveryTag = maxDeliveryTag; Channel channel = connectionHandler.createChannel(delegate.getChannelNumber()); migrateConfiguration(channel); log.info("Recovered {}", ChannelHandler.this); return channel; } }, config.getChannelRecoveryPolicy(), recoveryStats, config.getRecoverableExceptions(), true, false); notifyRecovery(); recoverConsumers(!viaConnectionRecovery); recoverySucceeded(); } catch (Exception e) { ShutdownSignalException sse = Exceptions.extractCause(e, ShutdownSignalException.class); if (sse != null) { if (Exceptions.isConnectionClosure(sse)) throw e; } else if (recoveryStats.isPolicyExceeded()) recoveryFailed(e); } }
java
synchronized void recoverChannel(boolean viaConnectionRecovery) throws Exception { recoveryPending.set(false); if (circuit.isClosed()) return; if (recoveryStats == null) { recoveryConsumers = consumerDeclarations.isEmpty() ? null : new LinkedHashMap<String, ConsumerDeclaration>(consumerDeclarations); recoveryStats = new RecurringStats(config.getChannelRecoveryPolicy()); recoveryStats.incrementTime(); } else if (recoveryStats.isPolicyExceeded()) { recoveryFailed(lastShutdownSignal); if (!viaConnectionRecovery) return; } try { notifyRecoveryStarted(); delegate = callWithRetries(new Callable<Channel>() { @Override public Channel call() throws Exception { log.info("Recovering {}", ChannelHandler.this); previousMaxDeliveryTag = maxDeliveryTag; Channel channel = connectionHandler.createChannel(delegate.getChannelNumber()); migrateConfiguration(channel); log.info("Recovered {}", ChannelHandler.this); return channel; } }, config.getChannelRecoveryPolicy(), recoveryStats, config.getRecoverableExceptions(), true, false); notifyRecovery(); recoverConsumers(!viaConnectionRecovery); recoverySucceeded(); } catch (Exception e) { ShutdownSignalException sse = Exceptions.extractCause(e, ShutdownSignalException.class); if (sse != null) { if (Exceptions.isConnectionClosure(sse)) throw e; } else if (recoveryStats.isPolicyExceeded()) recoveryFailed(e); } }
[ "synchronized", "void", "recoverChannel", "(", "boolean", "viaConnectionRecovery", ")", "throws", "Exception", "{", "recoveryPending", ".", "set", "(", "false", ")", ";", "if", "(", "circuit", ".", "isClosed", "(", ")", ")", "return", ";", "if", "(", "recoveryStats", "==", "null", ")", "{", "recoveryConsumers", "=", "consumerDeclarations", ".", "isEmpty", "(", ")", "?", "null", ":", "new", "LinkedHashMap", "<", "String", ",", "ConsumerDeclaration", ">", "(", "consumerDeclarations", ")", ";", "recoveryStats", "=", "new", "RecurringStats", "(", "config", ".", "getChannelRecoveryPolicy", "(", ")", ")", ";", "recoveryStats", ".", "incrementTime", "(", ")", ";", "}", "else", "if", "(", "recoveryStats", ".", "isPolicyExceeded", "(", ")", ")", "{", "recoveryFailed", "(", "lastShutdownSignal", ")", ";", "if", "(", "!", "viaConnectionRecovery", ")", "return", ";", "}", "try", "{", "notifyRecoveryStarted", "(", ")", ";", "delegate", "=", "callWithRetries", "(", "new", "Callable", "<", "Channel", ">", "(", ")", "{", "@", "Override", "public", "Channel", "call", "(", ")", "throws", "Exception", "{", "log", ".", "info", "(", "\"Recovering {}\"", ",", "ChannelHandler", ".", "this", ")", ";", "previousMaxDeliveryTag", "=", "maxDeliveryTag", ";", "Channel", "channel", "=", "connectionHandler", ".", "createChannel", "(", "delegate", ".", "getChannelNumber", "(", ")", ")", ";", "migrateConfiguration", "(", "channel", ")", ";", "log", ".", "info", "(", "\"Recovered {}\"", ",", "ChannelHandler", ".", "this", ")", ";", "return", "channel", ";", "}", "}", ",", "config", ".", "getChannelRecoveryPolicy", "(", ")", ",", "recoveryStats", ",", "config", ".", "getRecoverableExceptions", "(", ")", ",", "true", ",", "false", ")", ";", "notifyRecovery", "(", ")", ";", "recoverConsumers", "(", "!", "viaConnectionRecovery", ")", ";", "recoverySucceeded", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "ShutdownSignalException", "sse", "=", "Exceptions", ".", "extractCause", "(", "e", ",", "ShutdownSignalException", ".", "class", ")", ";", "if", "(", "sse", "!=", "null", ")", "{", "if", "(", "Exceptions", ".", "isConnectionClosure", "(", "sse", ")", ")", "throw", "e", ";", "}", "else", "if", "(", "recoveryStats", ".", "isPolicyExceeded", "(", ")", ")", "recoveryFailed", "(", "e", ")", ";", "}", "}" ]
Atomically recovers the channel. @throws Exception when recovery fails due to a connection closure
[ "Atomically", "recovers", "the", "channel", "." ]
ce347a69357fef1b34e92d92a4f9e68792d81255
https://github.com/jhalterman/lyra/blob/ce347a69357fef1b34e92d92a4f9e68792d81255/src/main/java/net/jodah/lyra/internal/ChannelHandler.java#L199-L240
909
jhalterman/lyra
src/main/java/net/jodah/lyra/internal/ChannelHandler.java
ChannelHandler.recoverConsumers
private void recoverConsumers(boolean recoverReferences) throws Exception { if (config.isConsumerRecoveryEnabled() && !recoveryPending.get() && recoveryConsumers != null) { Set<QueueDeclaration> recoveredQueues = new HashSet<QueueDeclaration>(); Set<String> recoveredExchanges = new HashSet<String>(); for (Iterator<Map.Entry<String, ConsumerDeclaration>> it = recoveryConsumers.entrySet() .iterator(); it.hasNext();) { Map.Entry<String, ConsumerDeclaration> entry = it.next(); ConsumerDeclaration consumerDeclaration = entry.getValue(); Object[] args = consumerDeclaration.args; ConsumerDelegate consumer = (ConsumerDelegate) args[args.length - 1]; String queueName = consumerDeclaration.queueDeclaration != null ? consumerDeclaration.queueDeclaration.name : (String) args[0]; try { // Recover referenced exchanges, queues and bindings if (recoverReferences) { List<Binding> queueBindings = connectionHandler.queueBindings.get(queueName); recoverRelatedExchanges(recoveredExchanges, queueBindings); if (consumerDeclaration.queueDeclaration != null && recoveredQueues.add(consumerDeclaration.queueDeclaration)) queueName = recoverQueue(queueName, consumerDeclaration.queueDeclaration, queueBindings); } // Recover consumer log.info("".equals(queueName) ? "Recovering consumer-{}{} via {}" : "Recovering consumer-{} of {} via {}", entry.getKey(), queueName, this); notifyConsumerRecoveryStarted(consumer); consumer.open(); consumerDeclaration.invoke(delegate); log.info("".equals(queueName) ? "Recovered consumer-{}{} via {}" : "Recovered consumer-{} of {} via {}", entry.getKey(), queueName, this); notifyConsumerRecoveryCompleted(consumer); } catch (Exception e) { log.error("Failed to recover consumer-{} via {}", entry.getKey(), this, e); notifyConsumerRecoveryFailure(consumer, e); ShutdownSignalException sse = Exceptions.extractCause(e, ShutdownSignalException.class); if (sse != null) { if (!Exceptions.isConnectionClosure(sse)) it.remove(); throw e; } } } } }
java
private void recoverConsumers(boolean recoverReferences) throws Exception { if (config.isConsumerRecoveryEnabled() && !recoveryPending.get() && recoveryConsumers != null) { Set<QueueDeclaration> recoveredQueues = new HashSet<QueueDeclaration>(); Set<String> recoveredExchanges = new HashSet<String>(); for (Iterator<Map.Entry<String, ConsumerDeclaration>> it = recoveryConsumers.entrySet() .iterator(); it.hasNext();) { Map.Entry<String, ConsumerDeclaration> entry = it.next(); ConsumerDeclaration consumerDeclaration = entry.getValue(); Object[] args = consumerDeclaration.args; ConsumerDelegate consumer = (ConsumerDelegate) args[args.length - 1]; String queueName = consumerDeclaration.queueDeclaration != null ? consumerDeclaration.queueDeclaration.name : (String) args[0]; try { // Recover referenced exchanges, queues and bindings if (recoverReferences) { List<Binding> queueBindings = connectionHandler.queueBindings.get(queueName); recoverRelatedExchanges(recoveredExchanges, queueBindings); if (consumerDeclaration.queueDeclaration != null && recoveredQueues.add(consumerDeclaration.queueDeclaration)) queueName = recoverQueue(queueName, consumerDeclaration.queueDeclaration, queueBindings); } // Recover consumer log.info("".equals(queueName) ? "Recovering consumer-{}{} via {}" : "Recovering consumer-{} of {} via {}", entry.getKey(), queueName, this); notifyConsumerRecoveryStarted(consumer); consumer.open(); consumerDeclaration.invoke(delegate); log.info("".equals(queueName) ? "Recovered consumer-{}{} via {}" : "Recovered consumer-{} of {} via {}", entry.getKey(), queueName, this); notifyConsumerRecoveryCompleted(consumer); } catch (Exception e) { log.error("Failed to recover consumer-{} via {}", entry.getKey(), this, e); notifyConsumerRecoveryFailure(consumer, e); ShutdownSignalException sse = Exceptions.extractCause(e, ShutdownSignalException.class); if (sse != null) { if (!Exceptions.isConnectionClosure(sse)) it.remove(); throw e; } } } } }
[ "private", "void", "recoverConsumers", "(", "boolean", "recoverReferences", ")", "throws", "Exception", "{", "if", "(", "config", ".", "isConsumerRecoveryEnabled", "(", ")", "&&", "!", "recoveryPending", ".", "get", "(", ")", "&&", "recoveryConsumers", "!=", "null", ")", "{", "Set", "<", "QueueDeclaration", ">", "recoveredQueues", "=", "new", "HashSet", "<", "QueueDeclaration", ">", "(", ")", ";", "Set", "<", "String", ">", "recoveredExchanges", "=", "new", "HashSet", "<", "String", ">", "(", ")", ";", "for", "(", "Iterator", "<", "Map", ".", "Entry", "<", "String", ",", "ConsumerDeclaration", ">", ">", "it", "=", "recoveryConsumers", ".", "entrySet", "(", ")", ".", "iterator", "(", ")", ";", "it", ".", "hasNext", "(", ")", ";", ")", "{", "Map", ".", "Entry", "<", "String", ",", "ConsumerDeclaration", ">", "entry", "=", "it", ".", "next", "(", ")", ";", "ConsumerDeclaration", "consumerDeclaration", "=", "entry", ".", "getValue", "(", ")", ";", "Object", "[", "]", "args", "=", "consumerDeclaration", ".", "args", ";", "ConsumerDelegate", "consumer", "=", "(", "ConsumerDelegate", ")", "args", "[", "args", ".", "length", "-", "1", "]", ";", "String", "queueName", "=", "consumerDeclaration", ".", "queueDeclaration", "!=", "null", "?", "consumerDeclaration", ".", "queueDeclaration", ".", "name", ":", "(", "String", ")", "args", "[", "0", "]", ";", "try", "{", "// Recover referenced exchanges, queues and bindings", "if", "(", "recoverReferences", ")", "{", "List", "<", "Binding", ">", "queueBindings", "=", "connectionHandler", ".", "queueBindings", ".", "get", "(", "queueName", ")", ";", "recoverRelatedExchanges", "(", "recoveredExchanges", ",", "queueBindings", ")", ";", "if", "(", "consumerDeclaration", ".", "queueDeclaration", "!=", "null", "&&", "recoveredQueues", ".", "add", "(", "consumerDeclaration", ".", "queueDeclaration", ")", ")", "queueName", "=", "recoverQueue", "(", "queueName", ",", "consumerDeclaration", ".", "queueDeclaration", ",", "queueBindings", ")", ";", "}", "// Recover consumer", "log", ".", "info", "(", "\"\"", ".", "equals", "(", "queueName", ")", "?", "\"Recovering consumer-{}{} via {}\"", ":", "\"Recovering consumer-{} of {} via {}\"", ",", "entry", ".", "getKey", "(", ")", ",", "queueName", ",", "this", ")", ";", "notifyConsumerRecoveryStarted", "(", "consumer", ")", ";", "consumer", ".", "open", "(", ")", ";", "consumerDeclaration", ".", "invoke", "(", "delegate", ")", ";", "log", ".", "info", "(", "\"\"", ".", "equals", "(", "queueName", ")", "?", "\"Recovered consumer-{}{} via {}\"", ":", "\"Recovered consumer-{} of {} via {}\"", ",", "entry", ".", "getKey", "(", ")", ",", "queueName", ",", "this", ")", ";", "notifyConsumerRecoveryCompleted", "(", "consumer", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "log", ".", "error", "(", "\"Failed to recover consumer-{} via {}\"", ",", "entry", ".", "getKey", "(", ")", ",", "this", ",", "e", ")", ";", "notifyConsumerRecoveryFailure", "(", "consumer", ",", "e", ")", ";", "ShutdownSignalException", "sse", "=", "Exceptions", ".", "extractCause", "(", "e", ",", "ShutdownSignalException", ".", "class", ")", ";", "if", "(", "sse", "!=", "null", ")", "{", "if", "(", "!", "Exceptions", ".", "isConnectionClosure", "(", "sse", ")", ")", "it", ".", "remove", "(", ")", ";", "throw", "e", ";", "}", "}", "}", "}", "}" ]
Recovers the channel's consumers along with any exchanges, exchange bindings, queues and queue bindings that are referenced by the consumer. If a consumer recovery fails due to a channel closure, then we will not attempt to recover that consumer or its references again. @param recoverReferences whether consumer references should be recovered @throws Exception when recovery fails due to a resource closure
[ "Recovers", "the", "channel", "s", "consumers", "along", "with", "any", "exchanges", "exchange", "bindings", "queues", "and", "queue", "bindings", "that", "are", "referenced", "by", "the", "consumer", ".", "If", "a", "consumer", "recovery", "fails", "due", "to", "a", "channel", "closure", "then", "we", "will", "not", "attempt", "to", "recover", "that", "consumer", "or", "its", "references", "again", "." ]
ce347a69357fef1b34e92d92a4f9e68792d81255
https://github.com/jhalterman/lyra/blob/ce347a69357fef1b34e92d92a4f9e68792d81255/src/main/java/net/jodah/lyra/internal/ChannelHandler.java#L402-L448
910
jhalterman/lyra
src/main/java/net/jodah/lyra/ConnectionOptions.java
ConnectionOptions.getAddresses
public Address[] getAddresses() { if (addresses != null) return addresses; if (hosts != null) { addresses = new Address[hosts.length]; for (int i = 0; i < hosts.length; i++) addresses[i] = new Address(hosts[i], factory.getPort()); return addresses; } Address address = factory == null ? new Address("localhost", -1) : new Address( factory.getHost(), factory.getPort()); return new Address[] { address }; }
java
public Address[] getAddresses() { if (addresses != null) return addresses; if (hosts != null) { addresses = new Address[hosts.length]; for (int i = 0; i < hosts.length; i++) addresses[i] = new Address(hosts[i], factory.getPort()); return addresses; } Address address = factory == null ? new Address("localhost", -1) : new Address( factory.getHost(), factory.getPort()); return new Address[] { address }; }
[ "public", "Address", "[", "]", "getAddresses", "(", ")", "{", "if", "(", "addresses", "!=", "null", ")", "return", "addresses", ";", "if", "(", "hosts", "!=", "null", ")", "{", "addresses", "=", "new", "Address", "[", "hosts", ".", "length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "hosts", ".", "length", ";", "i", "++", ")", "addresses", "[", "i", "]", "=", "new", "Address", "(", "hosts", "[", "i", "]", ",", "factory", ".", "getPort", "(", ")", ")", ";", "return", "addresses", ";", "}", "Address", "address", "=", "factory", "==", "null", "?", "new", "Address", "(", "\"localhost\"", ",", "-", "1", ")", ":", "new", "Address", "(", "factory", ".", "getHost", "(", ")", ",", "factory", ".", "getPort", "(", ")", ")", ";", "return", "new", "Address", "[", "]", "{", "address", "}", ";", "}" ]
Returns the addresses to attempt connections to, in round-robin order. @see #withAddresses(Address...) @see #withAddresses(String) @see #withHost(String) @see #withHosts(String...)
[ "Returns", "the", "addresses", "to", "attempt", "connections", "to", "in", "round", "-", "robin", "order", "." ]
ce347a69357fef1b34e92d92a4f9e68792d81255
https://github.com/jhalterman/lyra/blob/ce347a69357fef1b34e92d92a4f9e68792d81255/src/main/java/net/jodah/lyra/ConnectionOptions.java#L110-L124
911
jhalterman/lyra
src/main/java/net/jodah/lyra/ConnectionOptions.java
ConnectionOptions.withClientProperties
public ConnectionOptions withClientProperties(Map<String, Object> clientProperties) { factory.setClientProperties(Assert.notNull(clientProperties, "clientProperties")); return this; }
java
public ConnectionOptions withClientProperties(Map<String, Object> clientProperties) { factory.setClientProperties(Assert.notNull(clientProperties, "clientProperties")); return this; }
[ "public", "ConnectionOptions", "withClientProperties", "(", "Map", "<", "String", ",", "Object", ">", "clientProperties", ")", "{", "factory", ".", "setClientProperties", "(", "Assert", ".", "notNull", "(", "clientProperties", ",", "\"clientProperties\"", ")", ")", ";", "return", "this", ";", "}" ]
Sets the client properties. @throws NullPointerException if {@code clientProperties} is null
[ "Sets", "the", "client", "properties", "." ]
ce347a69357fef1b34e92d92a4f9e68792d81255
https://github.com/jhalterman/lyra/blob/ce347a69357fef1b34e92d92a4f9e68792d81255/src/main/java/net/jodah/lyra/ConnectionOptions.java#L181-L184
912
jhalterman/lyra
src/main/java/net/jodah/lyra/ConnectionOptions.java
ConnectionOptions.withNioParams
public ConnectionOptions withNioParams(NioParams nioParams) { this.nioParams = nioParams; factory.setNioParams(Assert.notNull(nioParams, "nioParams")); factory.useNio(); return this; }
java
public ConnectionOptions withNioParams(NioParams nioParams) { this.nioParams = nioParams; factory.setNioParams(Assert.notNull(nioParams, "nioParams")); factory.useNio(); return this; }
[ "public", "ConnectionOptions", "withNioParams", "(", "NioParams", "nioParams", ")", "{", "this", ".", "nioParams", "=", "nioParams", ";", "factory", ".", "setNioParams", "(", "Assert", ".", "notNull", "(", "nioParams", ",", "\"nioParams\"", ")", ")", ";", "factory", ".", "useNio", "(", ")", ";", "return", "this", ";", "}" ]
Support for Java non-blocking IO @param nioParams The NIO mode can be configured through the NioParams class
[ "Support", "for", "Java", "non", "-", "blocking", "IO" ]
ce347a69357fef1b34e92d92a4f9e68792d81255
https://github.com/jhalterman/lyra/blob/ce347a69357fef1b34e92d92a4f9e68792d81255/src/main/java/net/jodah/lyra/ConnectionOptions.java#L389-L394
913
monitorjbl/json-view
json-view/src/main/java/com/monitorjbl/json/Match.java
Match.include
public Match include(String... fields) { if(fields != null) { includes.addAll(Arrays.asList(fields)); } return this; }
java
public Match include(String... fields) { if(fields != null) { includes.addAll(Arrays.asList(fields)); } return this; }
[ "public", "Match", "include", "(", "String", "...", "fields", ")", "{", "if", "(", "fields", "!=", "null", ")", "{", "includes", ".", "addAll", "(", "Arrays", ".", "asList", "(", "fields", ")", ")", ";", "}", "return", "this", ";", "}" ]
Mark fields for inclusion during serialization. @param fields The fields to include @return Match
[ "Mark", "fields", "for", "inclusion", "during", "serialization", "." ]
c01505ac76e5416abe8af85c5816f60bd5d483ea
https://github.com/monitorjbl/json-view/blob/c01505ac76e5416abe8af85c5816f60bd5d483ea/json-view/src/main/java/com/monitorjbl/json/Match.java#L25-L30
914
monitorjbl/json-view
json-view/src/main/java/com/monitorjbl/json/Match.java
Match.exclude
public Match exclude(String... fields) { if(fields != null) { excludes.addAll(Arrays.asList(fields)); } return this; }
java
public Match exclude(String... fields) { if(fields != null) { excludes.addAll(Arrays.asList(fields)); } return this; }
[ "public", "Match", "exclude", "(", "String", "...", "fields", ")", "{", "if", "(", "fields", "!=", "null", ")", "{", "excludes", ".", "addAll", "(", "Arrays", ".", "asList", "(", "fields", ")", ")", ";", "}", "return", "this", ";", "}" ]
Mark fields for exclusion during serialization. @param fields The fields to exclude @return Match
[ "Mark", "fields", "for", "exclusion", "during", "serialization", "." ]
c01505ac76e5416abe8af85c5816f60bd5d483ea
https://github.com/monitorjbl/json-view/blob/c01505ac76e5416abe8af85c5816f60bd5d483ea/json-view/src/main/java/com/monitorjbl/json/Match.java#L38-L43
915
monitorjbl/json-view
json-view/src/main/java/com/monitorjbl/json/Match.java
Match.transform
@SuppressWarnings("unchecked") public <X, Y, Z> Match transform(String field, BiFunction<X, Y, Z> transformer) { transforms.put(field, (BiFunction<Object, Object, Object>) transformer); return this; }
java
@SuppressWarnings("unchecked") public <X, Y, Z> Match transform(String field, BiFunction<X, Y, Z> transformer) { transforms.put(field, (BiFunction<Object, Object, Object>) transformer); return this; }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "<", "X", ",", "Y", ",", "Z", ">", "Match", "transform", "(", "String", "field", ",", "BiFunction", "<", "X", ",", "Y", ",", "Z", ">", "transformer", ")", "{", "transforms", ".", "put", "(", "field", ",", "(", "BiFunction", "<", "Object", ",", "Object", ",", "Object", ">", ")", "transformer", ")", ";", "return", "this", ";", "}" ]
Mark a field for transformation during serialization. @param field The fields to include @param transformer The function to transform the field. Will be provided with the whole object and the field. @param <X> The object being serialized @param <Y> The field being serialized @param <Z> The value of the field to serialize @return Match
[ "Mark", "a", "field", "for", "transformation", "during", "serialization", "." ]
c01505ac76e5416abe8af85c5816f60bd5d483ea
https://github.com/monitorjbl/json-view/blob/c01505ac76e5416abe8af85c5816f60bd5d483ea/json-view/src/main/java/com/monitorjbl/json/Match.java#L55-L59
916
pwittchen/swipe
library/src/main/java/com/github/pwittchen/swipe/library/rx2/Swipe.java
Swipe.dispatchTouchEvent
public boolean dispatchTouchEvent(final MotionEvent event) { checkNotNull(event, "event == null"); boolean isEventConsumed = false; switch (event.getAction()) { case MotionEvent.ACTION_DOWN: // user started touching the screen onActionDown(event); break; case MotionEvent.ACTION_UP: // user stopped touching the screen isEventConsumed = onActionUp(event); break; case MotionEvent.ACTION_MOVE: // user is moving finger on the screen onActionMove(event); break; default: break; } return isEventConsumed; }
java
public boolean dispatchTouchEvent(final MotionEvent event) { checkNotNull(event, "event == null"); boolean isEventConsumed = false; switch (event.getAction()) { case MotionEvent.ACTION_DOWN: // user started touching the screen onActionDown(event); break; case MotionEvent.ACTION_UP: // user stopped touching the screen isEventConsumed = onActionUp(event); break; case MotionEvent.ACTION_MOVE: // user is moving finger on the screen onActionMove(event); break; default: break; } return isEventConsumed; }
[ "public", "boolean", "dispatchTouchEvent", "(", "final", "MotionEvent", "event", ")", "{", "checkNotNull", "(", "event", ",", "\"event == null\"", ")", ";", "boolean", "isEventConsumed", "=", "false", ";", "switch", "(", "event", ".", "getAction", "(", ")", ")", "{", "case", "MotionEvent", ".", "ACTION_DOWN", ":", "// user started touching the screen", "onActionDown", "(", "event", ")", ";", "break", ";", "case", "MotionEvent", ".", "ACTION_UP", ":", "// user stopped touching the screen", "isEventConsumed", "=", "onActionUp", "(", "event", ")", ";", "break", ";", "case", "MotionEvent", ".", "ACTION_MOVE", ":", "// user is moving finger on the screen", "onActionMove", "(", "event", ")", ";", "break", ";", "default", ":", "break", ";", "}", "return", "isEventConsumed", ";", "}" ]
Called to process touch screen events. @param event MotionEvent
[ "Called", "to", "process", "touch", "screen", "events", "." ]
ce90b609815b8f30658c5b2ed628cc152c8cb186
https://github.com/pwittchen/swipe/blob/ce90b609815b8f30658c5b2ed628cc152c8cb186/library/src/main/java/com/github/pwittchen/swipe/library/rx2/Swipe.java#L88-L107
917
trustyuri/trustyuri-java
src/main/java/net/trustyuri/CheckFile.java
CheckFile.check
public boolean check() throws IOException, TrustyUriException { TrustyUriModule module = ModuleDirectory.getModule(r.getModuleId()); if (module == null) { throw new TrustyUriException("ERROR: Not a trusty URI or unknown module"); } return module.hasCorrectHash(r); }
java
public boolean check() throws IOException, TrustyUriException { TrustyUriModule module = ModuleDirectory.getModule(r.getModuleId()); if (module == null) { throw new TrustyUriException("ERROR: Not a trusty URI or unknown module"); } return module.hasCorrectHash(r); }
[ "public", "boolean", "check", "(", ")", "throws", "IOException", ",", "TrustyUriException", "{", "TrustyUriModule", "module", "=", "ModuleDirectory", ".", "getModule", "(", "r", ".", "getModuleId", "(", ")", ")", ";", "if", "(", "module", "==", "null", ")", "{", "throw", "new", "TrustyUriException", "(", "\"ERROR: Not a trusty URI or unknown module\"", ")", ";", "}", "return", "module", ".", "hasCorrectHash", "(", "r", ")", ";", "}" ]
Checks whether the content matches the hash of the trusty URI. @return true if the content matches the hash
[ "Checks", "whether", "the", "content", "matches", "the", "hash", "of", "the", "trusty", "URI", "." ]
84b2939d320186ae57c41ffcb756e4f74d263a55
https://github.com/trustyuri/trustyuri-java/blob/84b2939d320186ae57c41ffcb756e4f74d263a55/src/main/java/net/trustyuri/CheckFile.java#L76-L82
918
milosmns/circular-slider-android
slider/src/main/java/me/angrybyte/circularslider/CircularSlider.java
CircularSlider.init
private void init(Context context, AttributeSet attrs, int defStyleAttr) { TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CircularSlider, defStyleAttr, 0); // read all available attributes float startAngle = a.getFloat(R.styleable.CircularSlider_start_angle, (float) Math.PI / 2); float angle = a.getFloat(R.styleable.CircularSlider_angle, (float) Math.PI / 2); int thumbSize = a.getDimensionPixelSize(R.styleable.CircularSlider_thumb_size, 50); int thumbColor = a.getColor(R.styleable.CircularSlider_thumb_color, Color.GRAY); int borderThickness = a.getDimensionPixelSize(R.styleable.CircularSlider_border_thickness, 20); int borderColor = a.getColor(R.styleable.CircularSlider_border_color, Color.RED); String borderGradientColors = a.getString(R.styleable.CircularSlider_border_gradient_colors); Drawable thumbImage = a.getDrawable(R.styleable.CircularSlider_thumb_image); // save those to fields (really, do we need setters here..?) setStartAngle(startAngle); setAngle(angle); setBorderThickness(borderThickness); setBorderColor(borderColor); if (borderGradientColors != null) { setBorderGradientColors(borderGradientColors.split(";")); } setThumbSize(thumbSize); setThumbImage(thumbImage); setThumbColor(thumbColor); // assign padding - check for version because of RTL layout compatibility int padding; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { int all = getPaddingLeft() + getPaddingRight() + getPaddingBottom() + getPaddingTop() + getPaddingEnd() + getPaddingStart(); padding = all / 6; } else { padding = (getPaddingLeft() + getPaddingRight() + getPaddingBottom() + getPaddingTop()) / 4; } setPadding(padding); a.recycle(); }
java
private void init(Context context, AttributeSet attrs, int defStyleAttr) { TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CircularSlider, defStyleAttr, 0); // read all available attributes float startAngle = a.getFloat(R.styleable.CircularSlider_start_angle, (float) Math.PI / 2); float angle = a.getFloat(R.styleable.CircularSlider_angle, (float) Math.PI / 2); int thumbSize = a.getDimensionPixelSize(R.styleable.CircularSlider_thumb_size, 50); int thumbColor = a.getColor(R.styleable.CircularSlider_thumb_color, Color.GRAY); int borderThickness = a.getDimensionPixelSize(R.styleable.CircularSlider_border_thickness, 20); int borderColor = a.getColor(R.styleable.CircularSlider_border_color, Color.RED); String borderGradientColors = a.getString(R.styleable.CircularSlider_border_gradient_colors); Drawable thumbImage = a.getDrawable(R.styleable.CircularSlider_thumb_image); // save those to fields (really, do we need setters here..?) setStartAngle(startAngle); setAngle(angle); setBorderThickness(borderThickness); setBorderColor(borderColor); if (borderGradientColors != null) { setBorderGradientColors(borderGradientColors.split(";")); } setThumbSize(thumbSize); setThumbImage(thumbImage); setThumbColor(thumbColor); // assign padding - check for version because of RTL layout compatibility int padding; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { int all = getPaddingLeft() + getPaddingRight() + getPaddingBottom() + getPaddingTop() + getPaddingEnd() + getPaddingStart(); padding = all / 6; } else { padding = (getPaddingLeft() + getPaddingRight() + getPaddingBottom() + getPaddingTop()) / 4; } setPadding(padding); a.recycle(); }
[ "private", "void", "init", "(", "Context", "context", ",", "AttributeSet", "attrs", ",", "int", "defStyleAttr", ")", "{", "TypedArray", "a", "=", "context", ".", "obtainStyledAttributes", "(", "attrs", ",", "R", ".", "styleable", ".", "CircularSlider", ",", "defStyleAttr", ",", "0", ")", ";", "// read all available attributes", "float", "startAngle", "=", "a", ".", "getFloat", "(", "R", ".", "styleable", ".", "CircularSlider_start_angle", ",", "(", "float", ")", "Math", ".", "PI", "/", "2", ")", ";", "float", "angle", "=", "a", ".", "getFloat", "(", "R", ".", "styleable", ".", "CircularSlider_angle", ",", "(", "float", ")", "Math", ".", "PI", "/", "2", ")", ";", "int", "thumbSize", "=", "a", ".", "getDimensionPixelSize", "(", "R", ".", "styleable", ".", "CircularSlider_thumb_size", ",", "50", ")", ";", "int", "thumbColor", "=", "a", ".", "getColor", "(", "R", ".", "styleable", ".", "CircularSlider_thumb_color", ",", "Color", ".", "GRAY", ")", ";", "int", "borderThickness", "=", "a", ".", "getDimensionPixelSize", "(", "R", ".", "styleable", ".", "CircularSlider_border_thickness", ",", "20", ")", ";", "int", "borderColor", "=", "a", ".", "getColor", "(", "R", ".", "styleable", ".", "CircularSlider_border_color", ",", "Color", ".", "RED", ")", ";", "String", "borderGradientColors", "=", "a", ".", "getString", "(", "R", ".", "styleable", ".", "CircularSlider_border_gradient_colors", ")", ";", "Drawable", "thumbImage", "=", "a", ".", "getDrawable", "(", "R", ".", "styleable", ".", "CircularSlider_thumb_image", ")", ";", "// save those to fields (really, do we need setters here..?)", "setStartAngle", "(", "startAngle", ")", ";", "setAngle", "(", "angle", ")", ";", "setBorderThickness", "(", "borderThickness", ")", ";", "setBorderColor", "(", "borderColor", ")", ";", "if", "(", "borderGradientColors", "!=", "null", ")", "{", "setBorderGradientColors", "(", "borderGradientColors", ".", "split", "(", "\";\"", ")", ")", ";", "}", "setThumbSize", "(", "thumbSize", ")", ";", "setThumbImage", "(", "thumbImage", ")", ";", "setThumbColor", "(", "thumbColor", ")", ";", "// assign padding - check for version because of RTL layout compatibility", "int", "padding", ";", "if", "(", "Build", ".", "VERSION", ".", "SDK_INT", ">=", "Build", ".", "VERSION_CODES", ".", "JELLY_BEAN_MR1", ")", "{", "int", "all", "=", "getPaddingLeft", "(", ")", "+", "getPaddingRight", "(", ")", "+", "getPaddingBottom", "(", ")", "+", "getPaddingTop", "(", ")", "+", "getPaddingEnd", "(", ")", "+", "getPaddingStart", "(", ")", ";", "padding", "=", "all", "/", "6", ";", "}", "else", "{", "padding", "=", "(", "getPaddingLeft", "(", ")", "+", "getPaddingRight", "(", ")", "+", "getPaddingBottom", "(", ")", "+", "getPaddingTop", "(", ")", ")", "/", "4", ";", "}", "setPadding", "(", "padding", ")", ";", "a", ".", "recycle", "(", ")", ";", "}" ]
common initializer method
[ "common", "initializer", "method" ]
f255cac7fda0664a4f81ca1d4917938b53a76257
https://github.com/milosmns/circular-slider-android/blob/f255cac7fda0664a4f81ca1d4917938b53a76257/slider/src/main/java/me/angrybyte/circularslider/CircularSlider.java#L79-L115
919
milosmns/circular-slider-android
slider/src/main/java/me/angrybyte/circularslider/CircularSlider.java
CircularSlider.updateSliderState
private void updateSliderState(int touchX, int touchY) { int distanceX = touchX - mCircleCenterX; int distanceY = mCircleCenterY - touchY; //noinspection SuspiciousNameCombination double c = Math.sqrt(Math.pow(distanceX, 2) + Math.pow(distanceY, 2)); mAngle = Math.acos(distanceX / c); if (distanceY < 0) { mAngle = -mAngle; } if (mListener != null) { // notify slider moved listener of the new position which should be in [0..1] range mListener.onSliderMoved((mAngle - mStartAngle) / (2 * Math.PI)); } }
java
private void updateSliderState(int touchX, int touchY) { int distanceX = touchX - mCircleCenterX; int distanceY = mCircleCenterY - touchY; //noinspection SuspiciousNameCombination double c = Math.sqrt(Math.pow(distanceX, 2) + Math.pow(distanceY, 2)); mAngle = Math.acos(distanceX / c); if (distanceY < 0) { mAngle = -mAngle; } if (mListener != null) { // notify slider moved listener of the new position which should be in [0..1] range mListener.onSliderMoved((mAngle - mStartAngle) / (2 * Math.PI)); } }
[ "private", "void", "updateSliderState", "(", "int", "touchX", ",", "int", "touchY", ")", "{", "int", "distanceX", "=", "touchX", "-", "mCircleCenterX", ";", "int", "distanceY", "=", "mCircleCenterY", "-", "touchY", ";", "//noinspection SuspiciousNameCombination", "double", "c", "=", "Math", ".", "sqrt", "(", "Math", ".", "pow", "(", "distanceX", ",", "2", ")", "+", "Math", ".", "pow", "(", "distanceY", ",", "2", ")", ")", ";", "mAngle", "=", "Math", ".", "acos", "(", "distanceX", "/", "c", ")", ";", "if", "(", "distanceY", "<", "0", ")", "{", "mAngle", "=", "-", "mAngle", ";", "}", "if", "(", "mListener", "!=", "null", ")", "{", "// notify slider moved listener of the new position which should be in [0..1] range", "mListener", ".", "onSliderMoved", "(", "(", "mAngle", "-", "mStartAngle", ")", "/", "(", "2", "*", "Math", ".", "PI", ")", ")", ";", "}", "}" ]
Invoked when slider starts moving or is currently moving. This method calculates and sets position and angle of the thumb. @param touchX Where is the touch identifier now on X axis @param touchY Where is the touch identifier now on Y axis
[ "Invoked", "when", "slider", "starts", "moving", "or", "is", "currently", "moving", ".", "This", "method", "calculates", "and", "sets", "position", "and", "angle", "of", "the", "thumb", "." ]
f255cac7fda0664a4f81ca1d4917938b53a76257
https://github.com/milosmns/circular-slider-android/blob/f255cac7fda0664a4f81ca1d4917938b53a76257/slider/src/main/java/me/angrybyte/circularslider/CircularSlider.java#L228-L242
920
ReactiveX/RxGroovy
src/main/java/rx/lang/groovy/RxGroovyExtensionModule.java
RxGroovyExtensionModule.specialCasedOverrideForCreate
private MetaMethod specialCasedOverrideForCreate(final Method m) { return new MetaMethod() { @Override public int getModifiers() { return m.getModifiers(); } @Override public String getName() { return m.getName(); } @Override public Class<?> getReturnType() { return m.getReturnType(); } @Override public CachedClass getDeclaringClass() { return ReflectionCache.getCachedClass(m.getDeclaringClass()); } @Override @SuppressWarnings("unchecked") public Object invoke(Object object, final Object[] arguments) { return Observable.create(new GroovyCreateWrapper((Closure) arguments[0])); } @Override public CachedClass[] getParameterTypes() { if (parameterTypes == null) { getParametersTypes0(); } return parameterTypes; } private synchronized void getParametersTypes0() { if (parameterTypes != null) return; Class [] npt = nativeParamTypes == null ? getPT() : nativeParamTypes; CachedClass[] pt = new CachedClass [npt.length]; for (int i = 0; i != npt.length; ++i) { if (Function.class.isAssignableFrom(npt[i])) { // function type to be replaced by closure pt[i] = ReflectionCache.getCachedClass(Closure.class); } else { // non-function type pt[i] = ReflectionCache.getCachedClass(npt[i]); } } nativeParamTypes = npt; setParametersTypes(pt); } @Override protected Class[] getPT() { return m.getParameterTypes(); } }; }
java
private MetaMethod specialCasedOverrideForCreate(final Method m) { return new MetaMethod() { @Override public int getModifiers() { return m.getModifiers(); } @Override public String getName() { return m.getName(); } @Override public Class<?> getReturnType() { return m.getReturnType(); } @Override public CachedClass getDeclaringClass() { return ReflectionCache.getCachedClass(m.getDeclaringClass()); } @Override @SuppressWarnings("unchecked") public Object invoke(Object object, final Object[] arguments) { return Observable.create(new GroovyCreateWrapper((Closure) arguments[0])); } @Override public CachedClass[] getParameterTypes() { if (parameterTypes == null) { getParametersTypes0(); } return parameterTypes; } private synchronized void getParametersTypes0() { if (parameterTypes != null) return; Class [] npt = nativeParamTypes == null ? getPT() : nativeParamTypes; CachedClass[] pt = new CachedClass [npt.length]; for (int i = 0; i != npt.length; ++i) { if (Function.class.isAssignableFrom(npt[i])) { // function type to be replaced by closure pt[i] = ReflectionCache.getCachedClass(Closure.class); } else { // non-function type pt[i] = ReflectionCache.getCachedClass(npt[i]); } } nativeParamTypes = npt; setParametersTypes(pt); } @Override protected Class[] getPT() { return m.getParameterTypes(); } }; }
[ "private", "MetaMethod", "specialCasedOverrideForCreate", "(", "final", "Method", "m", ")", "{", "return", "new", "MetaMethod", "(", ")", "{", "@", "Override", "public", "int", "getModifiers", "(", ")", "{", "return", "m", ".", "getModifiers", "(", ")", ";", "}", "@", "Override", "public", "String", "getName", "(", ")", "{", "return", "m", ".", "getName", "(", ")", ";", "}", "@", "Override", "public", "Class", "<", "?", ">", "getReturnType", "(", ")", "{", "return", "m", ".", "getReturnType", "(", ")", ";", "}", "@", "Override", "public", "CachedClass", "getDeclaringClass", "(", ")", "{", "return", "ReflectionCache", ".", "getCachedClass", "(", "m", ".", "getDeclaringClass", "(", ")", ")", ";", "}", "@", "Override", "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "Object", "invoke", "(", "Object", "object", ",", "final", "Object", "[", "]", "arguments", ")", "{", "return", "Observable", ".", "create", "(", "new", "GroovyCreateWrapper", "(", "(", "Closure", ")", "arguments", "[", "0", "]", ")", ")", ";", "}", "@", "Override", "public", "CachedClass", "[", "]", "getParameterTypes", "(", ")", "{", "if", "(", "parameterTypes", "==", "null", ")", "{", "getParametersTypes0", "(", ")", ";", "}", "return", "parameterTypes", ";", "}", "private", "synchronized", "void", "getParametersTypes0", "(", ")", "{", "if", "(", "parameterTypes", "!=", "null", ")", "return", ";", "Class", "[", "]", "npt", "=", "nativeParamTypes", "==", "null", "?", "getPT", "(", ")", ":", "nativeParamTypes", ";", "CachedClass", "[", "]", "pt", "=", "new", "CachedClass", "[", "npt", ".", "length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "!=", "npt", ".", "length", ";", "++", "i", ")", "{", "if", "(", "Function", ".", "class", ".", "isAssignableFrom", "(", "npt", "[", "i", "]", ")", ")", "{", "// function type to be replaced by closure", "pt", "[", "i", "]", "=", "ReflectionCache", ".", "getCachedClass", "(", "Closure", ".", "class", ")", ";", "}", "else", "{", "// non-function type", "pt", "[", "i", "]", "=", "ReflectionCache", ".", "getCachedClass", "(", "npt", "[", "i", "]", ")", ";", "}", "}", "nativeParamTypes", "=", "npt", ";", "setParametersTypes", "(", "pt", ")", ";", "}", "@", "Override", "protected", "Class", "[", "]", "getPT", "(", ")", "{", "return", "m", ".", "getParameterTypes", "(", ")", ";", "}", "}", ";", "}" ]
Special case until we finish migrating off the deprecated 'create' method signature
[ "Special", "case", "until", "we", "finish", "migrating", "off", "the", "deprecated", "create", "method", "signature" ]
57ac7a44a6a1d5ce3bfaaf35c52d8594034a1267
https://github.com/ReactiveX/RxGroovy/blob/57ac7a44a6a1d5ce3bfaaf35c52d8594034a1267/src/main/java/rx/lang/groovy/RxGroovyExtensionModule.java#L180-L244
921
janvanbesien/java-ipv6
src/main/java/com/googlecode/ipv6/IPv6AddressHelpers.java
IPv6AddressHelpers.rewriteIPv4MappedNotation
static String rewriteIPv4MappedNotation(String string) { if (!string.contains(".")) { return string; } else { int lastColon = string.lastIndexOf(":"); String firstPart = string.substring(0, lastColon + 1); String mappedIPv4Part = string.substring(lastColon + 1); if (mappedIPv4Part.contains(".")) { String[] dotSplits = DOT_DELIM.split(mappedIPv4Part); if (dotSplits.length != 4) throw new IllegalArgumentException(String.format("can not parse [%s]", string)); StringBuilder rewrittenString = new StringBuilder(); rewrittenString.append(firstPart); int byteZero = Integer.parseInt(dotSplits[0]); int byteOne = Integer.parseInt(dotSplits[1]); int byteTwo = Integer.parseInt(dotSplits[2]); int byteThree = Integer.parseInt(dotSplits[3]); rewrittenString.append(String.format("%02x", byteZero)); rewrittenString.append(String.format("%02x", byteOne)); rewrittenString.append(":"); rewrittenString.append(String.format("%02x", byteTwo)); rewrittenString.append(String.format("%02x", byteThree)); return rewrittenString.toString(); } else { throw new IllegalArgumentException(String.format("can not parse [%s]", string)); } } }
java
static String rewriteIPv4MappedNotation(String string) { if (!string.contains(".")) { return string; } else { int lastColon = string.lastIndexOf(":"); String firstPart = string.substring(0, lastColon + 1); String mappedIPv4Part = string.substring(lastColon + 1); if (mappedIPv4Part.contains(".")) { String[] dotSplits = DOT_DELIM.split(mappedIPv4Part); if (dotSplits.length != 4) throw new IllegalArgumentException(String.format("can not parse [%s]", string)); StringBuilder rewrittenString = new StringBuilder(); rewrittenString.append(firstPart); int byteZero = Integer.parseInt(dotSplits[0]); int byteOne = Integer.parseInt(dotSplits[1]); int byteTwo = Integer.parseInt(dotSplits[2]); int byteThree = Integer.parseInt(dotSplits[3]); rewrittenString.append(String.format("%02x", byteZero)); rewrittenString.append(String.format("%02x", byteOne)); rewrittenString.append(":"); rewrittenString.append(String.format("%02x", byteTwo)); rewrittenString.append(String.format("%02x", byteThree)); return rewrittenString.toString(); } else { throw new IllegalArgumentException(String.format("can not parse [%s]", string)); } } }
[ "static", "String", "rewriteIPv4MappedNotation", "(", "String", "string", ")", "{", "if", "(", "!", "string", ".", "contains", "(", "\".\"", ")", ")", "{", "return", "string", ";", "}", "else", "{", "int", "lastColon", "=", "string", ".", "lastIndexOf", "(", "\":\"", ")", ";", "String", "firstPart", "=", "string", ".", "substring", "(", "0", ",", "lastColon", "+", "1", ")", ";", "String", "mappedIPv4Part", "=", "string", ".", "substring", "(", "lastColon", "+", "1", ")", ";", "if", "(", "mappedIPv4Part", ".", "contains", "(", "\".\"", ")", ")", "{", "String", "[", "]", "dotSplits", "=", "DOT_DELIM", ".", "split", "(", "mappedIPv4Part", ")", ";", "if", "(", "dotSplits", ".", "length", "!=", "4", ")", "throw", "new", "IllegalArgumentException", "(", "String", ".", "format", "(", "\"can not parse [%s]\"", ",", "string", ")", ")", ";", "StringBuilder", "rewrittenString", "=", "new", "StringBuilder", "(", ")", ";", "rewrittenString", ".", "append", "(", "firstPart", ")", ";", "int", "byteZero", "=", "Integer", ".", "parseInt", "(", "dotSplits", "[", "0", "]", ")", ";", "int", "byteOne", "=", "Integer", ".", "parseInt", "(", "dotSplits", "[", "1", "]", ")", ";", "int", "byteTwo", "=", "Integer", ".", "parseInt", "(", "dotSplits", "[", "2", "]", ")", ";", "int", "byteThree", "=", "Integer", ".", "parseInt", "(", "dotSplits", "[", "3", "]", ")", ";", "rewrittenString", ".", "append", "(", "String", ".", "format", "(", "\"%02x\"", ",", "byteZero", ")", ")", ";", "rewrittenString", ".", "append", "(", "String", ".", "format", "(", "\"%02x\"", ",", "byteOne", ")", ")", ";", "rewrittenString", ".", "append", "(", "\":\"", ")", ";", "rewrittenString", ".", "append", "(", "String", ".", "format", "(", "\"%02x\"", ",", "byteTwo", ")", ")", ";", "rewrittenString", ".", "append", "(", "String", ".", "format", "(", "\"%02x\"", ",", "byteThree", ")", ")", ";", "return", "rewrittenString", ".", "toString", "(", ")", ";", "}", "else", "{", "throw", "new", "IllegalArgumentException", "(", "String", ".", "format", "(", "\"can not parse [%s]\"", ",", "string", ")", ")", ";", "}", "}", "}" ]
Replaces a w.x.y.z substring at the end of the given string with corresponding hexadecimal notation. This is useful in case the string was using IPv4-Mapped address notation.
[ "Replaces", "a", "w", ".", "x", ".", "y", ".", "z", "substring", "at", "the", "end", "of", "the", "given", "string", "with", "corresponding", "hexadecimal", "notation", ".", "This", "is", "useful", "in", "case", "the", "string", "was", "using", "IPv4", "-", "Mapped", "address", "notation", "." ]
9af15b4a6c0074f9fa23dfa030027c631b9c2f78
https://github.com/janvanbesien/java-ipv6/blob/9af15b4a6c0074f9fa23dfa030027c631b9c2f78/src/main/java/com/googlecode/ipv6/IPv6AddressHelpers.java#L100-L138
922
cternes/openkeepass
src/main/java/de/slackspace/openkeepass/domain/KeePassFileBuilder.java
KeePassFileBuilder.addTopGroups
public KeePassFileBuilder addTopGroups(Group... groups) { for (Group group : groups) { rootBuilder.addGroup(group); } return this; }
java
public KeePassFileBuilder addTopGroups(Group... groups) { for (Group group : groups) { rootBuilder.addGroup(group); } return this; }
[ "public", "KeePassFileBuilder", "addTopGroups", "(", "Group", "...", "groups", ")", "{", "for", "(", "Group", "group", ":", "groups", ")", "{", "rootBuilder", ".", "addGroup", "(", "group", ")", ";", "}", "return", "this", ";", "}" ]
Adds the given groups right under the root node. @param groups the groups which should be added @return the builder with added groups
[ "Adds", "the", "given", "groups", "right", "under", "the", "root", "node", "." ]
4a354aecaea38af3c0dce5eb81b533f297e8d94f
https://github.com/cternes/openkeepass/blob/4a354aecaea38af3c0dce5eb81b533f297e8d94f/src/main/java/de/slackspace/openkeepass/domain/KeePassFileBuilder.java#L66-L72
923
cternes/openkeepass
src/main/java/de/slackspace/openkeepass/domain/KeePassFileBuilder.java
KeePassFileBuilder.addTopEntries
public KeePassFileBuilder addTopEntries(Entry... entries) { for (Entry entry : entries) { topGroupBuilder.addEntry(entry); } return this; }
java
public KeePassFileBuilder addTopEntries(Entry... entries) { for (Entry entry : entries) { topGroupBuilder.addEntry(entry); } return this; }
[ "public", "KeePassFileBuilder", "addTopEntries", "(", "Entry", "...", "entries", ")", "{", "for", "(", "Entry", "entry", ":", "entries", ")", "{", "topGroupBuilder", ".", "addEntry", "(", "entry", ")", ";", "}", "return", "this", ";", "}" ]
Add the given entries right under the root node. @param entries the entries which should be added @return the builder with added entries
[ "Add", "the", "given", "entries", "right", "under", "the", "root", "node", "." ]
4a354aecaea38af3c0dce5eb81b533f297e8d94f
https://github.com/cternes/openkeepass/blob/4a354aecaea38af3c0dce5eb81b533f297e8d94f/src/main/java/de/slackspace/openkeepass/domain/KeePassFileBuilder.java#L81-L87
924
cternes/openkeepass
src/main/java/de/slackspace/openkeepass/domain/KeePassHeader.java
KeePassHeader.read
@SuppressWarnings("resource") public void read(byte[] keepassFile) throws IOException { SafeInputStream inputStream = new SafeInputStream(new BufferedInputStream(new ByteArrayInputStream(keepassFile))); inputStream.skipSafe(VERSION_SIGNATURE_LENGTH); // skip version if(fileFormatVersion == 0) { throw new UnsupportedOperationException("File format version not set! Make sure to call checkVersionSupport before "); } while (true) { try { int fieldId = inputStream.read(); byte[] fieldLength; if(fileFormatVersion < DATABASE_V4_FILE_VERSION_INT) { fieldLength = new byte[2]; } else { fieldLength = new byte[4]; } inputStream.readSafe(fieldLength); ByteBuffer fieldLengthBuffer = ByteBuffer.wrap(fieldLength); fieldLengthBuffer.order(ByteOrder.LITTLE_ENDIAN); int fieldLengthInt = ByteUtils.toUnsignedInt(fieldLengthBuffer.getShort()); if (fieldLengthInt > 0) { byte[] data = new byte[fieldLengthInt]; inputStream.readSafe(data); setValue(fieldId, data); } if (fieldId == 0) { break; } } catch (IOException e) { throw new KeePassHeaderUnreadableException("Could not read header input", e); } } }
java
@SuppressWarnings("resource") public void read(byte[] keepassFile) throws IOException { SafeInputStream inputStream = new SafeInputStream(new BufferedInputStream(new ByteArrayInputStream(keepassFile))); inputStream.skipSafe(VERSION_SIGNATURE_LENGTH); // skip version if(fileFormatVersion == 0) { throw new UnsupportedOperationException("File format version not set! Make sure to call checkVersionSupport before "); } while (true) { try { int fieldId = inputStream.read(); byte[] fieldLength; if(fileFormatVersion < DATABASE_V4_FILE_VERSION_INT) { fieldLength = new byte[2]; } else { fieldLength = new byte[4]; } inputStream.readSafe(fieldLength); ByteBuffer fieldLengthBuffer = ByteBuffer.wrap(fieldLength); fieldLengthBuffer.order(ByteOrder.LITTLE_ENDIAN); int fieldLengthInt = ByteUtils.toUnsignedInt(fieldLengthBuffer.getShort()); if (fieldLengthInt > 0) { byte[] data = new byte[fieldLengthInt]; inputStream.readSafe(data); setValue(fieldId, data); } if (fieldId == 0) { break; } } catch (IOException e) { throw new KeePassHeaderUnreadableException("Could not read header input", e); } } }
[ "@", "SuppressWarnings", "(", "\"resource\"", ")", "public", "void", "read", "(", "byte", "[", "]", "keepassFile", ")", "throws", "IOException", "{", "SafeInputStream", "inputStream", "=", "new", "SafeInputStream", "(", "new", "BufferedInputStream", "(", "new", "ByteArrayInputStream", "(", "keepassFile", ")", ")", ")", ";", "inputStream", ".", "skipSafe", "(", "VERSION_SIGNATURE_LENGTH", ")", ";", "// skip version\r", "if", "(", "fileFormatVersion", "==", "0", ")", "{", "throw", "new", "UnsupportedOperationException", "(", "\"File format version not set! Make sure to call checkVersionSupport before \"", ")", ";", "}", "while", "(", "true", ")", "{", "try", "{", "int", "fieldId", "=", "inputStream", ".", "read", "(", ")", ";", "byte", "[", "]", "fieldLength", ";", "if", "(", "fileFormatVersion", "<", "DATABASE_V4_FILE_VERSION_INT", ")", "{", "fieldLength", "=", "new", "byte", "[", "2", "]", ";", "}", "else", "{", "fieldLength", "=", "new", "byte", "[", "4", "]", ";", "}", "inputStream", ".", "readSafe", "(", "fieldLength", ")", ";", "ByteBuffer", "fieldLengthBuffer", "=", "ByteBuffer", ".", "wrap", "(", "fieldLength", ")", ";", "fieldLengthBuffer", ".", "order", "(", "ByteOrder", ".", "LITTLE_ENDIAN", ")", ";", "int", "fieldLengthInt", "=", "ByteUtils", ".", "toUnsignedInt", "(", "fieldLengthBuffer", ".", "getShort", "(", ")", ")", ";", "if", "(", "fieldLengthInt", ">", "0", ")", "{", "byte", "[", "]", "data", "=", "new", "byte", "[", "fieldLengthInt", "]", ";", "inputStream", ".", "readSafe", "(", "data", ")", ";", "setValue", "(", "fieldId", ",", "data", ")", ";", "}", "if", "(", "fieldId", "==", "0", ")", "{", "break", ";", "}", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "KeePassHeaderUnreadableException", "(", "\"Could not read header input\"", ",", "e", ")", ";", "}", "}", "}" ]
Initializes the header values from a given byte array. @param keepassFile the byte array to read from @throws IOException if the header cannot be read
[ "Initializes", "the", "header", "values", "from", "a", "given", "byte", "array", "." ]
4a354aecaea38af3c0dce5eb81b533f297e8d94f
https://github.com/cternes/openkeepass/blob/4a354aecaea38af3c0dce5eb81b533f297e8d94f/src/main/java/de/slackspace/openkeepass/domain/KeePassHeader.java#L180-L220
925
cternes/openkeepass
src/main/java/de/slackspace/openkeepass/domain/KeePassHeader.java
KeePassHeader.getBytes
public byte[] getBytes() { try { ByteArrayOutputStream stream = new ByteArrayOutputStream(); stream.write(DATABASE_V2_FILE_SIGNATURE_1); stream.write(DATABASE_V2_FILE_SIGNATURE_2); stream.write(DATABASE_V2_FILE_VERSION); for (int i = 2; i < 11; i++) { byte[] headerValue = getValue(i); // Write index stream.write(i); // Write length byte[] length = new byte[] { (byte) headerValue.length, 0 }; stream.write(length); // Write value stream.write(headerValue); } // Write terminating flag stream.write(getEndOfHeader()); return stream.toByteArray(); } catch (IOException e) { throw new KeePassHeaderUnreadableException("Could not write header value to stream", e); } }
java
public byte[] getBytes() { try { ByteArrayOutputStream stream = new ByteArrayOutputStream(); stream.write(DATABASE_V2_FILE_SIGNATURE_1); stream.write(DATABASE_V2_FILE_SIGNATURE_2); stream.write(DATABASE_V2_FILE_VERSION); for (int i = 2; i < 11; i++) { byte[] headerValue = getValue(i); // Write index stream.write(i); // Write length byte[] length = new byte[] { (byte) headerValue.length, 0 }; stream.write(length); // Write value stream.write(headerValue); } // Write terminating flag stream.write(getEndOfHeader()); return stream.toByteArray(); } catch (IOException e) { throw new KeePassHeaderUnreadableException("Could not write header value to stream", e); } }
[ "public", "byte", "[", "]", "getBytes", "(", ")", "{", "try", "{", "ByteArrayOutputStream", "stream", "=", "new", "ByteArrayOutputStream", "(", ")", ";", "stream", ".", "write", "(", "DATABASE_V2_FILE_SIGNATURE_1", ")", ";", "stream", ".", "write", "(", "DATABASE_V2_FILE_SIGNATURE_2", ")", ";", "stream", ".", "write", "(", "DATABASE_V2_FILE_VERSION", ")", ";", "for", "(", "int", "i", "=", "2", ";", "i", "<", "11", ";", "i", "++", ")", "{", "byte", "[", "]", "headerValue", "=", "getValue", "(", "i", ")", ";", "// Write index\r", "stream", ".", "write", "(", "i", ")", ";", "// Write length\r", "byte", "[", "]", "length", "=", "new", "byte", "[", "]", "{", "(", "byte", ")", "headerValue", ".", "length", ",", "0", "}", ";", "stream", ".", "write", "(", "length", ")", ";", "// Write value\r", "stream", ".", "write", "(", "headerValue", ")", ";", "}", "// Write terminating flag\r", "stream", ".", "write", "(", "getEndOfHeader", "(", ")", ")", ";", "return", "stream", ".", "toByteArray", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "KeePassHeaderUnreadableException", "(", "\"Could not write header value to stream\"", ",", "e", ")", ";", "}", "}" ]
Returns the whole header as byte array. @return header as byte array
[ "Returns", "the", "whole", "header", "as", "byte", "array", "." ]
4a354aecaea38af3c0dce5eb81b533f297e8d94f
https://github.com/cternes/openkeepass/blob/4a354aecaea38af3c0dce5eb81b533f297e8d94f/src/main/java/de/slackspace/openkeepass/domain/KeePassHeader.java#L227-L256
926
janvanbesien/java-ipv6
src/main/java/com/googlecode/ipv6/IPv6Network.java
IPv6Network.split
public Iterator<IPv6Network> split(IPv6NetworkMask size) { if (size.asPrefixLength() < this.getNetmask().asPrefixLength()) throw new IllegalArgumentException(String.format("Can not split a network of size %s in subnets of larger size %s", this.getNetmask().asPrefixLength(), size.asPrefixLength())); return new IPv6NetworkSplitsIterator(size); }
java
public Iterator<IPv6Network> split(IPv6NetworkMask size) { if (size.asPrefixLength() < this.getNetmask().asPrefixLength()) throw new IllegalArgumentException(String.format("Can not split a network of size %s in subnets of larger size %s", this.getNetmask().asPrefixLength(), size.asPrefixLength())); return new IPv6NetworkSplitsIterator(size); }
[ "public", "Iterator", "<", "IPv6Network", ">", "split", "(", "IPv6NetworkMask", "size", ")", "{", "if", "(", "size", ".", "asPrefixLength", "(", ")", "<", "this", ".", "getNetmask", "(", ")", ".", "asPrefixLength", "(", ")", ")", "throw", "new", "IllegalArgumentException", "(", "String", ".", "format", "(", "\"Can not split a network of size %s in subnets of larger size %s\"", ",", "this", ".", "getNetmask", "(", ")", ".", "asPrefixLength", "(", ")", ",", "size", ".", "asPrefixLength", "(", ")", ")", ")", ";", "return", "new", "IPv6NetworkSplitsIterator", "(", "size", ")", ";", "}" ]
Split a network in smaller subnets of a given size. @param size size (expressed as {@link com.googlecode.ipv6.IPv6NetworkMask}) of the subnets @return iterator of the splitted subnets. @throws IllegalArgumentException if the requested size is bigger than the original size
[ "Split", "a", "network", "in", "smaller", "subnets", "of", "a", "given", "size", "." ]
9af15b4a6c0074f9fa23dfa030027c631b9c2f78
https://github.com/janvanbesien/java-ipv6/blob/9af15b4a6c0074f9fa23dfa030027c631b9c2f78/src/main/java/com/googlecode/ipv6/IPv6Network.java#L126-L133
927
janvanbesien/java-ipv6
src/main/java/com/googlecode/ipv6/IPv6Address.java
IPv6Address.fromInetAddress
public static IPv6Address fromInetAddress(final InetAddress inetAddress) { if (inetAddress == null) throw new IllegalArgumentException("can not construct from [null]"); return fromByteArray(inetAddress.getAddress()); }
java
public static IPv6Address fromInetAddress(final InetAddress inetAddress) { if (inetAddress == null) throw new IllegalArgumentException("can not construct from [null]"); return fromByteArray(inetAddress.getAddress()); }
[ "public", "static", "IPv6Address", "fromInetAddress", "(", "final", "InetAddress", "inetAddress", ")", "{", "if", "(", "inetAddress", "==", "null", ")", "throw", "new", "IllegalArgumentException", "(", "\"can not construct from [null]\"", ")", ";", "return", "fromByteArray", "(", "inetAddress", ".", "getAddress", "(", ")", ")", ";", "}" ]
Create an IPv6 address from a java.net.Inet6Address. @param inetAddress Inet6Address representation @return IPv6 address
[ "Create", "an", "IPv6", "address", "from", "a", "java", ".", "net", ".", "Inet6Address", "." ]
9af15b4a6c0074f9fa23dfa030027c631b9c2f78
https://github.com/janvanbesien/java-ipv6/blob/9af15b4a6c0074f9fa23dfa030027c631b9c2f78/src/main/java/com/googlecode/ipv6/IPv6Address.java#L106-L112
928
janvanbesien/java-ipv6
src/main/java/com/googlecode/ipv6/IPv6Address.java
IPv6Address.fromByteArray
public static IPv6Address fromByteArray(final byte[] bytes) { if (bytes == null) throw new IllegalArgumentException("can not construct from [null]"); if (bytes.length != N_BYTES) throw new IllegalArgumentException("the byte array to construct from should be 16 bytes long"); ByteBuffer buf = ByteBuffer.allocate(N_BYTES); for (byte b : bytes) { buf.put(b); } buf.rewind(); LongBuffer longBuffer = buf.asLongBuffer(); return new IPv6Address(longBuffer.get(), longBuffer.get()); }
java
public static IPv6Address fromByteArray(final byte[] bytes) { if (bytes == null) throw new IllegalArgumentException("can not construct from [null]"); if (bytes.length != N_BYTES) throw new IllegalArgumentException("the byte array to construct from should be 16 bytes long"); ByteBuffer buf = ByteBuffer.allocate(N_BYTES); for (byte b : bytes) { buf.put(b); } buf.rewind(); LongBuffer longBuffer = buf.asLongBuffer(); return new IPv6Address(longBuffer.get(), longBuffer.get()); }
[ "public", "static", "IPv6Address", "fromByteArray", "(", "final", "byte", "[", "]", "bytes", ")", "{", "if", "(", "bytes", "==", "null", ")", "throw", "new", "IllegalArgumentException", "(", "\"can not construct from [null]\"", ")", ";", "if", "(", "bytes", ".", "length", "!=", "N_BYTES", ")", "throw", "new", "IllegalArgumentException", "(", "\"the byte array to construct from should be 16 bytes long\"", ")", ";", "ByteBuffer", "buf", "=", "ByteBuffer", ".", "allocate", "(", "N_BYTES", ")", ";", "for", "(", "byte", "b", ":", "bytes", ")", "{", "buf", ".", "put", "(", "b", ")", ";", "}", "buf", ".", "rewind", "(", ")", ";", "LongBuffer", "longBuffer", "=", "buf", ".", "asLongBuffer", "(", ")", ";", "return", "new", "IPv6Address", "(", "longBuffer", ".", "get", "(", ")", ",", "longBuffer", ".", "get", "(", ")", ")", ";", "}" ]
Create an IPv6 address from a byte array. @param bytes byte array with 16 bytes (interpreted unsigned) @return IPv6 address
[ "Create", "an", "IPv6", "address", "from", "a", "byte", "array", "." ]
9af15b4a6c0074f9fa23dfa030027c631b9c2f78
https://github.com/janvanbesien/java-ipv6/blob/9af15b4a6c0074f9fa23dfa030027c631b9c2f78/src/main/java/com/googlecode/ipv6/IPv6Address.java#L125-L141
929
janvanbesien/java-ipv6
src/main/java/com/googlecode/ipv6/IPv6Address.java
IPv6Address.add
public IPv6Address add(int value) { final long newLowBits = lowBits + value; if (value >= 0) { if (IPv6AddressHelpers.isLessThanUnsigned(newLowBits, lowBits)) { // oops, we added something positive and the result is smaller -> overflow detected (carry over one bit from low to high) return new IPv6Address(highBits + 1, newLowBits); } else { // no overflow return new IPv6Address(highBits, newLowBits); } } else { if (IPv6AddressHelpers.isLessThanUnsigned(lowBits, newLowBits)) { // oops, we added something negative and the result is bigger -> overflow detected (carry over one bit from high to low) return new IPv6Address(highBits - 1, newLowBits); } else { // no overflow return new IPv6Address(highBits, newLowBits); } } }
java
public IPv6Address add(int value) { final long newLowBits = lowBits + value; if (value >= 0) { if (IPv6AddressHelpers.isLessThanUnsigned(newLowBits, lowBits)) { // oops, we added something positive and the result is smaller -> overflow detected (carry over one bit from low to high) return new IPv6Address(highBits + 1, newLowBits); } else { // no overflow return new IPv6Address(highBits, newLowBits); } } else { if (IPv6AddressHelpers.isLessThanUnsigned(lowBits, newLowBits)) { // oops, we added something negative and the result is bigger -> overflow detected (carry over one bit from high to low) return new IPv6Address(highBits - 1, newLowBits); } else { // no overflow return new IPv6Address(highBits, newLowBits); } } }
[ "public", "IPv6Address", "add", "(", "int", "value", ")", "{", "final", "long", "newLowBits", "=", "lowBits", "+", "value", ";", "if", "(", "value", ">=", "0", ")", "{", "if", "(", "IPv6AddressHelpers", ".", "isLessThanUnsigned", "(", "newLowBits", ",", "lowBits", ")", ")", "{", "// oops, we added something positive and the result is smaller -> overflow detected (carry over one bit from low to high)", "return", "new", "IPv6Address", "(", "highBits", "+", "1", ",", "newLowBits", ")", ";", "}", "else", "{", "// no overflow", "return", "new", "IPv6Address", "(", "highBits", ",", "newLowBits", ")", ";", "}", "}", "else", "{", "if", "(", "IPv6AddressHelpers", ".", "isLessThanUnsigned", "(", "lowBits", ",", "newLowBits", ")", ")", "{", "// oops, we added something negative and the result is bigger -> overflow detected (carry over one bit from high to low)", "return", "new", "IPv6Address", "(", "highBits", "-", "1", ",", "newLowBits", ")", ";", "}", "else", "{", "// no overflow", "return", "new", "IPv6Address", "(", "highBits", ",", "newLowBits", ")", ";", "}", "}", "}" ]
Addition. Will never overflow, but wraps around when the highest ip address has been reached. @param value value to add @return new IPv6 address
[ "Addition", ".", "Will", "never", "overflow", "but", "wraps", "around", "when", "the", "highest", "ip", "address", "has", "been", "reached", "." ]
9af15b4a6c0074f9fa23dfa030027c631b9c2f78
https://github.com/janvanbesien/java-ipv6/blob/9af15b4a6c0074f9fa23dfa030027c631b9c2f78/src/main/java/com/googlecode/ipv6/IPv6Address.java#L196-L226
930
janvanbesien/java-ipv6
src/main/java/com/googlecode/ipv6/IPv6Address.java
IPv6Address.subtract
public IPv6Address subtract(int value) { final long newLowBits = lowBits - value; if (value >= 0) { if (IPv6AddressHelpers.isLessThanUnsigned(lowBits, newLowBits)) { // oops, we subtracted something postive and the result is bigger -> overflow detected (carry over one bit from high to low) return new IPv6Address(highBits - 1, newLowBits); } else { // no overflow return new IPv6Address(highBits, newLowBits); } } else { if (IPv6AddressHelpers.isLessThanUnsigned(newLowBits, lowBits)) { // oops, we subtracted something negative and the result is smaller -> overflow detected (carry over one bit from low to high) return new IPv6Address(highBits + 1, newLowBits); } else { // no overflow return new IPv6Address(highBits, newLowBits); } } }
java
public IPv6Address subtract(int value) { final long newLowBits = lowBits - value; if (value >= 0) { if (IPv6AddressHelpers.isLessThanUnsigned(lowBits, newLowBits)) { // oops, we subtracted something postive and the result is bigger -> overflow detected (carry over one bit from high to low) return new IPv6Address(highBits - 1, newLowBits); } else { // no overflow return new IPv6Address(highBits, newLowBits); } } else { if (IPv6AddressHelpers.isLessThanUnsigned(newLowBits, lowBits)) { // oops, we subtracted something negative and the result is smaller -> overflow detected (carry over one bit from low to high) return new IPv6Address(highBits + 1, newLowBits); } else { // no overflow return new IPv6Address(highBits, newLowBits); } } }
[ "public", "IPv6Address", "subtract", "(", "int", "value", ")", "{", "final", "long", "newLowBits", "=", "lowBits", "-", "value", ";", "if", "(", "value", ">=", "0", ")", "{", "if", "(", "IPv6AddressHelpers", ".", "isLessThanUnsigned", "(", "lowBits", ",", "newLowBits", ")", ")", "{", "// oops, we subtracted something postive and the result is bigger -> overflow detected (carry over one bit from high to low)", "return", "new", "IPv6Address", "(", "highBits", "-", "1", ",", "newLowBits", ")", ";", "}", "else", "{", "// no overflow", "return", "new", "IPv6Address", "(", "highBits", ",", "newLowBits", ")", ";", "}", "}", "else", "{", "if", "(", "IPv6AddressHelpers", ".", "isLessThanUnsigned", "(", "newLowBits", ",", "lowBits", ")", ")", "{", "// oops, we subtracted something negative and the result is smaller -> overflow detected (carry over one bit from low to high)", "return", "new", "IPv6Address", "(", "highBits", "+", "1", ",", "newLowBits", ")", ";", "}", "else", "{", "// no overflow", "return", "new", "IPv6Address", "(", "highBits", ",", "newLowBits", ")", ";", "}", "}", "}" ]
Subtraction. Will never underflow, but wraps around when the lowest ip address has been reached. @param value value to substract @return new IPv6 address
[ "Subtraction", ".", "Will", "never", "underflow", "but", "wraps", "around", "when", "the", "lowest", "ip", "address", "has", "been", "reached", "." ]
9af15b4a6c0074f9fa23dfa030027c631b9c2f78
https://github.com/janvanbesien/java-ipv6/blob/9af15b4a6c0074f9fa23dfa030027c631b9c2f78/src/main/java/com/googlecode/ipv6/IPv6Address.java#L234-L264
931
janvanbesien/java-ipv6
src/main/java/com/googlecode/ipv6/IPv6Address.java
IPv6Address.maskWithNetworkMask
public IPv6Address maskWithNetworkMask(final IPv6NetworkMask networkMask) { if (networkMask.asPrefixLength() == 128) { return this; } else if (networkMask.asPrefixLength() == 64) { return new IPv6Address(this.highBits, 0); } else if (networkMask.asPrefixLength() == 0) { return new IPv6Address(0, 0); } else if (networkMask.asPrefixLength() > 64) { // apply mask on low bits only final int remainingPrefixLength = networkMask.asPrefixLength() - 64; return new IPv6Address(this.highBits, this.lowBits & (0xFFFFFFFFFFFFFFFFL << (64 - remainingPrefixLength))); } else { // apply mask on high bits, low bits completely 0 return new IPv6Address(this.highBits & (0xFFFFFFFFFFFFFFFFL << (64 - networkMask.asPrefixLength())), 0); } }
java
public IPv6Address maskWithNetworkMask(final IPv6NetworkMask networkMask) { if (networkMask.asPrefixLength() == 128) { return this; } else if (networkMask.asPrefixLength() == 64) { return new IPv6Address(this.highBits, 0); } else if (networkMask.asPrefixLength() == 0) { return new IPv6Address(0, 0); } else if (networkMask.asPrefixLength() > 64) { // apply mask on low bits only final int remainingPrefixLength = networkMask.asPrefixLength() - 64; return new IPv6Address(this.highBits, this.lowBits & (0xFFFFFFFFFFFFFFFFL << (64 - remainingPrefixLength))); } else { // apply mask on high bits, low bits completely 0 return new IPv6Address(this.highBits & (0xFFFFFFFFFFFFFFFFL << (64 - networkMask.asPrefixLength())), 0); } }
[ "public", "IPv6Address", "maskWithNetworkMask", "(", "final", "IPv6NetworkMask", "networkMask", ")", "{", "if", "(", "networkMask", ".", "asPrefixLength", "(", ")", "==", "128", ")", "{", "return", "this", ";", "}", "else", "if", "(", "networkMask", ".", "asPrefixLength", "(", ")", "==", "64", ")", "{", "return", "new", "IPv6Address", "(", "this", ".", "highBits", ",", "0", ")", ";", "}", "else", "if", "(", "networkMask", ".", "asPrefixLength", "(", ")", "==", "0", ")", "{", "return", "new", "IPv6Address", "(", "0", ",", "0", ")", ";", "}", "else", "if", "(", "networkMask", ".", "asPrefixLength", "(", ")", ">", "64", ")", "{", "// apply mask on low bits only", "final", "int", "remainingPrefixLength", "=", "networkMask", ".", "asPrefixLength", "(", ")", "-", "64", ";", "return", "new", "IPv6Address", "(", "this", ".", "highBits", ",", "this", ".", "lowBits", "&", "(", "0xFFFFFFFFFFFFFFFF", "L", "<<", "(", "64", "-", "remainingPrefixLength", ")", ")", ")", ";", "}", "else", "{", "// apply mask on high bits, low bits completely 0", "return", "new", "IPv6Address", "(", "this", ".", "highBits", "&", "(", "0xFFFFFFFFFFFFFFFF", "L", "<<", "(", "64", "-", "networkMask", ".", "asPrefixLength", "(", ")", ")", ")", ",", "0", ")", ";", "}", "}" ]
Mask the address with the given network mask. @param networkMask network mask @return an address of which the last 128 - networkMask.asPrefixLength() bits are zero
[ "Mask", "the", "address", "with", "the", "given", "network", "mask", "." ]
9af15b4a6c0074f9fa23dfa030027c631b9c2f78
https://github.com/janvanbesien/java-ipv6/blob/9af15b4a6c0074f9fa23dfa030027c631b9c2f78/src/main/java/com/googlecode/ipv6/IPv6Address.java#L272-L297
932
janvanbesien/java-ipv6
src/main/java/com/googlecode/ipv6/IPv6Address.java
IPv6Address.setBit
public IPv6Address setBit(final int bit) { if (bit < 0 || bit > 127) throw new IllegalArgumentException("can only set bits in the interval [0, 127]"); if (bit < 64) { return new IPv6Address(this.highBits, this.lowBits | (1L << bit)); } else { return new IPv6Address(this.highBits | (1L << (bit - 64)), this.lowBits); } }
java
public IPv6Address setBit(final int bit) { if (bit < 0 || bit > 127) throw new IllegalArgumentException("can only set bits in the interval [0, 127]"); if (bit < 64) { return new IPv6Address(this.highBits, this.lowBits | (1L << bit)); } else { return new IPv6Address(this.highBits | (1L << (bit - 64)), this.lowBits); } }
[ "public", "IPv6Address", "setBit", "(", "final", "int", "bit", ")", "{", "if", "(", "bit", "<", "0", "||", "bit", ">", "127", ")", "throw", "new", "IllegalArgumentException", "(", "\"can only set bits in the interval [0, 127]\"", ")", ";", "if", "(", "bit", "<", "64", ")", "{", "return", "new", "IPv6Address", "(", "this", ".", "highBits", ",", "this", ".", "lowBits", "|", "(", "1L", "<<", "bit", ")", ")", ";", "}", "else", "{", "return", "new", "IPv6Address", "(", "this", ".", "highBits", "|", "(", "1L", "<<", "(", "bit", "-", "64", ")", ")", ",", "this", ".", "lowBits", ")", ";", "}", "}" ]
Set a bit in the address. @param bit to set (in the range [0, 127]) @return an address with the given bit set
[ "Set", "a", "bit", "in", "the", "address", "." ]
9af15b4a6c0074f9fa23dfa030027c631b9c2f78
https://github.com/janvanbesien/java-ipv6/blob/9af15b4a6c0074f9fa23dfa030027c631b9c2f78/src/main/java/com/googlecode/ipv6/IPv6Address.java#L334-L347
933
cternes/openkeepass
src/main/java/de/slackspace/openkeepass/util/SafeInputStream.java
SafeInputStream.skipSafe
public void skipSafe(long numBytes) throws IOException { long skippedBytes = inputStream.skip(numBytes); if (skippedBytes == -1) { throw new IOException("Could not skip '" + numBytes + "' bytes in stream"); } }
java
public void skipSafe(long numBytes) throws IOException { long skippedBytes = inputStream.skip(numBytes); if (skippedBytes == -1) { throw new IOException("Could not skip '" + numBytes + "' bytes in stream"); } }
[ "public", "void", "skipSafe", "(", "long", "numBytes", ")", "throws", "IOException", "{", "long", "skippedBytes", "=", "inputStream", ".", "skip", "(", "numBytes", ")", ";", "if", "(", "skippedBytes", "==", "-", "1", ")", "{", "throw", "new", "IOException", "(", "\"Could not skip '\"", "+", "numBytes", "+", "\"' bytes in stream\"", ")", ";", "}", "}" ]
Skips over and discards numBytes bytes of data from the underlying input stream. Will throw an exception if the given number of bytes could not be skipped. @param numBytes the number of bytes to skip @throws IOException if the given number of bytes could not be skipped
[ "Skips", "over", "and", "discards", "numBytes", "bytes", "of", "data", "from", "the", "underlying", "input", "stream", ".", "Will", "throw", "an", "exception", "if", "the", "given", "number", "of", "bytes", "could", "not", "be", "skipped", "." ]
4a354aecaea38af3c0dce5eb81b533f297e8d94f
https://github.com/cternes/openkeepass/blob/4a354aecaea38af3c0dce5eb81b533f297e8d94f/src/main/java/de/slackspace/openkeepass/util/SafeInputStream.java#L43-L49
934
cternes/openkeepass
src/main/java/de/slackspace/openkeepass/domain/KeePassFile.java
KeePassFile.getTopGroups
public List<Group> getTopGroups() { if (root != null && root.getGroups() != null && root.getGroups().size() == 1) { return root.getGroups().get(0).getGroups(); } return new ArrayList<Group>(); }
java
public List<Group> getTopGroups() { if (root != null && root.getGroups() != null && root.getGroups().size() == 1) { return root.getGroups().get(0).getGroups(); } return new ArrayList<Group>(); }
[ "public", "List", "<", "Group", ">", "getTopGroups", "(", ")", "{", "if", "(", "root", "!=", "null", "&&", "root", ".", "getGroups", "(", ")", "!=", "null", "&&", "root", ".", "getGroups", "(", ")", ".", "size", "(", ")", "==", "1", ")", "{", "return", "root", ".", "getGroups", "(", ")", ".", "get", "(", "0", ")", ".", "getGroups", "(", ")", ";", "}", "return", "new", "ArrayList", "<", "Group", ">", "(", ")", ";", "}" ]
Retrieves all groups at the root level of a KeePass database. @return a list of root level groups @see Group
[ "Retrieves", "all", "groups", "at", "the", "root", "level", "of", "a", "KeePass", "database", "." ]
4a354aecaea38af3c0dce5eb81b533f297e8d94f
https://github.com/cternes/openkeepass/blob/4a354aecaea38af3c0dce5eb81b533f297e8d94f/src/main/java/de/slackspace/openkeepass/domain/KeePassFile.java#L60-L65
935
cternes/openkeepass
src/main/java/de/slackspace/openkeepass/domain/KeePassFile.java
KeePassFile.getTopEntries
public List<Entry> getTopEntries() { if (root != null && root.getGroups() != null && root.getGroups().size() == 1) { return root.getGroups().get(0).getEntries(); } return new ArrayList<Entry>(); }
java
public List<Entry> getTopEntries() { if (root != null && root.getGroups() != null && root.getGroups().size() == 1) { return root.getGroups().get(0).getEntries(); } return new ArrayList<Entry>(); }
[ "public", "List", "<", "Entry", ">", "getTopEntries", "(", ")", "{", "if", "(", "root", "!=", "null", "&&", "root", ".", "getGroups", "(", ")", "!=", "null", "&&", "root", ".", "getGroups", "(", ")", ".", "size", "(", ")", "==", "1", ")", "{", "return", "root", ".", "getGroups", "(", ")", ".", "get", "(", "0", ")", ".", "getEntries", "(", ")", ";", "}", "return", "new", "ArrayList", "<", "Entry", ">", "(", ")", ";", "}" ]
Retrieves all entries at the root level of a KeePass database. @return a list of root level entries @see Entry
[ "Retrieves", "all", "entries", "at", "the", "root", "level", "of", "a", "KeePass", "database", "." ]
4a354aecaea38af3c0dce5eb81b533f297e8d94f
https://github.com/cternes/openkeepass/blob/4a354aecaea38af3c0dce5eb81b533f297e8d94f/src/main/java/de/slackspace/openkeepass/domain/KeePassFile.java#L73-L78
936
cternes/openkeepass
src/main/java/de/slackspace/openkeepass/domain/KeePassFile.java
KeePassFile.getEntries
public List<Entry> getEntries() { List<Entry> allEntries = new ArrayList<Entry>(); if (root != null) { getEntries(root, allEntries); } return allEntries; }
java
public List<Entry> getEntries() { List<Entry> allEntries = new ArrayList<Entry>(); if (root != null) { getEntries(root, allEntries); } return allEntries; }
[ "public", "List", "<", "Entry", ">", "getEntries", "(", ")", "{", "List", "<", "Entry", ">", "allEntries", "=", "new", "ArrayList", "<", "Entry", ">", "(", ")", ";", "if", "(", "root", "!=", "null", ")", "{", "getEntries", "(", "root", ",", "allEntries", ")", ";", "}", "return", "allEntries", ";", "}" ]
Retrieves a list of all entries in the KeePass database. @return a list of all entries @see Entry
[ "Retrieves", "a", "list", "of", "all", "entries", "in", "the", "KeePass", "database", "." ]
4a354aecaea38af3c0dce5eb81b533f297e8d94f
https://github.com/cternes/openkeepass/blob/4a354aecaea38af3c0dce5eb81b533f297e8d94f/src/main/java/de/slackspace/openkeepass/domain/KeePassFile.java#L191-L199
937
cternes/openkeepass
src/main/java/de/slackspace/openkeepass/domain/KeePassFile.java
KeePassFile.getGroups
public List<Group> getGroups() { List<Group> allGroups = new ArrayList<Group>(); if (root != null) { getGroups(root, allGroups); } return allGroups; }
java
public List<Group> getGroups() { List<Group> allGroups = new ArrayList<Group>(); if (root != null) { getGroups(root, allGroups); } return allGroups; }
[ "public", "List", "<", "Group", ">", "getGroups", "(", ")", "{", "List", "<", "Group", ">", "allGroups", "=", "new", "ArrayList", "<", "Group", ">", "(", ")", ";", "if", "(", "root", "!=", "null", ")", "{", "getGroups", "(", "root", ",", "allGroups", ")", ";", "}", "return", "allGroups", ";", "}" ]
Retrieves a list of all groups in the KeePass database. @return a list of all groups @see Group
[ "Retrieves", "a", "list", "of", "all", "groups", "in", "the", "KeePass", "database", "." ]
4a354aecaea38af3c0dce5eb81b533f297e8d94f
https://github.com/cternes/openkeepass/blob/4a354aecaea38af3c0dce5eb81b533f297e8d94f/src/main/java/de/slackspace/openkeepass/domain/KeePassFile.java#L207-L215
938
cternes/openkeepass
src/main/java/de/slackspace/openkeepass/domain/KeePassFile.java
KeePassFile.getEntryByUUID
public Entry getEntryByUUID(final UUID UUID) { List<Entry> allEntries = getEntries(); List<Entry> entries = ListFilter.filter(allEntries, new Filter<Entry>() { @Override public boolean matches(Entry item) { if (item.getUuid() != null && item.getUuid().compareTo(UUID) == 0) { return true; } else { return false; } } }); if (entries.size() == 1) { return entries.get(0); } else { return null; } }
java
public Entry getEntryByUUID(final UUID UUID) { List<Entry> allEntries = getEntries(); List<Entry> entries = ListFilter.filter(allEntries, new Filter<Entry>() { @Override public boolean matches(Entry item) { if (item.getUuid() != null && item.getUuid().compareTo(UUID) == 0) { return true; } else { return false; } } }); if (entries.size() == 1) { return entries.get(0); } else { return null; } }
[ "public", "Entry", "getEntryByUUID", "(", "final", "UUID", "UUID", ")", "{", "List", "<", "Entry", ">", "allEntries", "=", "getEntries", "(", ")", ";", "List", "<", "Entry", ">", "entries", "=", "ListFilter", ".", "filter", "(", "allEntries", ",", "new", "Filter", "<", "Entry", ">", "(", ")", "{", "@", "Override", "public", "boolean", "matches", "(", "Entry", "item", ")", "{", "if", "(", "item", ".", "getUuid", "(", ")", "!=", "null", "&&", "item", ".", "getUuid", "(", ")", ".", "compareTo", "(", "UUID", ")", "==", "0", ")", "{", "return", "true", ";", "}", "else", "{", "return", "false", ";", "}", "}", "}", ")", ";", "if", "(", "entries", ".", "size", "(", ")", "==", "1", ")", "{", "return", "entries", ".", "get", "(", "0", ")", ";", "}", "else", "{", "return", "null", ";", "}", "}" ]
Retrieves an entry based on its UUID. @param UUID the uuid which should be searched @return the found entry or null
[ "Retrieves", "an", "entry", "based", "on", "its", "UUID", "." ]
4a354aecaea38af3c0dce5eb81b533f297e8d94f
https://github.com/cternes/openkeepass/blob/4a354aecaea38af3c0dce5eb81b533f297e8d94f/src/main/java/de/slackspace/openkeepass/domain/KeePassFile.java#L271-L292
939
cternes/openkeepass
src/main/java/de/slackspace/openkeepass/domain/KeePassFile.java
KeePassFile.getGroupByUUID
public Group getGroupByUUID(final UUID UUID) { List<Group> allGroups = getGroups(); List<Group> groups = ListFilter.filter(allGroups, new Filter<Group>() { @Override public boolean matches(Group item) { if (item.getUuid() != null && item.getUuid().compareTo(UUID) == 0) { return true; } else { return false; } } }); if (groups.size() == 1) { return groups.get(0); } else { return null; } }
java
public Group getGroupByUUID(final UUID UUID) { List<Group> allGroups = getGroups(); List<Group> groups = ListFilter.filter(allGroups, new Filter<Group>() { @Override public boolean matches(Group item) { if (item.getUuid() != null && item.getUuid().compareTo(UUID) == 0) { return true; } else { return false; } } }); if (groups.size() == 1) { return groups.get(0); } else { return null; } }
[ "public", "Group", "getGroupByUUID", "(", "final", "UUID", "UUID", ")", "{", "List", "<", "Group", ">", "allGroups", "=", "getGroups", "(", ")", ";", "List", "<", "Group", ">", "groups", "=", "ListFilter", ".", "filter", "(", "allGroups", ",", "new", "Filter", "<", "Group", ">", "(", ")", "{", "@", "Override", "public", "boolean", "matches", "(", "Group", "item", ")", "{", "if", "(", "item", ".", "getUuid", "(", ")", "!=", "null", "&&", "item", ".", "getUuid", "(", ")", ".", "compareTo", "(", "UUID", ")", "==", "0", ")", "{", "return", "true", ";", "}", "else", "{", "return", "false", ";", "}", "}", "}", ")", ";", "if", "(", "groups", ".", "size", "(", ")", "==", "1", ")", "{", "return", "groups", ".", "get", "(", "0", ")", ";", "}", "else", "{", "return", "null", ";", "}", "}" ]
Retrieves a group based on its UUID. @param UUID the uuid which should be searched @return the found group or null
[ "Retrieves", "a", "group", "based", "on", "its", "UUID", "." ]
4a354aecaea38af3c0dce5eb81b533f297e8d94f
https://github.com/cternes/openkeepass/blob/4a354aecaea38af3c0dce5eb81b533f297e8d94f/src/main/java/de/slackspace/openkeepass/domain/KeePassFile.java#L301-L322
940
cternes/openkeepass
src/main/java/de/slackspace/openkeepass/KeePassDatabase.java
KeePassDatabase.getInstance
public static KeePassDatabase getInstance(File keePassDatabaseFile) { if (keePassDatabaseFile == null) { throw new IllegalArgumentException("You must provide a valid KeePass database file."); } InputStream keePassDatabaseStream = null; try { keePassDatabaseStream = new FileInputStream(keePassDatabaseFile); return getInstance(keePassDatabaseStream); } catch (FileNotFoundException e) { throw new IllegalArgumentException("The KeePass database file could not be found. You must provide a valid KeePass database file.", e); } finally { if (keePassDatabaseStream != null) { try { keePassDatabaseStream.close(); } catch (IOException e) { // Ignore } } } }
java
public static KeePassDatabase getInstance(File keePassDatabaseFile) { if (keePassDatabaseFile == null) { throw new IllegalArgumentException("You must provide a valid KeePass database file."); } InputStream keePassDatabaseStream = null; try { keePassDatabaseStream = new FileInputStream(keePassDatabaseFile); return getInstance(keePassDatabaseStream); } catch (FileNotFoundException e) { throw new IllegalArgumentException("The KeePass database file could not be found. You must provide a valid KeePass database file.", e); } finally { if (keePassDatabaseStream != null) { try { keePassDatabaseStream.close(); } catch (IOException e) { // Ignore } } } }
[ "public", "static", "KeePassDatabase", "getInstance", "(", "File", "keePassDatabaseFile", ")", "{", "if", "(", "keePassDatabaseFile", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"You must provide a valid KeePass database file.\"", ")", ";", "}", "InputStream", "keePassDatabaseStream", "=", "null", ";", "try", "{", "keePassDatabaseStream", "=", "new", "FileInputStream", "(", "keePassDatabaseFile", ")", ";", "return", "getInstance", "(", "keePassDatabaseStream", ")", ";", "}", "catch", "(", "FileNotFoundException", "e", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"The KeePass database file could not be found. You must provide a valid KeePass database file.\"", ",", "e", ")", ";", "}", "finally", "{", "if", "(", "keePassDatabaseStream", "!=", "null", ")", "{", "try", "{", "keePassDatabaseStream", ".", "close", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "// Ignore\r", "}", "}", "}", "}" ]
Retrieves a KeePassDatabase instance. The instance returned is based on the given database file and tries to parse the database header of it. @param keePassDatabaseFile a KeePass database file, must not be NULL @return a KeePassDatabase
[ "Retrieves", "a", "KeePassDatabase", "instance", ".", "The", "instance", "returned", "is", "based", "on", "the", "given", "database", "file", "and", "tries", "to", "parse", "the", "database", "header", "of", "it", "." ]
4a354aecaea38af3c0dce5eb81b533f297e8d94f
https://github.com/cternes/openkeepass/blob/4a354aecaea38af3c0dce5eb81b533f297e8d94f/src/main/java/de/slackspace/openkeepass/KeePassDatabase.java#L106-L126
941
cternes/openkeepass
src/main/java/de/slackspace/openkeepass/domain/Group.java
Group.getEntryByTitle
public Entry getEntryByTitle(String title) { for (Entry entry : entries) { if (entry.getTitle().equalsIgnoreCase(title)) { return entry; } } return null; }
java
public Entry getEntryByTitle(String title) { for (Entry entry : entries) { if (entry.getTitle().equalsIgnoreCase(title)) { return entry; } } return null; }
[ "public", "Entry", "getEntryByTitle", "(", "String", "title", ")", "{", "for", "(", "Entry", "entry", ":", "entries", ")", "{", "if", "(", "entry", ".", "getTitle", "(", ")", ".", "equalsIgnoreCase", "(", "title", ")", ")", "{", "return", "entry", ";", "}", "}", "return", "null", ";", "}" ]
Retrieves the entry with the given title. @param title the title of the entry which should be retrieved @return an entry with matching title
[ "Retrieves", "the", "entry", "with", "the", "given", "title", "." ]
4a354aecaea38af3c0dce5eb81b533f297e8d94f
https://github.com/cternes/openkeepass/blob/4a354aecaea38af3c0dce5eb81b533f297e8d94f/src/main/java/de/slackspace/openkeepass/domain/Group.java#L106-L113
942
cternes/openkeepass
src/main/java/de/slackspace/openkeepass/processor/IconEnricher.java
IconEnricher.enrichNodesWithIconData
public KeePassFile enrichNodesWithIconData(KeePassFile keePassFile) { CustomIcons iconLibrary = keePassFile.getMeta().getCustomIcons(); GroupZipper zipper = new GroupZipper(keePassFile); Iterator<Group> iter = zipper.iterator(); while (iter.hasNext()) { Group group = iter.next(); byte[] iconData = getIconData(group.getCustomIconUuid(), group.getIconId(), iconLibrary); Group groupWithIcon = new GroupBuilder(group).iconData(iconData).build(); zipper.replace(groupWithIcon); enrichEntriesWithIcons(iconLibrary, group); } return zipper.close(); }
java
public KeePassFile enrichNodesWithIconData(KeePassFile keePassFile) { CustomIcons iconLibrary = keePassFile.getMeta().getCustomIcons(); GroupZipper zipper = new GroupZipper(keePassFile); Iterator<Group> iter = zipper.iterator(); while (iter.hasNext()) { Group group = iter.next(); byte[] iconData = getIconData(group.getCustomIconUuid(), group.getIconId(), iconLibrary); Group groupWithIcon = new GroupBuilder(group).iconData(iconData).build(); zipper.replace(groupWithIcon); enrichEntriesWithIcons(iconLibrary, group); } return zipper.close(); }
[ "public", "KeePassFile", "enrichNodesWithIconData", "(", "KeePassFile", "keePassFile", ")", "{", "CustomIcons", "iconLibrary", "=", "keePassFile", ".", "getMeta", "(", ")", ".", "getCustomIcons", "(", ")", ";", "GroupZipper", "zipper", "=", "new", "GroupZipper", "(", "keePassFile", ")", ";", "Iterator", "<", "Group", ">", "iter", "=", "zipper", ".", "iterator", "(", ")", ";", "while", "(", "iter", ".", "hasNext", "(", ")", ")", "{", "Group", "group", "=", "iter", ".", "next", "(", ")", ";", "byte", "[", "]", "iconData", "=", "getIconData", "(", "group", ".", "getCustomIconUuid", "(", ")", ",", "group", ".", "getIconId", "(", ")", ",", "iconLibrary", ")", ";", "Group", "groupWithIcon", "=", "new", "GroupBuilder", "(", "group", ")", ".", "iconData", "(", "iconData", ")", ".", "build", "(", ")", ";", "zipper", ".", "replace", "(", "groupWithIcon", ")", ";", "enrichEntriesWithIcons", "(", "iconLibrary", ",", "group", ")", ";", "}", "return", "zipper", ".", "close", "(", ")", ";", "}" ]
Iterates through all nodes of the given KeePass file and replace the nodes with enriched icon data nodes. @param keePassFile the KeePass file which should be iterated @return an enriched KeePass file
[ "Iterates", "through", "all", "nodes", "of", "the", "given", "KeePass", "file", "and", "replace", "the", "nodes", "with", "enriched", "icon", "data", "nodes", "." ]
4a354aecaea38af3c0dce5eb81b533f297e8d94f
https://github.com/cternes/openkeepass/blob/4a354aecaea38af3c0dce5eb81b533f297e8d94f/src/main/java/de/slackspace/openkeepass/processor/IconEnricher.java#L42-L58
943
cternes/openkeepass
src/main/java/de/slackspace/openkeepass/domain/Binaries.java
Binaries.getBinaryById
public Binary getBinaryById(int id) { for (Binary binary : binaryList) { if (binary.getId() == id) { return binary; } } return null; }
java
public Binary getBinaryById(int id) { for (Binary binary : binaryList) { if (binary.getId() == id) { return binary; } } return null; }
[ "public", "Binary", "getBinaryById", "(", "int", "id", ")", "{", "for", "(", "Binary", "binary", ":", "binaryList", ")", "{", "if", "(", "binary", ".", "getId", "(", ")", "==", "id", ")", "{", "return", "binary", ";", "}", "}", "return", "null", ";", "}" ]
Retrieves a binary item based on its id. @param id the id which should be searched @return the binary item if found, null otherwise
[ "Retrieves", "a", "binary", "item", "based", "on", "its", "id", "." ]
4a354aecaea38af3c0dce5eb81b533f297e8d94f
https://github.com/cternes/openkeepass/blob/4a354aecaea38af3c0dce5eb81b533f297e8d94f/src/main/java/de/slackspace/openkeepass/domain/Binaries.java#L41-L49
944
janvanbesien/java-ipv6
src/main/java/com/googlecode/ipv6/IPv6AddressRange.java
IPv6AddressRange.extend
public IPv6AddressRange extend(IPv6Address address) { if (address.compareTo(first) < 0) return fromFirstAndLast(address, last); else if (address.compareTo(last) > 0) return fromFirstAndLast(first, address); else return this; }
java
public IPv6AddressRange extend(IPv6Address address) { if (address.compareTo(first) < 0) return fromFirstAndLast(address, last); else if (address.compareTo(last) > 0) return fromFirstAndLast(first, address); else return this; }
[ "public", "IPv6AddressRange", "extend", "(", "IPv6Address", "address", ")", "{", "if", "(", "address", ".", "compareTo", "(", "first", ")", "<", "0", ")", "return", "fromFirstAndLast", "(", "address", ",", "last", ")", ";", "else", "if", "(", "address", ".", "compareTo", "(", "last", ")", ">", "0", ")", "return", "fromFirstAndLast", "(", "first", ",", "address", ")", ";", "else", "return", "this", ";", "}" ]
Extend the range just enough at its head or tail such that the given address is included. @param address address to extend the range to @return new (bigger) range
[ "Extend", "the", "range", "just", "enough", "at", "its", "head", "or", "tail", "such", "that", "the", "given", "address", "is", "included", "." ]
9af15b4a6c0074f9fa23dfa030027c631b9c2f78
https://github.com/janvanbesien/java-ipv6/blob/9af15b4a6c0074f9fa23dfa030027c631b9c2f78/src/main/java/com/googlecode/ipv6/IPv6AddressRange.java#L131-L139
945
cternes/openkeepass
src/main/java/de/slackspace/openkeepass/domain/EntryBuilder.java
EntryBuilder.buildWithHistory
public Entry buildWithHistory() { if (originalEntry == null) { throw new IllegalArgumentException("originalEntry is not set"); } if (history == null) { history = new History(); } Entry entryWithoutHistory = new EntryBuilder(originalEntry).history(new History()).build(); history.getHistoricEntries().add(entryWithoutHistory); return build(); }
java
public Entry buildWithHistory() { if (originalEntry == null) { throw new IllegalArgumentException("originalEntry is not set"); } if (history == null) { history = new History(); } Entry entryWithoutHistory = new EntryBuilder(originalEntry).history(new History()).build(); history.getHistoricEntries().add(entryWithoutHistory); return build(); }
[ "public", "Entry", "buildWithHistory", "(", ")", "{", "if", "(", "originalEntry", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"originalEntry is not set\"", ")", ";", "}", "if", "(", "history", "==", "null", ")", "{", "history", "=", "new", "History", "(", ")", ";", "}", "Entry", "entryWithoutHistory", "=", "new", "EntryBuilder", "(", "originalEntry", ")", ".", "history", "(", "new", "History", "(", ")", ")", ".", "build", "(", ")", ";", "history", ".", "getHistoricEntries", "(", ")", ".", "add", "(", "entryWithoutHistory", ")", ";", "return", "build", "(", ")", ";", "}" ]
Builds a new entry and place the original one in the history list. @return the new entry.
[ "Builds", "a", "new", "entry", "and", "place", "the", "original", "one", "in", "the", "history", "list", "." ]
4a354aecaea38af3c0dce5eb81b533f297e8d94f
https://github.com/cternes/openkeepass/blob/4a354aecaea38af3c0dce5eb81b533f297e8d94f/src/main/java/de/slackspace/openkeepass/domain/EntryBuilder.java#L200-L212
946
cternes/openkeepass
src/main/java/de/slackspace/openkeepass/domain/CustomIcons.java
CustomIcons.getIconByUuid
public CustomIcon getIconByUuid(UUID uuid) { for (CustomIcon customIcon : customIconList) { if (customIcon.getUuid() != null && customIcon.getUuid().compareTo(uuid) == 0) { return customIcon; } } return null; }
java
public CustomIcon getIconByUuid(UUID uuid) { for (CustomIcon customIcon : customIconList) { if (customIcon.getUuid() != null && customIcon.getUuid().compareTo(uuid) == 0) { return customIcon; } } return null; }
[ "public", "CustomIcon", "getIconByUuid", "(", "UUID", "uuid", ")", "{", "for", "(", "CustomIcon", "customIcon", ":", "customIconList", ")", "{", "if", "(", "customIcon", ".", "getUuid", "(", ")", "!=", "null", "&&", "customIcon", ".", "getUuid", "(", ")", ".", "compareTo", "(", "uuid", ")", "==", "0", ")", "{", "return", "customIcon", ";", "}", "}", "return", "null", ";", "}" ]
Retrieves a custom icon based on its uuid. @param uuid the uuid which should be searched @return the custom icon if found, null otherwise
[ "Retrieves", "a", "custom", "icon", "based", "on", "its", "uuid", "." ]
4a354aecaea38af3c0dce5eb81b533f297e8d94f
https://github.com/cternes/openkeepass/blob/4a354aecaea38af3c0dce5eb81b533f297e8d94f/src/main/java/de/slackspace/openkeepass/domain/CustomIcons.java#L43-L51
947
janvanbesien/java-ipv6
src/main/java/com/googlecode/ipv6/IPv6AddressPool.java
IPv6AddressPool.allocate
public IPv6AddressPool allocate() { if (!isExhausted()) { // get the first range of free subnets, and take the first subnet of that range final IPv6AddressRange firstFreeRange = freeRanges.first(); final IPv6Network allocated = IPv6Network.fromAddressAndMask(firstFreeRange.getFirst(), allocationSubnetSize); return doAllocate(allocated, firstFreeRange); } else { // exhausted return null; } }
java
public IPv6AddressPool allocate() { if (!isExhausted()) { // get the first range of free subnets, and take the first subnet of that range final IPv6AddressRange firstFreeRange = freeRanges.first(); final IPv6Network allocated = IPv6Network.fromAddressAndMask(firstFreeRange.getFirst(), allocationSubnetSize); return doAllocate(allocated, firstFreeRange); } else { // exhausted return null; } }
[ "public", "IPv6AddressPool", "allocate", "(", ")", "{", "if", "(", "!", "isExhausted", "(", ")", ")", "{", "// get the first range of free subnets, and take the first subnet of that range", "final", "IPv6AddressRange", "firstFreeRange", "=", "freeRanges", ".", "first", "(", ")", ";", "final", "IPv6Network", "allocated", "=", "IPv6Network", ".", "fromAddressAndMask", "(", "firstFreeRange", ".", "getFirst", "(", ")", ",", "allocationSubnetSize", ")", ";", "return", "doAllocate", "(", "allocated", ",", "firstFreeRange", ")", ";", "}", "else", "{", "// exhausted", "return", "null", ";", "}", "}" ]
Allocate the first available subnet from the pool. @return resulting pool
[ "Allocate", "the", "first", "available", "subnet", "from", "the", "pool", "." ]
9af15b4a6c0074f9fa23dfa030027c631b9c2f78
https://github.com/janvanbesien/java-ipv6/blob/9af15b4a6c0074f9fa23dfa030027c631b9c2f78/src/main/java/com/googlecode/ipv6/IPv6AddressPool.java#L128-L143
948
janvanbesien/java-ipv6
src/main/java/com/googlecode/ipv6/IPv6AddressPool.java
IPv6AddressPool.allocate
public IPv6AddressPool allocate(IPv6Network toAllocate) { if (!contains(toAllocate)) throw new IllegalArgumentException( "can not allocate network which is not contained in the pool to allocate from [" + toAllocate + "]"); if (!this.allocationSubnetSize.equals(toAllocate.getNetmask())) throw new IllegalArgumentException( "can not allocate network with prefix length /" + toAllocate.getNetmask().asPrefixLength() + " from a pool configured to hand out subnets with prefix length /" + allocationSubnetSize); // go find the range that contains the requested subnet final IPv6AddressRange rangeToAllocateFrom = findFreeRangeContaining(toAllocate); if (rangeToAllocateFrom != null) { // found a range in which this subnet is free, allocate it return doAllocate(toAllocate, rangeToAllocateFrom); } else { // requested subnet not free return null; } }
java
public IPv6AddressPool allocate(IPv6Network toAllocate) { if (!contains(toAllocate)) throw new IllegalArgumentException( "can not allocate network which is not contained in the pool to allocate from [" + toAllocate + "]"); if (!this.allocationSubnetSize.equals(toAllocate.getNetmask())) throw new IllegalArgumentException( "can not allocate network with prefix length /" + toAllocate.getNetmask().asPrefixLength() + " from a pool configured to hand out subnets with prefix length /" + allocationSubnetSize); // go find the range that contains the requested subnet final IPv6AddressRange rangeToAllocateFrom = findFreeRangeContaining(toAllocate); if (rangeToAllocateFrom != null) { // found a range in which this subnet is free, allocate it return doAllocate(toAllocate, rangeToAllocateFrom); } else { // requested subnet not free return null; } }
[ "public", "IPv6AddressPool", "allocate", "(", "IPv6Network", "toAllocate", ")", "{", "if", "(", "!", "contains", "(", "toAllocate", ")", ")", "throw", "new", "IllegalArgumentException", "(", "\"can not allocate network which is not contained in the pool to allocate from [\"", "+", "toAllocate", "+", "\"]\"", ")", ";", "if", "(", "!", "this", ".", "allocationSubnetSize", ".", "equals", "(", "toAllocate", ".", "getNetmask", "(", ")", ")", ")", "throw", "new", "IllegalArgumentException", "(", "\"can not allocate network with prefix length /\"", "+", "toAllocate", ".", "getNetmask", "(", ")", ".", "asPrefixLength", "(", ")", "+", "\" from a pool configured to hand out subnets with prefix length /\"", "+", "allocationSubnetSize", ")", ";", "// go find the range that contains the requested subnet", "final", "IPv6AddressRange", "rangeToAllocateFrom", "=", "findFreeRangeContaining", "(", "toAllocate", ")", ";", "if", "(", "rangeToAllocateFrom", "!=", "null", ")", "{", "// found a range in which this subnet is free, allocate it", "return", "doAllocate", "(", "toAllocate", ",", "rangeToAllocateFrom", ")", ";", "}", "else", "{", "// requested subnet not free", "return", "null", ";", "}", "}" ]
Allocate the given subnet from the pool. @param toAllocate subnet to allocate from the pool @return resulting pool
[ "Allocate", "the", "given", "subnet", "from", "the", "pool", "." ]
9af15b4a6c0074f9fa23dfa030027c631b9c2f78
https://github.com/janvanbesien/java-ipv6/blob/9af15b4a6c0074f9fa23dfa030027c631b9c2f78/src/main/java/com/googlecode/ipv6/IPv6AddressPool.java#L151-L176
949
janvanbesien/java-ipv6
src/main/java/com/googlecode/ipv6/IPv6AddressPool.java
IPv6AddressPool.doAllocate
private IPv6AddressPool doAllocate(final IPv6Network toAllocate, final IPv6AddressRange rangeToAllocateFrom) { assert freeRanges.contains(rangeToAllocateFrom); assert rangeToAllocateFrom.contains(toAllocate); final TreeSet<IPv6AddressRange> newFreeRanges = new TreeSet<IPv6AddressRange>(this.freeRanges); // remove range from free ranges newFreeRanges.remove(rangeToAllocateFrom); // from the range, remove the allocated subnet final List<IPv6AddressRange> newRanges = rangeToAllocateFrom.remove(toAllocate); // and add the resulting ranges as new free ranges newFreeRanges.addAll(newRanges); return new IPv6AddressPool(underlyingRange, allocationSubnetSize, newFreeRanges, toAllocate); }
java
private IPv6AddressPool doAllocate(final IPv6Network toAllocate, final IPv6AddressRange rangeToAllocateFrom) { assert freeRanges.contains(rangeToAllocateFrom); assert rangeToAllocateFrom.contains(toAllocate); final TreeSet<IPv6AddressRange> newFreeRanges = new TreeSet<IPv6AddressRange>(this.freeRanges); // remove range from free ranges newFreeRanges.remove(rangeToAllocateFrom); // from the range, remove the allocated subnet final List<IPv6AddressRange> newRanges = rangeToAllocateFrom.remove(toAllocate); // and add the resulting ranges as new free ranges newFreeRanges.addAll(newRanges); return new IPv6AddressPool(underlyingRange, allocationSubnetSize, newFreeRanges, toAllocate); }
[ "private", "IPv6AddressPool", "doAllocate", "(", "final", "IPv6Network", "toAllocate", ",", "final", "IPv6AddressRange", "rangeToAllocateFrom", ")", "{", "assert", "freeRanges", ".", "contains", "(", "rangeToAllocateFrom", ")", ";", "assert", "rangeToAllocateFrom", ".", "contains", "(", "toAllocate", ")", ";", "final", "TreeSet", "<", "IPv6AddressRange", ">", "newFreeRanges", "=", "new", "TreeSet", "<", "IPv6AddressRange", ">", "(", "this", ".", "freeRanges", ")", ";", "// remove range from free ranges", "newFreeRanges", ".", "remove", "(", "rangeToAllocateFrom", ")", ";", "// from the range, remove the allocated subnet", "final", "List", "<", "IPv6AddressRange", ">", "newRanges", "=", "rangeToAllocateFrom", ".", "remove", "(", "toAllocate", ")", ";", "// and add the resulting ranges as new free ranges", "newFreeRanges", ".", "addAll", "(", "newRanges", ")", ";", "return", "new", "IPv6AddressPool", "(", "underlyingRange", ",", "allocationSubnetSize", ",", "newFreeRanges", ",", "toAllocate", ")", ";", "}" ]
Private helper method to perform the allocation of a subnet within one of the free ranges. @param toAllocate subnet to allocate @param rangeToAllocateFrom free range to allocate from @return resulting pool
[ "Private", "helper", "method", "to", "perform", "the", "allocation", "of", "a", "subnet", "within", "one", "of", "the", "free", "ranges", "." ]
9af15b4a6c0074f9fa23dfa030027c631b9c2f78
https://github.com/janvanbesien/java-ipv6/blob/9af15b4a6c0074f9fa23dfa030027c631b9c2f78/src/main/java/com/googlecode/ipv6/IPv6AddressPool.java#L206-L223
950
janvanbesien/java-ipv6
src/main/java/com/googlecode/ipv6/IPv6AddressPool.java
IPv6AddressPool.findFreeRangeBefore
private IPv6AddressRange findFreeRangeBefore(IPv6Network network) { for (IPv6AddressRange freeRange : freeRanges) { if (freeRange.getLast().add(1).equals(network.getFirst())) { return freeRange; } } // not found return null; }
java
private IPv6AddressRange findFreeRangeBefore(IPv6Network network) { for (IPv6AddressRange freeRange : freeRanges) { if (freeRange.getLast().add(1).equals(network.getFirst())) { return freeRange; } } // not found return null; }
[ "private", "IPv6AddressRange", "findFreeRangeBefore", "(", "IPv6Network", "network", ")", "{", "for", "(", "IPv6AddressRange", "freeRange", ":", "freeRanges", ")", "{", "if", "(", "freeRange", ".", "getLast", "(", ")", ".", "add", "(", "1", ")", ".", "equals", "(", "network", ".", "getFirst", "(", ")", ")", ")", "{", "return", "freeRange", ";", "}", "}", "// not found", "return", "null", ";", "}" ]
Private helper method to find the free range just before the given network.
[ "Private", "helper", "method", "to", "find", "the", "free", "range", "just", "before", "the", "given", "network", "." ]
9af15b4a6c0074f9fa23dfa030027c631b9c2f78
https://github.com/janvanbesien/java-ipv6/blob/9af15b4a6c0074f9fa23dfa030027c631b9c2f78/src/main/java/com/googlecode/ipv6/IPv6AddressPool.java#L279-L291
951
janvanbesien/java-ipv6
src/main/java/com/googlecode/ipv6/IPv6AddressPool.java
IPv6AddressPool.findFreeRangeAfter
private IPv6AddressRange findFreeRangeAfter(IPv6Network network) { for (IPv6AddressRange freeRange : freeRanges) { if (freeRange.getFirst().subtract(1).equals(network.getLast())) { return freeRange; } } // not found return null; }
java
private IPv6AddressRange findFreeRangeAfter(IPv6Network network) { for (IPv6AddressRange freeRange : freeRanges) { if (freeRange.getFirst().subtract(1).equals(network.getLast())) { return freeRange; } } // not found return null; }
[ "private", "IPv6AddressRange", "findFreeRangeAfter", "(", "IPv6Network", "network", ")", "{", "for", "(", "IPv6AddressRange", "freeRange", ":", "freeRanges", ")", "{", "if", "(", "freeRange", ".", "getFirst", "(", ")", ".", "subtract", "(", "1", ")", ".", "equals", "(", "network", ".", "getLast", "(", ")", ")", ")", "{", "return", "freeRange", ";", "}", "}", "// not found", "return", "null", ";", "}" ]
Private helper method to find the free range just after the given address.
[ "Private", "helper", "method", "to", "find", "the", "free", "range", "just", "after", "the", "given", "address", "." ]
9af15b4a6c0074f9fa23dfa030027c631b9c2f78
https://github.com/janvanbesien/java-ipv6/blob/9af15b4a6c0074f9fa23dfa030027c631b9c2f78/src/main/java/com/googlecode/ipv6/IPv6AddressPool.java#L296-L308
952
cternes/openkeepass
src/main/java/de/slackspace/openkeepass/domain/zipper/GroupZipper.java
GroupZipper.canRight
public boolean canRight() { if (parent == null) { return false; } if (index + 1 >= parent.getNode().getGroups().size()) { return false; } return true; }
java
public boolean canRight() { if (parent == null) { return false; } if (index + 1 >= parent.getNode().getGroups().size()) { return false; } return true; }
[ "public", "boolean", "canRight", "(", ")", "{", "if", "(", "parent", "==", "null", ")", "{", "return", "false", ";", "}", "if", "(", "index", "+", "1", ">=", "parent", ".", "getNode", "(", ")", ".", "getGroups", "(", ")", ".", "size", "(", ")", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}" ]
Returns true if it is possible to navigate right. @return true, if it is possible to navigate right
[ "Returns", "true", "if", "it", "is", "possible", "to", "navigate", "right", "." ]
4a354aecaea38af3c0dce5eb81b533f297e8d94f
https://github.com/cternes/openkeepass/blob/4a354aecaea38af3c0dce5eb81b533f297e8d94f/src/main/java/de/slackspace/openkeepass/domain/zipper/GroupZipper.java#L129-L139
953
cternes/openkeepass
src/main/java/de/slackspace/openkeepass/domain/zipper/GroupZipper.java
GroupZipper.right
public GroupZipper right() { if (!canRight()) { throw new NoSuchElementException("Could not move right because the last node at this level has already been reached"); } index++; node = parent.getNode().getGroups().get(index); return this; }
java
public GroupZipper right() { if (!canRight()) { throw new NoSuchElementException("Could not move right because the last node at this level has already been reached"); } index++; node = parent.getNode().getGroups().get(index); return this; }
[ "public", "GroupZipper", "right", "(", ")", "{", "if", "(", "!", "canRight", "(", ")", ")", "{", "throw", "new", "NoSuchElementException", "(", "\"Could not move right because the last node at this level has already been reached\"", ")", ";", "}", "index", "++", ";", "node", "=", "parent", ".", "getNode", "(", ")", ".", "getGroups", "(", ")", ".", "get", "(", "index", ")", ";", "return", "this", ";", "}" ]
Navigates right the tree to the next node at the same level. @return a new groupzipper which points to next node at the same level @throws NoSuchElementException if the last node at the current level has already been reached
[ "Navigates", "right", "the", "tree", "to", "the", "next", "node", "at", "the", "same", "level", "." ]
4a354aecaea38af3c0dce5eb81b533f297e8d94f
https://github.com/cternes/openkeepass/blob/4a354aecaea38af3c0dce5eb81b533f297e8d94f/src/main/java/de/slackspace/openkeepass/domain/zipper/GroupZipper.java#L149-L158
954
cternes/openkeepass
src/main/java/de/slackspace/openkeepass/domain/zipper/GroupZipper.java
GroupZipper.left
public GroupZipper left() { if (!canLeft()) { throw new NoSuchElementException("Could not move left because the first node at this level has already been reached"); } index--; node = parent.getNode().getGroups().get(index); return this; }
java
public GroupZipper left() { if (!canLeft()) { throw new NoSuchElementException("Could not move left because the first node at this level has already been reached"); } index--; node = parent.getNode().getGroups().get(index); return this; }
[ "public", "GroupZipper", "left", "(", ")", "{", "if", "(", "!", "canLeft", "(", ")", ")", "{", "throw", "new", "NoSuchElementException", "(", "\"Could not move left because the first node at this level has already been reached\"", ")", ";", "}", "index", "--", ";", "node", "=", "parent", ".", "getNode", "(", ")", ".", "getGroups", "(", ")", ".", "get", "(", "index", ")", ";", "return", "this", ";", "}" ]
Navigates left the tree to the previous node at the same level. @return a new groupzipper which points to the previous node at the same level @throws NoSuchElementException if the first node at the current level has already been reached
[ "Navigates", "left", "the", "tree", "to", "the", "previous", "node", "at", "the", "same", "level", "." ]
4a354aecaea38af3c0dce5eb81b533f297e8d94f
https://github.com/cternes/openkeepass/blob/4a354aecaea38af3c0dce5eb81b533f297e8d94f/src/main/java/de/slackspace/openkeepass/domain/zipper/GroupZipper.java#L182-L191
955
hgoebl/simplify-java
src/main/java/com/goebl/simplify/AbstractSimplify.java
AbstractSimplify.simplify
public T[] simplify(T[] points, double tolerance, boolean highestQuality) { if (points == null || points.length <= 2) { return points; } double sqTolerance = tolerance * tolerance; if (!highestQuality) { points = simplifyRadialDistance(points, sqTolerance); } points = simplifyDouglasPeucker(points, sqTolerance); return points; }
java
public T[] simplify(T[] points, double tolerance, boolean highestQuality) { if (points == null || points.length <= 2) { return points; } double sqTolerance = tolerance * tolerance; if (!highestQuality) { points = simplifyRadialDistance(points, sqTolerance); } points = simplifyDouglasPeucker(points, sqTolerance); return points; }
[ "public", "T", "[", "]", "simplify", "(", "T", "[", "]", "points", ",", "double", "tolerance", ",", "boolean", "highestQuality", ")", "{", "if", "(", "points", "==", "null", "||", "points", ".", "length", "<=", "2", ")", "{", "return", "points", ";", "}", "double", "sqTolerance", "=", "tolerance", "*", "tolerance", ";", "if", "(", "!", "highestQuality", ")", "{", "points", "=", "simplifyRadialDistance", "(", "points", ",", "sqTolerance", ")", ";", "}", "points", "=", "simplifyDouglasPeucker", "(", "points", ",", "sqTolerance", ")", ";", "return", "points", ";", "}" ]
Simplifies a list of points to a shorter list of points. @param points original list of points @param tolerance tolerance in the same measurement as the point coordinates @param highestQuality <tt>true</tt> for using Douglas-Peucker only, <tt>false</tt> for using Radial-Distance algorithm before applying Douglas-Peucker (should be a bit faster) @return simplified list of points
[ "Simplifies", "a", "list", "of", "points", "to", "a", "shorter", "list", "of", "points", "." ]
6b12ca1ae10f4ea01f0290d8c7f926f155809221
https://github.com/hgoebl/simplify-java/blob/6b12ca1ae10f4ea01f0290d8c7f926f155809221/src/main/java/com/goebl/simplify/AbstractSimplify.java#L30-L47
956
smartcat-labs/cassandra-migration-tool-java
src/main/java/io/smartcat/migration/Executor.java
Executor.migrate
public static boolean migrate(final Session session, final MigrationResources resources) { return MigrationEngine.withSession(session).migrate(resources); }
java
public static boolean migrate(final Session session, final MigrationResources resources) { return MigrationEngine.withSession(session).migrate(resources); }
[ "public", "static", "boolean", "migrate", "(", "final", "Session", "session", ",", "final", "MigrationResources", "resources", ")", "{", "return", "MigrationEngine", ".", "withSession", "(", "session", ")", ".", "migrate", "(", "resources", ")", ";", "}" ]
Execute all migrations in migration resource collection. @param session Datastax driver sesison object @param resources Migration resources collection @return Return success
[ "Execute", "all", "migrations", "in", "migration", "resource", "collection", "." ]
790a0580770fba707d31e0c767d380707c6da3fc
https://github.com/smartcat-labs/cassandra-migration-tool-java/blob/790a0580770fba707d31e0c767d380707c6da3fc/src/main/java/io/smartcat/migration/Executor.java#L20-L22
957
smartcat-labs/cassandra-migration-tool-java
src/main/java/io/smartcat/migration/CassandraVersioner.java
CassandraVersioner.getCurrentVersion
public int getCurrentVersion(final MigrationType type) { final Statement select = QueryBuilder.select().all().from(SCHEMA_VERSION_CF) .where(QueryBuilder.eq(TYPE, type.name())).limit(1).setConsistencyLevel(ConsistencyLevel.ALL); final ResultSet result = session.execute(select); final Row row = result.one(); return row == null ? 0 : row.getInt(VERSION); }
java
public int getCurrentVersion(final MigrationType type) { final Statement select = QueryBuilder.select().all().from(SCHEMA_VERSION_CF) .where(QueryBuilder.eq(TYPE, type.name())).limit(1).setConsistencyLevel(ConsistencyLevel.ALL); final ResultSet result = session.execute(select); final Row row = result.one(); return row == null ? 0 : row.getInt(VERSION); }
[ "public", "int", "getCurrentVersion", "(", "final", "MigrationType", "type", ")", "{", "final", "Statement", "select", "=", "QueryBuilder", ".", "select", "(", ")", ".", "all", "(", ")", ".", "from", "(", "SCHEMA_VERSION_CF", ")", ".", "where", "(", "QueryBuilder", ".", "eq", "(", "TYPE", ",", "type", ".", "name", "(", ")", ")", ")", ".", "limit", "(", "1", ")", ".", "setConsistencyLevel", "(", "ConsistencyLevel", ".", "ALL", ")", ";", "final", "ResultSet", "result", "=", "session", ".", "execute", "(", "select", ")", ";", "final", "Row", "row", "=", "result", ".", "one", "(", ")", ";", "return", "row", "==", "null", "?", "0", ":", "row", ".", "getInt", "(", "VERSION", ")", ";", "}" ]
Get current database version for given migration type with ALL consistency. Select one row since migration history is saved ordered descending by timestamp. If there are no rows in the schema_version table, return 0 as default database version. Data version is changed by executing migrations. @param type Migration type @return Database version for given type
[ "Get", "current", "database", "version", "for", "given", "migration", "type", "with", "ALL", "consistency", ".", "Select", "one", "row", "since", "migration", "history", "is", "saved", "ordered", "descending", "by", "timestamp", ".", "If", "there", "are", "no", "rows", "in", "the", "schema_version", "table", "return", "0", "as", "default", "database", "version", ".", "Data", "version", "is", "changed", "by", "executing", "migrations", "." ]
790a0580770fba707d31e0c767d380707c6da3fc
https://github.com/smartcat-labs/cassandra-migration-tool-java/blob/790a0580770fba707d31e0c767d380707c6da3fc/src/main/java/io/smartcat/migration/CassandraVersioner.java#L60-L67
958
smartcat-labs/cassandra-migration-tool-java
src/main/java/io/smartcat/migration/CassandraVersioner.java
CassandraVersioner.updateVersion
public boolean updateVersion(final Migration migration) { final Statement insert = QueryBuilder.insertInto(SCHEMA_VERSION_CF).value(TYPE, migration.getType().name()) .value(VERSION, migration.getVersion()).value(TIMESTAMP, System.currentTimeMillis()) .value(DESCRIPTION, migration.getDescription()).setConsistencyLevel(ConsistencyLevel.ALL); try { session.execute(insert); return true; } catch (final Exception e) { LOGGER.error("Failed to execute update version statement", e); return false; } }
java
public boolean updateVersion(final Migration migration) { final Statement insert = QueryBuilder.insertInto(SCHEMA_VERSION_CF).value(TYPE, migration.getType().name()) .value(VERSION, migration.getVersion()).value(TIMESTAMP, System.currentTimeMillis()) .value(DESCRIPTION, migration.getDescription()).setConsistencyLevel(ConsistencyLevel.ALL); try { session.execute(insert); return true; } catch (final Exception e) { LOGGER.error("Failed to execute update version statement", e); return false; } }
[ "public", "boolean", "updateVersion", "(", "final", "Migration", "migration", ")", "{", "final", "Statement", "insert", "=", "QueryBuilder", ".", "insertInto", "(", "SCHEMA_VERSION_CF", ")", ".", "value", "(", "TYPE", ",", "migration", ".", "getType", "(", ")", ".", "name", "(", ")", ")", ".", "value", "(", "VERSION", ",", "migration", ".", "getVersion", "(", ")", ")", ".", "value", "(", "TIMESTAMP", ",", "System", ".", "currentTimeMillis", "(", ")", ")", ".", "value", "(", "DESCRIPTION", ",", "migration", ".", "getDescription", "(", ")", ")", ".", "setConsistencyLevel", "(", "ConsistencyLevel", ".", "ALL", ")", ";", "try", "{", "session", ".", "execute", "(", "insert", ")", ";", "return", "true", ";", "}", "catch", "(", "final", "Exception", "e", ")", "{", "LOGGER", ".", "error", "(", "\"Failed to execute update version statement\"", ",", "e", ")", ";", "return", "false", ";", "}", "}" ]
Update current database version to the migration version. This is executed after migration success. @param migration Migration that updated the database version @return Success of version update
[ "Update", "current", "database", "version", "to", "the", "migration", "version", ".", "This", "is", "executed", "after", "migration", "success", "." ]
790a0580770fba707d31e0c767d380707c6da3fc
https://github.com/smartcat-labs/cassandra-migration-tool-java/blob/790a0580770fba707d31e0c767d380707c6da3fc/src/main/java/io/smartcat/migration/CassandraVersioner.java#L75-L87
959
smartcat-labs/cassandra-migration-tool-java
src/main/java/io/smartcat/migration/Migration.java
Migration.executeWithSchemaAgreement
protected void executeWithSchemaAgreement(Statement statement) throws SchemaAgreementException { ResultSet result = this.session.execute(statement); if (checkSchemaAgreement(result)) { return; } if (checkClusterSchemaAgreement()) { return; } throw new SchemaAgreementException( "Failed to propagate schema update to all nodes (schema agreement error)"); }
java
protected void executeWithSchemaAgreement(Statement statement) throws SchemaAgreementException { ResultSet result = this.session.execute(statement); if (checkSchemaAgreement(result)) { return; } if (checkClusterSchemaAgreement()) { return; } throw new SchemaAgreementException( "Failed to propagate schema update to all nodes (schema agreement error)"); }
[ "protected", "void", "executeWithSchemaAgreement", "(", "Statement", "statement", ")", "throws", "SchemaAgreementException", "{", "ResultSet", "result", "=", "this", ".", "session", ".", "execute", "(", "statement", ")", ";", "if", "(", "checkSchemaAgreement", "(", "result", ")", ")", "{", "return", ";", "}", "if", "(", "checkClusterSchemaAgreement", "(", ")", ")", "{", "return", ";", "}", "throw", "new", "SchemaAgreementException", "(", "\"Failed to propagate schema update to all nodes (schema agreement error)\"", ")", ";", "}" ]
Execute provided statement and checks if the schema migration has been propagated to all nodes in the cluster. Use this method when executing schema migrations. @param statement Statement to be executed @throws SchemaAgreementException exception
[ "Execute", "provided", "statement", "and", "checks", "if", "the", "schema", "migration", "has", "been", "propagated", "to", "all", "nodes", "in", "the", "cluster", ".", "Use", "this", "method", "when", "executing", "schema", "migrations", "." ]
790a0580770fba707d31e0c767d380707c6da3fc
https://github.com/smartcat-labs/cassandra-migration-tool-java/blob/790a0580770fba707d31e0c767d380707c6da3fc/src/main/java/io/smartcat/migration/Migration.java#L75-L87
960
microfocus-idol/haven-search-components
hod/src/main/java/com/hp/autonomy/searchcomponents/hod/beanconfiguration/HodAuthenticationConfiguration.java
HodAuthenticationConfiguration.authenticationInformationRetriever
@Bean @ConditionalOnMissingBean(AuthenticationInformationRetriever.class) public AuthenticationInformationRetriever<HodAuthentication<EntityType.Combined>, HodAuthenticationPrincipal> authenticationInformationRetriever() { @SuppressWarnings("unchecked") final AuthenticationInformationRetriever<HodAuthentication<EntityType.Combined>, HodAuthenticationPrincipal> retriever = new SpringSecurityAuthenticationInformationRetriever<>((Class<HodAuthentication<EntityType.Combined>>) (Class<?>) HodAuthentication.class, HodAuthenticationPrincipal.class); return retriever; }
java
@Bean @ConditionalOnMissingBean(AuthenticationInformationRetriever.class) public AuthenticationInformationRetriever<HodAuthentication<EntityType.Combined>, HodAuthenticationPrincipal> authenticationInformationRetriever() { @SuppressWarnings("unchecked") final AuthenticationInformationRetriever<HodAuthentication<EntityType.Combined>, HodAuthenticationPrincipal> retriever = new SpringSecurityAuthenticationInformationRetriever<>((Class<HodAuthentication<EntityType.Combined>>) (Class<?>) HodAuthentication.class, HodAuthenticationPrincipal.class); return retriever; }
[ "@", "Bean", "@", "ConditionalOnMissingBean", "(", "AuthenticationInformationRetriever", ".", "class", ")", "public", "AuthenticationInformationRetriever", "<", "HodAuthentication", "<", "EntityType", ".", "Combined", ">", ",", "HodAuthenticationPrincipal", ">", "authenticationInformationRetriever", "(", ")", "{", "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "final", "AuthenticationInformationRetriever", "<", "HodAuthentication", "<", "EntityType", ".", "Combined", ">", ",", "HodAuthenticationPrincipal", ">", "retriever", "=", "new", "SpringSecurityAuthenticationInformationRetriever", "<>", "(", "(", "Class", "<", "HodAuthentication", "<", "EntityType", ".", "Combined", ">", ">", ")", "(", "Class", "<", "?", ">", ")", "HodAuthentication", ".", "class", ",", "HodAuthenticationPrincipal", ".", "class", ")", ";", "return", "retriever", ";", "}" ]
Note that this bean cannot go in HavenSearchHodApplication because it would then cause a circular dependency in upstream applications
[ "Note", "that", "this", "bean", "cannot", "go", "in", "HavenSearchHodApplication", "because", "it", "would", "then", "cause", "a", "circular", "dependency", "in", "upstream", "applications" ]
6f5df74ba67ec0d3f86e73bc1dd0d6edd01a8e44
https://github.com/microfocus-idol/haven-search-components/blob/6f5df74ba67ec0d3f86e73bc1dd0d6edd01a8e44/hod/src/main/java/com/hp/autonomy/searchcomponents/hod/beanconfiguration/HodAuthenticationConfiguration.java#L20-L27
961
phax/ph-db
ph-db-jpa/src/main/java/com/helger/db/jpa/JPAEnabledManager.java
JPAEnabledManager.doSelectStatic
@Nonnull public static final <T> JPAExecutionResult <T> doSelectStatic (@Nonnull final Callable <T> aCallable) { ValueEnforcer.notNull (aCallable, "Callable"); final StopWatch aSW = StopWatch.createdStarted (); try { // Call callback final T ret = aCallable.call (); s_aStatsCounterSuccess.increment (); s_aStatsTimerExecutionSuccess.addTime (aSW.stopAndGetMillis ()); return JPAExecutionResult.createSuccess (ret); } catch (final Exception ex) { s_aStatsCounterError.increment (); s_aStatsTimerExecutionError.addTime (aSW.stopAndGetMillis ()); _invokeCustomExceptionCallback (ex); return JPAExecutionResult.<T> createFailure (ex); } finally { if (isDefaultExecutionWarnTimeEnabled ()) if (aSW.getMillis () > getDefaultExecutionWarnTime ()) onExecutionTimeExceeded ("Execution of select took too long: " + aCallable.toString (), aSW.getMillis ()); } }
java
@Nonnull public static final <T> JPAExecutionResult <T> doSelectStatic (@Nonnull final Callable <T> aCallable) { ValueEnforcer.notNull (aCallable, "Callable"); final StopWatch aSW = StopWatch.createdStarted (); try { // Call callback final T ret = aCallable.call (); s_aStatsCounterSuccess.increment (); s_aStatsTimerExecutionSuccess.addTime (aSW.stopAndGetMillis ()); return JPAExecutionResult.createSuccess (ret); } catch (final Exception ex) { s_aStatsCounterError.increment (); s_aStatsTimerExecutionError.addTime (aSW.stopAndGetMillis ()); _invokeCustomExceptionCallback (ex); return JPAExecutionResult.<T> createFailure (ex); } finally { if (isDefaultExecutionWarnTimeEnabled ()) if (aSW.getMillis () > getDefaultExecutionWarnTime ()) onExecutionTimeExceeded ("Execution of select took too long: " + aCallable.toString (), aSW.getMillis ()); } }
[ "@", "Nonnull", "public", "static", "final", "<", "T", ">", "JPAExecutionResult", "<", "T", ">", "doSelectStatic", "(", "@", "Nonnull", "final", "Callable", "<", "T", ">", "aCallable", ")", "{", "ValueEnforcer", ".", "notNull", "(", "aCallable", ",", "\"Callable\"", ")", ";", "final", "StopWatch", "aSW", "=", "StopWatch", ".", "createdStarted", "(", ")", ";", "try", "{", "// Call callback", "final", "T", "ret", "=", "aCallable", ".", "call", "(", ")", ";", "s_aStatsCounterSuccess", ".", "increment", "(", ")", ";", "s_aStatsTimerExecutionSuccess", ".", "addTime", "(", "aSW", ".", "stopAndGetMillis", "(", ")", ")", ";", "return", "JPAExecutionResult", ".", "createSuccess", "(", "ret", ")", ";", "}", "catch", "(", "final", "Exception", "ex", ")", "{", "s_aStatsCounterError", ".", "increment", "(", ")", ";", "s_aStatsTimerExecutionError", ".", "addTime", "(", "aSW", ".", "stopAndGetMillis", "(", ")", ")", ";", "_invokeCustomExceptionCallback", "(", "ex", ")", ";", "return", "JPAExecutionResult", ".", "<", "T", ">", "createFailure", "(", "ex", ")", ";", "}", "finally", "{", "if", "(", "isDefaultExecutionWarnTimeEnabled", "(", ")", ")", "if", "(", "aSW", ".", "getMillis", "(", ")", ">", "getDefaultExecutionWarnTime", "(", ")", ")", "onExecutionTimeExceeded", "(", "\"Execution of select took too long: \"", "+", "aCallable", ".", "toString", "(", ")", ",", "aSW", ".", "getMillis", "(", ")", ")", ";", "}", "}" ]
Perform a select, without a transaction @param aCallable The callable @return The return of the callable or <code>null</code> upon success @param <T> The return type of the callable
[ "Perform", "a", "select", "without", "a", "transaction" ]
8e04b247aead4f5e2515fa708eedc46a0a86d0e3
https://github.com/phax/ph-db/blob/8e04b247aead4f5e2515fa708eedc46a0a86d0e3/ph-db-jpa/src/main/java/com/helger/db/jpa/JPAEnabledManager.java#L395-L422
962
phax/ph-db
ph-db-jpa/src/main/java/com/helger/db/jpa/JPAEnabledManager.java
JPAEnabledManager.doSelect
@Nonnull public final <T> JPAExecutionResult <T> doSelect (@Nonnull final Callable <T> aCallable) { if (isUseTransactionsForSelect ()) { // Use transactions for select statement! return doInTransaction (aCallable); } // Ensure that only one transaction is active for all users! final EntityManager aEntityMgr = getEntityManager (); if (!isSyncEntityMgr ()) { // No synchronization required return doSelectStatic (aCallable); } // Sync on the whole entity manager, to have a cross-manager // synchronization! synchronized (aEntityMgr) { return doSelectStatic (aCallable); } }
java
@Nonnull public final <T> JPAExecutionResult <T> doSelect (@Nonnull final Callable <T> aCallable) { if (isUseTransactionsForSelect ()) { // Use transactions for select statement! return doInTransaction (aCallable); } // Ensure that only one transaction is active for all users! final EntityManager aEntityMgr = getEntityManager (); if (!isSyncEntityMgr ()) { // No synchronization required return doSelectStatic (aCallable); } // Sync on the whole entity manager, to have a cross-manager // synchronization! synchronized (aEntityMgr) { return doSelectStatic (aCallable); } }
[ "@", "Nonnull", "public", "final", "<", "T", ">", "JPAExecutionResult", "<", "T", ">", "doSelect", "(", "@", "Nonnull", "final", "Callable", "<", "T", ">", "aCallable", ")", "{", "if", "(", "isUseTransactionsForSelect", "(", ")", ")", "{", "// Use transactions for select statement!", "return", "doInTransaction", "(", "aCallable", ")", ";", "}", "// Ensure that only one transaction is active for all users!", "final", "EntityManager", "aEntityMgr", "=", "getEntityManager", "(", ")", ";", "if", "(", "!", "isSyncEntityMgr", "(", ")", ")", "{", "// No synchronization required", "return", "doSelectStatic", "(", "aCallable", ")", ";", "}", "// Sync on the whole entity manager, to have a cross-manager", "// synchronization!", "synchronized", "(", "aEntityMgr", ")", "{", "return", "doSelectStatic", "(", "aCallable", ")", ";", "}", "}" ]
Run a read-only query. By default no transaction is used, and the entity manager is synchronized. @param aCallable The callable to execute. @return A non-<code>null</code> result of the select. @param <T> Return type of the callable
[ "Run", "a", "read", "-", "only", "query", ".", "By", "default", "no", "transaction", "is", "used", "and", "the", "entity", "manager", "is", "synchronized", "." ]
8e04b247aead4f5e2515fa708eedc46a0a86d0e3
https://github.com/phax/ph-db/blob/8e04b247aead4f5e2515fa708eedc46a0a86d0e3/ph-db-jpa/src/main/java/com/helger/db/jpa/JPAEnabledManager.java#L434-L457
963
rapid7/conqueso-client-java
src/main/java/com/rapid7/conqueso/client/ConquesoClient.java
ConquesoClient.getPropertyValue
public String getPropertyValue(String key) { checkArgument(!Strings.isNullOrEmpty(key), "key"); String errorMessage = String.format("Failed to retrieve %s property from Conqueso server: %s", key, conquesoUrl.toExternalForm()); return readStringFromUrl("properties/" + key, errorMessage); }
java
public String getPropertyValue(String key) { checkArgument(!Strings.isNullOrEmpty(key), "key"); String errorMessage = String.format("Failed to retrieve %s property from Conqueso server: %s", key, conquesoUrl.toExternalForm()); return readStringFromUrl("properties/" + key, errorMessage); }
[ "public", "String", "getPropertyValue", "(", "String", "key", ")", "{", "checkArgument", "(", "!", "Strings", ".", "isNullOrEmpty", "(", "key", ")", ",", "\"key\"", ")", ";", "String", "errorMessage", "=", "String", ".", "format", "(", "\"Failed to retrieve %s property from Conqueso server: %s\"", ",", "key", ",", "conquesoUrl", ".", "toExternalForm", "(", ")", ")", ";", "return", "readStringFromUrl", "(", "\"properties/\"", "+", "key", ",", "errorMessage", ")", ";", "}" ]
Retrieve the latest value for the given property key from the Conqueso Server, returned as a String. @param key the property key to look up @return the latest property value @throws ConquesoCommunicationException if there's an error communicating with the Conqueso Server.
[ "Retrieve", "the", "latest", "value", "for", "the", "given", "property", "key", "from", "the", "Conqueso", "Server", "returned", "as", "a", "String", "." ]
fa4a7a6dbf67e5afe6b4f68cbc97b1929af864e2
https://github.com/rapid7/conqueso-client-java/blob/fa4a7a6dbf67e5afe6b4f68cbc97b1929af864e2/src/main/java/com/rapid7/conqueso/client/ConquesoClient.java#L419-L426
964
rapid7/conqueso-client-java
src/main/java/com/rapid7/conqueso/client/ConquesoClient.java
ConquesoClient.getRoles
public ImmutableList<RoleInfo> getRoles() { TypeReference<List<RoleInfo>> typeReference = new TypeReference<List<RoleInfo>>() { }; String errorMessage = String.format("Failed to retrieve roles from Conqueso server: %s", conquesoUrl.toExternalForm()); return ImmutableList.copyOf(readObjectFromJson(typeReference, "/api/roles", errorMessage)); }
java
public ImmutableList<RoleInfo> getRoles() { TypeReference<List<RoleInfo>> typeReference = new TypeReference<List<RoleInfo>>() { }; String errorMessage = String.format("Failed to retrieve roles from Conqueso server: %s", conquesoUrl.toExternalForm()); return ImmutableList.copyOf(readObjectFromJson(typeReference, "/api/roles", errorMessage)); }
[ "public", "ImmutableList", "<", "RoleInfo", ">", "getRoles", "(", ")", "{", "TypeReference", "<", "List", "<", "RoleInfo", ">>", "typeReference", "=", "new", "TypeReference", "<", "List", "<", "RoleInfo", ">", ">", "(", ")", "{", "}", ";", "String", "errorMessage", "=", "String", ".", "format", "(", "\"Failed to retrieve roles from Conqueso server: %s\"", ",", "conquesoUrl", ".", "toExternalForm", "(", ")", ")", ";", "return", "ImmutableList", ".", "copyOf", "(", "readObjectFromJson", "(", "typeReference", ",", "\"/api/roles\"", ",", "errorMessage", ")", ")", ";", "}" ]
Retrieve information about the roles from the Conqueso Server. @return the role information @throws ConquesoCommunicationException if there's an error communicating with the Conqueso Server.
[ "Retrieve", "information", "about", "the", "roles", "from", "the", "Conqueso", "Server", "." ]
fa4a7a6dbf67e5afe6b4f68cbc97b1929af864e2
https://github.com/rapid7/conqueso-client-java/blob/fa4a7a6dbf67e5afe6b4f68cbc97b1929af864e2/src/main/java/com/rapid7/conqueso/client/ConquesoClient.java#L433-L440
965
rapid7/conqueso-client-java
src/main/java/com/rapid7/conqueso/client/ConquesoClient.java
ConquesoClient.getRoleInstances
public ImmutableList<InstanceInfo> getRoleInstances(String roleName) { return getRoleInstancesWithMetadataImpl(roleName, Collections.<String, String>emptyMap()); }
java
public ImmutableList<InstanceInfo> getRoleInstances(String roleName) { return getRoleInstancesWithMetadataImpl(roleName, Collections.<String, String>emptyMap()); }
[ "public", "ImmutableList", "<", "InstanceInfo", ">", "getRoleInstances", "(", "String", "roleName", ")", "{", "return", "getRoleInstancesWithMetadataImpl", "(", "roleName", ",", "Collections", ".", "<", "String", ",", "String", ">", "emptyMap", "(", ")", ")", ";", "}" ]
Retrieve information about instances of a particular role from the Conqueso Server. @param roleName the role to retrieve @return the information about the instances of the given role @throws ConquesoCommunicationException if there's an error communicating with the Conqueso Server.
[ "Retrieve", "information", "about", "instances", "of", "a", "particular", "role", "from", "the", "Conqueso", "Server", "." ]
fa4a7a6dbf67e5afe6b4f68cbc97b1929af864e2
https://github.com/rapid7/conqueso-client-java/blob/fa4a7a6dbf67e5afe6b4f68cbc97b1929af864e2/src/main/java/com/rapid7/conqueso/client/ConquesoClient.java#L512-L514
966
bigdatagenomics/convert
convert/src/main/java/org/bdgenomics/convert/AbstractConverter.java
AbstractConverter.checkNotNull
protected final void checkNotNull(final ConversionStringency stringency, final Logger logger) { if (stringency == null) { throw new NullPointerException("stringency must not be null"); } if (logger == null) { throw new NullPointerException("logger must not be null"); } }
java
protected final void checkNotNull(final ConversionStringency stringency, final Logger logger) { if (stringency == null) { throw new NullPointerException("stringency must not be null"); } if (logger == null) { throw new NullPointerException("logger must not be null"); } }
[ "protected", "final", "void", "checkNotNull", "(", "final", "ConversionStringency", "stringency", ",", "final", "Logger", "logger", ")", "{", "if", "(", "stringency", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", "\"stringency must not be null\"", ")", ";", "}", "if", "(", "logger", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", "\"logger must not be null\"", ")", ";", "}", "}" ]
Check the specified conversion stringency and logger are not null. @param stringency conversion stringency, must not be null @param logger logger, must not be null @throws NullPointerException if either conversion stringency or logger are null
[ "Check", "the", "specified", "conversion", "stringency", "and", "logger", "are", "not", "null", "." ]
6bc1ddbef933742971af414cbb90fa41c1673358
https://github.com/bigdatagenomics/convert/blob/6bc1ddbef933742971af414cbb90fa41c1673358/convert/src/main/java/org/bdgenomics/convert/AbstractConverter.java#L85-L93
967
bigdatagenomics/convert
convert/src/main/java/org/bdgenomics/convert/AbstractConverter.java
AbstractConverter.warnOrThrow
protected final void warnOrThrow(final S source, final String message, final Throwable cause, final ConversionStringency stringency, final Logger logger) throws ConversionException { checkNotNull(stringency, logger); if (stringency.isLenient()) { if (cause != null) { logger.warn(String.format("could not convert %s to %s, %s", sourceClass.toString(), targetClass.toString(), message), cause); } else { logger.warn("could not convert {} to {}, {}", sourceClass.toString(), targetClass.toString(), message); } } else if (stringency.isStrict()) { throw new ConversionException(String.format("could not convert %s to %s, %s", sourceClass.toString(), targetClass.toString(), message), cause, source, sourceClass, targetClass); } }
java
protected final void warnOrThrow(final S source, final String message, final Throwable cause, final ConversionStringency stringency, final Logger logger) throws ConversionException { checkNotNull(stringency, logger); if (stringency.isLenient()) { if (cause != null) { logger.warn(String.format("could not convert %s to %s, %s", sourceClass.toString(), targetClass.toString(), message), cause); } else { logger.warn("could not convert {} to {}, {}", sourceClass.toString(), targetClass.toString(), message); } } else if (stringency.isStrict()) { throw new ConversionException(String.format("could not convert %s to %s, %s", sourceClass.toString(), targetClass.toString(), message), cause, source, sourceClass, targetClass); } }
[ "protected", "final", "void", "warnOrThrow", "(", "final", "S", "source", ",", "final", "String", "message", ",", "final", "Throwable", "cause", ",", "final", "ConversionStringency", "stringency", ",", "final", "Logger", "logger", ")", "throws", "ConversionException", "{", "checkNotNull", "(", "stringency", ",", "logger", ")", ";", "if", "(", "stringency", ".", "isLenient", "(", ")", ")", "{", "if", "(", "cause", "!=", "null", ")", "{", "logger", ".", "warn", "(", "String", ".", "format", "(", "\"could not convert %s to %s, %s\"", ",", "sourceClass", ".", "toString", "(", ")", ",", "targetClass", ".", "toString", "(", ")", ",", "message", ")", ",", "cause", ")", ";", "}", "else", "{", "logger", ".", "warn", "(", "\"could not convert {} to {}, {}\"", ",", "sourceClass", ".", "toString", "(", ")", ",", "targetClass", ".", "toString", "(", ")", ",", "message", ")", ";", "}", "}", "else", "if", "(", "stringency", ".", "isStrict", "(", ")", ")", "{", "throw", "new", "ConversionException", "(", "String", ".", "format", "(", "\"could not convert %s to %s, %s\"", ",", "sourceClass", ".", "toString", "(", ")", ",", "targetClass", ".", "toString", "(", ")", ",", "message", ")", ",", "cause", ",", "source", ",", "sourceClass", ",", "targetClass", ")", ";", "}", "}" ]
If the conversion stringency is lenient, log a warning with the specified message, or if the conversion stringency is strict, throw a ConversionException with the specified message and cause. @param source source @param message message @param cause cause @param stringency conversion stringency, must not be null @param logger logger, must not be null @throws ConversionException if the specified conversion stringency is strict @throws NullPointerException if either conversion stringency or logger are null
[ "If", "the", "conversion", "stringency", "is", "lenient", "log", "a", "warning", "with", "the", "specified", "message", "or", "if", "the", "conversion", "stringency", "is", "strict", "throw", "a", "ConversionException", "with", "the", "specified", "message", "and", "cause", "." ]
6bc1ddbef933742971af414cbb90fa41c1673358
https://github.com/bigdatagenomics/convert/blob/6bc1ddbef933742971af414cbb90fa41c1673358/convert/src/main/java/org/bdgenomics/convert/AbstractConverter.java#L108-L126
968
phax/ph-db
ph-db-api/src/main/java/com/helger/db/api/mysql/MySQLHelper.java
MySQLHelper.buildJDBCString
@Nonnull @Nonempty public static String buildJDBCString (@Nonnull @Nonempty final String sJdbcURL, @Nullable final Map <EMySQLConnectionProperty, String> aConnectionProperties) { ValueEnforcer.notEmpty (sJdbcURL, "JDBC URL"); ValueEnforcer.isTrue (sJdbcURL.startsWith (CJDBC_MySQL.CONNECTION_PREFIX), "The JDBC URL '" + sJdbcURL + "' does not seem to be a MySQL connection string!"); // Add the connection properties to the JDBC string final SimpleURL aURL = new SimpleURL (sJdbcURL); if (aConnectionProperties != null) for (final Map.Entry <EMySQLConnectionProperty, String> aEntry : aConnectionProperties.entrySet ()) aURL.add (aEntry.getKey ().getName (), aEntry.getValue ()); return aURL.getAsStringWithoutEncodedParameters (); }
java
@Nonnull @Nonempty public static String buildJDBCString (@Nonnull @Nonempty final String sJdbcURL, @Nullable final Map <EMySQLConnectionProperty, String> aConnectionProperties) { ValueEnforcer.notEmpty (sJdbcURL, "JDBC URL"); ValueEnforcer.isTrue (sJdbcURL.startsWith (CJDBC_MySQL.CONNECTION_PREFIX), "The JDBC URL '" + sJdbcURL + "' does not seem to be a MySQL connection string!"); // Add the connection properties to the JDBC string final SimpleURL aURL = new SimpleURL (sJdbcURL); if (aConnectionProperties != null) for (final Map.Entry <EMySQLConnectionProperty, String> aEntry : aConnectionProperties.entrySet ()) aURL.add (aEntry.getKey ().getName (), aEntry.getValue ()); return aURL.getAsStringWithoutEncodedParameters (); }
[ "@", "Nonnull", "@", "Nonempty", "public", "static", "String", "buildJDBCString", "(", "@", "Nonnull", "@", "Nonempty", "final", "String", "sJdbcURL", ",", "@", "Nullable", "final", "Map", "<", "EMySQLConnectionProperty", ",", "String", ">", "aConnectionProperties", ")", "{", "ValueEnforcer", ".", "notEmpty", "(", "sJdbcURL", ",", "\"JDBC URL\"", ")", ";", "ValueEnforcer", ".", "isTrue", "(", "sJdbcURL", ".", "startsWith", "(", "CJDBC_MySQL", ".", "CONNECTION_PREFIX", ")", ",", "\"The JDBC URL '\"", "+", "sJdbcURL", "+", "\"' does not seem to be a MySQL connection string!\"", ")", ";", "// Add the connection properties to the JDBC string", "final", "SimpleURL", "aURL", "=", "new", "SimpleURL", "(", "sJdbcURL", ")", ";", "if", "(", "aConnectionProperties", "!=", "null", ")", "for", "(", "final", "Map", ".", "Entry", "<", "EMySQLConnectionProperty", ",", "String", ">", "aEntry", ":", "aConnectionProperties", ".", "entrySet", "(", ")", ")", "aURL", ".", "(", "aEntry", ".", "getKey", "(", ")", ".", "getName", "(", ")", ",", "aEntry", ".", "getValue", "(", ")", ")", ";", "return", "aURL", ".", "getAsStringWithoutEncodedParameters", "(", ")", ";", "}" ]
Build the final connection string from the base JDBC URL and an optional set of connection properties. @param sJdbcURL The base JDBC URL. May neither be <code>null</code> nor empty and must started with {@link CJDBC_MySQL#CONNECTION_PREFIX} @param aConnectionProperties An map with all connection properties. May be <code>null</code> . @return The final JDBC connection string to be used. Never <code>null</code> or empty
[ "Build", "the", "final", "connection", "string", "from", "the", "base", "JDBC", "URL", "and", "an", "optional", "set", "of", "connection", "properties", "." ]
8e04b247aead4f5e2515fa708eedc46a0a86d0e3
https://github.com/phax/ph-db/blob/8e04b247aead4f5e2515fa708eedc46a0a86d0e3/ph-db-api/src/main/java/com/helger/db/api/mysql/MySQLHelper.java#L48-L63
969
microfocus-idol/haven-search-components
idol/src/main/java/com/hp/autonomy/searchcomponents/idol/fields/IdolFieldPathNormaliserImpl.java
IdolFieldPathNormaliserImpl.updatePattern
public Pattern updatePattern(final Collection<String> prefixes) { final String XML_PREFIX = prefixes.stream() .map(s -> Pattern.quote(s + "/")) .collect(Collectors.joining("|")); return XML_PATH_PATTERN = Pattern.compile("^/?(?:" + XML_PREFIX + ")?(?:" + IDX_PREFIX + ")?(?<fieldPath>[^/]+(?:/[^/]+)*)$"); }
java
public Pattern updatePattern(final Collection<String> prefixes) { final String XML_PREFIX = prefixes.stream() .map(s -> Pattern.quote(s + "/")) .collect(Collectors.joining("|")); return XML_PATH_PATTERN = Pattern.compile("^/?(?:" + XML_PREFIX + ")?(?:" + IDX_PREFIX + ")?(?<fieldPath>[^/]+(?:/[^/]+)*)$"); }
[ "public", "Pattern", "updatePattern", "(", "final", "Collection", "<", "String", ">", "prefixes", ")", "{", "final", "String", "XML_PREFIX", "=", "prefixes", ".", "stream", "(", ")", ".", "map", "(", "s", "->", "Pattern", ".", "quote", "(", "s", "+", "\"/\"", ")", ")", ".", "collect", "(", "Collectors", ".", "joining", "(", "\"|\"", ")", ")", ";", "return", "XML_PATH_PATTERN", "=", "Pattern", ".", "compile", "(", "\"^/?(?:\"", "+", "XML_PREFIX", "+", "\")?(?:\"", "+", "IDX_PREFIX", "+", "\")?(?<fieldPath>[^/]+(?:/[^/]+)*)$\"", ")", ";", "}" ]
We have to do it this way to break the circular dependency between the FieldsInfo deserializer and this.
[ "We", "have", "to", "do", "it", "this", "way", "to", "break", "the", "circular", "dependency", "between", "the", "FieldsInfo", "deserializer", "and", "this", "." ]
6f5df74ba67ec0d3f86e73bc1dd0d6edd01a8e44
https://github.com/microfocus-idol/haven-search-components/blob/6f5df74ba67ec0d3f86e73bc1dd0d6edd01a8e44/idol/src/main/java/com/hp/autonomy/searchcomponents/idol/fields/IdolFieldPathNormaliserImpl.java#L33-L39
970
microfocus-idol/haven-search-components
core/src/main/java/com/hp/autonomy/searchcomponents/core/search/DocumentTitleResolver.java
DocumentTitleResolver.resolveTitle
public static String resolveTitle(final String title, final String reference) { if (StringUtils.isBlank(title) && !StringUtils.isBlank(reference)) { // If there is no title, assume the reference is a path and take the last part (the "file name") final String[] splitReference = PATH_SEPARATOR_REGEX.split(reference); final String lastPart = splitReference[splitReference.length - 1]; return StringUtils.isBlank(lastPart) || reference.endsWith("/") || reference.endsWith("\\") ? reference : lastPart; } else { return title; } }
java
public static String resolveTitle(final String title, final String reference) { if (StringUtils.isBlank(title) && !StringUtils.isBlank(reference)) { // If there is no title, assume the reference is a path and take the last part (the "file name") final String[] splitReference = PATH_SEPARATOR_REGEX.split(reference); final String lastPart = splitReference[splitReference.length - 1]; return StringUtils.isBlank(lastPart) || reference.endsWith("/") || reference.endsWith("\\") ? reference : lastPart; } else { return title; } }
[ "public", "static", "String", "resolveTitle", "(", "final", "String", "title", ",", "final", "String", "reference", ")", "{", "if", "(", "StringUtils", ".", "isBlank", "(", "title", ")", "&&", "!", "StringUtils", ".", "isBlank", "(", "reference", ")", ")", "{", "// If there is no title, assume the reference is a path and take the last part (the \"file name\")", "final", "String", "[", "]", "splitReference", "=", "PATH_SEPARATOR_REGEX", ".", "split", "(", "reference", ")", ";", "final", "String", "lastPart", "=", "splitReference", "[", "splitReference", ".", "length", "-", "1", "]", ";", "return", "StringUtils", ".", "isBlank", "(", "lastPart", ")", "||", "reference", ".", "endsWith", "(", "\"/\"", ")", "||", "reference", ".", "endsWith", "(", "\"\\\\\"", ")", "?", "reference", ":", "lastPart", ";", "}", "else", "{", "return", "title", ";", "}", "}" ]
Determine a title to use for a document, given it's title and reference fields. @param title The document's title field @param reference The document's reference field @return The title to use (may be null if title and reference were null)
[ "Determine", "a", "title", "to", "use", "for", "a", "document", "given", "it", "s", "title", "and", "reference", "fields", "." ]
6f5df74ba67ec0d3f86e73bc1dd0d6edd01a8e44
https://github.com/microfocus-idol/haven-search-components/blob/6f5df74ba67ec0d3f86e73bc1dd0d6edd01a8e44/core/src/main/java/com/hp/autonomy/searchcomponents/core/search/DocumentTitleResolver.java#L20-L30
971
phax/ph-db
ph-db-api/src/main/java/com/helger/db/api/jdbc/JDBCHelper.java
JDBCHelper.getJDBCTypeFromClass
public static int getJDBCTypeFromClass (@Nonnull final Class <?> aClass) { ValueEnforcer.notNull (aClass, "Class"); if (!ClassHelper.isArrayClass (aClass)) { // CHAR, VARCHAR or LONGVARCHAR if (aClass.equals (String.class)) return Types.VARCHAR; if (aClass.equals (BigDecimal.class)) return Types.NUMERIC; // BIT or BOOLEAN if (aClass.equals (Boolean.class) || aClass.equals (boolean.class)) return Types.BOOLEAN; if (aClass.equals (Byte.class) || aClass.equals (byte.class)) return Types.TINYINT; if (aClass.equals (Character.class) || aClass.equals (char.class)) return Types.CHAR; if (aClass.equals (Double.class) || aClass.equals (double.class)) return Types.DOUBLE; if (aClass.equals (Float.class) || aClass.equals (float.class)) return Types.REAL; if (aClass.equals (Integer.class) || aClass.equals (int.class)) return Types.INTEGER; if (aClass.equals (Long.class) || aClass.equals (long.class)) return Types.BIGINT; if (aClass.equals (Short.class) || aClass.equals (short.class)) return Types.SMALLINT; if (aClass.equals (java.sql.Date.class)) return Types.DATE; if (aClass.equals (java.sql.Time.class)) return Types.TIME; if (aClass.equals (java.sql.Timestamp.class)) return Types.TIMESTAMP; if (aClass.equals (java.time.ZonedDateTime.class)) return Types.TIMESTAMP; if (aClass.equals (java.time.OffsetDateTime.class)) return Types.TIMESTAMP; if (aClass.equals (java.time.LocalDateTime.class)) return Types.TIMESTAMP; if (aClass.equals (java.time.LocalDate.class)) return Types.DATE; if (aClass.equals (java.time.LocalTime.class)) return Types.TIME; } else { final Class <?> aComponentType = aClass.getComponentType (); if (aComponentType.equals (byte.class)) return Types.VARBINARY; } LOGGER.warn ("Failed to resolve JDBC type from class " + aClass.getName ()); return Types.JAVA_OBJECT; }
java
public static int getJDBCTypeFromClass (@Nonnull final Class <?> aClass) { ValueEnforcer.notNull (aClass, "Class"); if (!ClassHelper.isArrayClass (aClass)) { // CHAR, VARCHAR or LONGVARCHAR if (aClass.equals (String.class)) return Types.VARCHAR; if (aClass.equals (BigDecimal.class)) return Types.NUMERIC; // BIT or BOOLEAN if (aClass.equals (Boolean.class) || aClass.equals (boolean.class)) return Types.BOOLEAN; if (aClass.equals (Byte.class) || aClass.equals (byte.class)) return Types.TINYINT; if (aClass.equals (Character.class) || aClass.equals (char.class)) return Types.CHAR; if (aClass.equals (Double.class) || aClass.equals (double.class)) return Types.DOUBLE; if (aClass.equals (Float.class) || aClass.equals (float.class)) return Types.REAL; if (aClass.equals (Integer.class) || aClass.equals (int.class)) return Types.INTEGER; if (aClass.equals (Long.class) || aClass.equals (long.class)) return Types.BIGINT; if (aClass.equals (Short.class) || aClass.equals (short.class)) return Types.SMALLINT; if (aClass.equals (java.sql.Date.class)) return Types.DATE; if (aClass.equals (java.sql.Time.class)) return Types.TIME; if (aClass.equals (java.sql.Timestamp.class)) return Types.TIMESTAMP; if (aClass.equals (java.time.ZonedDateTime.class)) return Types.TIMESTAMP; if (aClass.equals (java.time.OffsetDateTime.class)) return Types.TIMESTAMP; if (aClass.equals (java.time.LocalDateTime.class)) return Types.TIMESTAMP; if (aClass.equals (java.time.LocalDate.class)) return Types.DATE; if (aClass.equals (java.time.LocalTime.class)) return Types.TIME; } else { final Class <?> aComponentType = aClass.getComponentType (); if (aComponentType.equals (byte.class)) return Types.VARBINARY; } LOGGER.warn ("Failed to resolve JDBC type from class " + aClass.getName ()); return Types.JAVA_OBJECT; }
[ "public", "static", "int", "getJDBCTypeFromClass", "(", "@", "Nonnull", "final", "Class", "<", "?", ">", "aClass", ")", "{", "ValueEnforcer", ".", "notNull", "(", "aClass", ",", "\"Class\"", ")", ";", "if", "(", "!", "ClassHelper", ".", "isArrayClass", "(", "aClass", ")", ")", "{", "// CHAR, VARCHAR or LONGVARCHAR", "if", "(", "aClass", ".", "equals", "(", "String", ".", "class", ")", ")", "return", "Types", ".", "VARCHAR", ";", "if", "(", "aClass", ".", "equals", "(", "BigDecimal", ".", "class", ")", ")", "return", "Types", ".", "NUMERIC", ";", "// BIT or BOOLEAN", "if", "(", "aClass", ".", "equals", "(", "Boolean", ".", "class", ")", "||", "aClass", ".", "equals", "(", "boolean", ".", "class", ")", ")", "return", "Types", ".", "BOOLEAN", ";", "if", "(", "aClass", ".", "equals", "(", "Byte", ".", "class", ")", "||", "aClass", ".", "equals", "(", "byte", ".", "class", ")", ")", "return", "Types", ".", "TINYINT", ";", "if", "(", "aClass", ".", "equals", "(", "Character", ".", "class", ")", "||", "aClass", ".", "equals", "(", "char", ".", "class", ")", ")", "return", "Types", ".", "CHAR", ";", "if", "(", "aClass", ".", "equals", "(", "Double", ".", "class", ")", "||", "aClass", ".", "equals", "(", "double", ".", "class", ")", ")", "return", "Types", ".", "DOUBLE", ";", "if", "(", "aClass", ".", "equals", "(", "Float", ".", "class", ")", "||", "aClass", ".", "equals", "(", "float", ".", "class", ")", ")", "return", "Types", ".", "REAL", ";", "if", "(", "aClass", ".", "equals", "(", "Integer", ".", "class", ")", "||", "aClass", ".", "equals", "(", "int", ".", "class", ")", ")", "return", "Types", ".", "INTEGER", ";", "if", "(", "aClass", ".", "equals", "(", "Long", ".", "class", ")", "||", "aClass", ".", "equals", "(", "long", ".", "class", ")", ")", "return", "Types", ".", "BIGINT", ";", "if", "(", "aClass", ".", "equals", "(", "Short", ".", "class", ")", "||", "aClass", ".", "equals", "(", "short", ".", "class", ")", ")", "return", "Types", ".", "SMALLINT", ";", "if", "(", "aClass", ".", "equals", "(", "java", ".", "sql", ".", "Date", ".", "class", ")", ")", "return", "Types", ".", "DATE", ";", "if", "(", "aClass", ".", "equals", "(", "java", ".", "sql", ".", "Time", ".", "class", ")", ")", "return", "Types", ".", "TIME", ";", "if", "(", "aClass", ".", "equals", "(", "java", ".", "sql", ".", "Timestamp", ".", "class", ")", ")", "return", "Types", ".", "TIMESTAMP", ";", "if", "(", "aClass", ".", "equals", "(", "java", ".", "time", ".", "ZonedDateTime", ".", "class", ")", ")", "return", "Types", ".", "TIMESTAMP", ";", "if", "(", "aClass", ".", "equals", "(", "java", ".", "time", ".", "OffsetDateTime", ".", "class", ")", ")", "return", "Types", ".", "TIMESTAMP", ";", "if", "(", "aClass", ".", "equals", "(", "java", ".", "time", ".", "LocalDateTime", ".", "class", ")", ")", "return", "Types", ".", "TIMESTAMP", ";", "if", "(", "aClass", ".", "equals", "(", "java", ".", "time", ".", "LocalDate", ".", "class", ")", ")", "return", "Types", ".", "DATE", ";", "if", "(", "aClass", ".", "equals", "(", "java", ".", "time", ".", "LocalTime", ".", "class", ")", ")", "return", "Types", ".", "TIME", ";", "}", "else", "{", "final", "Class", "<", "?", ">", "aComponentType", "=", "aClass", ".", "getComponentType", "(", ")", ";", "if", "(", "aComponentType", ".", "equals", "(", "byte", ".", "class", ")", ")", "return", "Types", ".", "VARBINARY", ";", "}", "LOGGER", ".", "warn", "(", "\"Failed to resolve JDBC type from class \"", "+", "aClass", ".", "getName", "(", ")", ")", ";", "return", "Types", ".", "JAVA_OBJECT", ";", "}" ]
Determine the JDBC type from the passed class. @param aClass The class to check. May not be <code>null</code>. @return {@link Types#JAVA_OBJECT} if the type could not be determined. @see "http://java.sun.com/j2se/1.4.2/docs/guide/jdbc/getstart/mapping.html"
[ "Determine", "the", "JDBC", "type", "from", "the", "passed", "class", "." ]
8e04b247aead4f5e2515fa708eedc46a0a86d0e3
https://github.com/phax/ph-db/blob/8e04b247aead4f5e2515fa708eedc46a0a86d0e3/ph-db-api/src/main/java/com/helger/db/api/jdbc/JDBCHelper.java#L111-L182
972
phax/ph-db
ph-db-jdbc/src/main/java/com/helger/db/jdbc/h2/AbstractH2Connector.java
AbstractH2Connector.dumpDatabase
@Nonnull public final ESuccess dumpDatabase (@Nonnull @WillClose final OutputStream aOS) { ValueEnforcer.notNull (aOS, "OutputStream"); // Save the DB data to an SQL file try { LOGGER.info ("Dumping database '" + getDatabaseName () + "' to OutputStream"); try (final PrintWriter aPrintWriter = new PrintWriter (new NonBlockingBufferedWriter (StreamHelper.createWriter (aOS, StandardCharsets.UTF_8)))) { final DBExecutor aExecutor = new DBExecutor (this); final ESuccess ret = aExecutor.queryAll ("SCRIPT SIMPLE", aCurrentObject -> { if (aCurrentObject != null) { // The value of the first column is the script line aPrintWriter.println (aCurrentObject.get (0).getValue ()); } }); aPrintWriter.flush (); return ret; } } finally { StreamHelper.close (aOS); } }
java
@Nonnull public final ESuccess dumpDatabase (@Nonnull @WillClose final OutputStream aOS) { ValueEnforcer.notNull (aOS, "OutputStream"); // Save the DB data to an SQL file try { LOGGER.info ("Dumping database '" + getDatabaseName () + "' to OutputStream"); try (final PrintWriter aPrintWriter = new PrintWriter (new NonBlockingBufferedWriter (StreamHelper.createWriter (aOS, StandardCharsets.UTF_8)))) { final DBExecutor aExecutor = new DBExecutor (this); final ESuccess ret = aExecutor.queryAll ("SCRIPT SIMPLE", aCurrentObject -> { if (aCurrentObject != null) { // The value of the first column is the script line aPrintWriter.println (aCurrentObject.get (0).getValue ()); } }); aPrintWriter.flush (); return ret; } } finally { StreamHelper.close (aOS); } }
[ "@", "Nonnull", "public", "final", "ESuccess", "dumpDatabase", "(", "@", "Nonnull", "@", "WillClose", "final", "OutputStream", "aOS", ")", "{", "ValueEnforcer", ".", "notNull", "(", "aOS", ",", "\"OutputStream\"", ")", ";", "// Save the DB data to an SQL file", "try", "{", "LOGGER", ".", "info", "(", "\"Dumping database '\"", "+", "getDatabaseName", "(", ")", "+", "\"' to OutputStream\"", ")", ";", "try", "(", "final", "PrintWriter", "aPrintWriter", "=", "new", "PrintWriter", "(", "new", "NonBlockingBufferedWriter", "(", "StreamHelper", ".", "createWriter", "(", "aOS", ",", "StandardCharsets", ".", "UTF_8", ")", ")", ")", ")", "{", "final", "DBExecutor", "aExecutor", "=", "new", "DBExecutor", "(", "this", ")", ";", "final", "ESuccess", "ret", "=", "aExecutor", ".", "queryAll", "(", "\"SCRIPT SIMPLE\"", ",", "aCurrentObject", "->", "{", "if", "(", "aCurrentObject", "!=", "null", ")", "{", "// The value of the first column is the script line", "aPrintWriter", ".", "println", "(", "aCurrentObject", ".", "get", "(", "0", ")", ".", "getValue", "(", ")", ")", ";", "}", "}", ")", ";", "aPrintWriter", ".", "flush", "(", ")", ";", "return", "ret", ";", "}", "}", "finally", "{", "StreamHelper", ".", "close", "(", "aOS", ")", ";", "}", "}" ]
Dump the database to the passed output stream and closed the passed output stream. @param aOS The output stream to dump the DB content to. May not be <code>null</code>. Automatically closed when done. @return <code>true</code> upon success, <code>false</code> if an error occurred.
[ "Dump", "the", "database", "to", "the", "passed", "output", "stream", "and", "closed", "the", "passed", "output", "stream", "." ]
8e04b247aead4f5e2515fa708eedc46a0a86d0e3
https://github.com/phax/ph-db/blob/8e04b247aead4f5e2515fa708eedc46a0a86d0e3/ph-db-jdbc/src/main/java/com/helger/db/jdbc/h2/AbstractH2Connector.java#L151-L179
973
phax/ph-db
ph-db-jdbc/src/main/java/com/helger/db/jdbc/h2/AbstractH2Connector.java
AbstractH2Connector.createBackup
@Nonnull public final ESuccess createBackup (@Nonnull final File fDestFile) { ValueEnforcer.notNull (fDestFile, "DestFile"); LOGGER.info ("Backing up database '" + getDatabaseName () + "' to " + fDestFile); final DBExecutor aExecutor = new DBExecutor (this); return aExecutor.executeStatement ("BACKUP TO '" + fDestFile.getAbsolutePath () + "'"); }
java
@Nonnull public final ESuccess createBackup (@Nonnull final File fDestFile) { ValueEnforcer.notNull (fDestFile, "DestFile"); LOGGER.info ("Backing up database '" + getDatabaseName () + "' to " + fDestFile); final DBExecutor aExecutor = new DBExecutor (this); return aExecutor.executeStatement ("BACKUP TO '" + fDestFile.getAbsolutePath () + "'"); }
[ "@", "Nonnull", "public", "final", "ESuccess", "createBackup", "(", "@", "Nonnull", "final", "File", "fDestFile", ")", "{", "ValueEnforcer", ".", "notNull", "(", "fDestFile", ",", "\"DestFile\"", ")", ";", "LOGGER", ".", "info", "(", "\"Backing up database '\"", "+", "getDatabaseName", "(", ")", "+", "\"' to \"", "+", "fDestFile", ")", ";", "final", "DBExecutor", "aExecutor", "=", "new", "DBExecutor", "(", "this", ")", ";", "return", "aExecutor", ".", "executeStatement", "(", "\"BACKUP TO '\"", "+", "fDestFile", ".", "getAbsolutePath", "(", ")", "+", "\"'\"", ")", ";", "}" ]
Create a backup file. The file is a ZIP file. @param fDestFile Destination filename. May not be <code>null</code>. @return {@link ESuccess}
[ "Create", "a", "backup", "file", ".", "The", "file", "is", "a", "ZIP", "file", "." ]
8e04b247aead4f5e2515fa708eedc46a0a86d0e3
https://github.com/phax/ph-db/blob/8e04b247aead4f5e2515fa708eedc46a0a86d0e3/ph-db-jdbc/src/main/java/com/helger/db/jdbc/h2/AbstractH2Connector.java#L188-L196
974
microfocus-idol/haven-search-components
hod/src/main/java/com/hp/autonomy/searchcomponents/hod/search/HodDocumentsServiceImpl.java
HodDocumentsServiceImpl.addDomain
private HodSearchResult addDomain(final Iterable<ResourceName> indexIdentifiers, final HodSearchResult document) { // HOD does not return the domain for documents yet, but it does return the index final String index = document.getIndex(); String domain = null; // It's most likely that the returned documents will be in one of the indexes we are querying (hopefully the // names are unique between the domains...) for(final ResourceName indexIdentifier : indexIdentifiers) { if(index.equals(indexIdentifier.getName())) { domain = indexIdentifier.getDomain(); break; } } if(domain == null) { // If not, it might be a public index domain = PUBLIC_INDEX_NAMES.contains(index) ? ResourceName.PUBLIC_INDEXES_DOMAIN : getDomain(); } return document.toBuilder() .domain(domain) .build(); }
java
private HodSearchResult addDomain(final Iterable<ResourceName> indexIdentifiers, final HodSearchResult document) { // HOD does not return the domain for documents yet, but it does return the index final String index = document.getIndex(); String domain = null; // It's most likely that the returned documents will be in one of the indexes we are querying (hopefully the // names are unique between the domains...) for(final ResourceName indexIdentifier : indexIdentifiers) { if(index.equals(indexIdentifier.getName())) { domain = indexIdentifier.getDomain(); break; } } if(domain == null) { // If not, it might be a public index domain = PUBLIC_INDEX_NAMES.contains(index) ? ResourceName.PUBLIC_INDEXES_DOMAIN : getDomain(); } return document.toBuilder() .domain(domain) .build(); }
[ "private", "HodSearchResult", "addDomain", "(", "final", "Iterable", "<", "ResourceName", ">", "indexIdentifiers", ",", "final", "HodSearchResult", "document", ")", "{", "// HOD does not return the domain for documents yet, but it does return the index", "final", "String", "index", "=", "document", ".", "getIndex", "(", ")", ";", "String", "domain", "=", "null", ";", "// It's most likely that the returned documents will be in one of the indexes we are querying (hopefully the", "// names are unique between the domains...)", "for", "(", "final", "ResourceName", "indexIdentifier", ":", "indexIdentifiers", ")", "{", "if", "(", "index", ".", "equals", "(", "indexIdentifier", ".", "getName", "(", ")", ")", ")", "{", "domain", "=", "indexIdentifier", ".", "getDomain", "(", ")", ";", "break", ";", "}", "}", "if", "(", "domain", "==", "null", ")", "{", "// If not, it might be a public index", "domain", "=", "PUBLIC_INDEX_NAMES", ".", "contains", "(", "index", ")", "?", "ResourceName", ".", "PUBLIC_INDEXES_DOMAIN", ":", "getDomain", "(", ")", ";", "}", "return", "document", ".", "toBuilder", "(", ")", ".", "domain", "(", "domain", ")", ".", "build", "(", ")", ";", "}" ]
Add a domain to a FindDocument, given the collection of indexes which were queried against to return it from HOD
[ "Add", "a", "domain", "to", "a", "FindDocument", "given", "the", "collection", "of", "indexes", "which", "were", "queried", "against", "to", "return", "it", "from", "HOD" ]
6f5df74ba67ec0d3f86e73bc1dd0d6edd01a8e44
https://github.com/microfocus-idol/haven-search-components/blob/6f5df74ba67ec0d3f86e73bc1dd0d6edd01a8e44/hod/src/main/java/com/hp/autonomy/searchcomponents/hod/search/HodDocumentsServiceImpl.java#L230-L252
975
bigdatagenomics/convert
convert/src/main/java/org/bdgenomics/convert/bdgenomics/StringToTranscriptEffect.java
StringToTranscriptEffect.splitEffects
List<String> splitEffects(final String s) { return Splitter.on("&").omitEmptyStrings().splitToList(s); }
java
List<String> splitEffects(final String s) { return Splitter.on("&").omitEmptyStrings().splitToList(s); }
[ "List", "<", "String", ">", "splitEffects", "(", "final", "String", "s", ")", "{", "return", "Splitter", ".", "on", "(", "\"&\"", ")", ".", "omitEmptyStrings", "(", ")", ".", "splitToList", "(", "s", ")", ";", "}" ]
Split the specified string into a list of effects. @param s string to split @return the specified string split into a list of effects
[ "Split", "the", "specified", "string", "into", "a", "list", "of", "effects", "." ]
6bc1ddbef933742971af414cbb90fa41c1673358
https://github.com/bigdatagenomics/convert/blob/6bc1ddbef933742971af414cbb90fa41c1673358/convert/src/main/java/org/bdgenomics/convert/bdgenomics/StringToTranscriptEffect.java#L136-L138
976
bigdatagenomics/convert
convert/src/main/java/org/bdgenomics/convert/bdgenomics/StringToTranscriptEffect.java
StringToTranscriptEffect.splitMessages
List<VariantAnnotationMessage> splitMessages(final String s, final ConversionStringency stringency, final Logger logger) throws ConversionException { return Splitter .on("&") .omitEmptyStrings() .splitToList(s) .stream() .map(m -> variantAnnotationMessageConverter.convert(m, stringency, logger)) .collect(toList()); }
java
List<VariantAnnotationMessage> splitMessages(final String s, final ConversionStringency stringency, final Logger logger) throws ConversionException { return Splitter .on("&") .omitEmptyStrings() .splitToList(s) .stream() .map(m -> variantAnnotationMessageConverter.convert(m, stringency, logger)) .collect(toList()); }
[ "List", "<", "VariantAnnotationMessage", ">", "splitMessages", "(", "final", "String", "s", ",", "final", "ConversionStringency", "stringency", ",", "final", "Logger", "logger", ")", "throws", "ConversionException", "{", "return", "Splitter", ".", "on", "(", "\"&\"", ")", ".", "omitEmptyStrings", "(", ")", ".", "splitToList", "(", "s", ")", ".", "stream", "(", ")", ".", "map", "(", "m", "->", "variantAnnotationMessageConverter", ".", "convert", "(", "m", ",", "stringency", ",", "logger", ")", ")", ".", "collect", "(", "toList", "(", ")", ")", ";", "}" ]
Split the specified string into a list of variant annotation messages. @param s string to split @param stringency conversion stringency, must not be null @param logger logger, must not be null @return the specified string split into a list of variant annotation messages @throws ConversionException if conversion fails and the specified conversion stringency is strict @throws NullPointerException if either conversion stringency or logger are null
[ "Split", "the", "specified", "string", "into", "a", "list", "of", "variant", "annotation", "messages", "." ]
6bc1ddbef933742971af414cbb90fa41c1673358
https://github.com/bigdatagenomics/convert/blob/6bc1ddbef933742971af414cbb90fa41c1673358/convert/src/main/java/org/bdgenomics/convert/bdgenomics/StringToTranscriptEffect.java#L150-L160
977
bigdatagenomics/convert
convert/src/main/java/org/bdgenomics/convert/bdgenomics/StringToTranscriptEffect.java
StringToTranscriptEffect.emptyToNullInteger
static Integer emptyToNullInteger(final String s) { return "".equals(s) ? null : Integer.parseInt(s); }
java
static Integer emptyToNullInteger(final String s) { return "".equals(s) ? null : Integer.parseInt(s); }
[ "static", "Integer", "emptyToNullInteger", "(", "final", "String", "s", ")", "{", "return", "\"\"", ".", "equals", "(", "s", ")", "?", "null", ":", "Integer", ".", "parseInt", "(", "s", ")", ";", "}" ]
Parse the specified string into an integer, returning null if the string is empty. @param s string to parse @return the specified string parsed into an integer, or null if the string is empty
[ "Parse", "the", "specified", "string", "into", "an", "integer", "returning", "null", "if", "the", "string", "is", "empty", "." ]
6bc1ddbef933742971af414cbb90fa41c1673358
https://github.com/bigdatagenomics/convert/blob/6bc1ddbef933742971af414cbb90fa41c1673358/convert/src/main/java/org/bdgenomics/convert/bdgenomics/StringToTranscriptEffect.java#L178-L180
978
bigdatagenomics/convert
convert/src/main/java/org/bdgenomics/convert/bdgenomics/StringToTranscriptEffect.java
StringToTranscriptEffect.numerator
static Integer numerator(final String s) { if ("".equals(s)) { return null; } String[] tokens = s.split("/"); return emptyToNullInteger(tokens[0]); }
java
static Integer numerator(final String s) { if ("".equals(s)) { return null; } String[] tokens = s.split("/"); return emptyToNullInteger(tokens[0]); }
[ "static", "Integer", "numerator", "(", "final", "String", "s", ")", "{", "if", "(", "\"\"", ".", "equals", "(", "s", ")", ")", "{", "return", "null", ";", "}", "String", "[", "]", "tokens", "=", "s", ".", "split", "(", "\"/\"", ")", ";", "return", "emptyToNullInteger", "(", "tokens", "[", "0", "]", ")", ";", "}" ]
Parse the specified string as a fraction and return the numerator, if any. @param s string to parse @return the numerator from the specified string parsed as a fraction, or null if the string is empty
[ "Parse", "the", "specified", "string", "as", "a", "fraction", "and", "return", "the", "numerator", "if", "any", "." ]
6bc1ddbef933742971af414cbb90fa41c1673358
https://github.com/bigdatagenomics/convert/blob/6bc1ddbef933742971af414cbb90fa41c1673358/convert/src/main/java/org/bdgenomics/convert/bdgenomics/StringToTranscriptEffect.java#L188-L194
979
bigdatagenomics/convert
convert/src/main/java/org/bdgenomics/convert/bdgenomics/StringToTranscriptEffect.java
StringToTranscriptEffect.denominator
static Integer denominator(final String s) { if ("".equals(s)) { return null; } String[] tokens = s.split("/"); return (tokens.length < 2) ? null : emptyToNullInteger(tokens[1]); }
java
static Integer denominator(final String s) { if ("".equals(s)) { return null; } String[] tokens = s.split("/"); return (tokens.length < 2) ? null : emptyToNullInteger(tokens[1]); }
[ "static", "Integer", "denominator", "(", "final", "String", "s", ")", "{", "if", "(", "\"\"", ".", "equals", "(", "s", ")", ")", "{", "return", "null", ";", "}", "String", "[", "]", "tokens", "=", "s", ".", "split", "(", "\"/\"", ")", ";", "return", "(", "tokens", ".", "length", "<", "2", ")", "?", "null", ":", "emptyToNullInteger", "(", "tokens", "[", "1", "]", ")", ";", "}" ]
Parse the specified string as a fraction and return the denominator, if any. @param s string to parse @return the denominator from the specified string parsed as a fraction, or null if the string is empty or if the fraction has no denominator
[ "Parse", "the", "specified", "string", "as", "a", "fraction", "and", "return", "the", "denominator", "if", "any", "." ]
6bc1ddbef933742971af414cbb90fa41c1673358
https://github.com/bigdatagenomics/convert/blob/6bc1ddbef933742971af414cbb90fa41c1673358/convert/src/main/java/org/bdgenomics/convert/bdgenomics/StringToTranscriptEffect.java#L203-L209
980
phax/ph-db
ph-db-jpa/src/main/java/com/helger/db/jpa/JPAExecutionResult.java
JPAExecutionResult.createSuccess
@Nonnull public static <T> JPAExecutionResult <T> createSuccess (@Nullable final T aObj) { return new JPAExecutionResult <> (ESuccess.SUCCESS, aObj, null); }
java
@Nonnull public static <T> JPAExecutionResult <T> createSuccess (@Nullable final T aObj) { return new JPAExecutionResult <> (ESuccess.SUCCESS, aObj, null); }
[ "@", "Nonnull", "public", "static", "<", "T", ">", "JPAExecutionResult", "<", "T", ">", "createSuccess", "(", "@", "Nullable", "final", "T", "aObj", ")", "{", "return", "new", "JPAExecutionResult", "<>", "(", "ESuccess", ".", "SUCCESS", ",", "aObj", ",", "null", ")", ";", "}" ]
Create a new success object. @param aObj The returned value from the DB @return Never <code>null</code>. @param <T> Data type of provided parameter
[ "Create", "a", "new", "success", "object", "." ]
8e04b247aead4f5e2515fa708eedc46a0a86d0e3
https://github.com/phax/ph-db/blob/8e04b247aead4f5e2515fa708eedc46a0a86d0e3/ph-db-jpa/src/main/java/com/helger/db/jpa/JPAExecutionResult.java#L128-L132
981
phax/ph-db
ph-db-jpa/src/main/java/com/helger/db/jpa/JPAExecutionResult.java
JPAExecutionResult.createFailure
@Nonnull public static <T> JPAExecutionResult <T> createFailure (@Nullable final Exception ex) { return new JPAExecutionResult <> (ESuccess.FAILURE, null, ex); }
java
@Nonnull public static <T> JPAExecutionResult <T> createFailure (@Nullable final Exception ex) { return new JPAExecutionResult <> (ESuccess.FAILURE, null, ex); }
[ "@", "Nonnull", "public", "static", "<", "T", ">", "JPAExecutionResult", "<", "T", ">", "createFailure", "(", "@", "Nullable", "final", "Exception", "ex", ")", "{", "return", "new", "JPAExecutionResult", "<>", "(", "ESuccess", ".", "FAILURE", ",", "null", ",", "ex", ")", ";", "}" ]
Create a new failure object. @param ex The exception that occurred. @return Never <code>null</code>. @param <T> Data type - depends on callers requirements.
[ "Create", "a", "new", "failure", "object", "." ]
8e04b247aead4f5e2515fa708eedc46a0a86d0e3
https://github.com/phax/ph-db/blob/8e04b247aead4f5e2515fa708eedc46a0a86d0e3/ph-db-jpa/src/main/java/com/helger/db/jpa/JPAExecutionResult.java#L143-L147
982
Arasthel/AsyncJobLibrary
AsyncJob/src/main/java/com/arasthel/asyncjob/AsyncJob.java
AsyncJob.doOnMainThread
public static void doOnMainThread(final OnMainThreadJob onMainThreadJob) { uiHandler.post(new Runnable() { @Override public void run() { onMainThreadJob.doInUIThread(); } }); }
java
public static void doOnMainThread(final OnMainThreadJob onMainThreadJob) { uiHandler.post(new Runnable() { @Override public void run() { onMainThreadJob.doInUIThread(); } }); }
[ "public", "static", "void", "doOnMainThread", "(", "final", "OnMainThreadJob", "onMainThreadJob", ")", "{", "uiHandler", ".", "post", "(", "new", "Runnable", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "onMainThreadJob", ".", "doInUIThread", "(", ")", ";", "}", "}", ")", ";", "}" ]
Executes the provided code immediately on the UI Thread @param onMainThreadJob Interface that wraps the code to execute
[ "Executes", "the", "provided", "code", "immediately", "on", "the", "UI", "Thread" ]
64299f642724274c7805a69ee0d693ce7a0425b8
https://github.com/Arasthel/AsyncJobLibrary/blob/64299f642724274c7805a69ee0d693ce7a0425b8/AsyncJob/src/main/java/com/arasthel/asyncjob/AsyncJob.java#L42-L49
983
Arasthel/AsyncJobLibrary
AsyncJob/src/main/java/com/arasthel/asyncjob/AsyncJob.java
AsyncJob.doInBackground
public static void doInBackground(final OnBackgroundJob onBackgroundJob) { new Thread(new Runnable() { @Override public void run() { onBackgroundJob.doOnBackground(); } }).start(); }
java
public static void doInBackground(final OnBackgroundJob onBackgroundJob) { new Thread(new Runnable() { @Override public void run() { onBackgroundJob.doOnBackground(); } }).start(); }
[ "public", "static", "void", "doInBackground", "(", "final", "OnBackgroundJob", "onBackgroundJob", ")", "{", "new", "Thread", "(", "new", "Runnable", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "onBackgroundJob", ".", "doOnBackground", "(", ")", ";", "}", "}", ")", ".", "start", "(", ")", ";", "}" ]
Executes the provided code immediately on a background thread @param onBackgroundJob Interface that wraps the code to execute
[ "Executes", "the", "provided", "code", "immediately", "on", "a", "background", "thread" ]
64299f642724274c7805a69ee0d693ce7a0425b8
https://github.com/Arasthel/AsyncJobLibrary/blob/64299f642724274c7805a69ee0d693ce7a0425b8/AsyncJob/src/main/java/com/arasthel/asyncjob/AsyncJob.java#L55-L62
984
Arasthel/AsyncJobLibrary
AsyncJob/src/main/java/com/arasthel/asyncjob/AsyncJob.java
AsyncJob.doInBackground
public static FutureTask doInBackground(final OnBackgroundJob onBackgroundJob, ExecutorService executor) { FutureTask task = (FutureTask) executor.submit(new Runnable() { @Override public void run() { onBackgroundJob.doOnBackground(); } }); return task; }
java
public static FutureTask doInBackground(final OnBackgroundJob onBackgroundJob, ExecutorService executor) { FutureTask task = (FutureTask) executor.submit(new Runnable() { @Override public void run() { onBackgroundJob.doOnBackground(); } }); return task; }
[ "public", "static", "FutureTask", "doInBackground", "(", "final", "OnBackgroundJob", "onBackgroundJob", ",", "ExecutorService", "executor", ")", "{", "FutureTask", "task", "=", "(", "FutureTask", ")", "executor", ".", "submit", "(", "new", "Runnable", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "onBackgroundJob", ".", "doOnBackground", "(", ")", ";", "}", "}", ")", ";", "return", "task", ";", "}" ]
Executes the provided code immediately on a background thread that will be submitted to the provided ExecutorService @param onBackgroundJob Interface that wraps the code to execute @param executor Will queue the provided code
[ "Executes", "the", "provided", "code", "immediately", "on", "a", "background", "thread", "that", "will", "be", "submitted", "to", "the", "provided", "ExecutorService" ]
64299f642724274c7805a69ee0d693ce7a0425b8
https://github.com/Arasthel/AsyncJobLibrary/blob/64299f642724274c7805a69ee0d693ce7a0425b8/AsyncJob/src/main/java/com/arasthel/asyncjob/AsyncJob.java#L70-L79
985
Arasthel/AsyncJobLibrary
AsyncJob/src/main/java/com/arasthel/asyncjob/AsyncJob.java
AsyncJob.start
public void start() { if(actionInBackground != null) { Runnable jobToRun = new Runnable() { @Override public void run() { result = (JobResult) actionInBackground.doAsync(); onResult(); } }; if(getExecutorService() != null) { asyncFutureTask = (FutureTask) getExecutorService().submit(jobToRun); } else { asyncThread = new Thread(jobToRun); asyncThread.start(); } } }
java
public void start() { if(actionInBackground != null) { Runnable jobToRun = new Runnable() { @Override public void run() { result = (JobResult) actionInBackground.doAsync(); onResult(); } }; if(getExecutorService() != null) { asyncFutureTask = (FutureTask) getExecutorService().submit(jobToRun); } else { asyncThread = new Thread(jobToRun); asyncThread.start(); } } }
[ "public", "void", "start", "(", ")", "{", "if", "(", "actionInBackground", "!=", "null", ")", "{", "Runnable", "jobToRun", "=", "new", "Runnable", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "result", "=", "(", "JobResult", ")", "actionInBackground", ".", "doAsync", "(", ")", ";", "onResult", "(", ")", ";", "}", "}", ";", "if", "(", "getExecutorService", "(", ")", "!=", "null", ")", "{", "asyncFutureTask", "=", "(", "FutureTask", ")", "getExecutorService", "(", ")", ".", "submit", "(", "jobToRun", ")", ";", "}", "else", "{", "asyncThread", "=", "new", "Thread", "(", "jobToRun", ")", ";", "asyncThread", ".", "start", "(", ")", ";", "}", "}", "}" ]
Begins the background execution providing a result, similar to an AsyncTask. It will execute it on a new Thread or using the provided ExecutorService
[ "Begins", "the", "background", "execution", "providing", "a", "result", "similar", "to", "an", "AsyncTask", ".", "It", "will", "execute", "it", "on", "a", "new", "Thread", "or", "using", "the", "provided", "ExecutorService" ]
64299f642724274c7805a69ee0d693ce7a0425b8
https://github.com/Arasthel/AsyncJobLibrary/blob/64299f642724274c7805a69ee0d693ce7a0425b8/AsyncJob/src/main/java/com/arasthel/asyncjob/AsyncJob.java#L85-L103
986
Arasthel/AsyncJobLibrary
AsyncJob/src/main/java/com/arasthel/asyncjob/AsyncJob.java
AsyncJob.cancel
public void cancel() { if(actionInBackground != null) { if(executorService != null) { asyncFutureTask.cancel(true); } else { asyncThread.interrupt(); } } }
java
public void cancel() { if(actionInBackground != null) { if(executorService != null) { asyncFutureTask.cancel(true); } else { asyncThread.interrupt(); } } }
[ "public", "void", "cancel", "(", ")", "{", "if", "(", "actionInBackground", "!=", "null", ")", "{", "if", "(", "executorService", "!=", "null", ")", "{", "asyncFutureTask", ".", "cancel", "(", "true", ")", ";", "}", "else", "{", "asyncThread", ".", "interrupt", "(", ")", ";", "}", "}", "}" ]
Cancels the AsyncJob interrupting the inner thread.
[ "Cancels", "the", "AsyncJob", "interrupting", "the", "inner", "thread", "." ]
64299f642724274c7805a69ee0d693ce7a0425b8
https://github.com/Arasthel/AsyncJobLibrary/blob/64299f642724274c7805a69ee0d693ce7a0425b8/AsyncJob/src/main/java/com/arasthel/asyncjob/AsyncJob.java#L108-L116
987
outbrain/ob1k
ob1k-http/src/main/java/com/outbrain/ob1k/http/utils/UrlUtils.java
UrlUtils.replacePathParam
public static String replacePathParam(final String url, final String param, final String value) throws EncoderException { final String pathParam = param.startsWith("{") ? param : "{" + param + "}"; final String encodedValue = encode(value); return StringUtils.replace(url, pathParam, encodedValue); }
java
public static String replacePathParam(final String url, final String param, final String value) throws EncoderException { final String pathParam = param.startsWith("{") ? param : "{" + param + "}"; final String encodedValue = encode(value); return StringUtils.replace(url, pathParam, encodedValue); }
[ "public", "static", "String", "replacePathParam", "(", "final", "String", "url", ",", "final", "String", "param", ",", "final", "String", "value", ")", "throws", "EncoderException", "{", "final", "String", "pathParam", "=", "param", ".", "startsWith", "(", "\"{\"", ")", "?", "param", ":", "\"{\"", "+", "param", "+", "\"}\"", ";", "final", "String", "encodedValue", "=", "encode", "(", "value", ")", ";", "return", "StringUtils", ".", "replace", "(", "url", ",", "pathParam", ",", "encodedValue", ")", ";", "}" ]
Replaces path param in uri to a valid, encoded value @param url url to replace in (path params should be in the uri within curly braces) @param param name of the path param (not inside curly braces) @param value value to encode @return url with path param replaced to the value @throws EncoderException
[ "Replaces", "path", "param", "in", "uri", "to", "a", "valid", "encoded", "value" ]
9e43ab39230c5787065053da0f766d822d0fe4e7
https://github.com/outbrain/ob1k/blob/9e43ab39230c5787065053da0f766d822d0fe4e7/ob1k-http/src/main/java/com/outbrain/ob1k/http/utils/UrlUtils.java#L38-L43
988
outbrain/ob1k
ob1k-http/src/main/java/com/outbrain/ob1k/http/utils/UrlUtils.java
UrlUtils.extractPathParams
public static List<String> extractPathParams(final String url) { final List<String> pathParams = new ArrayList<>(); int index = url.indexOf('{'); while (index >= 0) { final int endIndex = url.indexOf('}', index); final String pathParam = url.substring(index + 1, endIndex); pathParams.add(pathParam); index = url.indexOf('{', endIndex); } return pathParams; }
java
public static List<String> extractPathParams(final String url) { final List<String> pathParams = new ArrayList<>(); int index = url.indexOf('{'); while (index >= 0) { final int endIndex = url.indexOf('}', index); final String pathParam = url.substring(index + 1, endIndex); pathParams.add(pathParam); index = url.indexOf('{', endIndex); } return pathParams; }
[ "public", "static", "List", "<", "String", ">", "extractPathParams", "(", "final", "String", "url", ")", "{", "final", "List", "<", "String", ">", "pathParams", "=", "new", "ArrayList", "<>", "(", ")", ";", "int", "index", "=", "url", ".", "indexOf", "(", "'", "'", ")", ";", "while", "(", "index", ">=", "0", ")", "{", "final", "int", "endIndex", "=", "url", ".", "indexOf", "(", "'", "'", ",", "index", ")", ";", "final", "String", "pathParam", "=", "url", ".", "substring", "(", "index", "+", "1", ",", "endIndex", ")", ";", "pathParams", ".", "add", "(", "pathParam", ")", ";", "index", "=", "url", ".", "indexOf", "(", "'", "'", ",", "endIndex", ")", ";", "}", "return", "pathParams", ";", "}" ]
Extracts all path params in url @param url url to find path params in @return list of path params
[ "Extracts", "all", "path", "params", "in", "url" ]
9e43ab39230c5787065053da0f766d822d0fe4e7
https://github.com/outbrain/ob1k/blob/9e43ab39230c5787065053da0f766d822d0fe4e7/ob1k-http/src/main/java/com/outbrain/ob1k/http/utils/UrlUtils.java#L51-L65
989
outbrain/ob1k
ob1k-http/src/main/java/com/outbrain/ob1k/http/ning/NingRequestBuilder.java
NingRequestBuilder.prepareRequestBody
private void prepareRequestBody() throws IOException { if (bodyByteArray != null) { setByteArrayBody(); } else if (bodyString != null) { setStringBody(); } else if (bodyObject != null) { setTypedBody(); } }
java
private void prepareRequestBody() throws IOException { if (bodyByteArray != null) { setByteArrayBody(); } else if (bodyString != null) { setStringBody(); } else if (bodyObject != null) { setTypedBody(); } }
[ "private", "void", "prepareRequestBody", "(", ")", "throws", "IOException", "{", "if", "(", "bodyByteArray", "!=", "null", ")", "{", "setByteArrayBody", "(", ")", ";", "}", "else", "if", "(", "bodyString", "!=", "null", ")", "{", "setStringBody", "(", ")", ";", "}", "else", "if", "(", "bodyObject", "!=", "null", ")", "{", "setTypedBody", "(", ")", ";", "}", "}" ]
Prepares the request body - setting the body, charset and content length by body type @throws IOException
[ "Prepares", "the", "request", "body", "-", "setting", "the", "body", "charset", "and", "content", "length", "by", "body", "type" ]
9e43ab39230c5787065053da0f766d822d0fe4e7
https://github.com/outbrain/ob1k/blob/9e43ab39230c5787065053da0f766d822d0fe4e7/ob1k-http/src/main/java/com/outbrain/ob1k/http/ning/NingRequestBuilder.java#L419-L428
990
outbrain/ob1k
ob1k-example/src/main/java/com/outbrain/ob1k/example/hello/server/services/HelloServiceImpl.java
HelloServiceImpl.helloUserStream
@Override public Observable<String> helloUserStream(final String name, final int repeats) { return interval(100, TimeUnit.MILLISECONDS).map(i -> "Hello, " + name + "! (#" + i + ")").take(repeats); }
java
@Override public Observable<String> helloUserStream(final String name, final int repeats) { return interval(100, TimeUnit.MILLISECONDS).map(i -> "Hello, " + name + "! (#" + i + ")").take(repeats); }
[ "@", "Override", "public", "Observable", "<", "String", ">", "helloUserStream", "(", "final", "String", "name", ",", "final", "int", "repeats", ")", "{", "return", "interval", "(", "100", ",", "TimeUnit", ".", "MILLISECONDS", ")", ".", "map", "(", "i", "->", "\"Hello, \"", "+", "name", "+", "\"! (#\"", "+", "i", "+", "\")\"", ")", ".", "take", "(", "repeats", ")", ";", "}" ]
Endpoint which receives username and repeats number, and returns stream of messages limited by the repeat number size @param name username (comes either from request body or as query param) @param repeats repeats (comes either from request body or as query param) @return stream of results (&gt;= repeats)
[ "Endpoint", "which", "receives", "username", "and", "repeats", "number", "and", "returns", "stream", "of", "messages", "limited", "by", "the", "repeat", "number", "size" ]
9e43ab39230c5787065053da0f766d822d0fe4e7
https://github.com/outbrain/ob1k/blob/9e43ab39230c5787065053da0f766d822d0fe4e7/ob1k-example/src/main/java/com/outbrain/ob1k/example/hello/server/services/HelloServiceImpl.java#L61-L64
991
outbrain/ob1k
ob1k-concurrent/src/main/java/com/outbrain/ob1k/concurrent/ComposableFutures.java
ComposableFutures.batchToStream
public static <T, R> Observable<List<R>> batchToStream(final List<T> elements, final int batchSize, final FutureSuccessHandler<T, R> producer) { return Observable.create(subscriber -> batchToStream(elements, batchSize, 0, subscriber, producer)); }
java
public static <T, R> Observable<List<R>> batchToStream(final List<T> elements, final int batchSize, final FutureSuccessHandler<T, R> producer) { return Observable.create(subscriber -> batchToStream(elements, batchSize, 0, subscriber, producer)); }
[ "public", "static", "<", "T", ",", "R", ">", "Observable", "<", "List", "<", "R", ">", ">", "batchToStream", "(", "final", "List", "<", "T", ">", "elements", ",", "final", "int", "batchSize", ",", "final", "FutureSuccessHandler", "<", "T", ",", "R", ">", "producer", ")", "{", "return", "Observable", ".", "create", "(", "subscriber", "->", "batchToStream", "(", "elements", ",", "batchSize", ",", "0", ",", "subscriber", ",", "producer", ")", ")", ";", "}" ]
Execute the producer on each element in the list in batches and return a stream of batch results. Every batch is executed in parallel and the next batch begins only after the previous one ended. The result of each batch is the next element in the stream. An error in one of the futures produced by the producer will end the stream with the error @param elements the input to the producer @param batchSize how many items will be processed in parallel @param producer produces a future based on input from the element list @param <T> the type of the elements in the input list @param <R> the result type of the future returning from the producer @return a stream containing the combined result of each batch
[ "Execute", "the", "producer", "on", "each", "element", "in", "the", "list", "in", "batches", "and", "return", "a", "stream", "of", "batch", "results", ".", "Every", "batch", "is", "executed", "in", "parallel", "and", "the", "next", "batch", "begins", "only", "after", "the", "previous", "one", "ended", ".", "The", "result", "of", "each", "batch", "is", "the", "next", "element", "in", "the", "stream", ".", "An", "error", "in", "one", "of", "the", "futures", "produced", "by", "the", "producer", "will", "end", "the", "stream", "with", "the", "error" ]
9e43ab39230c5787065053da0f766d822d0fe4e7
https://github.com/outbrain/ob1k/blob/9e43ab39230c5787065053da0f766d822d0fe4e7/ob1k-concurrent/src/main/java/com/outbrain/ob1k/concurrent/ComposableFutures.java#L338-L341
992
outbrain/ob1k
ob1k-concurrent/src/main/java/com/outbrain/ob1k/concurrent/ComposableFutures.java
ComposableFutures.submit
public static <T> ComposableFuture<T> submit(final Callable<T> task) { return submit(false, task); }
java
public static <T> ComposableFuture<T> submit(final Callable<T> task) { return submit(false, task); }
[ "public", "static", "<", "T", ">", "ComposableFuture", "<", "T", ">", "submit", "(", "final", "Callable", "<", "T", ">", "task", ")", "{", "return", "submit", "(", "false", ",", "task", ")", ";", "}" ]
sends a callable task to the default thread pool and returns a ComposableFuture that represent the result. @param task the task to run. @param <T> the future type @return a future representing the result.
[ "sends", "a", "callable", "task", "to", "the", "default", "thread", "pool", "and", "returns", "a", "ComposableFuture", "that", "represent", "the", "result", "." ]
9e43ab39230c5787065053da0f766d822d0fe4e7
https://github.com/outbrain/ob1k/blob/9e43ab39230c5787065053da0f766d822d0fe4e7/ob1k-concurrent/src/main/java/com/outbrain/ob1k/concurrent/ComposableFutures.java#L415-L417
993
outbrain/ob1k
ob1k-concurrent/src/main/java/com/outbrain/ob1k/concurrent/ComposableFutures.java
ComposableFutures.buildLazy
public static <T> ComposableFuture<T> buildLazy(final Producer<T> producer) { return LazyComposableFuture.build(producer); }
java
public static <T> ComposableFuture<T> buildLazy(final Producer<T> producer) { return LazyComposableFuture.build(producer); }
[ "public", "static", "<", "T", ">", "ComposableFuture", "<", "T", ">", "buildLazy", "(", "final", "Producer", "<", "T", ">", "producer", ")", "{", "return", "LazyComposableFuture", ".", "build", "(", "producer", ")", ";", "}" ]
builds a lazy future from a producer. the producer itself is cached and used afresh on every consumption. @param producer the result producer @param <T> the future type @return the future
[ "builds", "a", "lazy", "future", "from", "a", "producer", ".", "the", "producer", "itself", "is", "cached", "and", "used", "afresh", "on", "every", "consumption", "." ]
9e43ab39230c5787065053da0f766d822d0fe4e7
https://github.com/outbrain/ob1k/blob/9e43ab39230c5787065053da0f766d822d0fe4e7/ob1k-concurrent/src/main/java/com/outbrain/ob1k/concurrent/ComposableFutures.java#L492-L494
994
outbrain/ob1k
ob1k-concurrent/src/main/java/com/outbrain/ob1k/concurrent/ComposableFutures.java
ComposableFutures.withTimeout
public static <T> ComposableFuture<T> withTimeout(final ComposableFuture<T> future, final long duration, final TimeUnit unit) { return future.withTimeout(SchedulerServiceHolder.INSTANCE, duration, unit); }
java
public static <T> ComposableFuture<T> withTimeout(final ComposableFuture<T> future, final long duration, final TimeUnit unit) { return future.withTimeout(SchedulerServiceHolder.INSTANCE, duration, unit); }
[ "public", "static", "<", "T", ">", "ComposableFuture", "<", "T", ">", "withTimeout", "(", "final", "ComposableFuture", "<", "T", ">", "future", ",", "final", "long", "duration", ",", "final", "TimeUnit", "unit", ")", "{", "return", "future", ".", "withTimeout", "(", "SchedulerServiceHolder", ".", "INSTANCE", ",", "duration", ",", "unit", ")", ";", "}" ]
adds a time cap to the provided future. if response do not arrive after the specified time a TimeoutException is returned from the returned future. @param future the source future @param duration time duration before emitting a timeout @param unit the duration time unit @param <T> the future type @return a new future with a timeout
[ "adds", "a", "time", "cap", "to", "the", "provided", "future", ".", "if", "response", "do", "not", "arrive", "after", "the", "specified", "time", "a", "TimeoutException", "is", "returned", "from", "the", "returned", "future", "." ]
9e43ab39230c5787065053da0f766d822d0fe4e7
https://github.com/outbrain/ob1k/blob/9e43ab39230c5787065053da0f766d822d0fe4e7/ob1k-concurrent/src/main/java/com/outbrain/ob1k/concurrent/ComposableFutures.java#L518-L521
995
outbrain/ob1k
ob1k-concurrent/src/main/java/com/outbrain/ob1k/concurrent/ComposableFutures.java
ComposableFutures.retry
@Deprecated public static <T> ComposableFuture<T> retry(final int retries, final long duration, final TimeUnit unit, final FutureAction<T> action) { return action.execute().withTimeout(duration, unit).recoverWith(error -> { if (retries < 1) { return ComposableFutures.fromError(error); } return retry(retries - 1, action); }); }
java
@Deprecated public static <T> ComposableFuture<T> retry(final int retries, final long duration, final TimeUnit unit, final FutureAction<T> action) { return action.execute().withTimeout(duration, unit).recoverWith(error -> { if (retries < 1) { return ComposableFutures.fromError(error); } return retry(retries - 1, action); }); }
[ "@", "Deprecated", "public", "static", "<", "T", ">", "ComposableFuture", "<", "T", ">", "retry", "(", "final", "int", "retries", ",", "final", "long", "duration", ",", "final", "TimeUnit", "unit", ",", "final", "FutureAction", "<", "T", ">", "action", ")", "{", "return", "action", ".", "execute", "(", ")", ".", "withTimeout", "(", "duration", ",", "unit", ")", ".", "recoverWith", "(", "error", "->", "{", "if", "(", "retries", "<", "1", ")", "{", "return", "ComposableFutures", ".", "fromError", "(", "error", ")", ";", "}", "return", "retry", "(", "retries", "-", "1", ",", "action", ")", ";", "}", ")", ";", "}" ]
reties an eager future on failure "retries" times. each try is time capped with the specified time limit. @param retries max amount of retries @param duration the max time duration allowed for each try @param unit the duration time unit @param action the eager future provider @param <T> the future type @return the composed result. @deprecated please define execution cap outside of retry context
[ "reties", "an", "eager", "future", "on", "failure", "retries", "times", ".", "each", "try", "is", "time", "capped", "with", "the", "specified", "time", "limit", "." ]
9e43ab39230c5787065053da0f766d822d0fe4e7
https://github.com/outbrain/ob1k/blob/9e43ab39230c5787065053da0f766d822d0fe4e7/ob1k-concurrent/src/main/java/com/outbrain/ob1k/concurrent/ComposableFutures.java#L572-L582
996
outbrain/ob1k
ob1k-concurrent/src/main/java/com/outbrain/ob1k/concurrent/ComposableFutures.java
ComposableFutures.doubleDispatch
public static <T> ComposableFuture<T> doubleDispatch(final long duration, final TimeUnit unit, final FutureAction<T> action) { return EagerComposableFuture.doubleDispatch(action, duration, unit, getScheduler()); }
java
public static <T> ComposableFuture<T> doubleDispatch(final long duration, final TimeUnit unit, final FutureAction<T> action) { return EagerComposableFuture.doubleDispatch(action, duration, unit, getScheduler()); }
[ "public", "static", "<", "T", ">", "ComposableFuture", "<", "T", ">", "doubleDispatch", "(", "final", "long", "duration", ",", "final", "TimeUnit", "unit", ",", "final", "FutureAction", "<", "T", ">", "action", ")", "{", "return", "EagerComposableFuture", ".", "doubleDispatch", "(", "action", ",", "duration", ",", "unit", ",", "getScheduler", "(", ")", ")", ";", "}" ]
creates a future that fires the first future immediately and a second one after a specified time period if result hasn't arrived yet. should be used with eager futures. @param duration time to wait until the second future is fired @param unit the duration time unit @param action a provider of eager future @param <T> the type of the future @return the composed future
[ "creates", "a", "future", "that", "fires", "the", "first", "future", "immediately", "and", "a", "second", "one", "after", "a", "specified", "time", "period", "if", "result", "hasn", "t", "arrived", "yet", ".", "should", "be", "used", "with", "eager", "futures", "." ]
9e43ab39230c5787065053da0f766d822d0fe4e7
https://github.com/outbrain/ob1k/blob/9e43ab39230c5787065053da0f766d822d0fe4e7/ob1k-concurrent/src/main/java/com/outbrain/ob1k/concurrent/ComposableFutures.java#L595-L598
997
outbrain/ob1k
ob1k-concurrent/src/main/java/com/outbrain/ob1k/concurrent/ComposableFutures.java
ComposableFutures.toColdObservable
public static <T> Observable<T> toColdObservable(final List<ComposableFuture<T>> futures, final boolean failOnError) { return Observable.create(subscriber -> { final AtomicInteger counter = new AtomicInteger(futures.size()); final AtomicBoolean errorTrigger = new AtomicBoolean(false); for (final ComposableFuture<T> future : futures) { future.consume(provideObserverResult(subscriber, counter, errorTrigger, failOnError)); } }); }
java
public static <T> Observable<T> toColdObservable(final List<ComposableFuture<T>> futures, final boolean failOnError) { return Observable.create(subscriber -> { final AtomicInteger counter = new AtomicInteger(futures.size()); final AtomicBoolean errorTrigger = new AtomicBoolean(false); for (final ComposableFuture<T> future : futures) { future.consume(provideObserverResult(subscriber, counter, errorTrigger, failOnError)); } }); }
[ "public", "static", "<", "T", ">", "Observable", "<", "T", ">", "toColdObservable", "(", "final", "List", "<", "ComposableFuture", "<", "T", ">", ">", "futures", ",", "final", "boolean", "failOnError", ")", "{", "return", "Observable", ".", "create", "(", "subscriber", "->", "{", "final", "AtomicInteger", "counter", "=", "new", "AtomicInteger", "(", "futures", ".", "size", "(", ")", ")", ";", "final", "AtomicBoolean", "errorTrigger", "=", "new", "AtomicBoolean", "(", "false", ")", ";", "for", "(", "final", "ComposableFuture", "<", "T", ">", "future", ":", "futures", ")", "{", "future", ".", "consume", "(", "provideObserverResult", "(", "subscriber", ",", "counter", ",", "errorTrigger", ",", "failOnError", ")", ")", ";", "}", "}", ")", ";", "}" ]
translate a list of lazy futures to a cold Observable stream @param futures the lazy list of futures @param failOnError whether to close the stream upon a future error @param <T> the stream type @return the stream
[ "translate", "a", "list", "of", "lazy", "futures", "to", "a", "cold", "Observable", "stream" ]
9e43ab39230c5787065053da0f766d822d0fe4e7
https://github.com/outbrain/ob1k/blob/9e43ab39230c5787065053da0f766d822d0fe4e7/ob1k-concurrent/src/main/java/com/outbrain/ob1k/concurrent/ComposableFutures.java#L628-L637
998
outbrain/ob1k
ob1k-concurrent/src/main/java/com/outbrain/ob1k/concurrent/ComposableFutures.java
ComposableFutures.toColdObservable
public static <T> Observable<T> toColdObservable(final RecursiveFutureProvider<T> futureProvider) { return Observable.create(new Observable.OnSubscribe<T>() { @Override public void call(final Subscriber<? super T> subscriber) { recursiveChain(subscriber, futureProvider.createStopCriteria()); } private void recursiveChain(final Subscriber<? super T> subscriber, final Predicate<T> stopCriteria) { futureProvider.provide().consume(result -> { if (result.isSuccess()) { final T value = result.getValue(); subscriber.onNext(value); if (stopCriteria.apply(value)) { subscriber.onCompleted(); } else { recursiveChain(subscriber, stopCriteria); } } else { subscriber.onError(result.getError()); } }); } }); }
java
public static <T> Observable<T> toColdObservable(final RecursiveFutureProvider<T> futureProvider) { return Observable.create(new Observable.OnSubscribe<T>() { @Override public void call(final Subscriber<? super T> subscriber) { recursiveChain(subscriber, futureProvider.createStopCriteria()); } private void recursiveChain(final Subscriber<? super T> subscriber, final Predicate<T> stopCriteria) { futureProvider.provide().consume(result -> { if (result.isSuccess()) { final T value = result.getValue(); subscriber.onNext(value); if (stopCriteria.apply(value)) { subscriber.onCompleted(); } else { recursiveChain(subscriber, stopCriteria); } } else { subscriber.onError(result.getError()); } }); } }); }
[ "public", "static", "<", "T", ">", "Observable", "<", "T", ">", "toColdObservable", "(", "final", "RecursiveFutureProvider", "<", "T", ">", "futureProvider", ")", "{", "return", "Observable", ".", "create", "(", "new", "Observable", ".", "OnSubscribe", "<", "T", ">", "(", ")", "{", "@", "Override", "public", "void", "call", "(", "final", "Subscriber", "<", "?", "super", "T", ">", "subscriber", ")", "{", "recursiveChain", "(", "subscriber", ",", "futureProvider", ".", "createStopCriteria", "(", ")", ")", ";", "}", "private", "void", "recursiveChain", "(", "final", "Subscriber", "<", "?", "super", "T", ">", "subscriber", ",", "final", "Predicate", "<", "T", ">", "stopCriteria", ")", "{", "futureProvider", ".", "provide", "(", ")", ".", "consume", "(", "result", "->", "{", "if", "(", "result", ".", "isSuccess", "(", ")", ")", "{", "final", "T", "value", "=", "result", ".", "getValue", "(", ")", ";", "subscriber", ".", "onNext", "(", "value", ")", ";", "if", "(", "stopCriteria", ".", "apply", "(", "value", ")", ")", "{", "subscriber", ".", "onCompleted", "(", ")", ";", "}", "else", "{", "recursiveChain", "(", "subscriber", ",", "stopCriteria", ")", ";", "}", "}", "else", "{", "subscriber", ".", "onError", "(", "result", ".", "getError", "(", ")", ")", ";", "}", "}", ")", ";", "}", "}", ")", ";", "}" ]
creates new cold observable, given future provider, on each subscribe will consume the provided future and repeat until stop criteria will exists each result will be emitted to the stream @param futureProvider the future provider @param <T> the stream type @return the stream
[ "creates", "new", "cold", "observable", "given", "future", "provider", "on", "each", "subscribe", "will", "consume", "the", "provided", "future", "and", "repeat", "until", "stop", "criteria", "will", "exists", "each", "result", "will", "be", "emitted", "to", "the", "stream" ]
9e43ab39230c5787065053da0f766d822d0fe4e7
https://github.com/outbrain/ob1k/blob/9e43ab39230c5787065053da0f766d822d0fe4e7/ob1k-concurrent/src/main/java/com/outbrain/ob1k/concurrent/ComposableFutures.java#L649-L672
999
outbrain/ob1k
ob1k-concurrent/src/main/java/com/outbrain/ob1k/concurrent/ComposableFutures.java
ComposableFutures.toHotObservable
public static <T> Observable<T> toHotObservable(final List<ComposableFuture<T>> futures, final boolean failOnError) { final ReplaySubject<T> subject = ReplaySubject.create(futures.size()); final AtomicInteger counter = new AtomicInteger(futures.size()); final AtomicBoolean errorTrigger = new AtomicBoolean(false); for (final ComposableFuture<T> future : futures) { future.consume(provideObserverResult(subject, counter, errorTrigger, failOnError)); } return subject; }
java
public static <T> Observable<T> toHotObservable(final List<ComposableFuture<T>> futures, final boolean failOnError) { final ReplaySubject<T> subject = ReplaySubject.create(futures.size()); final AtomicInteger counter = new AtomicInteger(futures.size()); final AtomicBoolean errorTrigger = new AtomicBoolean(false); for (final ComposableFuture<T> future : futures) { future.consume(provideObserverResult(subject, counter, errorTrigger, failOnError)); } return subject; }
[ "public", "static", "<", "T", ">", "Observable", "<", "T", ">", "toHotObservable", "(", "final", "List", "<", "ComposableFuture", "<", "T", ">", ">", "futures", ",", "final", "boolean", "failOnError", ")", "{", "final", "ReplaySubject", "<", "T", ">", "subject", "=", "ReplaySubject", ".", "create", "(", "futures", ".", "size", "(", ")", ")", ";", "final", "AtomicInteger", "counter", "=", "new", "AtomicInteger", "(", "futures", ".", "size", "(", ")", ")", ";", "final", "AtomicBoolean", "errorTrigger", "=", "new", "AtomicBoolean", "(", "false", ")", ";", "for", "(", "final", "ComposableFuture", "<", "T", ">", "future", ":", "futures", ")", "{", "future", ".", "consume", "(", "provideObserverResult", "(", "subject", ",", "counter", ",", "errorTrigger", ",", "failOnError", ")", ")", ";", "}", "return", "subject", ";", "}" ]
translate a list of eager futures into a hot Observable stream the results of the futures will be stored in the stream for any future subscriber. @param futures the list of eager futures @param failOnError whether to close the stream upon a future error @param <T> the stream type @return the stream
[ "translate", "a", "list", "of", "eager", "futures", "into", "a", "hot", "Observable", "stream", "the", "results", "of", "the", "futures", "will", "be", "stored", "in", "the", "stream", "for", "any", "future", "subscriber", "." ]
9e43ab39230c5787065053da0f766d822d0fe4e7
https://github.com/outbrain/ob1k/blob/9e43ab39230c5787065053da0f766d822d0fe4e7/ob1k-concurrent/src/main/java/com/outbrain/ob1k/concurrent/ComposableFutures.java#L683-L693