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
163,100
darrachequesne/spring-data-jpa-datatables
src/main/java/org/springframework/data/jpa/datatables/mapping/DataTablesInput.java
DataTablesInput.addOrder
public void addOrder(String columnName, boolean ascending) { if (columnName == null) { return; } for (int i = 0; i < columns.size(); i++) { if (!columnName.equals(columns.get(i).getData())) { continue; } order.add(new Order(i, ascending ? "asc" : "desc")); } }
java
public void addOrder(String columnName, boolean ascending) { if (columnName == null) { return; } for (int i = 0; i < columns.size(); i++) { if (!columnName.equals(columns.get(i).getData())) { continue; } order.add(new Order(i, ascending ? "asc" : "desc")); } }
[ "public", "void", "addOrder", "(", "String", "columnName", ",", "boolean", "ascending", ")", "{", "if", "(", "columnName", "==", "null", ")", "{", "return", ";", "}", "for", "(", "int", "i", "=", "0", ";", "i", "<", "columns", ".", "size", "(", ")", ";", "i", "++", ")", "{", "if", "(", "!", "columnName", ".", "equals", "(", "columns", ".", "get", "(", "i", ")", ".", "getData", "(", ")", ")", ")", "{", "continue", ";", "}", "order", ".", "add", "(", "new", "Order", "(", "i", ",", "ascending", "?", "\"asc\"", ":", "\"desc\"", ")", ")", ";", "}", "}" ]
Add an order on the given column @param columnName the name of the column @param ascending whether the sorting is ascending or descending
[ "Add", "an", "order", "on", "the", "given", "column" ]
0174dec8f52595a8e4b79f32c79922d64b02b732
https://github.com/darrachequesne/spring-data-jpa-datatables/blob/0174dec8f52595a8e4b79f32c79922d64b02b732/src/main/java/org/springframework/data/jpa/datatables/mapping/DataTablesInput.java#L112-L122
163,101
mojohaus/flatten-maven-plugin
src/main/java/org/codehaus/mojo/flatten/cifriendly/CiModelInterpolator.java
CiModelInterpolator.interpolateModel
public Model interpolateModel(Model model, File projectDir, ModelBuildingRequest config, ModelProblemCollector problems) { interpolateObject(model, model, projectDir, config, problems); return model; }
java
public Model interpolateModel(Model model, File projectDir, ModelBuildingRequest config, ModelProblemCollector problems) { interpolateObject(model, model, projectDir, config, problems); return model; }
[ "public", "Model", "interpolateModel", "(", "Model", "model", ",", "File", "projectDir", ",", "ModelBuildingRequest", "config", ",", "ModelProblemCollector", "problems", ")", "{", "interpolateObject", "(", "model", ",", "model", ",", "projectDir", ",", "config", ",", "problems", ")", ";", "return", "model", ";", "}" ]
Empirical data from 3.x, actual =40
[ "Empirical", "data", "from", "3", ".", "x", "actual", "=", "40" ]
df25d03a4d6c06c4de5cfd9f52dfbe72e823e403
https://github.com/mojohaus/flatten-maven-plugin/blob/df25d03a4d6c06c4de5cfd9f52dfbe72e823e403/src/main/java/org/codehaus/mojo/flatten/cifriendly/CiModelInterpolator.java#L114-L119
163,102
mojohaus/flatten-maven-plugin
src/main/java/org/codehaus/mojo/flatten/cifriendly/CiInterpolatorImpl.java
CiInterpolatorImpl.interpolate
public String interpolate( String input, RecursionInterceptor recursionInterceptor ) throws InterpolationException { try { return interpolate( input, recursionInterceptor, new HashSet<String>() ); } finally { if ( !cacheAnswers ) { existingAnswers.clear(); } } }
java
public String interpolate( String input, RecursionInterceptor recursionInterceptor ) throws InterpolationException { try { return interpolate( input, recursionInterceptor, new HashSet<String>() ); } finally { if ( !cacheAnswers ) { existingAnswers.clear(); } } }
[ "public", "String", "interpolate", "(", "String", "input", ",", "RecursionInterceptor", "recursionInterceptor", ")", "throws", "InterpolationException", "{", "try", "{", "return", "interpolate", "(", "input", ",", "recursionInterceptor", ",", "new", "HashSet", "<", "String", ">", "(", ")", ")", ";", "}", "finally", "{", "if", "(", "!", "cacheAnswers", ")", "{", "existingAnswers", ".", "clear", "(", ")", ";", "}", "}", "}" ]
Entry point for recursive resolution of an expression and all of its nested expressions. @todo Ensure unresolvable expressions don't trigger infinite recursion.
[ "Entry", "point", "for", "recursive", "resolution", "of", "an", "expression", "and", "all", "of", "its", "nested", "expressions", "." ]
df25d03a4d6c06c4de5cfd9f52dfbe72e823e403
https://github.com/mojohaus/flatten-maven-plugin/blob/df25d03a4d6c06c4de5cfd9f52dfbe72e823e403/src/main/java/org/codehaus/mojo/flatten/cifriendly/CiInterpolatorImpl.java#L131-L145
163,103
mojohaus/flatten-maven-plugin
src/main/java/org/codehaus/mojo/flatten/cifriendly/CiInterpolatorImpl.java
CiInterpolatorImpl.getFeedback
public List getFeedback() { List<?> messages = new ArrayList(); for ( ValueSource vs : valueSources ) { List feedback = vs.getFeedback(); if ( feedback != null && !feedback.isEmpty() ) { messages.addAll( feedback ); } } return messages; }
java
public List getFeedback() { List<?> messages = new ArrayList(); for ( ValueSource vs : valueSources ) { List feedback = vs.getFeedback(); if ( feedback != null && !feedback.isEmpty() ) { messages.addAll( feedback ); } } return messages; }
[ "public", "List", "getFeedback", "(", ")", "{", "List", "<", "?", ">", "messages", "=", "new", "ArrayList", "(", ")", ";", "for", "(", "ValueSource", "vs", ":", "valueSources", ")", "{", "List", "feedback", "=", "vs", ".", "getFeedback", "(", ")", ";", "if", "(", "feedback", "!=", "null", "&&", "!", "feedback", ".", "isEmpty", "(", ")", ")", "{", "messages", ".", "addAll", "(", "feedback", ")", ";", "}", "}", "return", "messages", ";", "}" ]
Return any feedback messages and errors that were generated - but suppressed - during the interpolation process. Since unresolvable expressions will be left in the source string as-is, this feedback is optional, and will only be useful for debugging interpolation problems. @return a {@link List} that may be interspersed with {@link String} and {@link Throwable} instances.
[ "Return", "any", "feedback", "messages", "and", "errors", "that", "were", "generated", "-", "but", "suppressed", "-", "during", "the", "interpolation", "process", ".", "Since", "unresolvable", "expressions", "will", "be", "left", "in", "the", "source", "string", "as", "-", "is", "this", "feedback", "is", "optional", "and", "will", "only", "be", "useful", "for", "debugging", "interpolation", "problems", "." ]
df25d03a4d6c06c4de5cfd9f52dfbe72e823e403
https://github.com/mojohaus/flatten-maven-plugin/blob/df25d03a4d6c06c4de5cfd9f52dfbe72e823e403/src/main/java/org/codehaus/mojo/flatten/cifriendly/CiInterpolatorImpl.java#L301-L314
163,104
mojohaus/flatten-maven-plugin
src/main/java/org/codehaus/mojo/flatten/model/resolution/FlattenModelResolver.java
FlattenModelResolver.resolveModel
public ModelSource resolveModel( Parent parent ) throws UnresolvableModelException { Dependency parentDependency = new Dependency(); parentDependency.setGroupId(parent.getGroupId()); parentDependency.setArtifactId(parent.getArtifactId()); parentDependency.setVersion(parent.getVersion()); parentDependency.setClassifier(""); parentDependency.setType("pom"); Artifact parentArtifact = null; try { Iterable<ArtifactResult> artifactResults = depencencyResolver.resolveDependencies( projectBuildingRequest, singleton(parentDependency), null, null ); Iterator<ArtifactResult> iterator = artifactResults.iterator(); if (iterator.hasNext()) { parentArtifact = iterator.next().getArtifact(); } } catch (DependencyResolverException e) { throw new UnresolvableModelException( e.getMessage(), parent.getGroupId(), parent.getArtifactId(), parent.getVersion(), e ); } return resolveModel( parentArtifact.getGroupId(), parentArtifact.getArtifactId(), parentArtifact.getVersion() ); }
java
public ModelSource resolveModel( Parent parent ) throws UnresolvableModelException { Dependency parentDependency = new Dependency(); parentDependency.setGroupId(parent.getGroupId()); parentDependency.setArtifactId(parent.getArtifactId()); parentDependency.setVersion(parent.getVersion()); parentDependency.setClassifier(""); parentDependency.setType("pom"); Artifact parentArtifact = null; try { Iterable<ArtifactResult> artifactResults = depencencyResolver.resolveDependencies( projectBuildingRequest, singleton(parentDependency), null, null ); Iterator<ArtifactResult> iterator = artifactResults.iterator(); if (iterator.hasNext()) { parentArtifact = iterator.next().getArtifact(); } } catch (DependencyResolverException e) { throw new UnresolvableModelException( e.getMessage(), parent.getGroupId(), parent.getArtifactId(), parent.getVersion(), e ); } return resolveModel( parentArtifact.getGroupId(), parentArtifact.getArtifactId(), parentArtifact.getVersion() ); }
[ "public", "ModelSource", "resolveModel", "(", "Parent", "parent", ")", "throws", "UnresolvableModelException", "{", "Dependency", "parentDependency", "=", "new", "Dependency", "(", ")", ";", "parentDependency", ".", "setGroupId", "(", "parent", ".", "getGroupId", "(", ")", ")", ";", "parentDependency", ".", "setArtifactId", "(", "parent", ".", "getArtifactId", "(", ")", ")", ";", "parentDependency", ".", "setVersion", "(", "parent", ".", "getVersion", "(", ")", ")", ";", "parentDependency", ".", "setClassifier", "(", "\"\"", ")", ";", "parentDependency", ".", "setType", "(", "\"pom\"", ")", ";", "Artifact", "parentArtifact", "=", "null", ";", "try", "{", "Iterable", "<", "ArtifactResult", ">", "artifactResults", "=", "depencencyResolver", ".", "resolveDependencies", "(", "projectBuildingRequest", ",", "singleton", "(", "parentDependency", ")", ",", "null", ",", "null", ")", ";", "Iterator", "<", "ArtifactResult", ">", "iterator", "=", "artifactResults", ".", "iterator", "(", ")", ";", "if", "(", "iterator", ".", "hasNext", "(", ")", ")", "{", "parentArtifact", "=", "iterator", ".", "next", "(", ")", ".", "getArtifact", "(", ")", ";", "}", "}", "catch", "(", "DependencyResolverException", "e", ")", "{", "throw", "new", "UnresolvableModelException", "(", "e", ".", "getMessage", "(", ")", ",", "parent", ".", "getGroupId", "(", ")", ",", "parent", ".", "getArtifactId", "(", ")", ",", "parent", ".", "getVersion", "(", ")", ",", "e", ")", ";", "}", "return", "resolveModel", "(", "parentArtifact", ".", "getGroupId", "(", ")", ",", "parentArtifact", ".", "getArtifactId", "(", ")", ",", "parentArtifact", ".", "getVersion", "(", ")", ")", ";", "}" ]
Resolves the POM for the specified parent. @param parent the parent coordinates to resolve, must not be {@code null} @return The source of the requested POM, never {@code null} @since Apache-Maven-3.2.2 (MNG-5639)
[ "Resolves", "the", "POM", "for", "the", "specified", "parent", "." ]
df25d03a4d6c06c4de5cfd9f52dfbe72e823e403
https://github.com/mojohaus/flatten-maven-plugin/blob/df25d03a4d6c06c4de5cfd9f52dfbe72e823e403/src/main/java/org/codehaus/mojo/flatten/model/resolution/FlattenModelResolver.java#L138-L163
163,105
mojohaus/flatten-maven-plugin
src/main/java/org/codehaus/mojo/flatten/FlattenMojo.java
FlattenMojo.extractHeaderComment
protected String extractHeaderComment( File xmlFile ) throws MojoExecutionException { try { SAXParser parser = SAXParserFactory.newInstance().newSAXParser(); SaxHeaderCommentHandler handler = new SaxHeaderCommentHandler(); parser.setProperty( "http://xml.org/sax/properties/lexical-handler", handler ); parser.parse( xmlFile, handler ); return handler.getHeaderComment(); } catch ( Exception e ) { throw new MojoExecutionException( "Failed to parse XML from " + xmlFile, e ); } }
java
protected String extractHeaderComment( File xmlFile ) throws MojoExecutionException { try { SAXParser parser = SAXParserFactory.newInstance().newSAXParser(); SaxHeaderCommentHandler handler = new SaxHeaderCommentHandler(); parser.setProperty( "http://xml.org/sax/properties/lexical-handler", handler ); parser.parse( xmlFile, handler ); return handler.getHeaderComment(); } catch ( Exception e ) { throw new MojoExecutionException( "Failed to parse XML from " + xmlFile, e ); } }
[ "protected", "String", "extractHeaderComment", "(", "File", "xmlFile", ")", "throws", "MojoExecutionException", "{", "try", "{", "SAXParser", "parser", "=", "SAXParserFactory", ".", "newInstance", "(", ")", ".", "newSAXParser", "(", ")", ";", "SaxHeaderCommentHandler", "handler", "=", "new", "SaxHeaderCommentHandler", "(", ")", ";", "parser", ".", "setProperty", "(", "\"http://xml.org/sax/properties/lexical-handler\"", ",", "handler", ")", ";", "parser", ".", "parse", "(", "xmlFile", ",", "handler", ")", ";", "return", "handler", ".", "getHeaderComment", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "MojoExecutionException", "(", "\"Failed to parse XML from \"", "+", "xmlFile", ",", "e", ")", ";", "}", "}" ]
This method extracts the XML header comment if available. @param xmlFile is the XML {@link File} to parse. @return the XML comment between the XML header declaration and the root tag or <code>null</code> if NOT available. @throws MojoExecutionException if anything goes wrong.
[ "This", "method", "extracts", "the", "XML", "header", "comment", "if", "available", "." ]
df25d03a4d6c06c4de5cfd9f52dfbe72e823e403
https://github.com/mojohaus/flatten-maven-plugin/blob/df25d03a4d6c06c4de5cfd9f52dfbe72e823e403/src/main/java/org/codehaus/mojo/flatten/FlattenMojo.java#L356-L372
163,106
mojohaus/flatten-maven-plugin
src/main/java/org/codehaus/mojo/flatten/FlattenMojo.java
FlattenMojo.createFlattenedPom
protected Model createFlattenedPom( File pomFile ) throws MojoExecutionException, MojoFailureException { ModelBuildingRequest buildingRequest = createModelBuildingRequest( pomFile ); Model effectivePom = createEffectivePom( buildingRequest, isEmbedBuildProfileDependencies(), this.flattenMode ); Model flattenedPom = new Model(); // keep original encoding (we could also normalize to UTF-8 here) String modelEncoding = effectivePom.getModelEncoding(); if ( StringUtils.isEmpty( modelEncoding ) ) { modelEncoding = "UTF-8"; } flattenedPom.setModelEncoding( modelEncoding ); Model cleanPom = createCleanPom( effectivePom ); FlattenDescriptor descriptor = getFlattenDescriptor(); Model originalPom = this.project.getOriginalModel(); Model resolvedPom = this.project.getModel(); Model interpolatedPom = createResolvedPom( buildingRequest ); // copy the configured additional POM elements... for ( PomProperty<?> property : PomProperty.getPomProperties() ) { if ( property.isElement() ) { Model sourceModel = getSourceModel( descriptor, property, effectivePom, originalPom, resolvedPom, interpolatedPom, cleanPom ); if ( sourceModel == null ) { if ( property.isRequired() ) { throw new MojoFailureException( "Property " + property.getName() + " is required and can not be removed!" ); } } else { property.copy( sourceModel, flattenedPom ); } } } return flattenedPom; }
java
protected Model createFlattenedPom( File pomFile ) throws MojoExecutionException, MojoFailureException { ModelBuildingRequest buildingRequest = createModelBuildingRequest( pomFile ); Model effectivePom = createEffectivePom( buildingRequest, isEmbedBuildProfileDependencies(), this.flattenMode ); Model flattenedPom = new Model(); // keep original encoding (we could also normalize to UTF-8 here) String modelEncoding = effectivePom.getModelEncoding(); if ( StringUtils.isEmpty( modelEncoding ) ) { modelEncoding = "UTF-8"; } flattenedPom.setModelEncoding( modelEncoding ); Model cleanPom = createCleanPom( effectivePom ); FlattenDescriptor descriptor = getFlattenDescriptor(); Model originalPom = this.project.getOriginalModel(); Model resolvedPom = this.project.getModel(); Model interpolatedPom = createResolvedPom( buildingRequest ); // copy the configured additional POM elements... for ( PomProperty<?> property : PomProperty.getPomProperties() ) { if ( property.isElement() ) { Model sourceModel = getSourceModel( descriptor, property, effectivePom, originalPom, resolvedPom, interpolatedPom, cleanPom ); if ( sourceModel == null ) { if ( property.isRequired() ) { throw new MojoFailureException( "Property " + property.getName() + " is required and can not be removed!" ); } } else { property.copy( sourceModel, flattenedPom ); } } } return flattenedPom; }
[ "protected", "Model", "createFlattenedPom", "(", "File", "pomFile", ")", "throws", "MojoExecutionException", ",", "MojoFailureException", "{", "ModelBuildingRequest", "buildingRequest", "=", "createModelBuildingRequest", "(", "pomFile", ")", ";", "Model", "effectivePom", "=", "createEffectivePom", "(", "buildingRequest", ",", "isEmbedBuildProfileDependencies", "(", ")", ",", "this", ".", "flattenMode", ")", ";", "Model", "flattenedPom", "=", "new", "Model", "(", ")", ";", "// keep original encoding (we could also normalize to UTF-8 here)", "String", "modelEncoding", "=", "effectivePom", ".", "getModelEncoding", "(", ")", ";", "if", "(", "StringUtils", ".", "isEmpty", "(", "modelEncoding", ")", ")", "{", "modelEncoding", "=", "\"UTF-8\"", ";", "}", "flattenedPom", ".", "setModelEncoding", "(", "modelEncoding", ")", ";", "Model", "cleanPom", "=", "createCleanPom", "(", "effectivePom", ")", ";", "FlattenDescriptor", "descriptor", "=", "getFlattenDescriptor", "(", ")", ";", "Model", "originalPom", "=", "this", ".", "project", ".", "getOriginalModel", "(", ")", ";", "Model", "resolvedPom", "=", "this", ".", "project", ".", "getModel", "(", ")", ";", "Model", "interpolatedPom", "=", "createResolvedPom", "(", "buildingRequest", ")", ";", "// copy the configured additional POM elements...", "for", "(", "PomProperty", "<", "?", ">", "property", ":", "PomProperty", ".", "getPomProperties", "(", ")", ")", "{", "if", "(", "property", ".", "isElement", "(", ")", ")", "{", "Model", "sourceModel", "=", "getSourceModel", "(", "descriptor", ",", "property", ",", "effectivePom", ",", "originalPom", ",", "resolvedPom", ",", "interpolatedPom", ",", "cleanPom", ")", ";", "if", "(", "sourceModel", "==", "null", ")", "{", "if", "(", "property", ".", "isRequired", "(", ")", ")", "{", "throw", "new", "MojoFailureException", "(", "\"Property \"", "+", "property", ".", "getName", "(", ")", "+", "\" is required and can not be removed!\"", ")", ";", "}", "}", "else", "{", "property", ".", "copy", "(", "sourceModel", ",", "flattenedPom", ")", ";", "}", "}", "}", "return", "flattenedPom", ";", "}" ]
This method creates the flattened POM what is the main task of this plugin. @param pomFile is the name of the original POM file to read and transform. @return the {@link Model} of the flattened POM. @throws MojoExecutionException if anything goes wrong (e.g. POM can not be processed). @throws MojoFailureException if anything goes wrong (logical error).
[ "This", "method", "creates", "the", "flattened", "POM", "what", "is", "the", "main", "task", "of", "this", "plugin", "." ]
df25d03a4d6c06c4de5cfd9f52dfbe72e823e403
https://github.com/mojohaus/flatten-maven-plugin/blob/df25d03a4d6c06c4de5cfd9f52dfbe72e823e403/src/main/java/org/codehaus/mojo/flatten/FlattenMojo.java#L466-L514
163,107
twitter/twitter-korean-text
src/main/java/com/twitter/penguin/korean/util/CharacterUtils.java
CharacterUtils.toCodePoints
public final int toCodePoints(char[] src, int srcOff, int srcLen, int[] dest, int destOff) { if (srcLen < 0) { throw new IllegalArgumentException("srcLen must be >= 0"); } int codePointCount = 0; for (int i = 0; i < srcLen; ) { final int cp = codePointAt(src, srcOff + i, srcOff + srcLen); final int charCount = Character.charCount(cp); dest[destOff + codePointCount++] = cp; i += charCount; } return codePointCount; }
java
public final int toCodePoints(char[] src, int srcOff, int srcLen, int[] dest, int destOff) { if (srcLen < 0) { throw new IllegalArgumentException("srcLen must be >= 0"); } int codePointCount = 0; for (int i = 0; i < srcLen; ) { final int cp = codePointAt(src, srcOff + i, srcOff + srcLen); final int charCount = Character.charCount(cp); dest[destOff + codePointCount++] = cp; i += charCount; } return codePointCount; }
[ "public", "final", "int", "toCodePoints", "(", "char", "[", "]", "src", ",", "int", "srcOff", ",", "int", "srcLen", ",", "int", "[", "]", "dest", ",", "int", "destOff", ")", "{", "if", "(", "srcLen", "<", "0", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"srcLen must be >= 0\"", ")", ";", "}", "int", "codePointCount", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "srcLen", ";", ")", "{", "final", "int", "cp", "=", "codePointAt", "(", "src", ",", "srcOff", "+", "i", ",", "srcOff", "+", "srcLen", ")", ";", "final", "int", "charCount", "=", "Character", ".", "charCount", "(", "cp", ")", ";", "dest", "[", "destOff", "+", "codePointCount", "++", "]", "=", "cp", ";", "i", "+=", "charCount", ";", "}", "return", "codePointCount", ";", "}" ]
Converts a sequence of Java characters to a sequence of unicode code points. @return the number of code points written to the destination buffer
[ "Converts", "a", "sequence", "of", "Java", "characters", "to", "a", "sequence", "of", "unicode", "code", "points", "." ]
95bbe21fcc62fa7bf50b769ae80a5734fef6b903
https://github.com/twitter/twitter-korean-text/blob/95bbe21fcc62fa7bf50b769ae80a5734fef6b903/src/main/java/com/twitter/penguin/korean/util/CharacterUtils.java#L134-L146
163,108
twitter/twitter-korean-text
src/main/java/com/twitter/penguin/korean/util/CharacterUtils.java
CharacterUtils.toChars
public final int toChars(int[] src, int srcOff, int srcLen, char[] dest, int destOff) { if (srcLen < 0) { throw new IllegalArgumentException("srcLen must be >= 0"); } int written = 0; for (int i = 0; i < srcLen; ++i) { written += Character.toChars(src[srcOff + i], dest, destOff + written); } return written; }
java
public final int toChars(int[] src, int srcOff, int srcLen, char[] dest, int destOff) { if (srcLen < 0) { throw new IllegalArgumentException("srcLen must be >= 0"); } int written = 0; for (int i = 0; i < srcLen; ++i) { written += Character.toChars(src[srcOff + i], dest, destOff + written); } return written; }
[ "public", "final", "int", "toChars", "(", "int", "[", "]", "src", ",", "int", "srcOff", ",", "int", "srcLen", ",", "char", "[", "]", "dest", ",", "int", "destOff", ")", "{", "if", "(", "srcLen", "<", "0", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"srcLen must be >= 0\"", ")", ";", "}", "int", "written", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "srcLen", ";", "++", "i", ")", "{", "written", "+=", "Character", ".", "toChars", "(", "src", "[", "srcOff", "+", "i", "]", ",", "dest", ",", "destOff", "+", "written", ")", ";", "}", "return", "written", ";", "}" ]
Converts a sequence of unicode code points to a sequence of Java characters. @return the number of chars written to the destination buffer
[ "Converts", "a", "sequence", "of", "unicode", "code", "points", "to", "a", "sequence", "of", "Java", "characters", "." ]
95bbe21fcc62fa7bf50b769ae80a5734fef6b903
https://github.com/twitter/twitter-korean-text/blob/95bbe21fcc62fa7bf50b769ae80a5734fef6b903/src/main/java/com/twitter/penguin/korean/util/CharacterUtils.java#L153-L162
163,109
twitter/twitter-korean-text
src/main/java/com/twitter/penguin/korean/TwitterKoreanProcessorJava.java
TwitterKoreanProcessorJava.splitSentences
public static List<Sentence> splitSentences(CharSequence text) { return JavaConversions.seqAsJavaList( TwitterKoreanProcessor.splitSentences(text) ); }
java
public static List<Sentence> splitSentences(CharSequence text) { return JavaConversions.seqAsJavaList( TwitterKoreanProcessor.splitSentences(text) ); }
[ "public", "static", "List", "<", "Sentence", ">", "splitSentences", "(", "CharSequence", "text", ")", "{", "return", "JavaConversions", ".", "seqAsJavaList", "(", "TwitterKoreanProcessor", ".", "splitSentences", "(", "text", ")", ")", ";", "}" ]
Split input text into sentences. @param text Input text. @return List of Sentence objects.
[ "Split", "input", "text", "into", "sentences", "." ]
95bbe21fcc62fa7bf50b769ae80a5734fef6b903
https://github.com/twitter/twitter-korean-text/blob/95bbe21fcc62fa7bf50b769ae80a5734fef6b903/src/main/java/com/twitter/penguin/korean/TwitterKoreanProcessorJava.java#L143-L147
163,110
twitter/twitter-korean-text
src/main/java/com/twitter/penguin/korean/TwitterKoreanProcessorJava.java
TwitterKoreanProcessorJava.extractPhrases
public static List<KoreanPhraseExtractor.KoreanPhrase> extractPhrases(Seq<KoreanToken> tokens, boolean filterSpam, boolean includeHashtags) { return JavaConversions.seqAsJavaList( TwitterKoreanProcessor.extractPhrases(tokens, filterSpam, includeHashtags) ); }
java
public static List<KoreanPhraseExtractor.KoreanPhrase> extractPhrases(Seq<KoreanToken> tokens, boolean filterSpam, boolean includeHashtags) { return JavaConversions.seqAsJavaList( TwitterKoreanProcessor.extractPhrases(tokens, filterSpam, includeHashtags) ); }
[ "public", "static", "List", "<", "KoreanPhraseExtractor", ".", "KoreanPhrase", ">", "extractPhrases", "(", "Seq", "<", "KoreanToken", ">", "tokens", ",", "boolean", "filterSpam", ",", "boolean", "includeHashtags", ")", "{", "return", "JavaConversions", ".", "seqAsJavaList", "(", "TwitterKoreanProcessor", ".", "extractPhrases", "(", "tokens", ",", "filterSpam", ",", "includeHashtags", ")", ")", ";", "}" ]
Extract phrases from Korean input text @param tokens Korean tokens (output of tokenize(CharSequence text)). @return List of phrase CharSequences.
[ "Extract", "phrases", "from", "Korean", "input", "text" ]
95bbe21fcc62fa7bf50b769ae80a5734fef6b903
https://github.com/twitter/twitter-korean-text/blob/95bbe21fcc62fa7bf50b769ae80a5734fef6b903/src/main/java/com/twitter/penguin/korean/TwitterKoreanProcessorJava.java#L155-L159
163,111
twitter/twitter-korean-text
src/main/java/com/twitter/penguin/korean/TwitterKoreanProcessorJava.java
TwitterKoreanProcessorJava.detokenize
public static String detokenize(List<String> tokens) { return TwitterKoreanProcessor.detokenize(JavaConversions.iterableAsScalaIterable(tokens)); }
java
public static String detokenize(List<String> tokens) { return TwitterKoreanProcessor.detokenize(JavaConversions.iterableAsScalaIterable(tokens)); }
[ "public", "static", "String", "detokenize", "(", "List", "<", "String", ">", "tokens", ")", "{", "return", "TwitterKoreanProcessor", ".", "detokenize", "(", "JavaConversions", ".", "iterableAsScalaIterable", "(", "tokens", ")", ")", ";", "}" ]
Detokenize the input list of words. @param tokens List of words. @return Detokenized string.
[ "Detokenize", "the", "input", "list", "of", "words", "." ]
95bbe21fcc62fa7bf50b769ae80a5734fef6b903
https://github.com/twitter/twitter-korean-text/blob/95bbe21fcc62fa7bf50b769ae80a5734fef6b903/src/main/java/com/twitter/penguin/korean/TwitterKoreanProcessorJava.java#L167-L169
163,112
documents4j/documents4j
documents4j-server-standalone/src/main/java/com/documents4j/builder/ConverterServerBuilder.java
ConverterServerBuilder.baseUri
public ConverterServerBuilder baseUri(String baseUri) { checkNotNull(baseUri); this.baseUri = URI.create(baseUri); return this; }
java
public ConverterServerBuilder baseUri(String baseUri) { checkNotNull(baseUri); this.baseUri = URI.create(baseUri); return this; }
[ "public", "ConverterServerBuilder", "baseUri", "(", "String", "baseUri", ")", "{", "checkNotNull", "(", "baseUri", ")", ";", "this", ".", "baseUri", "=", "URI", ".", "create", "(", "baseUri", ")", ";", "return", "this", ";", "}" ]
Specifies the base URI of this conversion server. @param baseUri The URI under which this remote conversion server is reachable. @return This builder instance.
[ "Specifies", "the", "base", "URI", "of", "this", "conversion", "server", "." ]
eebb3ede43ffeb5fbfc85b3134f67a9c379a5594
https://github.com/documents4j/documents4j/blob/eebb3ede43ffeb5fbfc85b3134f67a9c379a5594/documents4j-server-standalone/src/main/java/com/documents4j/builder/ConverterServerBuilder.java#L92-L96
163,113
documents4j/documents4j
documents4j-server-standalone/src/main/java/com/documents4j/builder/ConverterServerBuilder.java
ConverterServerBuilder.workerPool
public ConverterServerBuilder workerPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit) { assertNumericArgument(corePoolSize, true); assertNumericArgument(maximumPoolSize, true); assertNumericArgument(corePoolSize + maximumPoolSize, false); assertNumericArgument(keepAliveTime, true); this.corePoolSize = corePoolSize; this.maximumPoolSize = maximumPoolSize; this.keepAliveTime = unit.toMillis(keepAliveTime); return this; }
java
public ConverterServerBuilder workerPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit) { assertNumericArgument(corePoolSize, true); assertNumericArgument(maximumPoolSize, true); assertNumericArgument(corePoolSize + maximumPoolSize, false); assertNumericArgument(keepAliveTime, true); this.corePoolSize = corePoolSize; this.maximumPoolSize = maximumPoolSize; this.keepAliveTime = unit.toMillis(keepAliveTime); return this; }
[ "public", "ConverterServerBuilder", "workerPool", "(", "int", "corePoolSize", ",", "int", "maximumPoolSize", ",", "long", "keepAliveTime", ",", "TimeUnit", "unit", ")", "{", "assertNumericArgument", "(", "corePoolSize", ",", "true", ")", ";", "assertNumericArgument", "(", "maximumPoolSize", ",", "true", ")", ";", "assertNumericArgument", "(", "corePoolSize", "+", "maximumPoolSize", ",", "false", ")", ";", "assertNumericArgument", "(", "keepAliveTime", ",", "true", ")", ";", "this", ".", "corePoolSize", "=", "corePoolSize", ";", "this", ".", "maximumPoolSize", "=", "maximumPoolSize", ";", "this", ".", "keepAliveTime", "=", "unit", ".", "toMillis", "(", "keepAliveTime", ")", ";", "return", "this", ";", "}" ]
Configures a worker pool for the converter. @param corePoolSize The core pool size of the worker pool. @param maximumPoolSize The maximum pool size of the worker pool. @param keepAliveTime The keep alive time of the worker pool. @param unit The time unit of the specified keep alive time. @return This builder instance.
[ "Configures", "a", "worker", "pool", "for", "the", "converter", "." ]
eebb3ede43ffeb5fbfc85b3134f67a9c379a5594
https://github.com/documents4j/documents4j/blob/eebb3ede43ffeb5fbfc85b3134f67a9c379a5594/documents4j-server-standalone/src/main/java/com/documents4j/builder/ConverterServerBuilder.java#L119-L128
163,114
documents4j/documents4j
documents4j-server-standalone/src/main/java/com/documents4j/builder/ConverterServerBuilder.java
ConverterServerBuilder.requestTimeout
public ConverterServerBuilder requestTimeout(long timeout, TimeUnit unit) { assertNumericArgument(timeout, true); this.requestTimeout = unit.toMillis(timeout); return this; }
java
public ConverterServerBuilder requestTimeout(long timeout, TimeUnit unit) { assertNumericArgument(timeout, true); this.requestTimeout = unit.toMillis(timeout); return this; }
[ "public", "ConverterServerBuilder", "requestTimeout", "(", "long", "timeout", ",", "TimeUnit", "unit", ")", "{", "assertNumericArgument", "(", "timeout", ",", "true", ")", ";", "this", ".", "requestTimeout", "=", "unit", ".", "toMillis", "(", "timeout", ")", ";", "return", "this", ";", "}" ]
Specifies the timeout for a network request. @param timeout The timeout for a network request. @param unit The time unit of the specified timeout. @return This builder instance.
[ "Specifies", "the", "timeout", "for", "a", "network", "request", "." ]
eebb3ede43ffeb5fbfc85b3134f67a9c379a5594
https://github.com/documents4j/documents4j/blob/eebb3ede43ffeb5fbfc85b3134f67a9c379a5594/documents4j-server-standalone/src/main/java/com/documents4j/builder/ConverterServerBuilder.java#L137-L141
163,115
documents4j/documents4j
documents4j-server-standalone/src/main/java/com/documents4j/builder/ConverterServerBuilder.java
ConverterServerBuilder.processTimeout
public ConverterServerBuilder processTimeout(long processTimeout, TimeUnit timeUnit) { assertNumericArgument(processTimeout, false); this.processTimeout = timeUnit.toMillis(processTimeout); return this; }
java
public ConverterServerBuilder processTimeout(long processTimeout, TimeUnit timeUnit) { assertNumericArgument(processTimeout, false); this.processTimeout = timeUnit.toMillis(processTimeout); return this; }
[ "public", "ConverterServerBuilder", "processTimeout", "(", "long", "processTimeout", ",", "TimeUnit", "timeUnit", ")", "{", "assertNumericArgument", "(", "processTimeout", ",", "false", ")", ";", "this", ".", "processTimeout", "=", "timeUnit", ".", "toMillis", "(", "processTimeout", ")", ";", "return", "this", ";", "}" ]
Returns the specified process time out in milliseconds. @return The process time out in milliseconds.
[ "Returns", "the", "specified", "process", "time", "out", "in", "milliseconds", "." ]
eebb3ede43ffeb5fbfc85b3134f67a9c379a5594
https://github.com/documents4j/documents4j/blob/eebb3ede43ffeb5fbfc85b3134f67a9c379a5594/documents4j-server-standalone/src/main/java/com/documents4j/builder/ConverterServerBuilder.java#L148-L152
163,116
documents4j/documents4j
documents4j-server-standalone/src/main/java/com/documents4j/builder/ConverterServerBuilder.java
ConverterServerBuilder.build
public HttpServer build() { checkNotNull(baseUri); StandaloneWebConverterConfiguration configuration = makeConfiguration(); // The configuration has to be configured both by a binder to make it injectable // and directly in order to trigger life cycle methods on the deployment container. ResourceConfig resourceConfig = ResourceConfig .forApplication(new WebConverterApplication(configuration)) .register(configuration); if (sslContext == null) { return GrizzlyHttpServerFactory.createHttpServer(baseUri, resourceConfig); } else { return GrizzlyHttpServerFactory.createHttpServer(baseUri, resourceConfig, true, new SSLEngineConfigurator(sslContext)); } }
java
public HttpServer build() { checkNotNull(baseUri); StandaloneWebConverterConfiguration configuration = makeConfiguration(); // The configuration has to be configured both by a binder to make it injectable // and directly in order to trigger life cycle methods on the deployment container. ResourceConfig resourceConfig = ResourceConfig .forApplication(new WebConverterApplication(configuration)) .register(configuration); if (sslContext == null) { return GrizzlyHttpServerFactory.createHttpServer(baseUri, resourceConfig); } else { return GrizzlyHttpServerFactory.createHttpServer(baseUri, resourceConfig, true, new SSLEngineConfigurator(sslContext)); } }
[ "public", "HttpServer", "build", "(", ")", "{", "checkNotNull", "(", "baseUri", ")", ";", "StandaloneWebConverterConfiguration", "configuration", "=", "makeConfiguration", "(", ")", ";", "// The configuration has to be configured both by a binder to make it injectable", "// and directly in order to trigger life cycle methods on the deployment container.", "ResourceConfig", "resourceConfig", "=", "ResourceConfig", ".", "forApplication", "(", "new", "WebConverterApplication", "(", "configuration", ")", ")", ".", "register", "(", "configuration", ")", ";", "if", "(", "sslContext", "==", "null", ")", "{", "return", "GrizzlyHttpServerFactory", ".", "createHttpServer", "(", "baseUri", ",", "resourceConfig", ")", ";", "}", "else", "{", "return", "GrizzlyHttpServerFactory", ".", "createHttpServer", "(", "baseUri", ",", "resourceConfig", ",", "true", ",", "new", "SSLEngineConfigurator", "(", "sslContext", ")", ")", ";", "}", "}" ]
Creates the conversion server that is specified by this builder. @return The conversion server that is specified by this builder.
[ "Creates", "the", "conversion", "server", "that", "is", "specified", "by", "this", "builder", "." ]
eebb3ede43ffeb5fbfc85b3134f67a9c379a5594
https://github.com/documents4j/documents4j/blob/eebb3ede43ffeb5fbfc85b3134f67a9c379a5594/documents4j-server-standalone/src/main/java/com/documents4j/builder/ConverterServerBuilder.java#L195-L208
163,117
bignerdranch/expandable-recycler-view
expandablerecyclerview/src/main/java/com/bignerdranch/expandablerecyclerview/ParentViewHolder.java
ParentViewHolder.getParentAdapterPosition
@UiThread public int getParentAdapterPosition() { int flatPosition = getAdapterPosition(); if (flatPosition == RecyclerView.NO_POSITION) { return flatPosition; } return mExpandableAdapter.getNearestParentPosition(flatPosition); }
java
@UiThread public int getParentAdapterPosition() { int flatPosition = getAdapterPosition(); if (flatPosition == RecyclerView.NO_POSITION) { return flatPosition; } return mExpandableAdapter.getNearestParentPosition(flatPosition); }
[ "@", "UiThread", "public", "int", "getParentAdapterPosition", "(", ")", "{", "int", "flatPosition", "=", "getAdapterPosition", "(", ")", ";", "if", "(", "flatPosition", "==", "RecyclerView", ".", "NO_POSITION", ")", "{", "return", "flatPosition", ";", "}", "return", "mExpandableAdapter", ".", "getNearestParentPosition", "(", "flatPosition", ")", ";", "}" ]
Returns the adapter position of the Parent associated with this ParentViewHolder @return The adapter position of the Parent if it still exists in the adapter. RecyclerView.NO_POSITION if item has been removed from the adapter, RecyclerView.Adapter.notifyDataSetChanged() has been called after the last layout pass or the ViewHolder has already been recycled.
[ "Returns", "the", "adapter", "position", "of", "the", "Parent", "associated", "with", "this", "ParentViewHolder" ]
930912510620894c531d236856fa79d646e2f1ed
https://github.com/bignerdranch/expandable-recycler-view/blob/930912510620894c531d236856fa79d646e2f1ed/expandablerecyclerview/src/main/java/com/bignerdranch/expandablerecyclerview/ParentViewHolder.java#L78-L86
163,118
bignerdranch/expandable-recycler-view
expandablerecyclerview/src/main/java/com/bignerdranch/expandablerecyclerview/ParentViewHolder.java
ParentViewHolder.expandView
@UiThread protected void expandView() { setExpanded(true); onExpansionToggled(false); if (mParentViewHolderExpandCollapseListener != null) { mParentViewHolderExpandCollapseListener.onParentExpanded(getAdapterPosition()); } }
java
@UiThread protected void expandView() { setExpanded(true); onExpansionToggled(false); if (mParentViewHolderExpandCollapseListener != null) { mParentViewHolderExpandCollapseListener.onParentExpanded(getAdapterPosition()); } }
[ "@", "UiThread", "protected", "void", "expandView", "(", ")", "{", "setExpanded", "(", "true", ")", ";", "onExpansionToggled", "(", "false", ")", ";", "if", "(", "mParentViewHolderExpandCollapseListener", "!=", "null", ")", "{", "mParentViewHolderExpandCollapseListener", ".", "onParentExpanded", "(", "getAdapterPosition", "(", ")", ")", ";", "}", "}" ]
Triggers expansion of the parent.
[ "Triggers", "expansion", "of", "the", "parent", "." ]
930912510620894c531d236856fa79d646e2f1ed
https://github.com/bignerdranch/expandable-recycler-view/blob/930912510620894c531d236856fa79d646e2f1ed/expandablerecyclerview/src/main/java/com/bignerdranch/expandablerecyclerview/ParentViewHolder.java#L180-L188
163,119
bignerdranch/expandable-recycler-view
expandablerecyclerview/src/main/java/com/bignerdranch/expandablerecyclerview/ParentViewHolder.java
ParentViewHolder.collapseView
@UiThread protected void collapseView() { setExpanded(false); onExpansionToggled(true); if (mParentViewHolderExpandCollapseListener != null) { mParentViewHolderExpandCollapseListener.onParentCollapsed(getAdapterPosition()); } }
java
@UiThread protected void collapseView() { setExpanded(false); onExpansionToggled(true); if (mParentViewHolderExpandCollapseListener != null) { mParentViewHolderExpandCollapseListener.onParentCollapsed(getAdapterPosition()); } }
[ "@", "UiThread", "protected", "void", "collapseView", "(", ")", "{", "setExpanded", "(", "false", ")", ";", "onExpansionToggled", "(", "true", ")", ";", "if", "(", "mParentViewHolderExpandCollapseListener", "!=", "null", ")", "{", "mParentViewHolderExpandCollapseListener", ".", "onParentCollapsed", "(", "getAdapterPosition", "(", ")", ")", ";", "}", "}" ]
Triggers collapse of the parent.
[ "Triggers", "collapse", "of", "the", "parent", "." ]
930912510620894c531d236856fa79d646e2f1ed
https://github.com/bignerdranch/expandable-recycler-view/blob/930912510620894c531d236856fa79d646e2f1ed/expandablerecyclerview/src/main/java/com/bignerdranch/expandablerecyclerview/ParentViewHolder.java#L193-L201
163,120
bignerdranch/expandable-recycler-view
expandablerecyclerview/src/main/java/com/bignerdranch/expandablerecyclerview/ExpandableRecyclerAdapter.java
ExpandableRecyclerAdapter.parentExpandedFromViewHolder
@UiThread protected void parentExpandedFromViewHolder(int flatParentPosition) { ExpandableWrapper<P, C> parentWrapper = mFlatItemList.get(flatParentPosition); updateExpandedParent(parentWrapper, flatParentPosition, true); }
java
@UiThread protected void parentExpandedFromViewHolder(int flatParentPosition) { ExpandableWrapper<P, C> parentWrapper = mFlatItemList.get(flatParentPosition); updateExpandedParent(parentWrapper, flatParentPosition, true); }
[ "@", "UiThread", "protected", "void", "parentExpandedFromViewHolder", "(", "int", "flatParentPosition", ")", "{", "ExpandableWrapper", "<", "P", ",", "C", ">", "parentWrapper", "=", "mFlatItemList", ".", "get", "(", "flatParentPosition", ")", ";", "updateExpandedParent", "(", "parentWrapper", ",", "flatParentPosition", ",", "true", ")", ";", "}" ]
Called when a ParentViewHolder has triggered an expansion for it's parent @param flatParentPosition the position of the parent that is calling to be expanded
[ "Called", "when", "a", "ParentViewHolder", "has", "triggered", "an", "expansion", "for", "it", "s", "parent" ]
930912510620894c531d236856fa79d646e2f1ed
https://github.com/bignerdranch/expandable-recycler-view/blob/930912510620894c531d236856fa79d646e2f1ed/expandablerecyclerview/src/main/java/com/bignerdranch/expandablerecyclerview/ExpandableRecyclerAdapter.java#L417-L421
163,121
bignerdranch/expandable-recycler-view
expandablerecyclerview/src/main/java/com/bignerdranch/expandablerecyclerview/ExpandableRecyclerAdapter.java
ExpandableRecyclerAdapter.parentCollapsedFromViewHolder
@UiThread protected void parentCollapsedFromViewHolder(int flatParentPosition) { ExpandableWrapper<P, C> parentWrapper = mFlatItemList.get(flatParentPosition); updateCollapsedParent(parentWrapper, flatParentPosition, true); }
java
@UiThread protected void parentCollapsedFromViewHolder(int flatParentPosition) { ExpandableWrapper<P, C> parentWrapper = mFlatItemList.get(flatParentPosition); updateCollapsedParent(parentWrapper, flatParentPosition, true); }
[ "@", "UiThread", "protected", "void", "parentCollapsedFromViewHolder", "(", "int", "flatParentPosition", ")", "{", "ExpandableWrapper", "<", "P", ",", "C", ">", "parentWrapper", "=", "mFlatItemList", ".", "get", "(", "flatParentPosition", ")", ";", "updateCollapsedParent", "(", "parentWrapper", ",", "flatParentPosition", ",", "true", ")", ";", "}" ]
Called when a ParentViewHolder has triggered a collapse for it's parent @param flatParentPosition the position of the parent that is calling to be collapsed
[ "Called", "when", "a", "ParentViewHolder", "has", "triggered", "a", "collapse", "for", "it", "s", "parent" ]
930912510620894c531d236856fa79d646e2f1ed
https://github.com/bignerdranch/expandable-recycler-view/blob/930912510620894c531d236856fa79d646e2f1ed/expandablerecyclerview/src/main/java/com/bignerdranch/expandablerecyclerview/ExpandableRecyclerAdapter.java#L428-L432
163,122
bignerdranch/expandable-recycler-view
expandablerecyclerview/src/main/java/com/bignerdranch/expandablerecyclerview/ExpandableRecyclerAdapter.java
ExpandableRecyclerAdapter.expandParentRange
@UiThread public void expandParentRange(int startParentPosition, int parentCount) { int endParentPosition = startParentPosition + parentCount; for (int i = startParentPosition; i < endParentPosition; i++) { expandParent(i); } }
java
@UiThread public void expandParentRange(int startParentPosition, int parentCount) { int endParentPosition = startParentPosition + parentCount; for (int i = startParentPosition; i < endParentPosition; i++) { expandParent(i); } }
[ "@", "UiThread", "public", "void", "expandParentRange", "(", "int", "startParentPosition", ",", "int", "parentCount", ")", "{", "int", "endParentPosition", "=", "startParentPosition", "+", "parentCount", ";", "for", "(", "int", "i", "=", "startParentPosition", ";", "i", "<", "endParentPosition", ";", "i", "++", ")", "{", "expandParent", "(", "i", ")", ";", "}", "}" ]
Expands all parents in a range of indices in the list of parents. @param startParentPosition The index at which to to start expanding parents @param parentCount The number of parents to expand
[ "Expands", "all", "parents", "in", "a", "range", "of", "indices", "in", "the", "list", "of", "parents", "." ]
930912510620894c531d236856fa79d646e2f1ed
https://github.com/bignerdranch/expandable-recycler-view/blob/930912510620894c531d236856fa79d646e2f1ed/expandablerecyclerview/src/main/java/com/bignerdranch/expandablerecyclerview/ExpandableRecyclerAdapter.java#L497-L503
163,123
bignerdranch/expandable-recycler-view
expandablerecyclerview/src/main/java/com/bignerdranch/expandablerecyclerview/ExpandableRecyclerAdapter.java
ExpandableRecyclerAdapter.collapseParentRange
@UiThread public void collapseParentRange(int startParentPosition, int parentCount) { int endParentPosition = startParentPosition + parentCount; for (int i = startParentPosition; i < endParentPosition; i++) { collapseParent(i); } }
java
@UiThread public void collapseParentRange(int startParentPosition, int parentCount) { int endParentPosition = startParentPosition + parentCount; for (int i = startParentPosition; i < endParentPosition; i++) { collapseParent(i); } }
[ "@", "UiThread", "public", "void", "collapseParentRange", "(", "int", "startParentPosition", ",", "int", "parentCount", ")", "{", "int", "endParentPosition", "=", "startParentPosition", "+", "parentCount", ";", "for", "(", "int", "i", "=", "startParentPosition", ";", "i", "<", "endParentPosition", ";", "i", "++", ")", "{", "collapseParent", "(", "i", ")", ";", "}", "}" ]
Collapses all parents in a range of indices in the list of parents. @param startParentPosition The index at which to to start collapsing parents @param parentCount The number of parents to collapse
[ "Collapses", "all", "parents", "in", "a", "range", "of", "indices", "in", "the", "list", "of", "parents", "." ]
930912510620894c531d236856fa79d646e2f1ed
https://github.com/bignerdranch/expandable-recycler-view/blob/930912510620894c531d236856fa79d646e2f1ed/expandablerecyclerview/src/main/java/com/bignerdranch/expandablerecyclerview/ExpandableRecyclerAdapter.java#L547-L553
163,124
bignerdranch/expandable-recycler-view
expandablerecyclerview/src/main/java/com/bignerdranch/expandablerecyclerview/ExpandableRecyclerAdapter.java
ExpandableRecyclerAdapter.generateFlattenedParentChildList
private List<ExpandableWrapper<P, C>> generateFlattenedParentChildList(List<P> parentList) { List<ExpandableWrapper<P, C>> flatItemList = new ArrayList<>(); int parentCount = parentList.size(); for (int i = 0; i < parentCount; i++) { P parent = parentList.get(i); generateParentWrapper(flatItemList, parent, parent.isInitiallyExpanded()); } return flatItemList; }
java
private List<ExpandableWrapper<P, C>> generateFlattenedParentChildList(List<P> parentList) { List<ExpandableWrapper<P, C>> flatItemList = new ArrayList<>(); int parentCount = parentList.size(); for (int i = 0; i < parentCount; i++) { P parent = parentList.get(i); generateParentWrapper(flatItemList, parent, parent.isInitiallyExpanded()); } return flatItemList; }
[ "private", "List", "<", "ExpandableWrapper", "<", "P", ",", "C", ">", ">", "generateFlattenedParentChildList", "(", "List", "<", "P", ">", "parentList", ")", "{", "List", "<", "ExpandableWrapper", "<", "P", ",", "C", ">", ">", "flatItemList", "=", "new", "ArrayList", "<>", "(", ")", ";", "int", "parentCount", "=", "parentList", ".", "size", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "parentCount", ";", "i", "++", ")", "{", "P", "parent", "=", "parentList", ".", "get", "(", "i", ")", ";", "generateParentWrapper", "(", "flatItemList", ",", "parent", ",", "parent", ".", "isInitiallyExpanded", "(", ")", ")", ";", "}", "return", "flatItemList", ";", "}" ]
Generates a full list of all parents and their children, in order. @param parentList A list of the parents from the {@link ExpandableRecyclerAdapter} @return A list of all parents and their children, expanded
[ "Generates", "a", "full", "list", "of", "all", "parents", "and", "their", "children", "in", "order", "." ]
930912510620894c531d236856fa79d646e2f1ed
https://github.com/bignerdranch/expandable-recycler-view/blob/930912510620894c531d236856fa79d646e2f1ed/expandablerecyclerview/src/main/java/com/bignerdranch/expandablerecyclerview/ExpandableRecyclerAdapter.java#L1320-L1330
163,125
bignerdranch/expandable-recycler-view
expandablerecyclerview/src/main/java/com/bignerdranch/expandablerecyclerview/ExpandableRecyclerAdapter.java
ExpandableRecyclerAdapter.generateFlattenedParentChildList
private List<ExpandableWrapper<P, C>> generateFlattenedParentChildList(List<P> parentList, Map<P, Boolean> savedLastExpansionState) { List<ExpandableWrapper<P, C>> flatItemList = new ArrayList<>(); int parentCount = parentList.size(); for (int i = 0; i < parentCount; i++) { P parent = parentList.get(i); Boolean lastExpandedState = savedLastExpansionState.get(parent); boolean shouldExpand = lastExpandedState == null ? parent.isInitiallyExpanded() : lastExpandedState; generateParentWrapper(flatItemList, parent, shouldExpand); } return flatItemList; }
java
private List<ExpandableWrapper<P, C>> generateFlattenedParentChildList(List<P> parentList, Map<P, Boolean> savedLastExpansionState) { List<ExpandableWrapper<P, C>> flatItemList = new ArrayList<>(); int parentCount = parentList.size(); for (int i = 0; i < parentCount; i++) { P parent = parentList.get(i); Boolean lastExpandedState = savedLastExpansionState.get(parent); boolean shouldExpand = lastExpandedState == null ? parent.isInitiallyExpanded() : lastExpandedState; generateParentWrapper(flatItemList, parent, shouldExpand); } return flatItemList; }
[ "private", "List", "<", "ExpandableWrapper", "<", "P", ",", "C", ">", ">", "generateFlattenedParentChildList", "(", "List", "<", "P", ">", "parentList", ",", "Map", "<", "P", ",", "Boolean", ">", "savedLastExpansionState", ")", "{", "List", "<", "ExpandableWrapper", "<", "P", ",", "C", ">", ">", "flatItemList", "=", "new", "ArrayList", "<>", "(", ")", ";", "int", "parentCount", "=", "parentList", ".", "size", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "parentCount", ";", "i", "++", ")", "{", "P", "parent", "=", "parentList", ".", "get", "(", "i", ")", ";", "Boolean", "lastExpandedState", "=", "savedLastExpansionState", ".", "get", "(", "parent", ")", ";", "boolean", "shouldExpand", "=", "lastExpandedState", "==", "null", "?", "parent", ".", "isInitiallyExpanded", "(", ")", ":", "lastExpandedState", ";", "generateParentWrapper", "(", "flatItemList", ",", "parent", ",", "shouldExpand", ")", ";", "}", "return", "flatItemList", ";", "}" ]
Generates a full list of all parents and their children, in order. Uses Map to preserve last expanded state. @param parentList A list of the parents from the {@link ExpandableRecyclerAdapter} @param savedLastExpansionState A map of the last expanded state for a given parent key. @return A list of all parents and their children, expanded accordingly
[ "Generates", "a", "full", "list", "of", "all", "parents", "and", "their", "children", "in", "order", ".", "Uses", "Map", "to", "preserve", "last", "expanded", "state", "." ]
930912510620894c531d236856fa79d646e2f1ed
https://github.com/bignerdranch/expandable-recycler-view/blob/930912510620894c531d236856fa79d646e2f1ed/expandablerecyclerview/src/main/java/com/bignerdranch/expandablerecyclerview/ExpandableRecyclerAdapter.java#L1341-L1354
163,126
bignerdranch/expandable-recycler-view
expandablerecyclerview/src/main/java/com/bignerdranch/expandablerecyclerview/ExpandableRecyclerAdapter.java
ExpandableRecyclerAdapter.generateExpandedStateMap
@NonNull @UiThread private HashMap<Integer, Boolean> generateExpandedStateMap() { HashMap<Integer, Boolean> parentHashMap = new HashMap<>(); int childCount = 0; int listItemCount = mFlatItemList.size(); for (int i = 0; i < listItemCount; i++) { if (mFlatItemList.get(i) != null) { ExpandableWrapper<P, C> listItem = mFlatItemList.get(i); if (listItem.isParent()) { parentHashMap.put(i - childCount, listItem.isExpanded()); } else { childCount++; } } } return parentHashMap; }
java
@NonNull @UiThread private HashMap<Integer, Boolean> generateExpandedStateMap() { HashMap<Integer, Boolean> parentHashMap = new HashMap<>(); int childCount = 0; int listItemCount = mFlatItemList.size(); for (int i = 0; i < listItemCount; i++) { if (mFlatItemList.get(i) != null) { ExpandableWrapper<P, C> listItem = mFlatItemList.get(i); if (listItem.isParent()) { parentHashMap.put(i - childCount, listItem.isExpanded()); } else { childCount++; } } } return parentHashMap; }
[ "@", "NonNull", "@", "UiThread", "private", "HashMap", "<", "Integer", ",", "Boolean", ">", "generateExpandedStateMap", "(", ")", "{", "HashMap", "<", "Integer", ",", "Boolean", ">", "parentHashMap", "=", "new", "HashMap", "<>", "(", ")", ";", "int", "childCount", "=", "0", ";", "int", "listItemCount", "=", "mFlatItemList", ".", "size", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "listItemCount", ";", "i", "++", ")", "{", "if", "(", "mFlatItemList", ".", "get", "(", "i", ")", "!=", "null", ")", "{", "ExpandableWrapper", "<", "P", ",", "C", ">", "listItem", "=", "mFlatItemList", ".", "get", "(", "i", ")", ";", "if", "(", "listItem", ".", "isParent", "(", ")", ")", "{", "parentHashMap", ".", "put", "(", "i", "-", "childCount", ",", "listItem", ".", "isExpanded", "(", ")", ")", ";", "}", "else", "{", "childCount", "++", ";", "}", "}", "}", "return", "parentHashMap", ";", "}" ]
Generates a HashMap used to store expanded state for items in the list on configuration change or whenever onResume is called. @return A HashMap containing the expanded state of all parents
[ "Generates", "a", "HashMap", "used", "to", "store", "expanded", "state", "for", "items", "in", "the", "list", "on", "configuration", "change", "or", "whenever", "onResume", "is", "called", "." ]
930912510620894c531d236856fa79d646e2f1ed
https://github.com/bignerdranch/expandable-recycler-view/blob/930912510620894c531d236856fa79d646e2f1ed/expandablerecyclerview/src/main/java/com/bignerdranch/expandablerecyclerview/ExpandableRecyclerAdapter.java#L1381-L1400
163,127
bignerdranch/expandable-recycler-view
expandablerecyclerview/src/main/java/com/bignerdranch/expandablerecyclerview/ExpandableRecyclerAdapter.java
ExpandableRecyclerAdapter.getFlatParentPosition
@UiThread private int getFlatParentPosition(int parentPosition) { int parentCount = 0; int listItemCount = mFlatItemList.size(); for (int i = 0; i < listItemCount; i++) { if (mFlatItemList.get(i).isParent()) { parentCount++; if (parentCount > parentPosition) { return i; } } } return INVALID_FLAT_POSITION; }
java
@UiThread private int getFlatParentPosition(int parentPosition) { int parentCount = 0; int listItemCount = mFlatItemList.size(); for (int i = 0; i < listItemCount; i++) { if (mFlatItemList.get(i).isParent()) { parentCount++; if (parentCount > parentPosition) { return i; } } } return INVALID_FLAT_POSITION; }
[ "@", "UiThread", "private", "int", "getFlatParentPosition", "(", "int", "parentPosition", ")", "{", "int", "parentCount", "=", "0", ";", "int", "listItemCount", "=", "mFlatItemList", ".", "size", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "listItemCount", ";", "i", "++", ")", "{", "if", "(", "mFlatItemList", ".", "get", "(", "i", ")", ".", "isParent", "(", ")", ")", "{", "parentCount", "++", ";", "if", "(", "parentCount", ">", "parentPosition", ")", "{", "return", "i", ";", "}", "}", "}", "return", "INVALID_FLAT_POSITION", ";", "}" ]
Gets the index of a ExpandableWrapper within the helper item list based on the index of the ExpandableWrapper. @param parentPosition The index of the parent in the list of parents @return The index of the parent in the merged list of children and parents
[ "Gets", "the", "index", "of", "a", "ExpandableWrapper", "within", "the", "helper", "item", "list", "based", "on", "the", "index", "of", "the", "ExpandableWrapper", "." ]
930912510620894c531d236856fa79d646e2f1ed
https://github.com/bignerdranch/expandable-recycler-view/blob/930912510620894c531d236856fa79d646e2f1ed/expandablerecyclerview/src/main/java/com/bignerdranch/expandablerecyclerview/ExpandableRecyclerAdapter.java#L1409-L1424
163,128
bignerdranch/expandable-recycler-view
expandablerecyclerview/src/main/java/com/bignerdranch/expandablerecyclerview/ChildViewHolder.java
ChildViewHolder.getParentAdapterPosition
@UiThread public int getParentAdapterPosition() { int flatPosition = getAdapterPosition(); if (mExpandableAdapter == null || flatPosition == RecyclerView.NO_POSITION) { return RecyclerView.NO_POSITION; } return mExpandableAdapter.getNearestParentPosition(flatPosition); }
java
@UiThread public int getParentAdapterPosition() { int flatPosition = getAdapterPosition(); if (mExpandableAdapter == null || flatPosition == RecyclerView.NO_POSITION) { return RecyclerView.NO_POSITION; } return mExpandableAdapter.getNearestParentPosition(flatPosition); }
[ "@", "UiThread", "public", "int", "getParentAdapterPosition", "(", ")", "{", "int", "flatPosition", "=", "getAdapterPosition", "(", ")", ";", "if", "(", "mExpandableAdapter", "==", "null", "||", "flatPosition", "==", "RecyclerView", ".", "NO_POSITION", ")", "{", "return", "RecyclerView", ".", "NO_POSITION", ";", "}", "return", "mExpandableAdapter", ".", "getNearestParentPosition", "(", "flatPosition", ")", ";", "}" ]
Returns the adapter position of the Parent associated with this ChildViewHolder @return The adapter position of the Parent if it still exists in the adapter. RecyclerView.NO_POSITION if item has been removed from the adapter, RecyclerView.Adapter.notifyDataSetChanged() has been called after the last layout pass or the ViewHolder has already been recycled.
[ "Returns", "the", "adapter", "position", "of", "the", "Parent", "associated", "with", "this", "ChildViewHolder" ]
930912510620894c531d236856fa79d646e2f1ed
https://github.com/bignerdranch/expandable-recycler-view/blob/930912510620894c531d236856fa79d646e2f1ed/expandablerecyclerview/src/main/java/com/bignerdranch/expandablerecyclerview/ChildViewHolder.java#L43-L51
163,129
bignerdranch/expandable-recycler-view
expandablerecyclerview/src/main/java/com/bignerdranch/expandablerecyclerview/ChildViewHolder.java
ChildViewHolder.getChildAdapterPosition
@UiThread public int getChildAdapterPosition() { int flatPosition = getAdapterPosition(); if (mExpandableAdapter == null || flatPosition == RecyclerView.NO_POSITION) { return RecyclerView.NO_POSITION; } return mExpandableAdapter.getChildPosition(flatPosition); }
java
@UiThread public int getChildAdapterPosition() { int flatPosition = getAdapterPosition(); if (mExpandableAdapter == null || flatPosition == RecyclerView.NO_POSITION) { return RecyclerView.NO_POSITION; } return mExpandableAdapter.getChildPosition(flatPosition); }
[ "@", "UiThread", "public", "int", "getChildAdapterPosition", "(", ")", "{", "int", "flatPosition", "=", "getAdapterPosition", "(", ")", ";", "if", "(", "mExpandableAdapter", "==", "null", "||", "flatPosition", "==", "RecyclerView", ".", "NO_POSITION", ")", "{", "return", "RecyclerView", ".", "NO_POSITION", ";", "}", "return", "mExpandableAdapter", ".", "getChildPosition", "(", "flatPosition", ")", ";", "}" ]
Returns the adapter position of the Child associated with this ChildViewHolder @return The adapter position of the Child if it still exists in the adapter. RecyclerView.NO_POSITION if item has been removed from the adapter, RecyclerView.Adapter.notifyDataSetChanged() has been called after the last layout pass or the ViewHolder has already been recycled.
[ "Returns", "the", "adapter", "position", "of", "the", "Child", "associated", "with", "this", "ChildViewHolder" ]
930912510620894c531d236856fa79d646e2f1ed
https://github.com/bignerdranch/expandable-recycler-view/blob/930912510620894c531d236856fa79d646e2f1ed/expandablerecyclerview/src/main/java/com/bignerdranch/expandablerecyclerview/ChildViewHolder.java#L61-L69
163,130
wwadge/bonecp
bonecp/src/main/java/com/jolbox/bonecp/PoolUtil.java
PoolUtil.fillLogParams
public static String fillLogParams(String sql, Map<Object, Object> logParams) { StringBuilder result = new StringBuilder(); Map<Object, Object> tmpLogParam = (logParams == null ? new HashMap<Object, Object>() : logParams); Iterator<Object> it = tmpLogParam.values().iterator(); boolean inQuote = false; boolean inQuote2 = false; char[] sqlChar = sql != null ? sql.toCharArray() : new char[]{}; for (int i=0; i < sqlChar.length; i++){ if (sqlChar[i] == '\''){ inQuote = !inQuote; } if (sqlChar[i] == '"'){ inQuote2 = !inQuote2; } if (sqlChar[i] == '?' && !(inQuote || inQuote2)){ if (it.hasNext()){ result.append(prettyPrint(it.next())); } else { result.append('?'); } } else { result.append(sqlChar[i]); } } return result.toString(); }
java
public static String fillLogParams(String sql, Map<Object, Object> logParams) { StringBuilder result = new StringBuilder(); Map<Object, Object> tmpLogParam = (logParams == null ? new HashMap<Object, Object>() : logParams); Iterator<Object> it = tmpLogParam.values().iterator(); boolean inQuote = false; boolean inQuote2 = false; char[] sqlChar = sql != null ? sql.toCharArray() : new char[]{}; for (int i=0; i < sqlChar.length; i++){ if (sqlChar[i] == '\''){ inQuote = !inQuote; } if (sqlChar[i] == '"'){ inQuote2 = !inQuote2; } if (sqlChar[i] == '?' && !(inQuote || inQuote2)){ if (it.hasNext()){ result.append(prettyPrint(it.next())); } else { result.append('?'); } } else { result.append(sqlChar[i]); } } return result.toString(); }
[ "public", "static", "String", "fillLogParams", "(", "String", "sql", ",", "Map", "<", "Object", ",", "Object", ">", "logParams", ")", "{", "StringBuilder", "result", "=", "new", "StringBuilder", "(", ")", ";", "Map", "<", "Object", ",", "Object", ">", "tmpLogParam", "=", "(", "logParams", "==", "null", "?", "new", "HashMap", "<", "Object", ",", "Object", ">", "(", ")", ":", "logParams", ")", ";", "Iterator", "<", "Object", ">", "it", "=", "tmpLogParam", ".", "values", "(", ")", ".", "iterator", "(", ")", ";", "boolean", "inQuote", "=", "false", ";", "boolean", "inQuote2", "=", "false", ";", "char", "[", "]", "sqlChar", "=", "sql", "!=", "null", "?", "sql", ".", "toCharArray", "(", ")", ":", "new", "char", "[", "]", "{", "}", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "sqlChar", ".", "length", ";", "i", "++", ")", "{", "if", "(", "sqlChar", "[", "i", "]", "==", "'", "'", ")", "{", "inQuote", "=", "!", "inQuote", ";", "}", "if", "(", "sqlChar", "[", "i", "]", "==", "'", "'", ")", "{", "inQuote2", "=", "!", "inQuote2", ";", "}", "if", "(", "sqlChar", "[", "i", "]", "==", "'", "'", "&&", "!", "(", "inQuote", "||", "inQuote2", ")", ")", "{", "if", "(", "it", ".", "hasNext", "(", ")", ")", "{", "result", ".", "append", "(", "prettyPrint", "(", "it", ".", "next", "(", ")", ")", ")", ";", "}", "else", "{", "result", ".", "append", "(", "'", "'", ")", ";", "}", "}", "else", "{", "result", ".", "append", "(", "sqlChar", "[", "i", "]", ")", ";", "}", "}", "return", "result", ".", "toString", "(", ")", ";", "}" ]
Returns sql statement used in this prepared statement together with the parameters. @param sql base sql statement @param logParams parameters to print out @return returns printable statement
[ "Returns", "sql", "statement", "used", "in", "this", "prepared", "statement", "together", "with", "the", "parameters", "." ]
74bc3287025fc137ca28909f0f7693edae37a15d
https://github.com/wwadge/bonecp/blob/74bc3287025fc137ca28909f0f7693edae37a15d/bonecp/src/main/java/com/jolbox/bonecp/PoolUtil.java#L46-L76
163,131
wwadge/bonecp
bonecp/src/main/java/com/jolbox/bonecp/ConnectionHandle.java
ConnectionHandle.sendInitSQL
protected static void sendInitSQL(Connection connection, String initSQL) throws SQLException{ // fetch any configured setup sql. if (initSQL != null){ Statement stmt = null; try{ stmt = connection.createStatement(); stmt.execute(initSQL); if (testSupport){ // only to aid code coverage, normally set to false stmt = null; } } finally{ if (stmt != null){ stmt.close(); } } } }
java
protected static void sendInitSQL(Connection connection, String initSQL) throws SQLException{ // fetch any configured setup sql. if (initSQL != null){ Statement stmt = null; try{ stmt = connection.createStatement(); stmt.execute(initSQL); if (testSupport){ // only to aid code coverage, normally set to false stmt = null; } } finally{ if (stmt != null){ stmt.close(); } } } }
[ "protected", "static", "void", "sendInitSQL", "(", "Connection", "connection", ",", "String", "initSQL", ")", "throws", "SQLException", "{", "// fetch any configured setup sql.\r", "if", "(", "initSQL", "!=", "null", ")", "{", "Statement", "stmt", "=", "null", ";", "try", "{", "stmt", "=", "connection", ".", "createStatement", "(", ")", ";", "stmt", ".", "execute", "(", "initSQL", ")", ";", "if", "(", "testSupport", ")", "{", "// only to aid code coverage, normally set to false\r", "stmt", "=", "null", ";", "}", "}", "finally", "{", "if", "(", "stmt", "!=", "null", ")", "{", "stmt", ".", "close", "(", ")", ";", "}", "}", "}", "}" ]
Sends out the SQL as defined in the config upon first init of the connection. @param connection @param initSQL @throws SQLException
[ "Sends", "out", "the", "SQL", "as", "defined", "in", "the", "config", "upon", "first", "init", "of", "the", "connection", "." ]
74bc3287025fc137ca28909f0f7693edae37a15d
https://github.com/wwadge/bonecp/blob/74bc3287025fc137ca28909f0f7693edae37a15d/bonecp/src/main/java/com/jolbox/bonecp/ConnectionHandle.java#L351-L367
163,132
wwadge/bonecp
bonecp/src/main/java/com/jolbox/bonecp/ConnectionHandle.java
ConnectionHandle.close
public void close() throws SQLException { try { if (this.resetConnectionOnClose /*FIXME: && !getAutoCommit() && !isTxResolved() */){ /*if (this.autoCommitStackTrace != null){ logger.debug(this.autoCommitStackTrace); this.autoCommitStackTrace = null; } else { logger.debug(DISABLED_AUTO_COMMIT_WARNING); }*/ rollback(); if (!getAutoCommit()){ setAutoCommit(true); } } if (this.logicallyClosed.compareAndSet(false, true)) { if (this.threadWatch != null){ this.threadWatch.interrupt(); // if we returned the connection to the pool, terminate thread watch thread if it's // running even if thread is still alive (eg thread has been recycled for use in some // container). this.threadWatch = null; } if (this.closeOpenStatements){ for (Entry<Statement, String> statementEntry: this.trackedStatement.entrySet()){ statementEntry.getKey().close(); if (this.detectUnclosedStatements){ logger.warn(String.format(UNCLOSED_LOG_ERROR_MESSAGE, statementEntry.getValue())); } } this.trackedStatement.clear(); } if (!this.connectionTrackingDisabled){ pool.getFinalizableRefs().remove(this.connection); } ConnectionHandle handle = null; //recreate can throw a SQLException in constructor on recreation try { handle = this.recreateConnectionHandle(); this.pool.connectionStrategy.cleanupConnection(this, handle); this.pool.releaseConnection(handle); } catch(SQLException e) { //check if the connection was already closed by the recreation if (!isClosed()) { this.pool.connectionStrategy.cleanupConnection(this, handle); this.pool.releaseConnection(this); } throw e; } if (this.doubleCloseCheck){ this.doubleCloseException = this.pool.captureStackTrace(CLOSED_TWICE_EXCEPTION_MESSAGE); } } else { if (this.doubleCloseCheck && this.doubleCloseException != null){ String currentLocation = this.pool.captureStackTrace("Last closed trace from thread ["+Thread.currentThread().getName()+"]:\n"); logger.error(String.format(LOG_ERROR_MESSAGE, this.doubleCloseException, currentLocation)); } } } catch (SQLException e) { throw markPossiblyBroken(e); } }
java
public void close() throws SQLException { try { if (this.resetConnectionOnClose /*FIXME: && !getAutoCommit() && !isTxResolved() */){ /*if (this.autoCommitStackTrace != null){ logger.debug(this.autoCommitStackTrace); this.autoCommitStackTrace = null; } else { logger.debug(DISABLED_AUTO_COMMIT_WARNING); }*/ rollback(); if (!getAutoCommit()){ setAutoCommit(true); } } if (this.logicallyClosed.compareAndSet(false, true)) { if (this.threadWatch != null){ this.threadWatch.interrupt(); // if we returned the connection to the pool, terminate thread watch thread if it's // running even if thread is still alive (eg thread has been recycled for use in some // container). this.threadWatch = null; } if (this.closeOpenStatements){ for (Entry<Statement, String> statementEntry: this.trackedStatement.entrySet()){ statementEntry.getKey().close(); if (this.detectUnclosedStatements){ logger.warn(String.format(UNCLOSED_LOG_ERROR_MESSAGE, statementEntry.getValue())); } } this.trackedStatement.clear(); } if (!this.connectionTrackingDisabled){ pool.getFinalizableRefs().remove(this.connection); } ConnectionHandle handle = null; //recreate can throw a SQLException in constructor on recreation try { handle = this.recreateConnectionHandle(); this.pool.connectionStrategy.cleanupConnection(this, handle); this.pool.releaseConnection(handle); } catch(SQLException e) { //check if the connection was already closed by the recreation if (!isClosed()) { this.pool.connectionStrategy.cleanupConnection(this, handle); this.pool.releaseConnection(this); } throw e; } if (this.doubleCloseCheck){ this.doubleCloseException = this.pool.captureStackTrace(CLOSED_TWICE_EXCEPTION_MESSAGE); } } else { if (this.doubleCloseCheck && this.doubleCloseException != null){ String currentLocation = this.pool.captureStackTrace("Last closed trace from thread ["+Thread.currentThread().getName()+"]:\n"); logger.error(String.format(LOG_ERROR_MESSAGE, this.doubleCloseException, currentLocation)); } } } catch (SQLException e) { throw markPossiblyBroken(e); } }
[ "public", "void", "close", "(", ")", "throws", "SQLException", "{", "try", "{", "if", "(", "this", ".", "resetConnectionOnClose", "/*FIXME: && !getAutoCommit() && !isTxResolved() */", ")", "{", "/*if (this.autoCommitStackTrace != null){\r\n\t\t\t\t\t\tlogger.debug(this.autoCommitStackTrace);\r\n\t\t\t\t\t\tthis.autoCommitStackTrace = null; \r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tlogger.debug(DISABLED_AUTO_COMMIT_WARNING);\r\n\t\t\t\t\t}*/", "rollback", "(", ")", ";", "if", "(", "!", "getAutoCommit", "(", ")", ")", "{", "setAutoCommit", "(", "true", ")", ";", "}", "}", "if", "(", "this", ".", "logicallyClosed", ".", "compareAndSet", "(", "false", ",", "true", ")", ")", "{", "if", "(", "this", ".", "threadWatch", "!=", "null", ")", "{", "this", ".", "threadWatch", ".", "interrupt", "(", ")", ";", "// if we returned the connection to the pool, terminate thread watch thread if it's\r", "// running even if thread is still alive (eg thread has been recycled for use in some\r", "// container).\r", "this", ".", "threadWatch", "=", "null", ";", "}", "if", "(", "this", ".", "closeOpenStatements", ")", "{", "for", "(", "Entry", "<", "Statement", ",", "String", ">", "statementEntry", ":", "this", ".", "trackedStatement", ".", "entrySet", "(", ")", ")", "{", "statementEntry", ".", "getKey", "(", ")", ".", "close", "(", ")", ";", "if", "(", "this", ".", "detectUnclosedStatements", ")", "{", "logger", ".", "warn", "(", "String", ".", "format", "(", "UNCLOSED_LOG_ERROR_MESSAGE", ",", "statementEntry", ".", "getValue", "(", ")", ")", ")", ";", "}", "}", "this", ".", "trackedStatement", ".", "clear", "(", ")", ";", "}", "if", "(", "!", "this", ".", "connectionTrackingDisabled", ")", "{", "pool", ".", "getFinalizableRefs", "(", ")", ".", "remove", "(", "this", ".", "connection", ")", ";", "}", "ConnectionHandle", "handle", "=", "null", ";", "//recreate can throw a SQLException in constructor on recreation\r", "try", "{", "handle", "=", "this", ".", "recreateConnectionHandle", "(", ")", ";", "this", ".", "pool", ".", "connectionStrategy", ".", "cleanupConnection", "(", "this", ",", "handle", ")", ";", "this", ".", "pool", ".", "releaseConnection", "(", "handle", ")", ";", "}", "catch", "(", "SQLException", "e", ")", "{", "//check if the connection was already closed by the recreation\r", "if", "(", "!", "isClosed", "(", ")", ")", "{", "this", ".", "pool", ".", "connectionStrategy", ".", "cleanupConnection", "(", "this", ",", "handle", ")", ";", "this", ".", "pool", ".", "releaseConnection", "(", "this", ")", ";", "}", "throw", "e", ";", "}", "if", "(", "this", ".", "doubleCloseCheck", ")", "{", "this", ".", "doubleCloseException", "=", "this", ".", "pool", ".", "captureStackTrace", "(", "CLOSED_TWICE_EXCEPTION_MESSAGE", ")", ";", "}", "}", "else", "{", "if", "(", "this", ".", "doubleCloseCheck", "&&", "this", ".", "doubleCloseException", "!=", "null", ")", "{", "String", "currentLocation", "=", "this", ".", "pool", ".", "captureStackTrace", "(", "\"Last closed trace from thread [\"", "+", "Thread", ".", "currentThread", "(", ")", ".", "getName", "(", ")", "+", "\"]:\\n\"", ")", ";", "logger", ".", "error", "(", "String", ".", "format", "(", "LOG_ERROR_MESSAGE", ",", "this", ".", "doubleCloseException", ",", "currentLocation", ")", ")", ";", "}", "}", "}", "catch", "(", "SQLException", "e", ")", "{", "throw", "markPossiblyBroken", "(", "e", ")", ";", "}", "}" ]
Release the connection back to the pool. @throws SQLException Never really thrown
[ "Release", "the", "connection", "back", "to", "the", "pool", "." ]
74bc3287025fc137ca28909f0f7693edae37a15d
https://github.com/wwadge/bonecp/blob/74bc3287025fc137ca28909f0f7693edae37a15d/bonecp/src/main/java/com/jolbox/bonecp/ConnectionHandle.java#L469-L538
163,133
wwadge/bonecp
bonecp/src/main/java/com/jolbox/bonecp/ConnectionHandle.java
ConnectionHandle.internalClose
protected void internalClose() throws SQLException { try { clearStatementCaches(true); if (this.connection != null){ // safety! this.connection.close(); if (!this.connectionTrackingDisabled && this.finalizableRefs != null){ this.finalizableRefs.remove(this.connection); } } this.logicallyClosed.set(true); } catch (SQLException e) { throw markPossiblyBroken(e); } }
java
protected void internalClose() throws SQLException { try { clearStatementCaches(true); if (this.connection != null){ // safety! this.connection.close(); if (!this.connectionTrackingDisabled && this.finalizableRefs != null){ this.finalizableRefs.remove(this.connection); } } this.logicallyClosed.set(true); } catch (SQLException e) { throw markPossiblyBroken(e); } }
[ "protected", "void", "internalClose", "(", ")", "throws", "SQLException", "{", "try", "{", "clearStatementCaches", "(", "true", ")", ";", "if", "(", "this", ".", "connection", "!=", "null", ")", "{", "// safety!\r", "this", ".", "connection", ".", "close", "(", ")", ";", "if", "(", "!", "this", ".", "connectionTrackingDisabled", "&&", "this", ".", "finalizableRefs", "!=", "null", ")", "{", "this", ".", "finalizableRefs", ".", "remove", "(", "this", ".", "connection", ")", ";", "}", "}", "this", ".", "logicallyClosed", ".", "set", "(", "true", ")", ";", "}", "catch", "(", "SQLException", "e", ")", "{", "throw", "markPossiblyBroken", "(", "e", ")", ";", "}", "}" ]
Close off the connection. @throws SQLException
[ "Close", "off", "the", "connection", "." ]
74bc3287025fc137ca28909f0f7693edae37a15d
https://github.com/wwadge/bonecp/blob/74bc3287025fc137ca28909f0f7693edae37a15d/bonecp/src/main/java/com/jolbox/bonecp/ConnectionHandle.java#L546-L560
163,134
wwadge/bonecp
bonecp/src/main/java/com/jolbox/bonecp/ConnectionHandle.java
ConnectionHandle.clearStatementCaches
protected void clearStatementCaches(boolean internalClose) { if (this.statementCachingEnabled){ // safety if (internalClose){ this.callableStatementCache.clear(); this.preparedStatementCache.clear(); } else { if (this.pool.closeConnectionWatch){ // debugging enabled? this.callableStatementCache.checkForProperClosure(); this.preparedStatementCache.checkForProperClosure(); } } } }
java
protected void clearStatementCaches(boolean internalClose) { if (this.statementCachingEnabled){ // safety if (internalClose){ this.callableStatementCache.clear(); this.preparedStatementCache.clear(); } else { if (this.pool.closeConnectionWatch){ // debugging enabled? this.callableStatementCache.checkForProperClosure(); this.preparedStatementCache.checkForProperClosure(); } } } }
[ "protected", "void", "clearStatementCaches", "(", "boolean", "internalClose", ")", "{", "if", "(", "this", ".", "statementCachingEnabled", ")", "{", "// safety\r", "if", "(", "internalClose", ")", "{", "this", ".", "callableStatementCache", ".", "clear", "(", ")", ";", "this", ".", "preparedStatementCache", ".", "clear", "(", ")", ";", "}", "else", "{", "if", "(", "this", ".", "pool", ".", "closeConnectionWatch", ")", "{", "// debugging enabled?\r", "this", ".", "callableStatementCache", ".", "checkForProperClosure", "(", ")", ";", "this", ".", "preparedStatementCache", ".", "checkForProperClosure", "(", ")", ";", "}", "}", "}", "}" ]
Clears out the statement handles. @param internalClose if true, close the inner statement handle too.
[ "Clears", "out", "the", "statement", "handles", "." ]
74bc3287025fc137ca28909f0f7693edae37a15d
https://github.com/wwadge/bonecp/blob/74bc3287025fc137ca28909f0f7693edae37a15d/bonecp/src/main/java/com/jolbox/bonecp/ConnectionHandle.java#L1490-L1504
163,135
wwadge/bonecp
bonecp/src/main/java/com/jolbox/bonecp/ConnectionHandle.java
ConnectionHandle.getProxyTarget
public Object getProxyTarget(){ try { return Proxy.getInvocationHandler(this.connection).invoke(null, this.getClass().getMethod("getProxyTarget"), null); } catch (Throwable t) { throw new RuntimeException("BoneCP: Internal error - transaction replay log is not turned on?", t); } }
java
public Object getProxyTarget(){ try { return Proxy.getInvocationHandler(this.connection).invoke(null, this.getClass().getMethod("getProxyTarget"), null); } catch (Throwable t) { throw new RuntimeException("BoneCP: Internal error - transaction replay log is not turned on?", t); } }
[ "public", "Object", "getProxyTarget", "(", ")", "{", "try", "{", "return", "Proxy", ".", "getInvocationHandler", "(", "this", ".", "connection", ")", ".", "invoke", "(", "null", ",", "this", ".", "getClass", "(", ")", ".", "getMethod", "(", "\"getProxyTarget\"", ")", ",", "null", ")", ";", "}", "catch", "(", "Throwable", "t", ")", "{", "throw", "new", "RuntimeException", "(", "\"BoneCP: Internal error - transaction replay log is not turned on?\"", ",", "t", ")", ";", "}", "}" ]
This method will be intercepted by the proxy if it is enabled to return the internal target. @return the target.
[ "This", "method", "will", "be", "intercepted", "by", "the", "proxy", "if", "it", "is", "enabled", "to", "return", "the", "internal", "target", "." ]
74bc3287025fc137ca28909f0f7693edae37a15d
https://github.com/wwadge/bonecp/blob/74bc3287025fc137ca28909f0f7693edae37a15d/bonecp/src/main/java/com/jolbox/bonecp/ConnectionHandle.java#L1611-L1617
163,136
wwadge/bonecp
bonecp/src/main/java/com/jolbox/bonecp/ConnectionHandle.java
ConnectionHandle.refreshConnection
public void refreshConnection() throws SQLException{ this.connection.close(); // if it's still in use, close it. try{ this.connection = this.pool.obtainRawInternalConnection(); } catch(SQLException e){ throw markPossiblyBroken(e); } }
java
public void refreshConnection() throws SQLException{ this.connection.close(); // if it's still in use, close it. try{ this.connection = this.pool.obtainRawInternalConnection(); } catch(SQLException e){ throw markPossiblyBroken(e); } }
[ "public", "void", "refreshConnection", "(", ")", "throws", "SQLException", "{", "this", ".", "connection", ".", "close", "(", ")", ";", "// if it's still in use, close it.\r", "try", "{", "this", ".", "connection", "=", "this", ".", "pool", ".", "obtainRawInternalConnection", "(", ")", ";", "}", "catch", "(", "SQLException", "e", ")", "{", "throw", "markPossiblyBroken", "(", "e", ")", ";", "}", "}" ]
Destroys the internal connection handle and creates a new one. @throws SQLException
[ "Destroys", "the", "internal", "connection", "handle", "and", "creates", "a", "new", "one", "." ]
74bc3287025fc137ca28909f0f7693edae37a15d
https://github.com/wwadge/bonecp/blob/74bc3287025fc137ca28909f0f7693edae37a15d/bonecp/src/main/java/com/jolbox/bonecp/ConnectionHandle.java#L1705-L1712
163,137
wwadge/bonecp
bonecp-spring/src/main/java/com/jolbox/bonecp/spring/DynamicDataSourceProxy.java
DynamicDataSourceProxy.switchDataSource
public void switchDataSource(BoneCPConfig newConfig) throws SQLException { logger.info("Switch to new datasource requested. New Config: "+newConfig); DataSource oldDS = getTargetDataSource(); if (!(oldDS instanceof BoneCPDataSource)){ throw new SQLException("Unknown datasource type! Was expecting BoneCPDataSource but received "+oldDS.getClass()+". Not switching datasource!"); } BoneCPDataSource newDS = new BoneCPDataSource(newConfig); newDS.getConnection().close(); // initialize a connection (+ throw it away) to force the datasource to initialize the pool // force application to start using the new one setTargetDataSource(newDS); logger.info("Shutting down old datasource slowly. Old Config: "+oldDS); // tell the old datasource to terminate. This terminates the pool lazily so existing checked out connections can still be used. ((BoneCPDataSource)oldDS).close(); }
java
public void switchDataSource(BoneCPConfig newConfig) throws SQLException { logger.info("Switch to new datasource requested. New Config: "+newConfig); DataSource oldDS = getTargetDataSource(); if (!(oldDS instanceof BoneCPDataSource)){ throw new SQLException("Unknown datasource type! Was expecting BoneCPDataSource but received "+oldDS.getClass()+". Not switching datasource!"); } BoneCPDataSource newDS = new BoneCPDataSource(newConfig); newDS.getConnection().close(); // initialize a connection (+ throw it away) to force the datasource to initialize the pool // force application to start using the new one setTargetDataSource(newDS); logger.info("Shutting down old datasource slowly. Old Config: "+oldDS); // tell the old datasource to terminate. This terminates the pool lazily so existing checked out connections can still be used. ((BoneCPDataSource)oldDS).close(); }
[ "public", "void", "switchDataSource", "(", "BoneCPConfig", "newConfig", ")", "throws", "SQLException", "{", "logger", ".", "info", "(", "\"Switch to new datasource requested. New Config: \"", "+", "newConfig", ")", ";", "DataSource", "oldDS", "=", "getTargetDataSource", "(", ")", ";", "if", "(", "!", "(", "oldDS", "instanceof", "BoneCPDataSource", ")", ")", "{", "throw", "new", "SQLException", "(", "\"Unknown datasource type! Was expecting BoneCPDataSource but received \"", "+", "oldDS", ".", "getClass", "(", ")", "+", "\". Not switching datasource!\"", ")", ";", "}", "BoneCPDataSource", "newDS", "=", "new", "BoneCPDataSource", "(", "newConfig", ")", ";", "newDS", ".", "getConnection", "(", ")", ".", "close", "(", ")", ";", "// initialize a connection (+ throw it away) to force the datasource to initialize the pool", "// force application to start using the new one ", "setTargetDataSource", "(", "newDS", ")", ";", "logger", ".", "info", "(", "\"Shutting down old datasource slowly. Old Config: \"", "+", "oldDS", ")", ";", "// tell the old datasource to terminate. This terminates the pool lazily so existing checked out connections can still be used.", "(", "(", "BoneCPDataSource", ")", "oldDS", ")", ".", "close", "(", ")", ";", "}" ]
Switch to a new DataSource using the given configuration. @param newConfig BoneCP DataSource to use. @throws SQLException
[ "Switch", "to", "a", "new", "DataSource", "using", "the", "given", "configuration", "." ]
74bc3287025fc137ca28909f0f7693edae37a15d
https://github.com/wwadge/bonecp/blob/74bc3287025fc137ca28909f0f7693edae37a15d/bonecp-spring/src/main/java/com/jolbox/bonecp/spring/DynamicDataSourceProxy.java#L64-L81
163,138
wwadge/bonecp
bonecp/src/main/java/com/jolbox/bonecp/MemorizeTransactionProxy.java
MemorizeTransactionProxy.memorize
protected static Connection memorize(final Connection target, final ConnectionHandle connectionHandle) { return (Connection) Proxy.newProxyInstance( ConnectionProxy.class.getClassLoader(), new Class[] {ConnectionProxy.class}, new MemorizeTransactionProxy(target, connectionHandle)); }
java
protected static Connection memorize(final Connection target, final ConnectionHandle connectionHandle) { return (Connection) Proxy.newProxyInstance( ConnectionProxy.class.getClassLoader(), new Class[] {ConnectionProxy.class}, new MemorizeTransactionProxy(target, connectionHandle)); }
[ "protected", "static", "Connection", "memorize", "(", "final", "Connection", "target", ",", "final", "ConnectionHandle", "connectionHandle", ")", "{", "return", "(", "Connection", ")", "Proxy", ".", "newProxyInstance", "(", "ConnectionProxy", ".", "class", ".", "getClassLoader", "(", ")", ",", "new", "Class", "[", "]", "{", "ConnectionProxy", ".", "class", "}", ",", "new", "MemorizeTransactionProxy", "(", "target", ",", "connectionHandle", ")", ")", ";", "}" ]
Wrap connection with a proxy. @param target connection handle @param connectionHandle originating bonecp connection @return Proxy to a connection.
[ "Wrap", "connection", "with", "a", "proxy", "." ]
74bc3287025fc137ca28909f0f7693edae37a15d
https://github.com/wwadge/bonecp/blob/74bc3287025fc137ca28909f0f7693edae37a15d/bonecp/src/main/java/com/jolbox/bonecp/MemorizeTransactionProxy.java#L79-L85
163,139
wwadge/bonecp
bonecp/src/main/java/com/jolbox/bonecp/MemorizeTransactionProxy.java
MemorizeTransactionProxy.memorize
protected static Statement memorize(final Statement target, final ConnectionHandle connectionHandle) { return (Statement) Proxy.newProxyInstance( StatementProxy.class.getClassLoader(), new Class[] {StatementProxy.class}, new MemorizeTransactionProxy(target, connectionHandle)); }
java
protected static Statement memorize(final Statement target, final ConnectionHandle connectionHandle) { return (Statement) Proxy.newProxyInstance( StatementProxy.class.getClassLoader(), new Class[] {StatementProxy.class}, new MemorizeTransactionProxy(target, connectionHandle)); }
[ "protected", "static", "Statement", "memorize", "(", "final", "Statement", "target", ",", "final", "ConnectionHandle", "connectionHandle", ")", "{", "return", "(", "Statement", ")", "Proxy", ".", "newProxyInstance", "(", "StatementProxy", ".", "class", ".", "getClassLoader", "(", ")", ",", "new", "Class", "[", "]", "{", "StatementProxy", ".", "class", "}", ",", "new", "MemorizeTransactionProxy", "(", "target", ",", "connectionHandle", ")", ")", ";", "}" ]
Wrap Statement with a proxy. @param target statement handle @param connectionHandle originating bonecp connection @return Proxy to a statement.
[ "Wrap", "Statement", "with", "a", "proxy", "." ]
74bc3287025fc137ca28909f0f7693edae37a15d
https://github.com/wwadge/bonecp/blob/74bc3287025fc137ca28909f0f7693edae37a15d/bonecp/src/main/java/com/jolbox/bonecp/MemorizeTransactionProxy.java#L92-L97
163,140
wwadge/bonecp
bonecp/src/main/java/com/jolbox/bonecp/MemorizeTransactionProxy.java
MemorizeTransactionProxy.memorize
protected static PreparedStatement memorize(final PreparedStatement target, final ConnectionHandle connectionHandle) { return (PreparedStatement) Proxy.newProxyInstance( PreparedStatementProxy.class.getClassLoader(), new Class[] {PreparedStatementProxy.class}, new MemorizeTransactionProxy(target, connectionHandle)); }
java
protected static PreparedStatement memorize(final PreparedStatement target, final ConnectionHandle connectionHandle) { return (PreparedStatement) Proxy.newProxyInstance( PreparedStatementProxy.class.getClassLoader(), new Class[] {PreparedStatementProxy.class}, new MemorizeTransactionProxy(target, connectionHandle)); }
[ "protected", "static", "PreparedStatement", "memorize", "(", "final", "PreparedStatement", "target", ",", "final", "ConnectionHandle", "connectionHandle", ")", "{", "return", "(", "PreparedStatement", ")", "Proxy", ".", "newProxyInstance", "(", "PreparedStatementProxy", ".", "class", ".", "getClassLoader", "(", ")", ",", "new", "Class", "[", "]", "{", "PreparedStatementProxy", ".", "class", "}", ",", "new", "MemorizeTransactionProxy", "(", "target", ",", "connectionHandle", ")", ")", ";", "}" ]
Wrap PreparedStatement with a proxy. @param target statement handle @param connectionHandle originating bonecp connection @return Proxy to a Preparedstatement.
[ "Wrap", "PreparedStatement", "with", "a", "proxy", "." ]
74bc3287025fc137ca28909f0f7693edae37a15d
https://github.com/wwadge/bonecp/blob/74bc3287025fc137ca28909f0f7693edae37a15d/bonecp/src/main/java/com/jolbox/bonecp/MemorizeTransactionProxy.java#L104-L109
163,141
wwadge/bonecp
bonecp/src/main/java/com/jolbox/bonecp/MemorizeTransactionProxy.java
MemorizeTransactionProxy.memorize
protected static CallableStatement memorize(final CallableStatement target, final ConnectionHandle connectionHandle) { return (CallableStatement) Proxy.newProxyInstance( CallableStatementProxy.class.getClassLoader(), new Class[] {CallableStatementProxy.class}, new MemorizeTransactionProxy(target, connectionHandle)); }
java
protected static CallableStatement memorize(final CallableStatement target, final ConnectionHandle connectionHandle) { return (CallableStatement) Proxy.newProxyInstance( CallableStatementProxy.class.getClassLoader(), new Class[] {CallableStatementProxy.class}, new MemorizeTransactionProxy(target, connectionHandle)); }
[ "protected", "static", "CallableStatement", "memorize", "(", "final", "CallableStatement", "target", ",", "final", "ConnectionHandle", "connectionHandle", ")", "{", "return", "(", "CallableStatement", ")", "Proxy", ".", "newProxyInstance", "(", "CallableStatementProxy", ".", "class", ".", "getClassLoader", "(", ")", ",", "new", "Class", "[", "]", "{", "CallableStatementProxy", ".", "class", "}", ",", "new", "MemorizeTransactionProxy", "(", "target", ",", "connectionHandle", ")", ")", ";", "}" ]
Wrap CallableStatement with a proxy. @param target statement handle @param connectionHandle originating bonecp connection @return Proxy to a Callablestatement.
[ "Wrap", "CallableStatement", "with", "a", "proxy", "." ]
74bc3287025fc137ca28909f0f7693edae37a15d
https://github.com/wwadge/bonecp/blob/74bc3287025fc137ca28909f0f7693edae37a15d/bonecp/src/main/java/com/jolbox/bonecp/MemorizeTransactionProxy.java#L117-L122
163,142
wwadge/bonecp
bonecp/src/main/java/com/jolbox/bonecp/MemorizeTransactionProxy.java
MemorizeTransactionProxy.runWithPossibleProxySwap
private Object runWithPossibleProxySwap(Method method, Object target, Object[] args) throws IllegalAccessException, InvocationTargetException { Object result; // swap with proxies to these too. if (method.getName().equals("createStatement")){ result = memorize((Statement)method.invoke(target, args), this.connectionHandle.get()); } else if (method.getName().equals("prepareStatement")){ result = memorize((PreparedStatement)method.invoke(target, args), this.connectionHandle.get()); } else if (method.getName().equals("prepareCall")){ result = memorize((CallableStatement)method.invoke(target, args), this.connectionHandle.get()); } else result = method.invoke(target, args); return result; }
java
private Object runWithPossibleProxySwap(Method method, Object target, Object[] args) throws IllegalAccessException, InvocationTargetException { Object result; // swap with proxies to these too. if (method.getName().equals("createStatement")){ result = memorize((Statement)method.invoke(target, args), this.connectionHandle.get()); } else if (method.getName().equals("prepareStatement")){ result = memorize((PreparedStatement)method.invoke(target, args), this.connectionHandle.get()); } else if (method.getName().equals("prepareCall")){ result = memorize((CallableStatement)method.invoke(target, args), this.connectionHandle.get()); } else result = method.invoke(target, args); return result; }
[ "private", "Object", "runWithPossibleProxySwap", "(", "Method", "method", ",", "Object", "target", ",", "Object", "[", "]", "args", ")", "throws", "IllegalAccessException", ",", "InvocationTargetException", "{", "Object", "result", ";", "// swap with proxies to these too.", "if", "(", "method", ".", "getName", "(", ")", ".", "equals", "(", "\"createStatement\"", ")", ")", "{", "result", "=", "memorize", "(", "(", "Statement", ")", "method", ".", "invoke", "(", "target", ",", "args", ")", ",", "this", ".", "connectionHandle", ".", "get", "(", ")", ")", ";", "}", "else", "if", "(", "method", ".", "getName", "(", ")", ".", "equals", "(", "\"prepareStatement\"", ")", ")", "{", "result", "=", "memorize", "(", "(", "PreparedStatement", ")", "method", ".", "invoke", "(", "target", ",", "args", ")", ",", "this", ".", "connectionHandle", ".", "get", "(", ")", ")", ";", "}", "else", "if", "(", "method", ".", "getName", "(", ")", ".", "equals", "(", "\"prepareCall\"", ")", ")", "{", "result", "=", "memorize", "(", "(", "CallableStatement", ")", "method", ".", "invoke", "(", "target", ",", "args", ")", ",", "this", ".", "connectionHandle", ".", "get", "(", ")", ")", ";", "}", "else", "result", "=", "method", ".", "invoke", "(", "target", ",", "args", ")", ";", "return", "result", ";", "}" ]
Runs the given method with the specified arguments, substituting with proxies where necessary @param method @param target proxy target @param args @return Proxy-fied result for statements, actual call result otherwise @throws IllegalAccessException @throws InvocationTargetException
[ "Runs", "the", "given", "method", "with", "the", "specified", "arguments", "substituting", "with", "proxies", "where", "necessary" ]
74bc3287025fc137ca28909f0f7693edae37a15d
https://github.com/wwadge/bonecp/blob/74bc3287025fc137ca28909f0f7693edae37a15d/bonecp/src/main/java/com/jolbox/bonecp/MemorizeTransactionProxy.java#L246-L261
163,143
wwadge/bonecp
bonecp/src/main/java/com/jolbox/bonecp/PoolWatchThread.java
PoolWatchThread.fillConnections
private void fillConnections(int connectionsToCreate) throws InterruptedException { try { for (int i=0; i < connectionsToCreate; i++){ // boolean dbDown = this.pool.getDbIsDown().get(); if (this.pool.poolShuttingDown){ break; } this.partition.addFreeConnection(new ConnectionHandle(null, this.partition, this.pool, false)); } } catch (Exception e) { logger.error("Error in trying to obtain a connection. Retrying in "+this.acquireRetryDelayInMs+"ms", e); Thread.sleep(this.acquireRetryDelayInMs); } }
java
private void fillConnections(int connectionsToCreate) throws InterruptedException { try { for (int i=0; i < connectionsToCreate; i++){ // boolean dbDown = this.pool.getDbIsDown().get(); if (this.pool.poolShuttingDown){ break; } this.partition.addFreeConnection(new ConnectionHandle(null, this.partition, this.pool, false)); } } catch (Exception e) { logger.error("Error in trying to obtain a connection. Retrying in "+this.acquireRetryDelayInMs+"ms", e); Thread.sleep(this.acquireRetryDelayInMs); } }
[ "private", "void", "fillConnections", "(", "int", "connectionsToCreate", ")", "throws", "InterruptedException", "{", "try", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "connectionsToCreate", ";", "i", "++", ")", "{", "//\tboolean dbDown = this.pool.getDbIsDown().get();\r", "if", "(", "this", ".", "pool", ".", "poolShuttingDown", ")", "{", "break", ";", "}", "this", ".", "partition", ".", "addFreeConnection", "(", "new", "ConnectionHandle", "(", "null", ",", "this", ".", "partition", ",", "this", ".", "pool", ",", "false", ")", ")", ";", "}", "}", "catch", "(", "Exception", "e", ")", "{", "logger", ".", "error", "(", "\"Error in trying to obtain a connection. Retrying in \"", "+", "this", ".", "acquireRetryDelayInMs", "+", "\"ms\"", ",", "e", ")", ";", "Thread", ".", "sleep", "(", "this", ".", "acquireRetryDelayInMs", ")", ";", "}", "}" ]
Adds new connections to the partition. @param connectionsToCreate number of connections to create @throws InterruptedException
[ "Adds", "new", "connections", "to", "the", "partition", "." ]
74bc3287025fc137ca28909f0f7693edae37a15d
https://github.com/wwadge/bonecp/blob/74bc3287025fc137ca28909f0f7693edae37a15d/bonecp/src/main/java/com/jolbox/bonecp/PoolWatchThread.java#L108-L122
163,144
wwadge/bonecp
bonecp/src/main/java/com/jolbox/bonecp/StatementCache.java
StatementCache.calculateCacheKey
public String calculateCacheKey(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability){ StringBuilder tmp = calculateCacheKeyInternal(sql, resultSetType, resultSetConcurrency); tmp.append(", H:"); tmp.append(resultSetHoldability); return tmp.toString(); }
java
public String calculateCacheKey(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability){ StringBuilder tmp = calculateCacheKeyInternal(sql, resultSetType, resultSetConcurrency); tmp.append(", H:"); tmp.append(resultSetHoldability); return tmp.toString(); }
[ "public", "String", "calculateCacheKey", "(", "String", "sql", ",", "int", "resultSetType", ",", "int", "resultSetConcurrency", ",", "int", "resultSetHoldability", ")", "{", "StringBuilder", "tmp", "=", "calculateCacheKeyInternal", "(", "sql", ",", "resultSetType", ",", "resultSetConcurrency", ")", ";", "tmp", ".", "append", "(", "\", H:\"", ")", ";", "tmp", ".", "append", "(", "resultSetHoldability", ")", ";", "return", "tmp", ".", "toString", "(", ")", ";", "}" ]
Simply appends the given parameters and returns it to obtain a cache key @param sql @param resultSetConcurrency @param resultSetHoldability @param resultSetType @return cache key to use
[ "Simply", "appends", "the", "given", "parameters", "and", "returns", "it", "to", "obtain", "a", "cache", "key" ]
74bc3287025fc137ca28909f0f7693edae37a15d
https://github.com/wwadge/bonecp/blob/74bc3287025fc137ca28909f0f7693edae37a15d/bonecp/src/main/java/com/jolbox/bonecp/StatementCache.java#L68-L76
163,145
wwadge/bonecp
bonecp/src/main/java/com/jolbox/bonecp/StatementCache.java
StatementCache.calculateCacheKeyInternal
private StringBuilder calculateCacheKeyInternal(String sql, int resultSetType, int resultSetConcurrency) { StringBuilder tmp = new StringBuilder(sql.length()+20); tmp.append(sql); tmp.append(", T"); tmp.append(resultSetType); tmp.append(", C"); tmp.append(resultSetConcurrency); return tmp; }
java
private StringBuilder calculateCacheKeyInternal(String sql, int resultSetType, int resultSetConcurrency) { StringBuilder tmp = new StringBuilder(sql.length()+20); tmp.append(sql); tmp.append(", T"); tmp.append(resultSetType); tmp.append(", C"); tmp.append(resultSetConcurrency); return tmp; }
[ "private", "StringBuilder", "calculateCacheKeyInternal", "(", "String", "sql", ",", "int", "resultSetType", ",", "int", "resultSetConcurrency", ")", "{", "StringBuilder", "tmp", "=", "new", "StringBuilder", "(", "sql", ".", "length", "(", ")", "+", "20", ")", ";", "tmp", ".", "append", "(", "sql", ")", ";", "tmp", ".", "append", "(", "\", T\"", ")", ";", "tmp", ".", "append", "(", "resultSetType", ")", ";", "tmp", ".", "append", "(", "\", C\"", ")", ";", "tmp", ".", "append", "(", "resultSetConcurrency", ")", ";", "return", "tmp", ";", "}" ]
Cache key calculation. @param sql @param resultSetType @param resultSetConcurrency @return cache key
[ "Cache", "key", "calculation", "." ]
74bc3287025fc137ca28909f0f7693edae37a15d
https://github.com/wwadge/bonecp/blob/74bc3287025fc137ca28909f0f7693edae37a15d/bonecp/src/main/java/com/jolbox/bonecp/StatementCache.java#L97-L107
163,146
wwadge/bonecp
bonecp/src/main/java/com/jolbox/bonecp/StatementCache.java
StatementCache.calculateCacheKey
public String calculateCacheKey(String sql, int autoGeneratedKeys) { StringBuilder tmp = new StringBuilder(sql.length()+4); tmp.append(sql); tmp.append(autoGeneratedKeys); return tmp.toString(); }
java
public String calculateCacheKey(String sql, int autoGeneratedKeys) { StringBuilder tmp = new StringBuilder(sql.length()+4); tmp.append(sql); tmp.append(autoGeneratedKeys); return tmp.toString(); }
[ "public", "String", "calculateCacheKey", "(", "String", "sql", ",", "int", "autoGeneratedKeys", ")", "{", "StringBuilder", "tmp", "=", "new", "StringBuilder", "(", "sql", ".", "length", "(", ")", "+", "4", ")", ";", "tmp", ".", "append", "(", "sql", ")", ";", "tmp", ".", "append", "(", "autoGeneratedKeys", ")", ";", "return", "tmp", ".", "toString", "(", ")", ";", "}" ]
Alternate version of autoGeneratedKeys. @param sql @param autoGeneratedKeys @return cache key to use.
[ "Alternate", "version", "of", "autoGeneratedKeys", "." ]
74bc3287025fc137ca28909f0f7693edae37a15d
https://github.com/wwadge/bonecp/blob/74bc3287025fc137ca28909f0f7693edae37a15d/bonecp/src/main/java/com/jolbox/bonecp/StatementCache.java#L115-L120
163,147
wwadge/bonecp
bonecp/src/main/java/com/jolbox/bonecp/StatementCache.java
StatementCache.calculateCacheKey
public String calculateCacheKey(String sql, int[] columnIndexes) { StringBuilder tmp = new StringBuilder(sql.length()+4); tmp.append(sql); for (int i=0; i < columnIndexes.length; i++){ tmp.append(columnIndexes[i]); tmp.append("CI,"); } return tmp.toString(); }
java
public String calculateCacheKey(String sql, int[] columnIndexes) { StringBuilder tmp = new StringBuilder(sql.length()+4); tmp.append(sql); for (int i=0; i < columnIndexes.length; i++){ tmp.append(columnIndexes[i]); tmp.append("CI,"); } return tmp.toString(); }
[ "public", "String", "calculateCacheKey", "(", "String", "sql", ",", "int", "[", "]", "columnIndexes", ")", "{", "StringBuilder", "tmp", "=", "new", "StringBuilder", "(", "sql", ".", "length", "(", ")", "+", "4", ")", ";", "tmp", ".", "append", "(", "sql", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "columnIndexes", ".", "length", ";", "i", "++", ")", "{", "tmp", ".", "append", "(", "columnIndexes", "[", "i", "]", ")", ";", "tmp", ".", "append", "(", "\"CI,\"", ")", ";", "}", "return", "tmp", ".", "toString", "(", ")", ";", "}" ]
Calculate a cache key. @param sql to use @param columnIndexes to use @return cache key to use.
[ "Calculate", "a", "cache", "key", "." ]
74bc3287025fc137ca28909f0f7693edae37a15d
https://github.com/wwadge/bonecp/blob/74bc3287025fc137ca28909f0f7693edae37a15d/bonecp/src/main/java/com/jolbox/bonecp/StatementCache.java#L127-L135
163,148
wwadge/bonecp
bonecp/src/main/java/com/jolbox/bonecp/ConnectionMaxAgeThread.java
ConnectionMaxAgeThread.run
public void run() { ConnectionHandle connection = null; long tmp; long nextCheckInMs = this.maxAgeInMs; int partitionSize= this.partition.getAvailableConnections(); long currentTime = System.currentTimeMillis(); for (int i=0; i < partitionSize; i++){ try { connection = this.partition.getFreeConnections().poll(); if (connection != null){ connection.setOriginatingPartition(this.partition); tmp = this.maxAgeInMs - (currentTime - connection.getConnectionCreationTimeInMs()); if (tmp < nextCheckInMs){ nextCheckInMs = tmp; } if (connection.isExpired(currentTime)){ // kill off this connection closeConnection(connection); continue; } if (this.lifoMode){ // we can't put it back normally or it will end up in front again. if (!(connection.getOriginatingPartition().getFreeConnections().offer(connection))){ connection.internalClose(); } } else { this.pool.putConnectionBackInPartition(connection); } Thread.sleep(20L); // test slowly, this is not an operation that we're in a hurry to deal with (avoid CPU spikes)... } } catch (Throwable e) { logger.error("Connection max age thread exception.", e); } } // throw it back on the queue }
java
public void run() { ConnectionHandle connection = null; long tmp; long nextCheckInMs = this.maxAgeInMs; int partitionSize= this.partition.getAvailableConnections(); long currentTime = System.currentTimeMillis(); for (int i=0; i < partitionSize; i++){ try { connection = this.partition.getFreeConnections().poll(); if (connection != null){ connection.setOriginatingPartition(this.partition); tmp = this.maxAgeInMs - (currentTime - connection.getConnectionCreationTimeInMs()); if (tmp < nextCheckInMs){ nextCheckInMs = tmp; } if (connection.isExpired(currentTime)){ // kill off this connection closeConnection(connection); continue; } if (this.lifoMode){ // we can't put it back normally or it will end up in front again. if (!(connection.getOriginatingPartition().getFreeConnections().offer(connection))){ connection.internalClose(); } } else { this.pool.putConnectionBackInPartition(connection); } Thread.sleep(20L); // test slowly, this is not an operation that we're in a hurry to deal with (avoid CPU spikes)... } } catch (Throwable e) { logger.error("Connection max age thread exception.", e); } } // throw it back on the queue }
[ "public", "void", "run", "(", ")", "{", "ConnectionHandle", "connection", "=", "null", ";", "long", "tmp", ";", "long", "nextCheckInMs", "=", "this", ".", "maxAgeInMs", ";", "int", "partitionSize", "=", "this", ".", "partition", ".", "getAvailableConnections", "(", ")", ";", "long", "currentTime", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "partitionSize", ";", "i", "++", ")", "{", "try", "{", "connection", "=", "this", ".", "partition", ".", "getFreeConnections", "(", ")", ".", "poll", "(", ")", ";", "if", "(", "connection", "!=", "null", ")", "{", "connection", ".", "setOriginatingPartition", "(", "this", ".", "partition", ")", ";", "tmp", "=", "this", ".", "maxAgeInMs", "-", "(", "currentTime", "-", "connection", ".", "getConnectionCreationTimeInMs", "(", ")", ")", ";", "if", "(", "tmp", "<", "nextCheckInMs", ")", "{", "nextCheckInMs", "=", "tmp", ";", "}", "if", "(", "connection", ".", "isExpired", "(", "currentTime", ")", ")", "{", "// kill off this connection\r", "closeConnection", "(", "connection", ")", ";", "continue", ";", "}", "if", "(", "this", ".", "lifoMode", ")", "{", "// we can't put it back normally or it will end up in front again.\r", "if", "(", "!", "(", "connection", ".", "getOriginatingPartition", "(", ")", ".", "getFreeConnections", "(", ")", ".", "offer", "(", "connection", ")", ")", ")", "{", "connection", ".", "internalClose", "(", ")", ";", "}", "}", "else", "{", "this", ".", "pool", ".", "putConnectionBackInPartition", "(", "connection", ")", ";", "}", "Thread", ".", "sleep", "(", "20L", ")", ";", "// test slowly, this is not an operation that we're in a hurry to deal with (avoid CPU spikes)...\r", "}", "}", "catch", "(", "Throwable", "e", ")", "{", "logger", ".", "error", "(", "\"Connection max age thread exception.\"", ",", "e", ")", ";", "}", "}", "// throw it back on the queue\r", "}" ]
Invoked periodically.
[ "Invoked", "periodically", "." ]
74bc3287025fc137ca28909f0f7693edae37a15d
https://github.com/wwadge/bonecp/blob/74bc3287025fc137ca28909f0f7693edae37a15d/bonecp/src/main/java/com/jolbox/bonecp/ConnectionMaxAgeThread.java#L59-L105
163,149
wwadge/bonecp
bonecp/src/main/java/com/jolbox/bonecp/ConnectionMaxAgeThread.java
ConnectionMaxAgeThread.closeConnection
protected void closeConnection(ConnectionHandle connection) { if (connection != null) { try { connection.internalClose(); } catch (Throwable t) { logger.error("Destroy connection exception", t); } finally { this.pool.postDestroyConnection(connection); } } }
java
protected void closeConnection(ConnectionHandle connection) { if (connection != null) { try { connection.internalClose(); } catch (Throwable t) { logger.error("Destroy connection exception", t); } finally { this.pool.postDestroyConnection(connection); } } }
[ "protected", "void", "closeConnection", "(", "ConnectionHandle", "connection", ")", "{", "if", "(", "connection", "!=", "null", ")", "{", "try", "{", "connection", ".", "internalClose", "(", ")", ";", "}", "catch", "(", "Throwable", "t", ")", "{", "logger", ".", "error", "(", "\"Destroy connection exception\"", ",", "t", ")", ";", "}", "finally", "{", "this", ".", "pool", ".", "postDestroyConnection", "(", "connection", ")", ";", "}", "}", "}" ]
Closes off this connection @param connection to close
[ "Closes", "off", "this", "connection" ]
74bc3287025fc137ca28909f0f7693edae37a15d
https://github.com/wwadge/bonecp/blob/74bc3287025fc137ca28909f0f7693edae37a15d/bonecp/src/main/java/com/jolbox/bonecp/ConnectionMaxAgeThread.java#L111-L121
163,150
wwadge/bonecp
bonecp/src/main/java/com/jolbox/bonecp/BoneCPConfig.java
BoneCPConfig.setIdleMaxAge
public void setIdleMaxAge(long idleMaxAge, TimeUnit timeUnit) { this.idleMaxAgeInSeconds = TimeUnit.SECONDS.convert(idleMaxAge, checkNotNull(timeUnit)); }
java
public void setIdleMaxAge(long idleMaxAge, TimeUnit timeUnit) { this.idleMaxAgeInSeconds = TimeUnit.SECONDS.convert(idleMaxAge, checkNotNull(timeUnit)); }
[ "public", "void", "setIdleMaxAge", "(", "long", "idleMaxAge", ",", "TimeUnit", "timeUnit", ")", "{", "this", ".", "idleMaxAgeInSeconds", "=", "TimeUnit", ".", "SECONDS", ".", "convert", "(", "idleMaxAge", ",", "checkNotNull", "(", "timeUnit", ")", ")", ";", "}" ]
Sets Idle max age. The time, for a connection to remain unused before it is closed off. Do not use aggressive values here! @param idleMaxAge time after which a connection is closed off @param timeUnit idleMaxAge time granularity.
[ "Sets", "Idle", "max", "age", "." ]
74bc3287025fc137ca28909f0f7693edae37a15d
https://github.com/wwadge/bonecp/blob/74bc3287025fc137ca28909f0f7693edae37a15d/bonecp/src/main/java/com/jolbox/bonecp/BoneCPConfig.java#L490-L492
163,151
wwadge/bonecp
bonecp/src/main/java/com/jolbox/bonecp/BoneCPConfig.java
BoneCPConfig.setAcquireRetryDelay
public void setAcquireRetryDelay(long acquireRetryDelay, TimeUnit timeUnit) { this.acquireRetryDelayInMs = TimeUnit.MILLISECONDS.convert(acquireRetryDelay, timeUnit); }
java
public void setAcquireRetryDelay(long acquireRetryDelay, TimeUnit timeUnit) { this.acquireRetryDelayInMs = TimeUnit.MILLISECONDS.convert(acquireRetryDelay, timeUnit); }
[ "public", "void", "setAcquireRetryDelay", "(", "long", "acquireRetryDelay", ",", "TimeUnit", "timeUnit", ")", "{", "this", ".", "acquireRetryDelayInMs", "=", "TimeUnit", ".", "MILLISECONDS", ".", "convert", "(", "acquireRetryDelay", ",", "timeUnit", ")", ";", "}" ]
Sets the number of ms to wait before attempting to obtain a connection again after a failure. @param acquireRetryDelay the acquireRetryDelay to set @param timeUnit time granularity
[ "Sets", "the", "number", "of", "ms", "to", "wait", "before", "attempting", "to", "obtain", "a", "connection", "again", "after", "a", "failure", "." ]
74bc3287025fc137ca28909f0f7693edae37a15d
https://github.com/wwadge/bonecp/blob/74bc3287025fc137ca28909f0f7693edae37a15d/bonecp/src/main/java/com/jolbox/bonecp/BoneCPConfig.java#L767-L769
163,152
wwadge/bonecp
bonecp/src/main/java/com/jolbox/bonecp/BoneCPConfig.java
BoneCPConfig.setQueryExecuteTimeLimit
public void setQueryExecuteTimeLimit(long queryExecuteTimeLimit, TimeUnit timeUnit) { this.queryExecuteTimeLimitInMs = TimeUnit.MILLISECONDS.convert(queryExecuteTimeLimit, timeUnit); }
java
public void setQueryExecuteTimeLimit(long queryExecuteTimeLimit, TimeUnit timeUnit) { this.queryExecuteTimeLimitInMs = TimeUnit.MILLISECONDS.convert(queryExecuteTimeLimit, timeUnit); }
[ "public", "void", "setQueryExecuteTimeLimit", "(", "long", "queryExecuteTimeLimit", ",", "TimeUnit", "timeUnit", ")", "{", "this", ".", "queryExecuteTimeLimitInMs", "=", "TimeUnit", ".", "MILLISECONDS", ".", "convert", "(", "queryExecuteTimeLimit", ",", "timeUnit", ")", ";", "}" ]
Queries taking longer than this limit to execute are logged. @param queryExecuteTimeLimit the limit to set in milliseconds. @param timeUnit
[ "Queries", "taking", "longer", "than", "this", "limit", "to", "execute", "are", "logged", "." ]
74bc3287025fc137ca28909f0f7693edae37a15d
https://github.com/wwadge/bonecp/blob/74bc3287025fc137ca28909f0f7693edae37a15d/bonecp/src/main/java/com/jolbox/bonecp/BoneCPConfig.java#L919-L921
163,153
wwadge/bonecp
bonecp/src/main/java/com/jolbox/bonecp/BoneCPConfig.java
BoneCPConfig.setConnectionTimeout
public void setConnectionTimeout(long connectionTimeout, TimeUnit timeUnit) { this.connectionTimeoutInMs = TimeUnit.MILLISECONDS.convert(connectionTimeout, timeUnit); }
java
public void setConnectionTimeout(long connectionTimeout, TimeUnit timeUnit) { this.connectionTimeoutInMs = TimeUnit.MILLISECONDS.convert(connectionTimeout, timeUnit); }
[ "public", "void", "setConnectionTimeout", "(", "long", "connectionTimeout", ",", "TimeUnit", "timeUnit", ")", "{", "this", ".", "connectionTimeoutInMs", "=", "TimeUnit", ".", "MILLISECONDS", ".", "convert", "(", "connectionTimeout", ",", "timeUnit", ")", ";", "}" ]
Sets the maximum time to wait before a call to getConnection is timed out. Setting this to zero is similar to setting it to Long.MAX_VALUE @param connectionTimeout @param timeUnit the unit of the connectionTimeout argument
[ "Sets", "the", "maximum", "time", "to", "wait", "before", "a", "call", "to", "getConnection", "is", "timed", "out", "." ]
74bc3287025fc137ca28909f0f7693edae37a15d
https://github.com/wwadge/bonecp/blob/74bc3287025fc137ca28909f0f7693edae37a15d/bonecp/src/main/java/com/jolbox/bonecp/BoneCPConfig.java#L1027-L1029
163,154
wwadge/bonecp
bonecp/src/main/java/com/jolbox/bonecp/BoneCPConfig.java
BoneCPConfig.setCloseConnectionWatchTimeout
public void setCloseConnectionWatchTimeout(long closeConnectionWatchTimeout, TimeUnit timeUnit) { this.closeConnectionWatchTimeoutInMs = TimeUnit.MILLISECONDS.convert(closeConnectionWatchTimeout, timeUnit); }
java
public void setCloseConnectionWatchTimeout(long closeConnectionWatchTimeout, TimeUnit timeUnit) { this.closeConnectionWatchTimeoutInMs = TimeUnit.MILLISECONDS.convert(closeConnectionWatchTimeout, timeUnit); }
[ "public", "void", "setCloseConnectionWatchTimeout", "(", "long", "closeConnectionWatchTimeout", ",", "TimeUnit", "timeUnit", ")", "{", "this", ".", "closeConnectionWatchTimeoutInMs", "=", "TimeUnit", ".", "MILLISECONDS", ".", "convert", "(", "closeConnectionWatchTimeout", ",", "timeUnit", ")", ";", "}" ]
Sets the time to wait when close connection watch threads are enabled. 0 = wait forever. @param closeConnectionWatchTimeout the watchTimeout to set @param timeUnit Time granularity
[ "Sets", "the", "time", "to", "wait", "when", "close", "connection", "watch", "threads", "are", "enabled", ".", "0", "=", "wait", "forever", "." ]
74bc3287025fc137ca28909f0f7693edae37a15d
https://github.com/wwadge/bonecp/blob/74bc3287025fc137ca28909f0f7693edae37a15d/bonecp/src/main/java/com/jolbox/bonecp/BoneCPConfig.java#L1106-L1108
163,155
wwadge/bonecp
bonecp/src/main/java/com/jolbox/bonecp/BoneCPConfig.java
BoneCPConfig.setMaxConnectionAge
public void setMaxConnectionAge(long maxConnectionAge, TimeUnit timeUnit) { this.maxConnectionAgeInSeconds = TimeUnit.SECONDS.convert(maxConnectionAge, timeUnit); }
java
public void setMaxConnectionAge(long maxConnectionAge, TimeUnit timeUnit) { this.maxConnectionAgeInSeconds = TimeUnit.SECONDS.convert(maxConnectionAge, timeUnit); }
[ "public", "void", "setMaxConnectionAge", "(", "long", "maxConnectionAge", ",", "TimeUnit", "timeUnit", ")", "{", "this", ".", "maxConnectionAgeInSeconds", "=", "TimeUnit", ".", "SECONDS", ".", "convert", "(", "maxConnectionAge", ",", "timeUnit", ")", ";", "}" ]
Sets the maxConnectionAge. Any connections older than this setting will be closed off whether it is idle or not. Connections currently in use will not be affected until they are returned to the pool. @param maxConnectionAge the maxConnectionAge to set. @param timeUnit the unit of the maxConnectionAge argument.
[ "Sets", "the", "maxConnectionAge", ".", "Any", "connections", "older", "than", "this", "setting", "will", "be", "closed", "off", "whether", "it", "is", "idle", "or", "not", ".", "Connections", "currently", "in", "use", "will", "not", "be", "affected", "until", "they", "are", "returned", "to", "the", "pool", "." ]
74bc3287025fc137ca28909f0f7693edae37a15d
https://github.com/wwadge/bonecp/blob/74bc3287025fc137ca28909f0f7693edae37a15d/bonecp/src/main/java/com/jolbox/bonecp/BoneCPConfig.java#L1200-L1202
163,156
wwadge/bonecp
bonecp/src/main/java/com/jolbox/bonecp/BoneCPConfig.java
BoneCPConfig.parseXML
private Properties parseXML(Document doc, String sectionName) { int found = -1; Properties results = new Properties(); NodeList config = null; if (sectionName == null){ config = doc.getElementsByTagName("default-config"); found = 0; } else { config = doc.getElementsByTagName("named-config"); if(config != null && config.getLength() > 0) { for (int i = 0; i < config.getLength(); i++) { Node node = config.item(i); if(node.getNodeType() == Node.ELEMENT_NODE ){ NamedNodeMap attributes = node.getAttributes(); if (attributes != null && attributes.getLength() > 0){ Node name = attributes.getNamedItem("name"); if (name.getNodeValue().equalsIgnoreCase(sectionName)){ found = i; break; } } } } } if (found == -1){ config = null; logger.warn("Did not find "+sectionName+" section in config file. Reverting to defaults."); } } if(config != null && config.getLength() > 0) { Node node = config.item(found); if(node.getNodeType() == Node.ELEMENT_NODE){ Element elementEntry = (Element)node; NodeList childNodeList = elementEntry.getChildNodes(); for (int j = 0; j < childNodeList.getLength(); j++) { Node node_j = childNodeList.item(j); if (node_j.getNodeType() == Node.ELEMENT_NODE) { Element piece = (Element) node_j; NamedNodeMap attributes = piece.getAttributes(); if (attributes != null && attributes.getLength() > 0){ results.put(attributes.item(0).getNodeValue(), piece.getTextContent()); } } } } } return results; }
java
private Properties parseXML(Document doc, String sectionName) { int found = -1; Properties results = new Properties(); NodeList config = null; if (sectionName == null){ config = doc.getElementsByTagName("default-config"); found = 0; } else { config = doc.getElementsByTagName("named-config"); if(config != null && config.getLength() > 0) { for (int i = 0; i < config.getLength(); i++) { Node node = config.item(i); if(node.getNodeType() == Node.ELEMENT_NODE ){ NamedNodeMap attributes = node.getAttributes(); if (attributes != null && attributes.getLength() > 0){ Node name = attributes.getNamedItem("name"); if (name.getNodeValue().equalsIgnoreCase(sectionName)){ found = i; break; } } } } } if (found == -1){ config = null; logger.warn("Did not find "+sectionName+" section in config file. Reverting to defaults."); } } if(config != null && config.getLength() > 0) { Node node = config.item(found); if(node.getNodeType() == Node.ELEMENT_NODE){ Element elementEntry = (Element)node; NodeList childNodeList = elementEntry.getChildNodes(); for (int j = 0; j < childNodeList.getLength(); j++) { Node node_j = childNodeList.item(j); if (node_j.getNodeType() == Node.ELEMENT_NODE) { Element piece = (Element) node_j; NamedNodeMap attributes = piece.getAttributes(); if (attributes != null && attributes.getLength() > 0){ results.put(attributes.item(0).getNodeValue(), piece.getTextContent()); } } } } } return results; }
[ "private", "Properties", "parseXML", "(", "Document", "doc", ",", "String", "sectionName", ")", "{", "int", "found", "=", "-", "1", ";", "Properties", "results", "=", "new", "Properties", "(", ")", ";", "NodeList", "config", "=", "null", ";", "if", "(", "sectionName", "==", "null", ")", "{", "config", "=", "doc", ".", "getElementsByTagName", "(", "\"default-config\"", ")", ";", "found", "=", "0", ";", "}", "else", "{", "config", "=", "doc", ".", "getElementsByTagName", "(", "\"named-config\"", ")", ";", "if", "(", "config", "!=", "null", "&&", "config", ".", "getLength", "(", ")", ">", "0", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "config", ".", "getLength", "(", ")", ";", "i", "++", ")", "{", "Node", "node", "=", "config", ".", "item", "(", "i", ")", ";", "if", "(", "node", ".", "getNodeType", "(", ")", "==", "Node", ".", "ELEMENT_NODE", ")", "{", "NamedNodeMap", "attributes", "=", "node", ".", "getAttributes", "(", ")", ";", "if", "(", "attributes", "!=", "null", "&&", "attributes", ".", "getLength", "(", ")", ">", "0", ")", "{", "Node", "name", "=", "attributes", ".", "getNamedItem", "(", "\"name\"", ")", ";", "if", "(", "name", ".", "getNodeValue", "(", ")", ".", "equalsIgnoreCase", "(", "sectionName", ")", ")", "{", "found", "=", "i", ";", "break", ";", "}", "}", "}", "}", "}", "if", "(", "found", "==", "-", "1", ")", "{", "config", "=", "null", ";", "logger", ".", "warn", "(", "\"Did not find \"", "+", "sectionName", "+", "\" section in config file. Reverting to defaults.\"", ")", ";", "}", "}", "if", "(", "config", "!=", "null", "&&", "config", ".", "getLength", "(", ")", ">", "0", ")", "{", "Node", "node", "=", "config", ".", "item", "(", "found", ")", ";", "if", "(", "node", ".", "getNodeType", "(", ")", "==", "Node", ".", "ELEMENT_NODE", ")", "{", "Element", "elementEntry", "=", "(", "Element", ")", "node", ";", "NodeList", "childNodeList", "=", "elementEntry", ".", "getChildNodes", "(", ")", ";", "for", "(", "int", "j", "=", "0", ";", "j", "<", "childNodeList", ".", "getLength", "(", ")", ";", "j", "++", ")", "{", "Node", "node_j", "=", "childNodeList", ".", "item", "(", "j", ")", ";", "if", "(", "node_j", ".", "getNodeType", "(", ")", "==", "Node", ".", "ELEMENT_NODE", ")", "{", "Element", "piece", "=", "(", "Element", ")", "node_j", ";", "NamedNodeMap", "attributes", "=", "piece", ".", "getAttributes", "(", ")", ";", "if", "(", "attributes", "!=", "null", "&&", "attributes", ".", "getLength", "(", ")", ">", "0", ")", "{", "results", ".", "put", "(", "attributes", ".", "item", "(", "0", ")", ".", "getNodeValue", "(", ")", ",", "piece", ".", "getTextContent", "(", ")", ")", ";", "}", "}", "}", "}", "}", "return", "results", ";", "}" ]
Parses the given XML doc to extract the properties and return them into a java.util.Properties. @param doc to parse @param sectionName which section to extract @return Properties map
[ "Parses", "the", "given", "XML", "doc", "to", "extract", "the", "properties", "and", "return", "them", "into", "a", "java", ".", "util", ".", "Properties", "." ]
74bc3287025fc137ca28909f0f7693edae37a15d
https://github.com/wwadge/bonecp/blob/74bc3287025fc137ca28909f0f7693edae37a15d/bonecp/src/main/java/com/jolbox/bonecp/BoneCPConfig.java#L1485-L1535
163,157
wwadge/bonecp
bonecp/src/main/java/com/jolbox/bonecp/BoneCPConfig.java
BoneCPConfig.loadClass
protected Class<?> loadClass(String clazz) throws ClassNotFoundException { if (this.classLoader == null){ return Class.forName(clazz); } return Class.forName(clazz, true, this.classLoader); }
java
protected Class<?> loadClass(String clazz) throws ClassNotFoundException { if (this.classLoader == null){ return Class.forName(clazz); } return Class.forName(clazz, true, this.classLoader); }
[ "protected", "Class", "<", "?", ">", "loadClass", "(", "String", "clazz", ")", "throws", "ClassNotFoundException", "{", "if", "(", "this", ".", "classLoader", "==", "null", ")", "{", "return", "Class", ".", "forName", "(", "clazz", ")", ";", "}", "return", "Class", ".", "forName", "(", "clazz", ",", "true", ",", "this", ".", "classLoader", ")", ";", "}" ]
Loads the given class, respecting the given classloader. @param clazz class to load @return Loaded class @throws ClassNotFoundException
[ "Loads", "the", "given", "class", "respecting", "the", "given", "classloader", "." ]
74bc3287025fc137ca28909f0f7693edae37a15d
https://github.com/wwadge/bonecp/blob/74bc3287025fc137ca28909f0f7693edae37a15d/bonecp/src/main/java/com/jolbox/bonecp/BoneCPConfig.java#L1755-L1762
163,158
wwadge/bonecp
bonecp/src/main/java/com/jolbox/bonecp/BoneCPConfig.java
BoneCPConfig.hasSameConfiguration
public boolean hasSameConfiguration(BoneCPConfig that){ if ( that != null && Objects.equal(this.acquireIncrement, that.getAcquireIncrement()) && Objects.equal(this.acquireRetryDelayInMs, that.getAcquireRetryDelayInMs()) && Objects.equal(this.closeConnectionWatch, that.isCloseConnectionWatch()) && Objects.equal(this.logStatementsEnabled, that.isLogStatementsEnabled()) && Objects.equal(this.connectionHook, that.getConnectionHook()) && Objects.equal(this.connectionTestStatement, that.getConnectionTestStatement()) && Objects.equal(this.idleConnectionTestPeriodInSeconds, that.getIdleConnectionTestPeriod(TimeUnit.SECONDS)) && Objects.equal(this.idleMaxAgeInSeconds, that.getIdleMaxAge(TimeUnit.SECONDS)) && Objects.equal(this.initSQL, that.getInitSQL()) && Objects.equal(this.jdbcUrl, that.getJdbcUrl()) && Objects.equal(this.maxConnectionsPerPartition, that.getMaxConnectionsPerPartition()) && Objects.equal(this.minConnectionsPerPartition, that.getMinConnectionsPerPartition()) && Objects.equal(this.partitionCount, that.getPartitionCount()) && Objects.equal(this.releaseHelperThreads, that.getReleaseHelperThreads()) && Objects.equal(this.statementsCacheSize, that.getStatementsCacheSize()) && Objects.equal(this.username, that.getUsername()) && Objects.equal(this.password, that.getPassword()) && Objects.equal(this.lazyInit, that.isLazyInit()) && Objects.equal(this.transactionRecoveryEnabled, that.isTransactionRecoveryEnabled()) && Objects.equal(this.acquireRetryAttempts, that.getAcquireRetryAttempts()) && Objects.equal(this.statementReleaseHelperThreads, that.getStatementReleaseHelperThreads()) && Objects.equal(this.closeConnectionWatchTimeoutInMs, that.getCloseConnectionWatchTimeout()) && Objects.equal(this.connectionTimeoutInMs, that.getConnectionTimeoutInMs()) && Objects.equal(this.datasourceBean, that.getDatasourceBean()) && Objects.equal(this.getQueryExecuteTimeLimitInMs(), that.getQueryExecuteTimeLimitInMs()) && Objects.equal(this.poolAvailabilityThreshold, that.getPoolAvailabilityThreshold()) && Objects.equal(this.poolName, that.getPoolName()) && Objects.equal(this.disableConnectionTracking, that.isDisableConnectionTracking()) ){ return true; } return false; }
java
public boolean hasSameConfiguration(BoneCPConfig that){ if ( that != null && Objects.equal(this.acquireIncrement, that.getAcquireIncrement()) && Objects.equal(this.acquireRetryDelayInMs, that.getAcquireRetryDelayInMs()) && Objects.equal(this.closeConnectionWatch, that.isCloseConnectionWatch()) && Objects.equal(this.logStatementsEnabled, that.isLogStatementsEnabled()) && Objects.equal(this.connectionHook, that.getConnectionHook()) && Objects.equal(this.connectionTestStatement, that.getConnectionTestStatement()) && Objects.equal(this.idleConnectionTestPeriodInSeconds, that.getIdleConnectionTestPeriod(TimeUnit.SECONDS)) && Objects.equal(this.idleMaxAgeInSeconds, that.getIdleMaxAge(TimeUnit.SECONDS)) && Objects.equal(this.initSQL, that.getInitSQL()) && Objects.equal(this.jdbcUrl, that.getJdbcUrl()) && Objects.equal(this.maxConnectionsPerPartition, that.getMaxConnectionsPerPartition()) && Objects.equal(this.minConnectionsPerPartition, that.getMinConnectionsPerPartition()) && Objects.equal(this.partitionCount, that.getPartitionCount()) && Objects.equal(this.releaseHelperThreads, that.getReleaseHelperThreads()) && Objects.equal(this.statementsCacheSize, that.getStatementsCacheSize()) && Objects.equal(this.username, that.getUsername()) && Objects.equal(this.password, that.getPassword()) && Objects.equal(this.lazyInit, that.isLazyInit()) && Objects.equal(this.transactionRecoveryEnabled, that.isTransactionRecoveryEnabled()) && Objects.equal(this.acquireRetryAttempts, that.getAcquireRetryAttempts()) && Objects.equal(this.statementReleaseHelperThreads, that.getStatementReleaseHelperThreads()) && Objects.equal(this.closeConnectionWatchTimeoutInMs, that.getCloseConnectionWatchTimeout()) && Objects.equal(this.connectionTimeoutInMs, that.getConnectionTimeoutInMs()) && Objects.equal(this.datasourceBean, that.getDatasourceBean()) && Objects.equal(this.getQueryExecuteTimeLimitInMs(), that.getQueryExecuteTimeLimitInMs()) && Objects.equal(this.poolAvailabilityThreshold, that.getPoolAvailabilityThreshold()) && Objects.equal(this.poolName, that.getPoolName()) && Objects.equal(this.disableConnectionTracking, that.isDisableConnectionTracking()) ){ return true; } return false; }
[ "public", "boolean", "hasSameConfiguration", "(", "BoneCPConfig", "that", ")", "{", "if", "(", "that", "!=", "null", "&&", "Objects", ".", "equal", "(", "this", ".", "acquireIncrement", ",", "that", ".", "getAcquireIncrement", "(", ")", ")", "&&", "Objects", ".", "equal", "(", "this", ".", "acquireRetryDelayInMs", ",", "that", ".", "getAcquireRetryDelayInMs", "(", ")", ")", "&&", "Objects", ".", "equal", "(", "this", ".", "closeConnectionWatch", ",", "that", ".", "isCloseConnectionWatch", "(", ")", ")", "&&", "Objects", ".", "equal", "(", "this", ".", "logStatementsEnabled", ",", "that", ".", "isLogStatementsEnabled", "(", ")", ")", "&&", "Objects", ".", "equal", "(", "this", ".", "connectionHook", ",", "that", ".", "getConnectionHook", "(", ")", ")", "&&", "Objects", ".", "equal", "(", "this", ".", "connectionTestStatement", ",", "that", ".", "getConnectionTestStatement", "(", ")", ")", "&&", "Objects", ".", "equal", "(", "this", ".", "idleConnectionTestPeriodInSeconds", ",", "that", ".", "getIdleConnectionTestPeriod", "(", "TimeUnit", ".", "SECONDS", ")", ")", "&&", "Objects", ".", "equal", "(", "this", ".", "idleMaxAgeInSeconds", ",", "that", ".", "getIdleMaxAge", "(", "TimeUnit", ".", "SECONDS", ")", ")", "&&", "Objects", ".", "equal", "(", "this", ".", "initSQL", ",", "that", ".", "getInitSQL", "(", ")", ")", "&&", "Objects", ".", "equal", "(", "this", ".", "jdbcUrl", ",", "that", ".", "getJdbcUrl", "(", ")", ")", "&&", "Objects", ".", "equal", "(", "this", ".", "maxConnectionsPerPartition", ",", "that", ".", "getMaxConnectionsPerPartition", "(", ")", ")", "&&", "Objects", ".", "equal", "(", "this", ".", "minConnectionsPerPartition", ",", "that", ".", "getMinConnectionsPerPartition", "(", ")", ")", "&&", "Objects", ".", "equal", "(", "this", ".", "partitionCount", ",", "that", ".", "getPartitionCount", "(", ")", ")", "&&", "Objects", ".", "equal", "(", "this", ".", "releaseHelperThreads", ",", "that", ".", "getReleaseHelperThreads", "(", ")", ")", "&&", "Objects", ".", "equal", "(", "this", ".", "statementsCacheSize", ",", "that", ".", "getStatementsCacheSize", "(", ")", ")", "&&", "Objects", ".", "equal", "(", "this", ".", "username", ",", "that", ".", "getUsername", "(", ")", ")", "&&", "Objects", ".", "equal", "(", "this", ".", "password", ",", "that", ".", "getPassword", "(", ")", ")", "&&", "Objects", ".", "equal", "(", "this", ".", "lazyInit", ",", "that", ".", "isLazyInit", "(", ")", ")", "&&", "Objects", ".", "equal", "(", "this", ".", "transactionRecoveryEnabled", ",", "that", ".", "isTransactionRecoveryEnabled", "(", ")", ")", "&&", "Objects", ".", "equal", "(", "this", ".", "acquireRetryAttempts", ",", "that", ".", "getAcquireRetryAttempts", "(", ")", ")", "&&", "Objects", ".", "equal", "(", "this", ".", "statementReleaseHelperThreads", ",", "that", ".", "getStatementReleaseHelperThreads", "(", ")", ")", "&&", "Objects", ".", "equal", "(", "this", ".", "closeConnectionWatchTimeoutInMs", ",", "that", ".", "getCloseConnectionWatchTimeout", "(", ")", ")", "&&", "Objects", ".", "equal", "(", "this", ".", "connectionTimeoutInMs", ",", "that", ".", "getConnectionTimeoutInMs", "(", ")", ")", "&&", "Objects", ".", "equal", "(", "this", ".", "datasourceBean", ",", "that", ".", "getDatasourceBean", "(", ")", ")", "&&", "Objects", ".", "equal", "(", "this", ".", "getQueryExecuteTimeLimitInMs", "(", ")", ",", "that", ".", "getQueryExecuteTimeLimitInMs", "(", ")", ")", "&&", "Objects", ".", "equal", "(", "this", ".", "poolAvailabilityThreshold", ",", "that", ".", "getPoolAvailabilityThreshold", "(", ")", ")", "&&", "Objects", ".", "equal", "(", "this", ".", "poolName", ",", "that", ".", "getPoolName", "(", ")", ")", "&&", "Objects", ".", "equal", "(", "this", ".", "disableConnectionTracking", ",", "that", ".", "isDisableConnectionTracking", "(", ")", ")", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}" ]
Returns true if this instance has the same config as a given config. @param that @return true if the instance has the same config, false otherwise.
[ "Returns", "true", "if", "this", "instance", "has", "the", "same", "config", "as", "a", "given", "config", "." ]
74bc3287025fc137ca28909f0f7693edae37a15d
https://github.com/wwadge/bonecp/blob/74bc3287025fc137ca28909f0f7693edae37a15d/bonecp/src/main/java/com/jolbox/bonecp/BoneCPConfig.java#L1797-L1832
163,159
wwadge/bonecp
bonecp/src/main/java/com/jolbox/bonecp/AbstractConnectionStrategy.java
AbstractConnectionStrategy.preConnection
protected long preConnection() throws SQLException{ long statsObtainTime = 0; if (this.pool.poolShuttingDown){ throw new SQLException(this.pool.shutdownStackTrace); } if (this.pool.statisticsEnabled){ statsObtainTime = System.nanoTime(); this.pool.statistics.incrementConnectionsRequested(); } return statsObtainTime; }
java
protected long preConnection() throws SQLException{ long statsObtainTime = 0; if (this.pool.poolShuttingDown){ throw new SQLException(this.pool.shutdownStackTrace); } if (this.pool.statisticsEnabled){ statsObtainTime = System.nanoTime(); this.pool.statistics.incrementConnectionsRequested(); } return statsObtainTime; }
[ "protected", "long", "preConnection", "(", ")", "throws", "SQLException", "{", "long", "statsObtainTime", "=", "0", ";", "if", "(", "this", ".", "pool", ".", "poolShuttingDown", ")", "{", "throw", "new", "SQLException", "(", "this", ".", "pool", ".", "shutdownStackTrace", ")", ";", "}", "if", "(", "this", ".", "pool", ".", "statisticsEnabled", ")", "{", "statsObtainTime", "=", "System", ".", "nanoTime", "(", ")", ";", "this", ".", "pool", ".", "statistics", ".", "incrementConnectionsRequested", "(", ")", ";", "}", "return", "statsObtainTime", ";", "}" ]
Prep for a new connection @return if stats are enabled, return the nanoTime when this connection was requested. @throws SQLException
[ "Prep", "for", "a", "new", "connection" ]
74bc3287025fc137ca28909f0f7693edae37a15d
https://github.com/wwadge/bonecp/blob/74bc3287025fc137ca28909f0f7693edae37a15d/bonecp/src/main/java/com/jolbox/bonecp/AbstractConnectionStrategy.java#L48-L62
163,160
wwadge/bonecp
bonecp/src/main/java/com/jolbox/bonecp/AbstractConnectionStrategy.java
AbstractConnectionStrategy.postConnection
protected void postConnection(ConnectionHandle handle, long statsObtainTime){ handle.renewConnection(); // mark it as being logically "open" // Give an application a chance to do something with it. if (handle.getConnectionHook() != null){ handle.getConnectionHook().onCheckOut(handle); } if (this.pool.closeConnectionWatch){ // a debugging tool this.pool.watchConnection(handle); } if (this.pool.statisticsEnabled){ this.pool.statistics.addCumulativeConnectionWaitTime(System.nanoTime()-statsObtainTime); } }
java
protected void postConnection(ConnectionHandle handle, long statsObtainTime){ handle.renewConnection(); // mark it as being logically "open" // Give an application a chance to do something with it. if (handle.getConnectionHook() != null){ handle.getConnectionHook().onCheckOut(handle); } if (this.pool.closeConnectionWatch){ // a debugging tool this.pool.watchConnection(handle); } if (this.pool.statisticsEnabled){ this.pool.statistics.addCumulativeConnectionWaitTime(System.nanoTime()-statsObtainTime); } }
[ "protected", "void", "postConnection", "(", "ConnectionHandle", "handle", ",", "long", "statsObtainTime", ")", "{", "handle", ".", "renewConnection", "(", ")", ";", "// mark it as being logically \"open\"\r", "// Give an application a chance to do something with it.\r", "if", "(", "handle", ".", "getConnectionHook", "(", ")", "!=", "null", ")", "{", "handle", ".", "getConnectionHook", "(", ")", ".", "onCheckOut", "(", "handle", ")", ";", "}", "if", "(", "this", ".", "pool", ".", "closeConnectionWatch", ")", "{", "// a debugging tool\r", "this", ".", "pool", ".", "watchConnection", "(", "handle", ")", ";", "}", "if", "(", "this", ".", "pool", ".", "statisticsEnabled", ")", "{", "this", ".", "pool", ".", "statistics", ".", "addCumulativeConnectionWaitTime", "(", "System", ".", "nanoTime", "(", ")", "-", "statsObtainTime", ")", ";", "}", "}" ]
After obtaining a connection, perform additional tasks. @param handle @param statsObtainTime
[ "After", "obtaining", "a", "connection", "perform", "additional", "tasks", "." ]
74bc3287025fc137ca28909f0f7693edae37a15d
https://github.com/wwadge/bonecp/blob/74bc3287025fc137ca28909f0f7693edae37a15d/bonecp/src/main/java/com/jolbox/bonecp/AbstractConnectionStrategy.java#L69-L85
163,161
wwadge/bonecp
bonecp/src/main/java/com/jolbox/bonecp/BoneCPDataSource.java
BoneCPDataSource.getPool
public BoneCP getPool() { FinalWrapper<BoneCP> wrapper = this.pool; return wrapper == null ? null : wrapper.value; }
java
public BoneCP getPool() { FinalWrapper<BoneCP> wrapper = this.pool; return wrapper == null ? null : wrapper.value; }
[ "public", "BoneCP", "getPool", "(", ")", "{", "FinalWrapper", "<", "BoneCP", ">", "wrapper", "=", "this", ".", "pool", ";", "return", "wrapper", "==", "null", "?", "null", ":", "wrapper", ".", "value", ";", "}" ]
Returns a handle to the pool. Useful to obtain a handle to the statistics for example. @return pool
[ "Returns", "a", "handle", "to", "the", "pool", ".", "Useful", "to", "obtain", "a", "handle", "to", "the", "statistics", "for", "example", "." ]
74bc3287025fc137ca28909f0f7693edae37a15d
https://github.com/wwadge/bonecp/blob/74bc3287025fc137ca28909f0f7693edae37a15d/bonecp/src/main/java/com/jolbox/bonecp/BoneCPDataSource.java#L297-L300
163,162
wwadge/bonecp
bonecp-hbnprovider/src/main/java/com/jolbox/bonecp/provider/BoneCPConnectionProvider.java
BoneCPConnectionProvider.configure
public void configure(Properties props) throws HibernateException { try{ this.config = new BoneCPConfig(props); // old hibernate config String url = props.getProperty(CONFIG_CONNECTION_URL); String username = props.getProperty(CONFIG_CONNECTION_USERNAME); String password = props.getProperty(CONFIG_CONNECTION_PASSWORD); String driver = props.getProperty(CONFIG_CONNECTION_DRIVER_CLASS); if (url == null){ url = props.getProperty(CONFIG_CONNECTION_URL_ALTERNATE); } if (username == null){ username = props.getProperty(CONFIG_CONNECTION_USERNAME_ALTERNATE); } if (password == null){ password = props.getProperty(CONFIG_CONNECTION_PASSWORD_ALTERNATE); } if (driver == null){ driver = props.getProperty(CONFIG_CONNECTION_DRIVER_CLASS_ALTERNATE); } if (url != null){ this.config.setJdbcUrl(url); } if (username != null){ this.config.setUsername(username); } if (password != null){ this.config.setPassword(password); } // Remember Isolation level this.isolation = ConfigurationHelper.getInteger(AvailableSettings.ISOLATION, props); this.autocommit = ConfigurationHelper.getBoolean(AvailableSettings.AUTOCOMMIT, props); logger.debug(this.config.toString()); if (driver != null && !driver.trim().equals("")){ loadClass(driver); } if (this.config.getConnectionHookClassName() != null){ Object hookClass = loadClass(this.config.getConnectionHookClassName()).newInstance(); this.config.setConnectionHook((ConnectionHook) hookClass); } // create the connection pool this.pool = createPool(this.config); } catch (Exception e) { throw new HibernateException(e); } }
java
public void configure(Properties props) throws HibernateException { try{ this.config = new BoneCPConfig(props); // old hibernate config String url = props.getProperty(CONFIG_CONNECTION_URL); String username = props.getProperty(CONFIG_CONNECTION_USERNAME); String password = props.getProperty(CONFIG_CONNECTION_PASSWORD); String driver = props.getProperty(CONFIG_CONNECTION_DRIVER_CLASS); if (url == null){ url = props.getProperty(CONFIG_CONNECTION_URL_ALTERNATE); } if (username == null){ username = props.getProperty(CONFIG_CONNECTION_USERNAME_ALTERNATE); } if (password == null){ password = props.getProperty(CONFIG_CONNECTION_PASSWORD_ALTERNATE); } if (driver == null){ driver = props.getProperty(CONFIG_CONNECTION_DRIVER_CLASS_ALTERNATE); } if (url != null){ this.config.setJdbcUrl(url); } if (username != null){ this.config.setUsername(username); } if (password != null){ this.config.setPassword(password); } // Remember Isolation level this.isolation = ConfigurationHelper.getInteger(AvailableSettings.ISOLATION, props); this.autocommit = ConfigurationHelper.getBoolean(AvailableSettings.AUTOCOMMIT, props); logger.debug(this.config.toString()); if (driver != null && !driver.trim().equals("")){ loadClass(driver); } if (this.config.getConnectionHookClassName() != null){ Object hookClass = loadClass(this.config.getConnectionHookClassName()).newInstance(); this.config.setConnectionHook((ConnectionHook) hookClass); } // create the connection pool this.pool = createPool(this.config); } catch (Exception e) { throw new HibernateException(e); } }
[ "public", "void", "configure", "(", "Properties", "props", ")", "throws", "HibernateException", "{", "try", "{", "this", ".", "config", "=", "new", "BoneCPConfig", "(", "props", ")", ";", "// old hibernate config\r", "String", "url", "=", "props", ".", "getProperty", "(", "CONFIG_CONNECTION_URL", ")", ";", "String", "username", "=", "props", ".", "getProperty", "(", "CONFIG_CONNECTION_USERNAME", ")", ";", "String", "password", "=", "props", ".", "getProperty", "(", "CONFIG_CONNECTION_PASSWORD", ")", ";", "String", "driver", "=", "props", ".", "getProperty", "(", "CONFIG_CONNECTION_DRIVER_CLASS", ")", ";", "if", "(", "url", "==", "null", ")", "{", "url", "=", "props", ".", "getProperty", "(", "CONFIG_CONNECTION_URL_ALTERNATE", ")", ";", "}", "if", "(", "username", "==", "null", ")", "{", "username", "=", "props", ".", "getProperty", "(", "CONFIG_CONNECTION_USERNAME_ALTERNATE", ")", ";", "}", "if", "(", "password", "==", "null", ")", "{", "password", "=", "props", ".", "getProperty", "(", "CONFIG_CONNECTION_PASSWORD_ALTERNATE", ")", ";", "}", "if", "(", "driver", "==", "null", ")", "{", "driver", "=", "props", ".", "getProperty", "(", "CONFIG_CONNECTION_DRIVER_CLASS_ALTERNATE", ")", ";", "}", "if", "(", "url", "!=", "null", ")", "{", "this", ".", "config", ".", "setJdbcUrl", "(", "url", ")", ";", "}", "if", "(", "username", "!=", "null", ")", "{", "this", ".", "config", ".", "setUsername", "(", "username", ")", ";", "}", "if", "(", "password", "!=", "null", ")", "{", "this", ".", "config", ".", "setPassword", "(", "password", ")", ";", "}", "// Remember Isolation level\r", "this", ".", "isolation", "=", "ConfigurationHelper", ".", "getInteger", "(", "AvailableSettings", ".", "ISOLATION", ",", "props", ")", ";", "this", ".", "autocommit", "=", "ConfigurationHelper", ".", "getBoolean", "(", "AvailableSettings", ".", "AUTOCOMMIT", ",", "props", ")", ";", "logger", ".", "debug", "(", "this", ".", "config", ".", "toString", "(", ")", ")", ";", "if", "(", "driver", "!=", "null", "&&", "!", "driver", ".", "trim", "(", ")", ".", "equals", "(", "\"\"", ")", ")", "{", "loadClass", "(", "driver", ")", ";", "}", "if", "(", "this", ".", "config", ".", "getConnectionHookClassName", "(", ")", "!=", "null", ")", "{", "Object", "hookClass", "=", "loadClass", "(", "this", ".", "config", ".", "getConnectionHookClassName", "(", ")", ")", ".", "newInstance", "(", ")", ";", "this", ".", "config", ".", "setConnectionHook", "(", "(", "ConnectionHook", ")", "hookClass", ")", ";", "}", "// create the connection pool\r", "this", ".", "pool", "=", "createPool", "(", "this", ".", "config", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "HibernateException", "(", "e", ")", ";", "}", "}" ]
Pool configuration. @param props @throws HibernateException
[ "Pool", "configuration", "." ]
74bc3287025fc137ca28909f0f7693edae37a15d
https://github.com/wwadge/bonecp/blob/74bc3287025fc137ca28909f0f7693edae37a15d/bonecp-hbnprovider/src/main/java/com/jolbox/bonecp/provider/BoneCPConnectionProvider.java#L94-L145
163,163
wwadge/bonecp
bonecp-hbnprovider/src/main/java/com/jolbox/bonecp/provider/BoneCPConnectionProvider.java
BoneCPConnectionProvider.createPool
protected BoneCP createPool(BoneCPConfig config) { try{ return new BoneCP(config); } catch (SQLException e) { throw new HibernateException(e); } }
java
protected BoneCP createPool(BoneCPConfig config) { try{ return new BoneCP(config); } catch (SQLException e) { throw new HibernateException(e); } }
[ "protected", "BoneCP", "createPool", "(", "BoneCPConfig", "config", ")", "{", "try", "{", "return", "new", "BoneCP", "(", "config", ")", ";", "}", "catch", "(", "SQLException", "e", ")", "{", "throw", "new", "HibernateException", "(", "e", ")", ";", "}", "}" ]
Creates the given connection pool with the given configuration. Extracted here to make unit mocking easier. @param config configuration object. @return BoneCP connection pool handle.
[ "Creates", "the", "given", "connection", "pool", "with", "the", "given", "configuration", ".", "Extracted", "here", "to", "make", "unit", "mocking", "easier", "." ]
74bc3287025fc137ca28909f0f7693edae37a15d
https://github.com/wwadge/bonecp/blob/74bc3287025fc137ca28909f0f7693edae37a15d/bonecp-hbnprovider/src/main/java/com/jolbox/bonecp/provider/BoneCPConnectionProvider.java#L165-L171
163,164
wwadge/bonecp
bonecp-hbnprovider/src/main/java/com/jolbox/bonecp/provider/BoneCPConnectionProvider.java
BoneCPConnectionProvider.mapToProperties
private Properties mapToProperties(Map<String, String> map) { Properties p = new Properties(); for (Map.Entry<String,String> entry : map.entrySet()) { p.put(entry.getKey(), entry.getValue()); } return p; }
java
private Properties mapToProperties(Map<String, String> map) { Properties p = new Properties(); for (Map.Entry<String,String> entry : map.entrySet()) { p.put(entry.getKey(), entry.getValue()); } return p; }
[ "private", "Properties", "mapToProperties", "(", "Map", "<", "String", ",", "String", ">", "map", ")", "{", "Properties", "p", "=", "new", "Properties", "(", ")", ";", "for", "(", "Map", ".", "Entry", "<", "String", ",", "String", ">", "entry", ":", "map", ".", "entrySet", "(", ")", ")", "{", "p", ".", "put", "(", "entry", ".", "getKey", "(", ")", ",", "entry", ".", "getValue", "(", ")", ")", ";", "}", "return", "p", ";", "}" ]
Legacy conversion. @param map @return Properties
[ "Legacy", "conversion", "." ]
74bc3287025fc137ca28909f0f7693edae37a15d
https://github.com/wwadge/bonecp/blob/74bc3287025fc137ca28909f0f7693edae37a15d/bonecp-hbnprovider/src/main/java/com/jolbox/bonecp/provider/BoneCPConnectionProvider.java#L260-L266
163,165
wwadge/bonecp
bonecp/src/main/java/com/jolbox/bonecp/CachedConnectionStrategy.java
CachedConnectionStrategy.stealExistingAllocations
protected synchronized void stealExistingAllocations(){ for (ConnectionHandle handle: this.threadFinalizableRefs.keySet()){ // if they're not in use, pretend they are in use now and close them off. // this method assumes that the strategy has been flipped back to non-caching mode // prior to this method invocation. if (handle.logicallyClosed.compareAndSet(true, false)){ try { this.pool.releaseConnection(handle); } catch (SQLException e) { logger.error("Error releasing connection", e); } } } if (this.warnApp.compareAndSet(false, true)){ // only issue warning once. logger.warn("Cached strategy chosen, but more threads are requesting a connection than are configured. Switching permanently to default strategy."); } this.threadFinalizableRefs.clear(); }
java
protected synchronized void stealExistingAllocations(){ for (ConnectionHandle handle: this.threadFinalizableRefs.keySet()){ // if they're not in use, pretend they are in use now and close them off. // this method assumes that the strategy has been flipped back to non-caching mode // prior to this method invocation. if (handle.logicallyClosed.compareAndSet(true, false)){ try { this.pool.releaseConnection(handle); } catch (SQLException e) { logger.error("Error releasing connection", e); } } } if (this.warnApp.compareAndSet(false, true)){ // only issue warning once. logger.warn("Cached strategy chosen, but more threads are requesting a connection than are configured. Switching permanently to default strategy."); } this.threadFinalizableRefs.clear(); }
[ "protected", "synchronized", "void", "stealExistingAllocations", "(", ")", "{", "for", "(", "ConnectionHandle", "handle", ":", "this", ".", "threadFinalizableRefs", ".", "keySet", "(", ")", ")", "{", "// if they're not in use, pretend they are in use now and close them off.\r", "// this method assumes that the strategy has been flipped back to non-caching mode\r", "// prior to this method invocation.\r", "if", "(", "handle", ".", "logicallyClosed", ".", "compareAndSet", "(", "true", ",", "false", ")", ")", "{", "try", "{", "this", ".", "pool", ".", "releaseConnection", "(", "handle", ")", ";", "}", "catch", "(", "SQLException", "e", ")", "{", "logger", ".", "error", "(", "\"Error releasing connection\"", ",", "e", ")", ";", "}", "}", "}", "if", "(", "this", ".", "warnApp", ".", "compareAndSet", "(", "false", ",", "true", ")", ")", "{", "// only issue warning once.\r", "logger", ".", "warn", "(", "\"Cached strategy chosen, but more threads are requesting a connection than are configured. Switching permanently to default strategy.\"", ")", ";", "}", "this", ".", "threadFinalizableRefs", ".", "clear", "(", ")", ";", "}" ]
Tries to close off all the unused assigned connections back to the pool. Assumes that the strategy mode has already been flipped prior to calling this routine. Called whenever our no of connection requests > no of threads.
[ "Tries", "to", "close", "off", "all", "the", "unused", "assigned", "connections", "back", "to", "the", "pool", ".", "Assumes", "that", "the", "strategy", "mode", "has", "already", "been", "flipped", "prior", "to", "calling", "this", "routine", ".", "Called", "whenever", "our", "no", "of", "connection", "requests", ">", "no", "of", "threads", "." ]
74bc3287025fc137ca28909f0f7693edae37a15d
https://github.com/wwadge/bonecp/blob/74bc3287025fc137ca28909f0f7693edae37a15d/bonecp/src/main/java/com/jolbox/bonecp/CachedConnectionStrategy.java#L84-L103
163,166
wwadge/bonecp
bonecp/src/main/java/com/jolbox/bonecp/CachedConnectionStrategy.java
CachedConnectionStrategy.threadWatch
protected void threadWatch(final ConnectionHandle c) { this.threadFinalizableRefs.put(c, new FinalizableWeakReference<Thread>(Thread.currentThread(), this.finalizableRefQueue) { public void finalizeReferent() { try { if (!CachedConnectionStrategy.this.pool.poolShuttingDown){ logger.debug("Monitored thread is dead, closing off allocated connection."); } c.internalClose(); } catch (SQLException e) { e.printStackTrace(); } CachedConnectionStrategy.this.threadFinalizableRefs.remove(c); } }); }
java
protected void threadWatch(final ConnectionHandle c) { this.threadFinalizableRefs.put(c, new FinalizableWeakReference<Thread>(Thread.currentThread(), this.finalizableRefQueue) { public void finalizeReferent() { try { if (!CachedConnectionStrategy.this.pool.poolShuttingDown){ logger.debug("Monitored thread is dead, closing off allocated connection."); } c.internalClose(); } catch (SQLException e) { e.printStackTrace(); } CachedConnectionStrategy.this.threadFinalizableRefs.remove(c); } }); }
[ "protected", "void", "threadWatch", "(", "final", "ConnectionHandle", "c", ")", "{", "this", ".", "threadFinalizableRefs", ".", "put", "(", "c", ",", "new", "FinalizableWeakReference", "<", "Thread", ">", "(", "Thread", ".", "currentThread", "(", ")", ",", "this", ".", "finalizableRefQueue", ")", "{", "public", "void", "finalizeReferent", "(", ")", "{", "try", "{", "if", "(", "!", "CachedConnectionStrategy", ".", "this", ".", "pool", ".", "poolShuttingDown", ")", "{", "logger", ".", "debug", "(", "\"Monitored thread is dead, closing off allocated connection.\"", ")", ";", "}", "c", ".", "internalClose", "(", ")", ";", "}", "catch", "(", "SQLException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "CachedConnectionStrategy", ".", "this", ".", "threadFinalizableRefs", ".", "remove", "(", "c", ")", ";", "}", "}", ")", ";", "}" ]
Keep track of this handle tied to which thread so that if the thread is terminated we can reclaim our connection handle. We also @param c connection handle to track.
[ "Keep", "track", "of", "this", "handle", "tied", "to", "which", "thread", "so", "that", "if", "the", "thread", "is", "terminated", "we", "can", "reclaim", "our", "connection", "handle", ".", "We", "also" ]
74bc3287025fc137ca28909f0f7693edae37a15d
https://github.com/wwadge/bonecp/blob/74bc3287025fc137ca28909f0f7693edae37a15d/bonecp/src/main/java/com/jolbox/bonecp/CachedConnectionStrategy.java#L109-L123
163,167
wwadge/bonecp
bonecp/src/main/java/com/jolbox/bonecp/BoneCP.java
BoneCP.shutdown
public synchronized void shutdown(){ if (!this.poolShuttingDown){ logger.info("Shutting down connection pool..."); this.poolShuttingDown = true; this.shutdownStackTrace = captureStackTrace(SHUTDOWN_LOCATION_TRACE); this.keepAliveScheduler.shutdownNow(); // stop threads from firing. this.maxAliveScheduler.shutdownNow(); // stop threads from firing. this.connectionsScheduler.shutdownNow(); // stop threads from firing. this.asyncExecutor.shutdownNow(); try { this.connectionsScheduler.awaitTermination(5, TimeUnit.SECONDS); this.maxAliveScheduler.awaitTermination(5, TimeUnit.SECONDS); this.keepAliveScheduler.awaitTermination(5, TimeUnit.SECONDS); this.asyncExecutor.awaitTermination(5, TimeUnit.SECONDS); if (this.closeConnectionExecutor != null){ this.closeConnectionExecutor.shutdownNow(); this.closeConnectionExecutor.awaitTermination(5, TimeUnit.SECONDS); } } catch (InterruptedException e) { // do nothing } this.connectionStrategy.terminateAllConnections(); unregisterDriver(); registerUnregisterJMX(false); if (finalizableRefQueue != null) { finalizableRefQueue.close(); } logger.info("Connection pool has been shutdown."); } }
java
public synchronized void shutdown(){ if (!this.poolShuttingDown){ logger.info("Shutting down connection pool..."); this.poolShuttingDown = true; this.shutdownStackTrace = captureStackTrace(SHUTDOWN_LOCATION_TRACE); this.keepAliveScheduler.shutdownNow(); // stop threads from firing. this.maxAliveScheduler.shutdownNow(); // stop threads from firing. this.connectionsScheduler.shutdownNow(); // stop threads from firing. this.asyncExecutor.shutdownNow(); try { this.connectionsScheduler.awaitTermination(5, TimeUnit.SECONDS); this.maxAliveScheduler.awaitTermination(5, TimeUnit.SECONDS); this.keepAliveScheduler.awaitTermination(5, TimeUnit.SECONDS); this.asyncExecutor.awaitTermination(5, TimeUnit.SECONDS); if (this.closeConnectionExecutor != null){ this.closeConnectionExecutor.shutdownNow(); this.closeConnectionExecutor.awaitTermination(5, TimeUnit.SECONDS); } } catch (InterruptedException e) { // do nothing } this.connectionStrategy.terminateAllConnections(); unregisterDriver(); registerUnregisterJMX(false); if (finalizableRefQueue != null) { finalizableRefQueue.close(); } logger.info("Connection pool has been shutdown."); } }
[ "public", "synchronized", "void", "shutdown", "(", ")", "{", "if", "(", "!", "this", ".", "poolShuttingDown", ")", "{", "logger", ".", "info", "(", "\"Shutting down connection pool...\"", ")", ";", "this", ".", "poolShuttingDown", "=", "true", ";", "this", ".", "shutdownStackTrace", "=", "captureStackTrace", "(", "SHUTDOWN_LOCATION_TRACE", ")", ";", "this", ".", "keepAliveScheduler", ".", "shutdownNow", "(", ")", ";", "// stop threads from firing.\r", "this", ".", "maxAliveScheduler", ".", "shutdownNow", "(", ")", ";", "// stop threads from firing.\r", "this", ".", "connectionsScheduler", ".", "shutdownNow", "(", ")", ";", "// stop threads from firing.\r", "this", ".", "asyncExecutor", ".", "shutdownNow", "(", ")", ";", "try", "{", "this", ".", "connectionsScheduler", ".", "awaitTermination", "(", "5", ",", "TimeUnit", ".", "SECONDS", ")", ";", "this", ".", "maxAliveScheduler", ".", "awaitTermination", "(", "5", ",", "TimeUnit", ".", "SECONDS", ")", ";", "this", ".", "keepAliveScheduler", ".", "awaitTermination", "(", "5", ",", "TimeUnit", ".", "SECONDS", ")", ";", "this", ".", "asyncExecutor", ".", "awaitTermination", "(", "5", ",", "TimeUnit", ".", "SECONDS", ")", ";", "if", "(", "this", ".", "closeConnectionExecutor", "!=", "null", ")", "{", "this", ".", "closeConnectionExecutor", ".", "shutdownNow", "(", ")", ";", "this", ".", "closeConnectionExecutor", ".", "awaitTermination", "(", "5", ",", "TimeUnit", ".", "SECONDS", ")", ";", "}", "}", "catch", "(", "InterruptedException", "e", ")", "{", "// do nothing\r", "}", "this", ".", "connectionStrategy", ".", "terminateAllConnections", "(", ")", ";", "unregisterDriver", "(", ")", ";", "registerUnregisterJMX", "(", "false", ")", ";", "if", "(", "finalizableRefQueue", "!=", "null", ")", "{", "finalizableRefQueue", ".", "close", "(", ")", ";", "}", "logger", ".", "info", "(", "\"Connection pool has been shutdown.\"", ")", ";", "}", "}" ]
Closes off this connection pool.
[ "Closes", "off", "this", "connection", "pool", "." ]
74bc3287025fc137ca28909f0f7693edae37a15d
https://github.com/wwadge/bonecp/blob/74bc3287025fc137ca28909f0f7693edae37a15d/bonecp/src/main/java/com/jolbox/bonecp/BoneCP.java#L155-L189
163,168
wwadge/bonecp
bonecp/src/main/java/com/jolbox/bonecp/BoneCP.java
BoneCP.unregisterDriver
protected void unregisterDriver(){ String jdbcURL = this.config.getJdbcUrl(); if ((jdbcURL != null) && this.config.isDeregisterDriverOnClose()){ logger.info("Unregistering JDBC driver for : "+jdbcURL); try { DriverManager.deregisterDriver(DriverManager.getDriver(jdbcURL)); } catch (SQLException e) { logger.info("Unregistering driver failed.", e); } } }
java
protected void unregisterDriver(){ String jdbcURL = this.config.getJdbcUrl(); if ((jdbcURL != null) && this.config.isDeregisterDriverOnClose()){ logger.info("Unregistering JDBC driver for : "+jdbcURL); try { DriverManager.deregisterDriver(DriverManager.getDriver(jdbcURL)); } catch (SQLException e) { logger.info("Unregistering driver failed.", e); } } }
[ "protected", "void", "unregisterDriver", "(", ")", "{", "String", "jdbcURL", "=", "this", ".", "config", ".", "getJdbcUrl", "(", ")", ";", "if", "(", "(", "jdbcURL", "!=", "null", ")", "&&", "this", ".", "config", ".", "isDeregisterDriverOnClose", "(", ")", ")", "{", "logger", ".", "info", "(", "\"Unregistering JDBC driver for : \"", "+", "jdbcURL", ")", ";", "try", "{", "DriverManager", ".", "deregisterDriver", "(", "DriverManager", ".", "getDriver", "(", "jdbcURL", ")", ")", ";", "}", "catch", "(", "SQLException", "e", ")", "{", "logger", ".", "info", "(", "\"Unregistering driver failed.\"", ",", "e", ")", ";", "}", "}", "}" ]
Drops a driver from the DriverManager's list.
[ "Drops", "a", "driver", "from", "the", "DriverManager", "s", "list", "." ]
74bc3287025fc137ca28909f0f7693edae37a15d
https://github.com/wwadge/bonecp/blob/74bc3287025fc137ca28909f0f7693edae37a15d/bonecp/src/main/java/com/jolbox/bonecp/BoneCP.java#L192-L202
163,169
wwadge/bonecp
bonecp/src/main/java/com/jolbox/bonecp/BoneCP.java
BoneCP.destroyConnection
protected void destroyConnection(ConnectionHandle conn) { postDestroyConnection(conn); conn.setInReplayMode(true); // we're dead, stop attempting to replay anything try { conn.internalClose(); } catch (SQLException e) { logger.error("Error in attempting to close connection", e); } }
java
protected void destroyConnection(ConnectionHandle conn) { postDestroyConnection(conn); conn.setInReplayMode(true); // we're dead, stop attempting to replay anything try { conn.internalClose(); } catch (SQLException e) { logger.error("Error in attempting to close connection", e); } }
[ "protected", "void", "destroyConnection", "(", "ConnectionHandle", "conn", ")", "{", "postDestroyConnection", "(", "conn", ")", ";", "conn", ".", "setInReplayMode", "(", "true", ")", ";", "// we're dead, stop attempting to replay anything\r", "try", "{", "conn", ".", "internalClose", "(", ")", ";", "}", "catch", "(", "SQLException", "e", ")", "{", "logger", ".", "error", "(", "\"Error in attempting to close connection\"", ",", "e", ")", ";", "}", "}" ]
Physically close off the internal connection. @param conn
[ "Physically", "close", "off", "the", "internal", "connection", "." ]
74bc3287025fc137ca28909f0f7693edae37a15d
https://github.com/wwadge/bonecp/blob/74bc3287025fc137ca28909f0f7693edae37a15d/bonecp/src/main/java/com/jolbox/bonecp/BoneCP.java#L214-L222
163,170
wwadge/bonecp
bonecp/src/main/java/com/jolbox/bonecp/BoneCP.java
BoneCP.postDestroyConnection
protected void postDestroyConnection(ConnectionHandle handle){ ConnectionPartition partition = handle.getOriginatingPartition(); if (this.finalizableRefQueue != null && handle.getInternalConnection() != null){ //safety this.finalizableRefs.remove(handle.getInternalConnection()); // assert o != null : "Did not manage to remove connection from finalizable ref queue"; } partition.updateCreatedConnections(-1); partition.setUnableToCreateMoreTransactions(false); // we can create new ones now, this is an optimization // "Destroying" for us means: don't put it back in the pool. if (handle.getConnectionHook() != null){ handle.getConnectionHook().onDestroy(handle); } }
java
protected void postDestroyConnection(ConnectionHandle handle){ ConnectionPartition partition = handle.getOriginatingPartition(); if (this.finalizableRefQueue != null && handle.getInternalConnection() != null){ //safety this.finalizableRefs.remove(handle.getInternalConnection()); // assert o != null : "Did not manage to remove connection from finalizable ref queue"; } partition.updateCreatedConnections(-1); partition.setUnableToCreateMoreTransactions(false); // we can create new ones now, this is an optimization // "Destroying" for us means: don't put it back in the pool. if (handle.getConnectionHook() != null){ handle.getConnectionHook().onDestroy(handle); } }
[ "protected", "void", "postDestroyConnection", "(", "ConnectionHandle", "handle", ")", "{", "ConnectionPartition", "partition", "=", "handle", ".", "getOriginatingPartition", "(", ")", ";", "if", "(", "this", ".", "finalizableRefQueue", "!=", "null", "&&", "handle", ".", "getInternalConnection", "(", ")", "!=", "null", ")", "{", "//safety\r", "this", ".", "finalizableRefs", ".", "remove", "(", "handle", ".", "getInternalConnection", "(", ")", ")", ";", "//\t\t\tassert o != null : \"Did not manage to remove connection from finalizable ref queue\";\r", "}", "partition", ".", "updateCreatedConnections", "(", "-", "1", ")", ";", "partition", ".", "setUnableToCreateMoreTransactions", "(", "false", ")", ";", "// we can create new ones now, this is an optimization\r", "// \"Destroying\" for us means: don't put it back in the pool.\r", "if", "(", "handle", ".", "getConnectionHook", "(", ")", "!=", "null", ")", "{", "handle", ".", "getConnectionHook", "(", ")", ".", "onDestroy", "(", "handle", ")", ";", "}", "}" ]
Update counters and call hooks. @param handle connection handle.
[ "Update", "counters", "and", "call", "hooks", "." ]
74bc3287025fc137ca28909f0f7693edae37a15d
https://github.com/wwadge/bonecp/blob/74bc3287025fc137ca28909f0f7693edae37a15d/bonecp/src/main/java/com/jolbox/bonecp/BoneCP.java#L227-L244
163,171
wwadge/bonecp
bonecp/src/main/java/com/jolbox/bonecp/BoneCP.java
BoneCP.obtainInternalConnection
protected Connection obtainInternalConnection(ConnectionHandle connectionHandle) throws SQLException { boolean tryAgain = false; Connection result = null; Connection oldRawConnection = connectionHandle.getInternalConnection(); String url = this.getConfig().getJdbcUrl(); int acquireRetryAttempts = this.getConfig().getAcquireRetryAttempts(); long acquireRetryDelayInMs = this.getConfig().getAcquireRetryDelayInMs(); AcquireFailConfig acquireConfig = new AcquireFailConfig(); acquireConfig.setAcquireRetryAttempts(new AtomicInteger(acquireRetryAttempts)); acquireConfig.setAcquireRetryDelayInMs(acquireRetryDelayInMs); acquireConfig.setLogMessage("Failed to acquire connection to "+url); ConnectionHook connectionHook = this.getConfig().getConnectionHook(); do{ result = null; try { // keep track of this hook. result = this.obtainRawInternalConnection(); tryAgain = false; if (acquireRetryAttempts != this.getConfig().getAcquireRetryAttempts()){ logger.info("Successfully re-established connection to "+url); } this.getDbIsDown().set(false); connectionHandle.setInternalConnection(result); // call the hook, if available. if (connectionHook != null){ connectionHook.onAcquire(connectionHandle); } ConnectionHandle.sendInitSQL(result, this.getConfig().getInitSQL()); } catch (SQLException e) { // call the hook, if available. if (connectionHook != null){ tryAgain = connectionHook.onAcquireFail(e, acquireConfig); } else { logger.error(String.format("Failed to acquire connection to %s. Sleeping for %d ms. Attempts left: %d", url, acquireRetryDelayInMs, acquireRetryAttempts), e); try { if (acquireRetryAttempts > 0){ Thread.sleep(acquireRetryDelayInMs); } tryAgain = (acquireRetryAttempts--) > 0; } catch (InterruptedException e1) { tryAgain=false; } } if (!tryAgain){ if (oldRawConnection != null) { oldRawConnection.close(); } if (result != null) { result.close(); } connectionHandle.setInternalConnection(oldRawConnection); throw e; } } } while (tryAgain); return result; }
java
protected Connection obtainInternalConnection(ConnectionHandle connectionHandle) throws SQLException { boolean tryAgain = false; Connection result = null; Connection oldRawConnection = connectionHandle.getInternalConnection(); String url = this.getConfig().getJdbcUrl(); int acquireRetryAttempts = this.getConfig().getAcquireRetryAttempts(); long acquireRetryDelayInMs = this.getConfig().getAcquireRetryDelayInMs(); AcquireFailConfig acquireConfig = new AcquireFailConfig(); acquireConfig.setAcquireRetryAttempts(new AtomicInteger(acquireRetryAttempts)); acquireConfig.setAcquireRetryDelayInMs(acquireRetryDelayInMs); acquireConfig.setLogMessage("Failed to acquire connection to "+url); ConnectionHook connectionHook = this.getConfig().getConnectionHook(); do{ result = null; try { // keep track of this hook. result = this.obtainRawInternalConnection(); tryAgain = false; if (acquireRetryAttempts != this.getConfig().getAcquireRetryAttempts()){ logger.info("Successfully re-established connection to "+url); } this.getDbIsDown().set(false); connectionHandle.setInternalConnection(result); // call the hook, if available. if (connectionHook != null){ connectionHook.onAcquire(connectionHandle); } ConnectionHandle.sendInitSQL(result, this.getConfig().getInitSQL()); } catch (SQLException e) { // call the hook, if available. if (connectionHook != null){ tryAgain = connectionHook.onAcquireFail(e, acquireConfig); } else { logger.error(String.format("Failed to acquire connection to %s. Sleeping for %d ms. Attempts left: %d", url, acquireRetryDelayInMs, acquireRetryAttempts), e); try { if (acquireRetryAttempts > 0){ Thread.sleep(acquireRetryDelayInMs); } tryAgain = (acquireRetryAttempts--) > 0; } catch (InterruptedException e1) { tryAgain=false; } } if (!tryAgain){ if (oldRawConnection != null) { oldRawConnection.close(); } if (result != null) { result.close(); } connectionHandle.setInternalConnection(oldRawConnection); throw e; } } } while (tryAgain); return result; }
[ "protected", "Connection", "obtainInternalConnection", "(", "ConnectionHandle", "connectionHandle", ")", "throws", "SQLException", "{", "boolean", "tryAgain", "=", "false", ";", "Connection", "result", "=", "null", ";", "Connection", "oldRawConnection", "=", "connectionHandle", ".", "getInternalConnection", "(", ")", ";", "String", "url", "=", "this", ".", "getConfig", "(", ")", ".", "getJdbcUrl", "(", ")", ";", "int", "acquireRetryAttempts", "=", "this", ".", "getConfig", "(", ")", ".", "getAcquireRetryAttempts", "(", ")", ";", "long", "acquireRetryDelayInMs", "=", "this", ".", "getConfig", "(", ")", ".", "getAcquireRetryDelayInMs", "(", ")", ";", "AcquireFailConfig", "acquireConfig", "=", "new", "AcquireFailConfig", "(", ")", ";", "acquireConfig", ".", "setAcquireRetryAttempts", "(", "new", "AtomicInteger", "(", "acquireRetryAttempts", ")", ")", ";", "acquireConfig", ".", "setAcquireRetryDelayInMs", "(", "acquireRetryDelayInMs", ")", ";", "acquireConfig", ".", "setLogMessage", "(", "\"Failed to acquire connection to \"", "+", "url", ")", ";", "ConnectionHook", "connectionHook", "=", "this", ".", "getConfig", "(", ")", ".", "getConnectionHook", "(", ")", ";", "do", "{", "result", "=", "null", ";", "try", "{", "// keep track of this hook.\r", "result", "=", "this", ".", "obtainRawInternalConnection", "(", ")", ";", "tryAgain", "=", "false", ";", "if", "(", "acquireRetryAttempts", "!=", "this", ".", "getConfig", "(", ")", ".", "getAcquireRetryAttempts", "(", ")", ")", "{", "logger", ".", "info", "(", "\"Successfully re-established connection to \"", "+", "url", ")", ";", "}", "this", ".", "getDbIsDown", "(", ")", ".", "set", "(", "false", ")", ";", "connectionHandle", ".", "setInternalConnection", "(", "result", ")", ";", "// call the hook, if available.\r", "if", "(", "connectionHook", "!=", "null", ")", "{", "connectionHook", ".", "onAcquire", "(", "connectionHandle", ")", ";", "}", "ConnectionHandle", ".", "sendInitSQL", "(", "result", ",", "this", ".", "getConfig", "(", ")", ".", "getInitSQL", "(", ")", ")", ";", "}", "catch", "(", "SQLException", "e", ")", "{", "// call the hook, if available.\r", "if", "(", "connectionHook", "!=", "null", ")", "{", "tryAgain", "=", "connectionHook", ".", "onAcquireFail", "(", "e", ",", "acquireConfig", ")", ";", "}", "else", "{", "logger", ".", "error", "(", "String", ".", "format", "(", "\"Failed to acquire connection to %s. Sleeping for %d ms. Attempts left: %d\"", ",", "url", ",", "acquireRetryDelayInMs", ",", "acquireRetryAttempts", ")", ",", "e", ")", ";", "try", "{", "if", "(", "acquireRetryAttempts", ">", "0", ")", "{", "Thread", ".", "sleep", "(", "acquireRetryDelayInMs", ")", ";", "}", "tryAgain", "=", "(", "acquireRetryAttempts", "--", ")", ">", "0", ";", "}", "catch", "(", "InterruptedException", "e1", ")", "{", "tryAgain", "=", "false", ";", "}", "}", "if", "(", "!", "tryAgain", ")", "{", "if", "(", "oldRawConnection", "!=", "null", ")", "{", "oldRawConnection", ".", "close", "(", ")", ";", "}", "if", "(", "result", "!=", "null", ")", "{", "result", ".", "close", "(", ")", ";", "}", "connectionHandle", ".", "setInternalConnection", "(", "oldRawConnection", ")", ";", "throw", "e", ";", "}", "}", "}", "while", "(", "tryAgain", ")", ";", "return", "result", ";", "}" ]
Obtains a database connection, retrying if necessary. @param connectionHandle @return A DB connection. @throws SQLException
[ "Obtains", "a", "database", "connection", "retrying", "if", "necessary", "." ]
74bc3287025fc137ca28909f0f7693edae37a15d
https://github.com/wwadge/bonecp/blob/74bc3287025fc137ca28909f0f7693edae37a15d/bonecp/src/main/java/com/jolbox/bonecp/BoneCP.java#L251-L317
163,172
wwadge/bonecp
bonecp/src/main/java/com/jolbox/bonecp/BoneCP.java
BoneCP.registerUnregisterJMX
protected void registerUnregisterJMX(boolean doRegister) { if (this.mbs == null ){ // this way makes it easier for mocking. this.mbs = ManagementFactory.getPlatformMBeanServer(); } try { String suffix = ""; if (this.config.getPoolName()!=null){ suffix="-"+this.config.getPoolName(); } ObjectName name = new ObjectName(MBEAN_BONECP +suffix); ObjectName configname = new ObjectName(MBEAN_CONFIG + suffix); if (doRegister){ if (!this.mbs.isRegistered(name)){ this.mbs.registerMBean(this.statistics, name); } if (!this.mbs.isRegistered(configname)){ this.mbs.registerMBean(this.config, configname); } } else { if (this.mbs.isRegistered(name)){ this.mbs.unregisterMBean(name); } if (this.mbs.isRegistered(configname)){ this.mbs.unregisterMBean(configname); } } } catch (Exception e) { logger.error("Unable to start/stop JMX", e); } }
java
protected void registerUnregisterJMX(boolean doRegister) { if (this.mbs == null ){ // this way makes it easier for mocking. this.mbs = ManagementFactory.getPlatformMBeanServer(); } try { String suffix = ""; if (this.config.getPoolName()!=null){ suffix="-"+this.config.getPoolName(); } ObjectName name = new ObjectName(MBEAN_BONECP +suffix); ObjectName configname = new ObjectName(MBEAN_CONFIG + suffix); if (doRegister){ if (!this.mbs.isRegistered(name)){ this.mbs.registerMBean(this.statistics, name); } if (!this.mbs.isRegistered(configname)){ this.mbs.registerMBean(this.config, configname); } } else { if (this.mbs.isRegistered(name)){ this.mbs.unregisterMBean(name); } if (this.mbs.isRegistered(configname)){ this.mbs.unregisterMBean(configname); } } } catch (Exception e) { logger.error("Unable to start/stop JMX", e); } }
[ "protected", "void", "registerUnregisterJMX", "(", "boolean", "doRegister", ")", "{", "if", "(", "this", ".", "mbs", "==", "null", ")", "{", "// this way makes it easier for mocking.\r", "this", ".", "mbs", "=", "ManagementFactory", ".", "getPlatformMBeanServer", "(", ")", ";", "}", "try", "{", "String", "suffix", "=", "\"\"", ";", "if", "(", "this", ".", "config", ".", "getPoolName", "(", ")", "!=", "null", ")", "{", "suffix", "=", "\"-\"", "+", "this", ".", "config", ".", "getPoolName", "(", ")", ";", "}", "ObjectName", "name", "=", "new", "ObjectName", "(", "MBEAN_BONECP", "+", "suffix", ")", ";", "ObjectName", "configname", "=", "new", "ObjectName", "(", "MBEAN_CONFIG", "+", "suffix", ")", ";", "if", "(", "doRegister", ")", "{", "if", "(", "!", "this", ".", "mbs", ".", "isRegistered", "(", "name", ")", ")", "{", "this", ".", "mbs", ".", "registerMBean", "(", "this", ".", "statistics", ",", "name", ")", ";", "}", "if", "(", "!", "this", ".", "mbs", ".", "isRegistered", "(", "configname", ")", ")", "{", "this", ".", "mbs", ".", "registerMBean", "(", "this", ".", "config", ",", "configname", ")", ";", "}", "}", "else", "{", "if", "(", "this", ".", "mbs", ".", "isRegistered", "(", "name", ")", ")", "{", "this", ".", "mbs", ".", "unregisterMBean", "(", "name", ")", ";", "}", "if", "(", "this", ".", "mbs", ".", "isRegistered", "(", "configname", ")", ")", "{", "this", ".", "mbs", ".", "unregisterMBean", "(", "configname", ")", ";", "}", "}", "}", "catch", "(", "Exception", "e", ")", "{", "logger", ".", "error", "(", "\"Unable to start/stop JMX\"", ",", "e", ")", ";", "}", "}" ]
Initialises JMX stuff. @param doRegister if true, perform registration, if false unregister
[ "Initialises", "JMX", "stuff", "." ]
74bc3287025fc137ca28909f0f7693edae37a15d
https://github.com/wwadge/bonecp/blob/74bc3287025fc137ca28909f0f7693edae37a15d/bonecp/src/main/java/com/jolbox/bonecp/BoneCP.java#L508-L541
163,173
wwadge/bonecp
bonecp/src/main/java/com/jolbox/bonecp/BoneCP.java
BoneCP.watchConnection
protected void watchConnection(ConnectionHandle connectionHandle) { String message = captureStackTrace(UNCLOSED_EXCEPTION_MESSAGE); this.closeConnectionExecutor.submit(new CloseThreadMonitor(Thread.currentThread(), connectionHandle, message, this.closeConnectionWatchTimeoutInMs)); }
java
protected void watchConnection(ConnectionHandle connectionHandle) { String message = captureStackTrace(UNCLOSED_EXCEPTION_MESSAGE); this.closeConnectionExecutor.submit(new CloseThreadMonitor(Thread.currentThread(), connectionHandle, message, this.closeConnectionWatchTimeoutInMs)); }
[ "protected", "void", "watchConnection", "(", "ConnectionHandle", "connectionHandle", ")", "{", "String", "message", "=", "captureStackTrace", "(", "UNCLOSED_EXCEPTION_MESSAGE", ")", ";", "this", ".", "closeConnectionExecutor", ".", "submit", "(", "new", "CloseThreadMonitor", "(", "Thread", ".", "currentThread", "(", ")", ",", "connectionHandle", ",", "message", ",", "this", ".", "closeConnectionWatchTimeoutInMs", ")", ")", ";", "}" ]
Starts off a new thread to monitor this connection attempt. @param connectionHandle to monitor
[ "Starts", "off", "a", "new", "thread", "to", "monitor", "this", "connection", "attempt", "." ]
74bc3287025fc137ca28909f0f7693edae37a15d
https://github.com/wwadge/bonecp/blob/74bc3287025fc137ca28909f0f7693edae37a15d/bonecp/src/main/java/com/jolbox/bonecp/BoneCP.java#L557-L560
163,174
wwadge/bonecp
bonecp/src/main/java/com/jolbox/bonecp/BoneCP.java
BoneCP.getAsyncConnection
public ListenableFuture<Connection> getAsyncConnection(){ return this.asyncExecutor.submit(new Callable<Connection>() { public Connection call() throws Exception { return getConnection(); }}); }
java
public ListenableFuture<Connection> getAsyncConnection(){ return this.asyncExecutor.submit(new Callable<Connection>() { public Connection call() throws Exception { return getConnection(); }}); }
[ "public", "ListenableFuture", "<", "Connection", ">", "getAsyncConnection", "(", ")", "{", "return", "this", ".", "asyncExecutor", ".", "submit", "(", "new", "Callable", "<", "Connection", ">", "(", ")", "{", "public", "Connection", "call", "(", ")", "throws", "Exception", "{", "return", "getConnection", "(", ")", ";", "}", "}", ")", ";", "}" ]
Obtain a connection asynchronously by queueing a request to obtain a connection in a separate thread. Use as follows:<p> Future&lt;Connection&gt; result = pool.getAsyncConnection();<p> ... do something else in your application here ...<p> Connection connection = result.get(); // get the connection<p> @return A Future task returning a connection.
[ "Obtain", "a", "connection", "asynchronously", "by", "queueing", "a", "request", "to", "obtain", "a", "connection", "in", "a", "separate", "thread", "." ]
74bc3287025fc137ca28909f0f7693edae37a15d
https://github.com/wwadge/bonecp/blob/74bc3287025fc137ca28909f0f7693edae37a15d/bonecp/src/main/java/com/jolbox/bonecp/BoneCP.java#L588-L595
163,175
wwadge/bonecp
bonecp/src/main/java/com/jolbox/bonecp/BoneCP.java
BoneCP.maybeSignalForMoreConnections
protected void maybeSignalForMoreConnections(ConnectionPartition connectionPartition) { if (!connectionPartition.isUnableToCreateMoreTransactions() && !this.poolShuttingDown && connectionPartition.getAvailableConnections()*100/connectionPartition.getMaxConnections() <= this.poolAvailabilityThreshold){ connectionPartition.getPoolWatchThreadSignalQueue().offer(new Object()); // item being pushed is not important. } }
java
protected void maybeSignalForMoreConnections(ConnectionPartition connectionPartition) { if (!connectionPartition.isUnableToCreateMoreTransactions() && !this.poolShuttingDown && connectionPartition.getAvailableConnections()*100/connectionPartition.getMaxConnections() <= this.poolAvailabilityThreshold){ connectionPartition.getPoolWatchThreadSignalQueue().offer(new Object()); // item being pushed is not important. } }
[ "protected", "void", "maybeSignalForMoreConnections", "(", "ConnectionPartition", "connectionPartition", ")", "{", "if", "(", "!", "connectionPartition", ".", "isUnableToCreateMoreTransactions", "(", ")", "&&", "!", "this", ".", "poolShuttingDown", "&&", "connectionPartition", ".", "getAvailableConnections", "(", ")", "*", "100", "/", "connectionPartition", ".", "getMaxConnections", "(", ")", "<=", "this", ".", "poolAvailabilityThreshold", ")", "{", "connectionPartition", ".", "getPoolWatchThreadSignalQueue", "(", ")", ".", "offer", "(", "new", "Object", "(", ")", ")", ";", "// item being pushed is not important.\r", "}", "}" ]
Tests if this partition has hit a threshold and signal to the pool watch thread to create new connections @param connectionPartition to test for.
[ "Tests", "if", "this", "partition", "has", "hit", "a", "threshold", "and", "signal", "to", "the", "pool", "watch", "thread", "to", "create", "new", "connections" ]
74bc3287025fc137ca28909f0f7693edae37a15d
https://github.com/wwadge/bonecp/blob/74bc3287025fc137ca28909f0f7693edae37a15d/bonecp/src/main/java/com/jolbox/bonecp/BoneCP.java#L601-L608
163,176
wwadge/bonecp
bonecp/src/main/java/com/jolbox/bonecp/BoneCP.java
BoneCP.internalReleaseConnection
protected void internalReleaseConnection(ConnectionHandle connectionHandle) throws SQLException { if (!this.cachedPoolStrategy){ connectionHandle.clearStatementCaches(false); } if (connectionHandle.getReplayLog() != null){ connectionHandle.getReplayLog().clear(); connectionHandle.recoveryResult.getReplaceTarget().clear(); } if (connectionHandle.isExpired() || (!this.poolShuttingDown && connectionHandle.isPossiblyBroken() && !isConnectionHandleAlive(connectionHandle))){ if (connectionHandle.isExpired()) { connectionHandle.internalClose(); } ConnectionPartition connectionPartition = connectionHandle.getOriginatingPartition(); postDestroyConnection(connectionHandle); maybeSignalForMoreConnections(connectionPartition); connectionHandle.clearStatementCaches(true); return; // don't place back in queue - connection is broken or expired. } connectionHandle.setConnectionLastUsedInMs(System.currentTimeMillis()); if (!this.poolShuttingDown){ putConnectionBackInPartition(connectionHandle); } else { connectionHandle.internalClose(); } }
java
protected void internalReleaseConnection(ConnectionHandle connectionHandle) throws SQLException { if (!this.cachedPoolStrategy){ connectionHandle.clearStatementCaches(false); } if (connectionHandle.getReplayLog() != null){ connectionHandle.getReplayLog().clear(); connectionHandle.recoveryResult.getReplaceTarget().clear(); } if (connectionHandle.isExpired() || (!this.poolShuttingDown && connectionHandle.isPossiblyBroken() && !isConnectionHandleAlive(connectionHandle))){ if (connectionHandle.isExpired()) { connectionHandle.internalClose(); } ConnectionPartition connectionPartition = connectionHandle.getOriginatingPartition(); postDestroyConnection(connectionHandle); maybeSignalForMoreConnections(connectionPartition); connectionHandle.clearStatementCaches(true); return; // don't place back in queue - connection is broken or expired. } connectionHandle.setConnectionLastUsedInMs(System.currentTimeMillis()); if (!this.poolShuttingDown){ putConnectionBackInPartition(connectionHandle); } else { connectionHandle.internalClose(); } }
[ "protected", "void", "internalReleaseConnection", "(", "ConnectionHandle", "connectionHandle", ")", "throws", "SQLException", "{", "if", "(", "!", "this", ".", "cachedPoolStrategy", ")", "{", "connectionHandle", ".", "clearStatementCaches", "(", "false", ")", ";", "}", "if", "(", "connectionHandle", ".", "getReplayLog", "(", ")", "!=", "null", ")", "{", "connectionHandle", ".", "getReplayLog", "(", ")", ".", "clear", "(", ")", ";", "connectionHandle", ".", "recoveryResult", ".", "getReplaceTarget", "(", ")", ".", "clear", "(", ")", ";", "}", "if", "(", "connectionHandle", ".", "isExpired", "(", ")", "||", "(", "!", "this", ".", "poolShuttingDown", "&&", "connectionHandle", ".", "isPossiblyBroken", "(", ")", "&&", "!", "isConnectionHandleAlive", "(", "connectionHandle", ")", ")", ")", "{", "if", "(", "connectionHandle", ".", "isExpired", "(", ")", ")", "{", "connectionHandle", ".", "internalClose", "(", ")", ";", "}", "ConnectionPartition", "connectionPartition", "=", "connectionHandle", ".", "getOriginatingPartition", "(", ")", ";", "postDestroyConnection", "(", "connectionHandle", ")", ";", "maybeSignalForMoreConnections", "(", "connectionPartition", ")", ";", "connectionHandle", ".", "clearStatementCaches", "(", "true", ")", ";", "return", ";", "// don't place back in queue - connection is broken or expired.\r", "}", "connectionHandle", ".", "setConnectionLastUsedInMs", "(", "System", ".", "currentTimeMillis", "(", ")", ")", ";", "if", "(", "!", "this", ".", "poolShuttingDown", ")", "{", "putConnectionBackInPartition", "(", "connectionHandle", ")", ";", "}", "else", "{", "connectionHandle", ".", "internalClose", "(", ")", ";", "}", "}" ]
Release a connection by placing the connection back in the pool. @param connectionHandle Connection being released. @throws SQLException
[ "Release", "a", "connection", "by", "placing", "the", "connection", "back", "in", "the", "pool", "." ]
74bc3287025fc137ca28909f0f7693edae37a15d
https://github.com/wwadge/bonecp/blob/74bc3287025fc137ca28909f0f7693edae37a15d/bonecp/src/main/java/com/jolbox/bonecp/BoneCP.java#L637-L671
163,177
wwadge/bonecp
bonecp/src/main/java/com/jolbox/bonecp/BoneCP.java
BoneCP.putConnectionBackInPartition
protected void putConnectionBackInPartition(ConnectionHandle connectionHandle) throws SQLException { if (this.cachedPoolStrategy && ((CachedConnectionStrategy)this.connectionStrategy).tlConnections.dumbGet().getValue()){ connectionHandle.logicallyClosed.set(true); ((CachedConnectionStrategy)this.connectionStrategy).tlConnections.set(new AbstractMap.SimpleEntry<ConnectionHandle, Boolean>(connectionHandle, false)); } else { BlockingQueue<ConnectionHandle> queue = connectionHandle.getOriginatingPartition().getFreeConnections(); if (!queue.offer(connectionHandle)){ // this shouldn't fail connectionHandle.internalClose(); } } }
java
protected void putConnectionBackInPartition(ConnectionHandle connectionHandle) throws SQLException { if (this.cachedPoolStrategy && ((CachedConnectionStrategy)this.connectionStrategy).tlConnections.dumbGet().getValue()){ connectionHandle.logicallyClosed.set(true); ((CachedConnectionStrategy)this.connectionStrategy).tlConnections.set(new AbstractMap.SimpleEntry<ConnectionHandle, Boolean>(connectionHandle, false)); } else { BlockingQueue<ConnectionHandle> queue = connectionHandle.getOriginatingPartition().getFreeConnections(); if (!queue.offer(connectionHandle)){ // this shouldn't fail connectionHandle.internalClose(); } } }
[ "protected", "void", "putConnectionBackInPartition", "(", "ConnectionHandle", "connectionHandle", ")", "throws", "SQLException", "{", "if", "(", "this", ".", "cachedPoolStrategy", "&&", "(", "(", "CachedConnectionStrategy", ")", "this", ".", "connectionStrategy", ")", ".", "tlConnections", ".", "dumbGet", "(", ")", ".", "getValue", "(", ")", ")", "{", "connectionHandle", ".", "logicallyClosed", ".", "set", "(", "true", ")", ";", "(", "(", "CachedConnectionStrategy", ")", "this", ".", "connectionStrategy", ")", ".", "tlConnections", ".", "set", "(", "new", "AbstractMap", ".", "SimpleEntry", "<", "ConnectionHandle", ",", "Boolean", ">", "(", "connectionHandle", ",", "false", ")", ")", ";", "}", "else", "{", "BlockingQueue", "<", "ConnectionHandle", ">", "queue", "=", "connectionHandle", ".", "getOriginatingPartition", "(", ")", ".", "getFreeConnections", "(", ")", ";", "if", "(", "!", "queue", ".", "offer", "(", "connectionHandle", ")", ")", "{", "// this shouldn't fail\r", "connectionHandle", ".", "internalClose", "(", ")", ";", "}", "}", "}" ]
Places a connection back in the originating partition. @param connectionHandle to place back @throws SQLException on error
[ "Places", "a", "connection", "back", "in", "the", "originating", "partition", "." ]
74bc3287025fc137ca28909f0f7693edae37a15d
https://github.com/wwadge/bonecp/blob/74bc3287025fc137ca28909f0f7693edae37a15d/bonecp/src/main/java/com/jolbox/bonecp/BoneCP.java#L679-L692
163,178
wwadge/bonecp
bonecp/src/main/java/com/jolbox/bonecp/BoneCP.java
BoneCP.isConnectionHandleAlive
public boolean isConnectionHandleAlive(ConnectionHandle connection) { Statement stmt = null; boolean result = false; boolean logicallyClosed = connection.logicallyClosed.get(); try { connection.logicallyClosed.compareAndSet(true, false); // avoid checks later on if it's marked as closed. String testStatement = this.config.getConnectionTestStatement(); ResultSet rs = null; if (testStatement == null) { // Make a call to fetch the metadata instead of a dummy query. rs = connection.getMetaData().getTables( null, null, KEEPALIVEMETADATA, METADATATABLE ); } else { stmt = connection.createStatement(); stmt.execute(testStatement); } if (rs != null) { rs.close(); } result = true; } catch (SQLException e) { // connection must be broken! result = false; } finally { connection.logicallyClosed.set(logicallyClosed); connection.setConnectionLastResetInMs(System.currentTimeMillis()); result = closeStatement(stmt, result); } return result; }
java
public boolean isConnectionHandleAlive(ConnectionHandle connection) { Statement stmt = null; boolean result = false; boolean logicallyClosed = connection.logicallyClosed.get(); try { connection.logicallyClosed.compareAndSet(true, false); // avoid checks later on if it's marked as closed. String testStatement = this.config.getConnectionTestStatement(); ResultSet rs = null; if (testStatement == null) { // Make a call to fetch the metadata instead of a dummy query. rs = connection.getMetaData().getTables( null, null, KEEPALIVEMETADATA, METADATATABLE ); } else { stmt = connection.createStatement(); stmt.execute(testStatement); } if (rs != null) { rs.close(); } result = true; } catch (SQLException e) { // connection must be broken! result = false; } finally { connection.logicallyClosed.set(logicallyClosed); connection.setConnectionLastResetInMs(System.currentTimeMillis()); result = closeStatement(stmt, result); } return result; }
[ "public", "boolean", "isConnectionHandleAlive", "(", "ConnectionHandle", "connection", ")", "{", "Statement", "stmt", "=", "null", ";", "boolean", "result", "=", "false", ";", "boolean", "logicallyClosed", "=", "connection", ".", "logicallyClosed", ".", "get", "(", ")", ";", "try", "{", "connection", ".", "logicallyClosed", ".", "compareAndSet", "(", "true", ",", "false", ")", ";", "// avoid checks later on if it's marked as closed.\r", "String", "testStatement", "=", "this", ".", "config", ".", "getConnectionTestStatement", "(", ")", ";", "ResultSet", "rs", "=", "null", ";", "if", "(", "testStatement", "==", "null", ")", "{", "// Make a call to fetch the metadata instead of a dummy query.\r", "rs", "=", "connection", ".", "getMetaData", "(", ")", ".", "getTables", "(", "null", ",", "null", ",", "KEEPALIVEMETADATA", ",", "METADATATABLE", ")", ";", "}", "else", "{", "stmt", "=", "connection", ".", "createStatement", "(", ")", ";", "stmt", ".", "execute", "(", "testStatement", ")", ";", "}", "if", "(", "rs", "!=", "null", ")", "{", "rs", ".", "close", "(", ")", ";", "}", "result", "=", "true", ";", "}", "catch", "(", "SQLException", "e", ")", "{", "// connection must be broken!\r", "result", "=", "false", ";", "}", "finally", "{", "connection", ".", "logicallyClosed", ".", "set", "(", "logicallyClosed", ")", ";", "connection", ".", "setConnectionLastResetInMs", "(", "System", ".", "currentTimeMillis", "(", ")", ")", ";", "result", "=", "closeStatement", "(", "stmt", ",", "result", ")", ";", "}", "return", "result", ";", "}" ]
Sends a dummy statement to the server to keep the connection alive @param connection Connection handle to perform activity on @return true if test query worked, false otherwise
[ "Sends", "a", "dummy", "statement", "to", "the", "server", "to", "keep", "the", "connection", "alive" ]
74bc3287025fc137ca28909f0f7693edae37a15d
https://github.com/wwadge/bonecp/blob/74bc3287025fc137ca28909f0f7693edae37a15d/bonecp/src/main/java/com/jolbox/bonecp/BoneCP.java#L699-L731
163,179
wwadge/bonecp
bonecp/src/main/java/com/jolbox/bonecp/BoneCP.java
BoneCP.getTotalLeased
public int getTotalLeased(){ int total=0; for (int i=0; i < this.partitionCount && this.partitions[i] != null; i++){ total+=this.partitions[i].getCreatedConnections()-this.partitions[i].getAvailableConnections(); } return total; }
java
public int getTotalLeased(){ int total=0; for (int i=0; i < this.partitionCount && this.partitions[i] != null; i++){ total+=this.partitions[i].getCreatedConnections()-this.partitions[i].getAvailableConnections(); } return total; }
[ "public", "int", "getTotalLeased", "(", ")", "{", "int", "total", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "this", ".", "partitionCount", "&&", "this", ".", "partitions", "[", "i", "]", "!=", "null", ";", "i", "++", ")", "{", "total", "+=", "this", ".", "partitions", "[", "i", "]", ".", "getCreatedConnections", "(", ")", "-", "this", ".", "partitions", "[", "i", "]", ".", "getAvailableConnections", "(", ")", ";", "}", "return", "total", ";", "}" ]
Return total number of connections currently in use by an application @return no of leased connections
[ "Return", "total", "number", "of", "connections", "currently", "in", "use", "by", "an", "application" ]
74bc3287025fc137ca28909f0f7693edae37a15d
https://github.com/wwadge/bonecp/blob/74bc3287025fc137ca28909f0f7693edae37a15d/bonecp/src/main/java/com/jolbox/bonecp/BoneCP.java#L752-L758
163,180
wwadge/bonecp
bonecp/src/main/java/com/jolbox/bonecp/BoneCP.java
BoneCP.getTotalCreatedConnections
public int getTotalCreatedConnections(){ int total=0; for (int i=0; i < this.partitionCount && this.partitions[i] != null; i++){ total+=this.partitions[i].getCreatedConnections(); } return total; }
java
public int getTotalCreatedConnections(){ int total=0; for (int i=0; i < this.partitionCount && this.partitions[i] != null; i++){ total+=this.partitions[i].getCreatedConnections(); } return total; }
[ "public", "int", "getTotalCreatedConnections", "(", ")", "{", "int", "total", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "this", ".", "partitionCount", "&&", "this", ".", "partitions", "[", "i", "]", "!=", "null", ";", "i", "++", ")", "{", "total", "+=", "this", ".", "partitions", "[", "i", "]", ".", "getCreatedConnections", "(", ")", ";", "}", "return", "total", ";", "}" ]
Return total number of connections created in all partitions. @return number of created connections
[ "Return", "total", "number", "of", "connections", "created", "in", "all", "partitions", "." ]
74bc3287025fc137ca28909f0f7693edae37a15d
https://github.com/wwadge/bonecp/blob/74bc3287025fc137ca28909f0f7693edae37a15d/bonecp/src/main/java/com/jolbox/bonecp/BoneCP.java#L777-L783
163,181
wwadge/bonecp
bonecp/src/main/java/com/jolbox/bonecp/ConnectionPartition.java
ConnectionPartition.addFreeConnection
protected void addFreeConnection(ConnectionHandle connectionHandle) throws SQLException{ connectionHandle.setOriginatingPartition(this); // assume success to avoid racing where we insert an item in a queue and having that item immediately // taken and closed off thus decrementing the created connection count. updateCreatedConnections(1); if (!this.disableTracking){ trackConnectionFinalizer(connectionHandle); } // the instant the following line is executed, consumers can start making use of this // connection. if (!this.freeConnections.offer(connectionHandle)){ // we failed. rollback. updateCreatedConnections(-1); // compensate our createdConnection count. if (!this.disableTracking){ this.pool.getFinalizableRefs().remove(connectionHandle.getInternalConnection()); } // terminate the internal handle. connectionHandle.internalClose(); } }
java
protected void addFreeConnection(ConnectionHandle connectionHandle) throws SQLException{ connectionHandle.setOriginatingPartition(this); // assume success to avoid racing where we insert an item in a queue and having that item immediately // taken and closed off thus decrementing the created connection count. updateCreatedConnections(1); if (!this.disableTracking){ trackConnectionFinalizer(connectionHandle); } // the instant the following line is executed, consumers can start making use of this // connection. if (!this.freeConnections.offer(connectionHandle)){ // we failed. rollback. updateCreatedConnections(-1); // compensate our createdConnection count. if (!this.disableTracking){ this.pool.getFinalizableRefs().remove(connectionHandle.getInternalConnection()); } // terminate the internal handle. connectionHandle.internalClose(); } }
[ "protected", "void", "addFreeConnection", "(", "ConnectionHandle", "connectionHandle", ")", "throws", "SQLException", "{", "connectionHandle", ".", "setOriginatingPartition", "(", "this", ")", ";", "// assume success to avoid racing where we insert an item in a queue and having that item immediately\r", "// taken and closed off thus decrementing the created connection count.\r", "updateCreatedConnections", "(", "1", ")", ";", "if", "(", "!", "this", ".", "disableTracking", ")", "{", "trackConnectionFinalizer", "(", "connectionHandle", ")", ";", "}", "// the instant the following line is executed, consumers can start making use of this \r", "// connection.\r", "if", "(", "!", "this", ".", "freeConnections", ".", "offer", "(", "connectionHandle", ")", ")", "{", "// we failed. rollback.\r", "updateCreatedConnections", "(", "-", "1", ")", ";", "// compensate our createdConnection count.\r", "if", "(", "!", "this", ".", "disableTracking", ")", "{", "this", ".", "pool", ".", "getFinalizableRefs", "(", ")", ".", "remove", "(", "connectionHandle", ".", "getInternalConnection", "(", ")", ")", ";", "}", "// terminate the internal handle.\r", "connectionHandle", ".", "internalClose", "(", ")", ";", "}", "}" ]
Adds a free connection. @param connectionHandle @throws SQLException on error
[ "Adds", "a", "free", "connection", "." ]
74bc3287025fc137ca28909f0f7693edae37a15d
https://github.com/wwadge/bonecp/blob/74bc3287025fc137ca28909f0f7693edae37a15d/bonecp/src/main/java/com/jolbox/bonecp/ConnectionPartition.java#L108-L129
163,182
wwadge/bonecp
bonecp/src/main/java/com/jolbox/bonecp/DefaultConnectionStrategy.java
DefaultConnectionStrategy.terminateAllConnections
public void terminateAllConnections(){ this.terminationLock.lock(); try{ // close off all connections. for (int i=0; i < this.pool.partitionCount; i++) { this.pool.partitions[i].setUnableToCreateMoreTransactions(false); // we can create new ones now, this is an optimization List<ConnectionHandle> clist = new LinkedList<ConnectionHandle>(); this.pool.partitions[i].getFreeConnections().drainTo(clist); for (ConnectionHandle c: clist){ this.pool.destroyConnection(c); } } } finally { this.terminationLock.unlock(); } }
java
public void terminateAllConnections(){ this.terminationLock.lock(); try{ // close off all connections. for (int i=0; i < this.pool.partitionCount; i++) { this.pool.partitions[i].setUnableToCreateMoreTransactions(false); // we can create new ones now, this is an optimization List<ConnectionHandle> clist = new LinkedList<ConnectionHandle>(); this.pool.partitions[i].getFreeConnections().drainTo(clist); for (ConnectionHandle c: clist){ this.pool.destroyConnection(c); } } } finally { this.terminationLock.unlock(); } }
[ "public", "void", "terminateAllConnections", "(", ")", "{", "this", ".", "terminationLock", ".", "lock", "(", ")", ";", "try", "{", "// close off all connections.\r", "for", "(", "int", "i", "=", "0", ";", "i", "<", "this", ".", "pool", ".", "partitionCount", ";", "i", "++", ")", "{", "this", ".", "pool", ".", "partitions", "[", "i", "]", ".", "setUnableToCreateMoreTransactions", "(", "false", ")", ";", "// we can create new ones now, this is an optimization\r", "List", "<", "ConnectionHandle", ">", "clist", "=", "new", "LinkedList", "<", "ConnectionHandle", ">", "(", ")", ";", "this", ".", "pool", ".", "partitions", "[", "i", "]", ".", "getFreeConnections", "(", ")", ".", "drainTo", "(", "clist", ")", ";", "for", "(", "ConnectionHandle", "c", ":", "clist", ")", "{", "this", ".", "pool", ".", "destroyConnection", "(", "c", ")", ";", "}", "}", "}", "finally", "{", "this", ".", "terminationLock", ".", "unlock", "(", ")", ";", "}", "}" ]
Closes off all connections in all partitions.
[ "Closes", "off", "all", "connections", "in", "all", "partitions", "." ]
74bc3287025fc137ca28909f0f7693edae37a15d
https://github.com/wwadge/bonecp/blob/74bc3287025fc137ca28909f0f7693edae37a15d/bonecp/src/main/java/com/jolbox/bonecp/DefaultConnectionStrategy.java#L103-L119
163,183
wwadge/bonecp
bonecp/src/main/java/com/jolbox/bonecp/StatementHandle.java
StatementHandle.queryTimerEnd
protected void queryTimerEnd(String sql, long queryStartTime) { if ((this.queryExecuteTimeLimit != 0) && (this.connectionHook != null)){ long timeElapsed = (System.nanoTime() - queryStartTime); if (timeElapsed > this.queryExecuteTimeLimit){ this.connectionHook.onQueryExecuteTimeLimitExceeded(this.connectionHandle, this, sql, this.logParams, timeElapsed); } } if (this.statisticsEnabled){ this.statistics.incrementStatementsExecuted(); this.statistics.addStatementExecuteTime(System.nanoTime() - queryStartTime); } }
java
protected void queryTimerEnd(String sql, long queryStartTime) { if ((this.queryExecuteTimeLimit != 0) && (this.connectionHook != null)){ long timeElapsed = (System.nanoTime() - queryStartTime); if (timeElapsed > this.queryExecuteTimeLimit){ this.connectionHook.onQueryExecuteTimeLimitExceeded(this.connectionHandle, this, sql, this.logParams, timeElapsed); } } if (this.statisticsEnabled){ this.statistics.incrementStatementsExecuted(); this.statistics.addStatementExecuteTime(System.nanoTime() - queryStartTime); } }
[ "protected", "void", "queryTimerEnd", "(", "String", "sql", ",", "long", "queryStartTime", ")", "{", "if", "(", "(", "this", ".", "queryExecuteTimeLimit", "!=", "0", ")", "&&", "(", "this", ".", "connectionHook", "!=", "null", ")", ")", "{", "long", "timeElapsed", "=", "(", "System", ".", "nanoTime", "(", ")", "-", "queryStartTime", ")", ";", "if", "(", "timeElapsed", ">", "this", ".", "queryExecuteTimeLimit", ")", "{", "this", ".", "connectionHook", ".", "onQueryExecuteTimeLimitExceeded", "(", "this", ".", "connectionHandle", ",", "this", ",", "sql", ",", "this", ".", "logParams", ",", "timeElapsed", ")", ";", "}", "}", "if", "(", "this", ".", "statisticsEnabled", ")", "{", "this", ".", "statistics", ".", "incrementStatementsExecuted", "(", ")", ";", "this", ".", "statistics", ".", "addStatementExecuteTime", "(", "System", ".", "nanoTime", "(", ")", "-", "queryStartTime", ")", ";", "}", "}" ]
Call the onQueryExecuteTimeLimitExceeded hook if necessary @param sql sql statement that took too long @param queryStartTime time when query was started.
[ "Call", "the", "onQueryExecuteTimeLimitExceeded", "hook", "if", "necessary" ]
74bc3287025fc137ca28909f0f7693edae37a15d
https://github.com/wwadge/bonecp/blob/74bc3287025fc137ca28909f0f7693edae37a15d/bonecp/src/main/java/com/jolbox/bonecp/StatementHandle.java#L274-L290
163,184
puniverse/capsule
capsule-util/src/main/java/co/paralleluniverse/common/ProcessUtil.java
ProcessUtil.getMBeanServerConnection
public static MBeanServerConnection getMBeanServerConnection(Process p, boolean startAgent) { try { final JMXServiceURL serviceURL = getLocalConnectorAddress(p, startAgent); final JMXConnector connector = JMXConnectorFactory.connect(serviceURL); final MBeanServerConnection mbsc = connector.getMBeanServerConnection(); return mbsc; } catch (Exception e) { throw new RuntimeException(e); } }
java
public static MBeanServerConnection getMBeanServerConnection(Process p, boolean startAgent) { try { final JMXServiceURL serviceURL = getLocalConnectorAddress(p, startAgent); final JMXConnector connector = JMXConnectorFactory.connect(serviceURL); final MBeanServerConnection mbsc = connector.getMBeanServerConnection(); return mbsc; } catch (Exception e) { throw new RuntimeException(e); } }
[ "public", "static", "MBeanServerConnection", "getMBeanServerConnection", "(", "Process", "p", ",", "boolean", "startAgent", ")", "{", "try", "{", "final", "JMXServiceURL", "serviceURL", "=", "getLocalConnectorAddress", "(", "p", ",", "startAgent", ")", ";", "final", "JMXConnector", "connector", "=", "JMXConnectorFactory", ".", "connect", "(", "serviceURL", ")", ";", "final", "MBeanServerConnection", "mbsc", "=", "connector", ".", "getMBeanServerConnection", "(", ")", ";", "return", "mbsc", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "}" ]
Connects to a child JVM process @param p the process to which to connect @param startAgent whether to installed the JMX agent in the target process if not already in place @return an {@link MBeanServerConnection} to the process's MBean server
[ "Connects", "to", "a", "child", "JVM", "process" ]
291a54e501a32aaf0284707b8c1fbff6a566822b
https://github.com/puniverse/capsule/blob/291a54e501a32aaf0284707b8c1fbff6a566822b/capsule-util/src/main/java/co/paralleluniverse/common/ProcessUtil.java#L67-L76
163,185
puniverse/capsule
capsule-util/src/main/java/co/paralleluniverse/common/ProcessUtil.java
ProcessUtil.getLocalConnectorAddress
public static JMXServiceURL getLocalConnectorAddress(Process p, boolean startAgent) { return getLocalConnectorAddress(Integer.toString(getPid(p)), startAgent); }
java
public static JMXServiceURL getLocalConnectorAddress(Process p, boolean startAgent) { return getLocalConnectorAddress(Integer.toString(getPid(p)), startAgent); }
[ "public", "static", "JMXServiceURL", "getLocalConnectorAddress", "(", "Process", "p", ",", "boolean", "startAgent", ")", "{", "return", "getLocalConnectorAddress", "(", "Integer", ".", "toString", "(", "getPid", "(", "p", ")", ")", ",", "startAgent", ")", ";", "}" ]
Returns the JMX connector address of a child process. @param p the process to which to connect @param startAgent whether to installed the JMX agent in the target process if not already in place @return a {@link JMXServiceURL} to the process's MBean server
[ "Returns", "the", "JMX", "connector", "address", "of", "a", "child", "process", "." ]
291a54e501a32aaf0284707b8c1fbff6a566822b
https://github.com/puniverse/capsule/blob/291a54e501a32aaf0284707b8c1fbff6a566822b/capsule-util/src/main/java/co/paralleluniverse/common/ProcessUtil.java#L85-L87
163,186
puniverse/capsule
capsule-util/src/main/java/co/paralleluniverse/capsule/Jar.java
Jar.setAttribute
public final Jar setAttribute(String name, String value) { verifyNotSealed(); if (jos != null) throw new IllegalStateException("Manifest cannot be modified after entries are added."); getManifest().getMainAttributes().putValue(name, value); return this; }
java
public final Jar setAttribute(String name, String value) { verifyNotSealed(); if (jos != null) throw new IllegalStateException("Manifest cannot be modified after entries are added."); getManifest().getMainAttributes().putValue(name, value); return this; }
[ "public", "final", "Jar", "setAttribute", "(", "String", "name", ",", "String", "value", ")", "{", "verifyNotSealed", "(", ")", ";", "if", "(", "jos", "!=", "null", ")", "throw", "new", "IllegalStateException", "(", "\"Manifest cannot be modified after entries are added.\"", ")", ";", "getManifest", "(", ")", ".", "getMainAttributes", "(", ")", ".", "putValue", "(", "name", ",", "value", ")", ";", "return", "this", ";", "}" ]
Sets an attribute in the main section of the manifest. @param name the attribute's name @param value the attribute's value @return {@code this} @throws IllegalStateException if entries have been added or the JAR has been written prior to calling this methods.
[ "Sets", "an", "attribute", "in", "the", "main", "section", "of", "the", "manifest", "." ]
291a54e501a32aaf0284707b8c1fbff6a566822b
https://github.com/puniverse/capsule/blob/291a54e501a32aaf0284707b8c1fbff6a566822b/capsule-util/src/main/java/co/paralleluniverse/capsule/Jar.java#L135-L141
163,187
puniverse/capsule
capsule-util/src/main/java/co/paralleluniverse/capsule/Jar.java
Jar.setAttribute
public final Jar setAttribute(String section, String name, String value) { verifyNotSealed(); if (jos != null) throw new IllegalStateException("Manifest cannot be modified after entries are added."); Attributes attr = getManifest().getAttributes(section); if (attr == null) { attr = new Attributes(); getManifest().getEntries().put(section, attr); } attr.putValue(name, value); return this; }
java
public final Jar setAttribute(String section, String name, String value) { verifyNotSealed(); if (jos != null) throw new IllegalStateException("Manifest cannot be modified after entries are added."); Attributes attr = getManifest().getAttributes(section); if (attr == null) { attr = new Attributes(); getManifest().getEntries().put(section, attr); } attr.putValue(name, value); return this; }
[ "public", "final", "Jar", "setAttribute", "(", "String", "section", ",", "String", "name", ",", "String", "value", ")", "{", "verifyNotSealed", "(", ")", ";", "if", "(", "jos", "!=", "null", ")", "throw", "new", "IllegalStateException", "(", "\"Manifest cannot be modified after entries are added.\"", ")", ";", "Attributes", "attr", "=", "getManifest", "(", ")", ".", "getAttributes", "(", "section", ")", ";", "if", "(", "attr", "==", "null", ")", "{", "attr", "=", "new", "Attributes", "(", ")", ";", "getManifest", "(", ")", ".", "getEntries", "(", ")", ".", "put", "(", "section", ",", "attr", ")", ";", "}", "attr", ".", "putValue", "(", "name", ",", "value", ")", ";", "return", "this", ";", "}" ]
Sets an attribute in a non-main section of the manifest. @param section the section's name @param name the attribute's name @param value the attribute's value @return {@code this} @throws IllegalStateException if entries have been added or the JAR has been written prior to calling this methods.
[ "Sets", "an", "attribute", "in", "a", "non", "-", "main", "section", "of", "the", "manifest", "." ]
291a54e501a32aaf0284707b8c1fbff6a566822b
https://github.com/puniverse/capsule/blob/291a54e501a32aaf0284707b8c1fbff6a566822b/capsule-util/src/main/java/co/paralleluniverse/capsule/Jar.java#L152-L163
163,188
puniverse/capsule
capsule-util/src/main/java/co/paralleluniverse/capsule/Jar.java
Jar.setListAttribute
public Jar setListAttribute(String name, Collection<?> values) { return setAttribute(name, join(values)); }
java
public Jar setListAttribute(String name, Collection<?> values) { return setAttribute(name, join(values)); }
[ "public", "Jar", "setListAttribute", "(", "String", "name", ",", "Collection", "<", "?", ">", "values", ")", "{", "return", "setAttribute", "(", "name", ",", "join", "(", "values", ")", ")", ";", "}" ]
Sets an attribute in the main section of the manifest to a list. The list elements will be joined with a single whitespace character. @param name the attribute's name @param values the attribute's value @return {@code this} @throws IllegalStateException if entries have been added or the JAR has been written prior to calling this methods.
[ "Sets", "an", "attribute", "in", "the", "main", "section", "of", "the", "manifest", "to", "a", "list", ".", "The", "list", "elements", "will", "be", "joined", "with", "a", "single", "whitespace", "character", "." ]
291a54e501a32aaf0284707b8c1fbff6a566822b
https://github.com/puniverse/capsule/blob/291a54e501a32aaf0284707b8c1fbff6a566822b/capsule-util/src/main/java/co/paralleluniverse/capsule/Jar.java#L174-L176
163,189
puniverse/capsule
capsule-util/src/main/java/co/paralleluniverse/capsule/Jar.java
Jar.setMapAttribute
public Jar setMapAttribute(String name, Map<String, ?> values) { return setAttribute(name, join(values)); }
java
public Jar setMapAttribute(String name, Map<String, ?> values) { return setAttribute(name, join(values)); }
[ "public", "Jar", "setMapAttribute", "(", "String", "name", ",", "Map", "<", "String", ",", "?", ">", "values", ")", "{", "return", "setAttribute", "(", "name", ",", "join", "(", "values", ")", ")", ";", "}" ]
Sets an attribute in the main section of the manifest to a map. The map entries will be joined with a single whitespace character, and each key-value pair will be joined with a '='. @param name the attribute's name @param values the attribute's value @return {@code this} @throws IllegalStateException if entries have been added or the JAR has been written prior to calling this methods.
[ "Sets", "an", "attribute", "in", "the", "main", "section", "of", "the", "manifest", "to", "a", "map", ".", "The", "map", "entries", "will", "be", "joined", "with", "a", "single", "whitespace", "character", "and", "each", "key", "-", "value", "pair", "will", "be", "joined", "with", "a", "=", "." ]
291a54e501a32aaf0284707b8c1fbff6a566822b
https://github.com/puniverse/capsule/blob/291a54e501a32aaf0284707b8c1fbff6a566822b/capsule-util/src/main/java/co/paralleluniverse/capsule/Jar.java#L201-L203
163,190
puniverse/capsule
capsule-util/src/main/java/co/paralleluniverse/capsule/Jar.java
Jar.getAttribute
public String getAttribute(String section, String name) { Attributes attr = getManifest().getAttributes(section); return attr != null ? attr.getValue(name) : null; }
java
public String getAttribute(String section, String name) { Attributes attr = getManifest().getAttributes(section); return attr != null ? attr.getValue(name) : null; }
[ "public", "String", "getAttribute", "(", "String", "section", ",", "String", "name", ")", "{", "Attributes", "attr", "=", "getManifest", "(", ")", ".", "getAttributes", "(", "section", ")", ";", "return", "attr", "!=", "null", "?", "attr", ".", "getValue", "(", "name", ")", ":", "null", ";", "}" ]
Returns an attribute's value from a non-main section of this JAR's manifest. @param section the manifest's section @param name the attribute's name
[ "Returns", "an", "attribute", "s", "value", "from", "a", "non", "-", "main", "section", "of", "this", "JAR", "s", "manifest", "." ]
291a54e501a32aaf0284707b8c1fbff6a566822b
https://github.com/puniverse/capsule/blob/291a54e501a32aaf0284707b8c1fbff6a566822b/capsule-util/src/main/java/co/paralleluniverse/capsule/Jar.java#L234-L237
163,191
puniverse/capsule
capsule-util/src/main/java/co/paralleluniverse/capsule/Jar.java
Jar.getListAttribute
public List<String> getListAttribute(String section, String name) { return split(getAttribute(section, name)); }
java
public List<String> getListAttribute(String section, String name) { return split(getAttribute(section, name)); }
[ "public", "List", "<", "String", ">", "getListAttribute", "(", "String", "section", ",", "String", "name", ")", "{", "return", "split", "(", "getAttribute", "(", "section", ",", "name", ")", ")", ";", "}" ]
Returns an attribute's list value from a non-main section of this JAR's manifest. The attributes string value will be split on whitespace into the returned list. The returned list may be safely modified. @param section the manifest's section @param name the attribute's name
[ "Returns", "an", "attribute", "s", "list", "value", "from", "a", "non", "-", "main", "section", "of", "this", "JAR", "s", "manifest", ".", "The", "attributes", "string", "value", "will", "be", "split", "on", "whitespace", "into", "the", "returned", "list", ".", "The", "returned", "list", "may", "be", "safely", "modified", "." ]
291a54e501a32aaf0284707b8c1fbff6a566822b
https://github.com/puniverse/capsule/blob/291a54e501a32aaf0284707b8c1fbff6a566822b/capsule-util/src/main/java/co/paralleluniverse/capsule/Jar.java#L258-L260
163,192
puniverse/capsule
capsule-util/src/main/java/co/paralleluniverse/capsule/Jar.java
Jar.getMapAttribute
public Map<String, String> getMapAttribute(String name, String defaultValue) { return mapSplit(getAttribute(name), defaultValue); }
java
public Map<String, String> getMapAttribute(String name, String defaultValue) { return mapSplit(getAttribute(name), defaultValue); }
[ "public", "Map", "<", "String", ",", "String", ">", "getMapAttribute", "(", "String", "name", ",", "String", "defaultValue", ")", "{", "return", "mapSplit", "(", "getAttribute", "(", "name", ")", ",", "defaultValue", ")", ";", "}" ]
Returns an attribute's map value from this JAR's manifest's main section. The attributes string value will be split on whitespace into map entries, and each entry will be split on '=' to get the key-value pair. The returned map may be safely modified. @param name the attribute's name
[ "Returns", "an", "attribute", "s", "map", "value", "from", "this", "JAR", "s", "manifest", "s", "main", "section", ".", "The", "attributes", "string", "value", "will", "be", "split", "on", "whitespace", "into", "map", "entries", "and", "each", "entry", "will", "be", "split", "on", "=", "to", "get", "the", "key", "-", "value", "pair", ".", "The", "returned", "map", "may", "be", "safely", "modified", "." ]
291a54e501a32aaf0284707b8c1fbff6a566822b
https://github.com/puniverse/capsule/blob/291a54e501a32aaf0284707b8c1fbff6a566822b/capsule-util/src/main/java/co/paralleluniverse/capsule/Jar.java#L269-L271
163,193
puniverse/capsule
capsule-util/src/main/java/co/paralleluniverse/capsule/Jar.java
Jar.addClass
public Jar addClass(Class<?> clazz) throws IOException { final String resource = clazz.getName().replace('.', '/') + ".class"; return addEntry(resource, clazz.getClassLoader().getResourceAsStream(resource)); }
java
public Jar addClass(Class<?> clazz) throws IOException { final String resource = clazz.getName().replace('.', '/') + ".class"; return addEntry(resource, clazz.getClassLoader().getResourceAsStream(resource)); }
[ "public", "Jar", "addClass", "(", "Class", "<", "?", ">", "clazz", ")", "throws", "IOException", "{", "final", "String", "resource", "=", "clazz", ".", "getName", "(", ")", ".", "replace", "(", "'", "'", ",", "'", "'", ")", "+", "\".class\"", ";", "return", "addEntry", "(", "resource", ",", "clazz", ".", "getClassLoader", "(", ")", ".", "getResourceAsStream", "(", "resource", ")", ")", ";", "}" ]
Adds a class entry to this JAR. @param clazz the class to add to the JAR. @return {@code this}
[ "Adds", "a", "class", "entry", "to", "this", "JAR", "." ]
291a54e501a32aaf0284707b8c1fbff6a566822b
https://github.com/puniverse/capsule/blob/291a54e501a32aaf0284707b8c1fbff6a566822b/capsule-util/src/main/java/co/paralleluniverse/capsule/Jar.java#L379-L382
163,194
puniverse/capsule
capsule-util/src/main/java/co/paralleluniverse/capsule/Jar.java
Jar.addPackageOf
public Jar addPackageOf(Class<?> clazz, Filter filter) throws IOException { try { final String path = clazz.getPackage().getName().replace('.', '/'); URL dirURL = clazz.getClassLoader().getResource(path); if (dirURL != null && dirURL.getProtocol().equals("file")) addDir(Paths.get(path), Paths.get(dirURL.toURI()), filter, false); else { if (dirURL == null) // In case of a jar file, we can't actually find a directory. dirURL = clazz.getClassLoader().getResource(clazz.getName().replace('.', '/') + ".class"); if (dirURL.getProtocol().equals("jar")) { final URI jarUri = new URI(dirURL.getPath().substring(0, dirURL.getPath().indexOf('!'))); try (JarInputStream jis1 = newJarInputStream(Files.newInputStream(Paths.get(jarUri)))) { for (JarEntry entry; (entry = jis1.getNextJarEntry()) != null;) { try { if (entry.getName().startsWith(path + '/')) { if (filter == null || filter.filter(entry.getName())) addEntryNoClose(jos, entry.getName(), jis1); } } catch (ZipException e) { if (!e.getMessage().startsWith("duplicate entry")) throw e; } } } } else throw new AssertionError(); } return this; } catch (URISyntaxException e) { throw new AssertionError(e); } }
java
public Jar addPackageOf(Class<?> clazz, Filter filter) throws IOException { try { final String path = clazz.getPackage().getName().replace('.', '/'); URL dirURL = clazz.getClassLoader().getResource(path); if (dirURL != null && dirURL.getProtocol().equals("file")) addDir(Paths.get(path), Paths.get(dirURL.toURI()), filter, false); else { if (dirURL == null) // In case of a jar file, we can't actually find a directory. dirURL = clazz.getClassLoader().getResource(clazz.getName().replace('.', '/') + ".class"); if (dirURL.getProtocol().equals("jar")) { final URI jarUri = new URI(dirURL.getPath().substring(0, dirURL.getPath().indexOf('!'))); try (JarInputStream jis1 = newJarInputStream(Files.newInputStream(Paths.get(jarUri)))) { for (JarEntry entry; (entry = jis1.getNextJarEntry()) != null;) { try { if (entry.getName().startsWith(path + '/')) { if (filter == null || filter.filter(entry.getName())) addEntryNoClose(jos, entry.getName(), jis1); } } catch (ZipException e) { if (!e.getMessage().startsWith("duplicate entry")) throw e; } } } } else throw new AssertionError(); } return this; } catch (URISyntaxException e) { throw new AssertionError(e); } }
[ "public", "Jar", "addPackageOf", "(", "Class", "<", "?", ">", "clazz", ",", "Filter", "filter", ")", "throws", "IOException", "{", "try", "{", "final", "String", "path", "=", "clazz", ".", "getPackage", "(", ")", ".", "getName", "(", ")", ".", "replace", "(", "'", "'", ",", "'", "'", ")", ";", "URL", "dirURL", "=", "clazz", ".", "getClassLoader", "(", ")", ".", "getResource", "(", "path", ")", ";", "if", "(", "dirURL", "!=", "null", "&&", "dirURL", ".", "getProtocol", "(", ")", ".", "equals", "(", "\"file\"", ")", ")", "addDir", "(", "Paths", ".", "get", "(", "path", ")", ",", "Paths", ".", "get", "(", "dirURL", ".", "toURI", "(", ")", ")", ",", "filter", ",", "false", ")", ";", "else", "{", "if", "(", "dirURL", "==", "null", ")", "// In case of a jar file, we can't actually find a directory.", "dirURL", "=", "clazz", ".", "getClassLoader", "(", ")", ".", "getResource", "(", "clazz", ".", "getName", "(", ")", ".", "replace", "(", "'", "'", ",", "'", "'", ")", "+", "\".class\"", ")", ";", "if", "(", "dirURL", ".", "getProtocol", "(", ")", ".", "equals", "(", "\"jar\"", ")", ")", "{", "final", "URI", "jarUri", "=", "new", "URI", "(", "dirURL", ".", "getPath", "(", ")", ".", "substring", "(", "0", ",", "dirURL", ".", "getPath", "(", ")", ".", "indexOf", "(", "'", "'", ")", ")", ")", ";", "try", "(", "JarInputStream", "jis1", "=", "newJarInputStream", "(", "Files", ".", "newInputStream", "(", "Paths", ".", "get", "(", "jarUri", ")", ")", ")", ")", "{", "for", "(", "JarEntry", "entry", ";", "(", "entry", "=", "jis1", ".", "getNextJarEntry", "(", ")", ")", "!=", "null", ";", ")", "{", "try", "{", "if", "(", "entry", ".", "getName", "(", ")", ".", "startsWith", "(", "path", "+", "'", "'", ")", ")", "{", "if", "(", "filter", "==", "null", "||", "filter", ".", "filter", "(", "entry", ".", "getName", "(", ")", ")", ")", "addEntryNoClose", "(", "jos", ",", "entry", ".", "getName", "(", ")", ",", "jis1", ")", ";", "}", "}", "catch", "(", "ZipException", "e", ")", "{", "if", "(", "!", "e", ".", "getMessage", "(", ")", ".", "startsWith", "(", "\"duplicate entry\"", ")", ")", "throw", "e", ";", "}", "}", "}", "}", "else", "throw", "new", "AssertionError", "(", ")", ";", "}", "return", "this", ";", "}", "catch", "(", "URISyntaxException", "e", ")", "{", "throw", "new", "AssertionError", "(", "e", ")", ";", "}", "}" ]
Adds the contents of a Java package to this JAR. @param clazz a class whose package we wish to add to the JAR. @param filter a filter to select particular classes @return {@code this}
[ "Adds", "the", "contents", "of", "a", "Java", "package", "to", "this", "JAR", "." ]
291a54e501a32aaf0284707b8c1fbff6a566822b
https://github.com/puniverse/capsule/blob/291a54e501a32aaf0284707b8c1fbff6a566822b/capsule-util/src/main/java/co/paralleluniverse/capsule/Jar.java#L487-L519
163,195
puniverse/capsule
capsule-util/src/main/java/co/paralleluniverse/capsule/Jar.java
Jar.setJarPrefix
public Jar setJarPrefix(String value) { verifyNotSealed(); if (jos != null) throw new IllegalStateException("Really executable cannot be set after entries are added."); if (value != null && jarPrefixFile != null) throw new IllegalStateException("A prefix has already been set (" + jarPrefixFile + ")"); this.jarPrefixStr = value; return this; }
java
public Jar setJarPrefix(String value) { verifyNotSealed(); if (jos != null) throw new IllegalStateException("Really executable cannot be set after entries are added."); if (value != null && jarPrefixFile != null) throw new IllegalStateException("A prefix has already been set (" + jarPrefixFile + ")"); this.jarPrefixStr = value; return this; }
[ "public", "Jar", "setJarPrefix", "(", "String", "value", ")", "{", "verifyNotSealed", "(", ")", ";", "if", "(", "jos", "!=", "null", ")", "throw", "new", "IllegalStateException", "(", "\"Really executable cannot be set after entries are added.\"", ")", ";", "if", "(", "value", "!=", "null", "&&", "jarPrefixFile", "!=", "null", ")", "throw", "new", "IllegalStateException", "(", "\"A prefix has already been set (\"", "+", "jarPrefixFile", "+", "\")\"", ")", ";", "this", ".", "jarPrefixStr", "=", "value", ";", "return", "this", ";", "}" ]
Sets a string that will be prepended to the JAR file's data. @param value the prefix, or {@code null} for none. @return {@code this}
[ "Sets", "a", "string", "that", "will", "be", "prepended", "to", "the", "JAR", "file", "s", "data", "." ]
291a54e501a32aaf0284707b8c1fbff6a566822b
https://github.com/puniverse/capsule/blob/291a54e501a32aaf0284707b8c1fbff6a566822b/capsule-util/src/main/java/co/paralleluniverse/capsule/Jar.java#L592-L600
163,196
puniverse/capsule
capsule-util/src/main/java/co/paralleluniverse/capsule/Jar.java
Jar.setJarPrefix
public Jar setJarPrefix(Path file) { verifyNotSealed(); if (jos != null) throw new IllegalStateException("Really executable cannot be set after entries are added."); if (file != null && jarPrefixStr != null) throw new IllegalStateException("A prefix has already been set (" + jarPrefixStr + ")"); this.jarPrefixFile = file; return this; }
java
public Jar setJarPrefix(Path file) { verifyNotSealed(); if (jos != null) throw new IllegalStateException("Really executable cannot be set after entries are added."); if (file != null && jarPrefixStr != null) throw new IllegalStateException("A prefix has already been set (" + jarPrefixStr + ")"); this.jarPrefixFile = file; return this; }
[ "public", "Jar", "setJarPrefix", "(", "Path", "file", ")", "{", "verifyNotSealed", "(", ")", ";", "if", "(", "jos", "!=", "null", ")", "throw", "new", "IllegalStateException", "(", "\"Really executable cannot be set after entries are added.\"", ")", ";", "if", "(", "file", "!=", "null", "&&", "jarPrefixStr", "!=", "null", ")", "throw", "new", "IllegalStateException", "(", "\"A prefix has already been set (\"", "+", "jarPrefixStr", "+", "\")\"", ")", ";", "this", ".", "jarPrefixFile", "=", "file", ";", "return", "this", ";", "}" ]
Sets a file whose contents will be prepended to the JAR file's data. @param file the prefix file, or {@code null} for none. @return {@code this}
[ "Sets", "a", "file", "whose", "contents", "will", "be", "prepended", "to", "the", "JAR", "file", "s", "data", "." ]
291a54e501a32aaf0284707b8c1fbff6a566822b
https://github.com/puniverse/capsule/blob/291a54e501a32aaf0284707b8c1fbff6a566822b/capsule-util/src/main/java/co/paralleluniverse/capsule/Jar.java#L608-L616
163,197
puniverse/capsule
capsule-util/src/main/java/co/paralleluniverse/capsule/Jar.java
Jar.write
public <T extends OutputStream> T write(T os) throws IOException { close(); if (!(this.os instanceof ByteArrayOutputStream)) throw new IllegalStateException("Cannot write to another target if setOutputStream has been called"); final byte[] content = ((ByteArrayOutputStream) this.os).toByteArray(); if (packer != null) packer.pack(new JarInputStream(new ByteArrayInputStream(content)), os); else os.write(content); os.close(); return os; }
java
public <T extends OutputStream> T write(T os) throws IOException { close(); if (!(this.os instanceof ByteArrayOutputStream)) throw new IllegalStateException("Cannot write to another target if setOutputStream has been called"); final byte[] content = ((ByteArrayOutputStream) this.os).toByteArray(); if (packer != null) packer.pack(new JarInputStream(new ByteArrayInputStream(content)), os); else os.write(content); os.close(); return os; }
[ "public", "<", "T", "extends", "OutputStream", ">", "T", "write", "(", "T", "os", ")", "throws", "IOException", "{", "close", "(", ")", ";", "if", "(", "!", "(", "this", ".", "os", "instanceof", "ByteArrayOutputStream", ")", ")", "throw", "new", "IllegalStateException", "(", "\"Cannot write to another target if setOutputStream has been called\"", ")", ";", "final", "byte", "[", "]", "content", "=", "(", "(", "ByteArrayOutputStream", ")", "this", ".", "os", ")", ".", "toByteArray", "(", ")", ";", "if", "(", "packer", "!=", "null", ")", "packer", ".", "pack", "(", "new", "JarInputStream", "(", "new", "ByteArrayInputStream", "(", "content", ")", ")", ",", "os", ")", ";", "else", "os", ".", "write", "(", "content", ")", ";", "os", ".", "close", "(", ")", ";", "return", "os", ";", "}" ]
Writes this JAR to an output stream, and closes the stream.
[ "Writes", "this", "JAR", "to", "an", "output", "stream", "and", "closes", "the", "stream", "." ]
291a54e501a32aaf0284707b8c1fbff6a566822b
https://github.com/puniverse/capsule/blob/291a54e501a32aaf0284707b8c1fbff6a566822b/capsule-util/src/main/java/co/paralleluniverse/capsule/Jar.java#L702-L716
163,198
puniverse/capsule
capsule-util/src/main/java/co/paralleluniverse/capsule/CapsuleLauncher.java
CapsuleLauncher.newCapsule
public Capsule newCapsule(String mode, Path wrappedJar) { final String oldMode = properties.getProperty(PROP_MODE); final ClassLoader oldCl = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(capsuleClass.getClassLoader()); try { setProperty(PROP_MODE, mode); final Constructor<?> ctor = accessible(capsuleClass.getDeclaredConstructor(Path.class)); final Object capsule = ctor.newInstance(jarFile); if (wrappedJar != null) { final Method setTarget = accessible(capsuleClass.getDeclaredMethod("setTarget", Path.class)); setTarget.invoke(capsule, wrappedJar); } return wrap(capsule); } catch (ReflectiveOperationException e) { throw new RuntimeException("Could not create capsule instance.", e); } finally { setProperty(PROP_MODE, oldMode); Thread.currentThread().setContextClassLoader(oldCl); } }
java
public Capsule newCapsule(String mode, Path wrappedJar) { final String oldMode = properties.getProperty(PROP_MODE); final ClassLoader oldCl = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(capsuleClass.getClassLoader()); try { setProperty(PROP_MODE, mode); final Constructor<?> ctor = accessible(capsuleClass.getDeclaredConstructor(Path.class)); final Object capsule = ctor.newInstance(jarFile); if (wrappedJar != null) { final Method setTarget = accessible(capsuleClass.getDeclaredMethod("setTarget", Path.class)); setTarget.invoke(capsule, wrappedJar); } return wrap(capsule); } catch (ReflectiveOperationException e) { throw new RuntimeException("Could not create capsule instance.", e); } finally { setProperty(PROP_MODE, oldMode); Thread.currentThread().setContextClassLoader(oldCl); } }
[ "public", "Capsule", "newCapsule", "(", "String", "mode", ",", "Path", "wrappedJar", ")", "{", "final", "String", "oldMode", "=", "properties", ".", "getProperty", "(", "PROP_MODE", ")", ";", "final", "ClassLoader", "oldCl", "=", "Thread", ".", "currentThread", "(", ")", ".", "getContextClassLoader", "(", ")", ";", "Thread", ".", "currentThread", "(", ")", ".", "setContextClassLoader", "(", "capsuleClass", ".", "getClassLoader", "(", ")", ")", ";", "try", "{", "setProperty", "(", "PROP_MODE", ",", "mode", ")", ";", "final", "Constructor", "<", "?", ">", "ctor", "=", "accessible", "(", "capsuleClass", ".", "getDeclaredConstructor", "(", "Path", ".", "class", ")", ")", ";", "final", "Object", "capsule", "=", "ctor", ".", "newInstance", "(", "jarFile", ")", ";", "if", "(", "wrappedJar", "!=", "null", ")", "{", "final", "Method", "setTarget", "=", "accessible", "(", "capsuleClass", ".", "getDeclaredMethod", "(", "\"setTarget\"", ",", "Path", ".", "class", ")", ")", ";", "setTarget", ".", "invoke", "(", "capsule", ",", "wrappedJar", ")", ";", "}", "return", "wrap", "(", "capsule", ")", ";", "}", "catch", "(", "ReflectiveOperationException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "\"Could not create capsule instance.\"", ",", "e", ")", ";", "}", "finally", "{", "setProperty", "(", "PROP_MODE", ",", "oldMode", ")", ";", "Thread", ".", "currentThread", "(", ")", ".", "setContextClassLoader", "(", "oldCl", ")", ";", "}", "}" ]
Creates a new capsule @param mode the capsule mode, or {@code null} for the default mode @param wrappedJar a path to a capsule JAR that will be launched (wrapped) by the empty capsule in {@code jarFile} or {@code null} if no wrapped capsule is wanted @return the capsule.
[ "Creates", "a", "new", "capsule" ]
291a54e501a32aaf0284707b8c1fbff6a566822b
https://github.com/puniverse/capsule/blob/291a54e501a32aaf0284707b8c1fbff6a566822b/capsule-util/src/main/java/co/paralleluniverse/capsule/CapsuleLauncher.java#L137-L159
163,199
puniverse/capsule
capsule-util/src/main/java/co/paralleluniverse/capsule/CapsuleLauncher.java
CapsuleLauncher.findJavaHomes
@SuppressWarnings("unchecked") public static Map<String, List<Path>> findJavaHomes() { try { return (Map<String, List<Path>>) accessible(Class.forName(CAPSULE_CLASS_NAME).getDeclaredMethod("getJavaHomes")).invoke(null); } catch (ReflectiveOperationException e) { throw new AssertionError(e); } }
java
@SuppressWarnings("unchecked") public static Map<String, List<Path>> findJavaHomes() { try { return (Map<String, List<Path>>) accessible(Class.forName(CAPSULE_CLASS_NAME).getDeclaredMethod("getJavaHomes")).invoke(null); } catch (ReflectiveOperationException e) { throw new AssertionError(e); } }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "static", "Map", "<", "String", ",", "List", "<", "Path", ">", ">", "findJavaHomes", "(", ")", "{", "try", "{", "return", "(", "Map", "<", "String", ",", "List", "<", "Path", ">", ">", ")", "accessible", "(", "Class", ".", "forName", "(", "CAPSULE_CLASS_NAME", ")", ".", "getDeclaredMethod", "(", "\"getJavaHomes\"", ")", ")", ".", "invoke", "(", "null", ")", ";", "}", "catch", "(", "ReflectiveOperationException", "e", ")", "{", "throw", "new", "AssertionError", "(", "e", ")", ";", "}", "}" ]
Returns all known Java installations @return a map from the version strings to their respective paths of the Java installations.
[ "Returns", "all", "known", "Java", "installations" ]
291a54e501a32aaf0284707b8c1fbff6a566822b
https://github.com/puniverse/capsule/blob/291a54e501a32aaf0284707b8c1fbff6a566822b/capsule-util/src/main/java/co/paralleluniverse/capsule/CapsuleLauncher.java#L257-L264