repo
stringlengths
7
58
path
stringlengths
12
218
func_name
stringlengths
3
140
original_string
stringlengths
73
34.1k
language
stringclasses
1 value
code
stringlengths
73
34.1k
code_tokens
list
docstring
stringlengths
3
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
105
339
partition
stringclasses
1 value
wcm-io/wcm-io-handler
media/src/main/java/io/wcm/handler/mediasource/inline/InlineRendition.java
InlineRendition.isMatchingFileExtension
private boolean isMatchingFileExtension() { String[] fileExtensions = mediaArgs.getFileExtensions(); if (fileExtensions == null || fileExtensions.length == 0) { return true; } for (String fileExtension : fileExtensions) { if (StringUtils.equalsIgnoreCase(fileExtension, getFileExtension())) { return true; } } return false; }
java
private boolean isMatchingFileExtension() { String[] fileExtensions = mediaArgs.getFileExtensions(); if (fileExtensions == null || fileExtensions.length == 0) { return true; } for (String fileExtension : fileExtensions) { if (StringUtils.equalsIgnoreCase(fileExtension, getFileExtension())) { return true; } } return false; }
[ "private", "boolean", "isMatchingFileExtension", "(", ")", "{", "String", "[", "]", "fileExtensions", "=", "mediaArgs", ".", "getFileExtensions", "(", ")", ";", "if", "(", "fileExtensions", "==", "null", "||", "fileExtensions", ".", "length", "==", "0", ")", ...
Checks if the file extension of the current binary matches with the requested extensions from the media args. @return true if file extension matches
[ "Checks", "if", "the", "file", "extension", "of", "the", "current", "binary", "matches", "with", "the", "requested", "extensions", "from", "the", "media", "args", "." ]
b0fc1c11a3ceb89efb73826dcfd480d6a00c19af
https://github.com/wcm-io/wcm-io-handler/blob/b0fc1c11a3ceb89efb73826dcfd480d6a00c19af/media/src/main/java/io/wcm/handler/mediasource/inline/InlineRendition.java#L309-L320
train
wcm-io/wcm-io-handler
media/src/main/java/io/wcm/handler/mediasource/inline/InlineRendition.java
InlineRendition.getRequestedDimension
private Dimension getRequestedDimension() { // check for fixed dimensions from media args if (mediaArgs.getFixedWidth() > 0 || mediaArgs.getFixedHeight() > 0) { return new Dimension(mediaArgs.getFixedWidth(), mediaArgs.getFixedHeight()); } // check for dimensions from mediaformat (evaluate only first media format) MediaFormat[] mediaFormats = mediaArgs.getMediaFormats(); if (mediaFormats != null && mediaFormats.length > 0) { Dimension dimension = mediaFormats[0].getMinDimension(); if (dimension != null) { return dimension; } } // fallback to 0/0 - no specific dimension requested return new Dimension(0, 0); }
java
private Dimension getRequestedDimension() { // check for fixed dimensions from media args if (mediaArgs.getFixedWidth() > 0 || mediaArgs.getFixedHeight() > 0) { return new Dimension(mediaArgs.getFixedWidth(), mediaArgs.getFixedHeight()); } // check for dimensions from mediaformat (evaluate only first media format) MediaFormat[] mediaFormats = mediaArgs.getMediaFormats(); if (mediaFormats != null && mediaFormats.length > 0) { Dimension dimension = mediaFormats[0].getMinDimension(); if (dimension != null) { return dimension; } } // fallback to 0/0 - no specific dimension requested return new Dimension(0, 0); }
[ "private", "Dimension", "getRequestedDimension", "(", ")", "{", "// check for fixed dimensions from media args", "if", "(", "mediaArgs", ".", "getFixedWidth", "(", ")", ">", "0", "||", "mediaArgs", ".", "getFixedHeight", "(", ")", ">", "0", ")", "{", "return", "...
Requested dimensions either from media format or fixed dimensions from media args. @return Requested dimensions
[ "Requested", "dimensions", "either", "from", "media", "format", "or", "fixed", "dimensions", "from", "media", "args", "." ]
b0fc1c11a3ceb89efb73826dcfd480d6a00c19af
https://github.com/wcm-io/wcm-io-handler/blob/b0fc1c11a3ceb89efb73826dcfd480d6a00c19af/media/src/main/java/io/wcm/handler/mediasource/inline/InlineRendition.java#L326-L344
train
wcm-io/wcm-io-handler
url/src/main/java/io/wcm/handler/url/suffix/SuffixParser.java
SuffixParser.getResources
public @NotNull List<Resource> getResources() { return getResources((Predicate<Resource>)null, (Resource)null); }
java
public @NotNull List<Resource> getResources() { return getResources((Predicate<Resource>)null, (Resource)null); }
[ "public", "@", "NotNull", "List", "<", "Resource", ">", "getResources", "(", ")", "{", "return", "getResources", "(", "(", "Predicate", "<", "Resource", ">", ")", "null", ",", "(", "Resource", ")", "null", ")", ";", "}" ]
Get the resources within the current page selected in the suffix of the URL @return a list containing the Resources
[ "Get", "the", "resources", "within", "the", "current", "page", "selected", "in", "the", "suffix", "of", "the", "URL" ]
b0fc1c11a3ceb89efb73826dcfd480d6a00c19af
https://github.com/wcm-io/wcm-io-handler/blob/b0fc1c11a3ceb89efb73826dcfd480d6a00c19af/url/src/main/java/io/wcm/handler/url/suffix/SuffixParser.java#L232-L234
train
wcm-io/wcm-io-handler
url/src/main/java/io/wcm/handler/url/suffix/SuffixBuilder.java
SuffixBuilder.build
public @NotNull String build() { SortedMap<String, Object> sortedParameterMap = new TreeMap<>(parameterMap); // gather resource paths in a treeset (having them in a defined order helps with caching) SortedSet<String> resourcePathsSet = new TreeSet<>(); // iterate over all parts that should be kept from the current request for (String nextPart : initialSuffixParts) { // if this is a key-value-part: if (nextPart.indexOf(KEY_VALUE_DELIMITER) > 0) { String key = decodeKey(nextPart); // decode and keep the part if it is not overridden in the given parameter-map if (!sortedParameterMap.containsKey(key)) { String value = decodeValue(nextPart); sortedParameterMap.put(key, value); } } else { // decode and keep the resource paths (unless they are specified again in resourcePaths) String path = decodeResourcePathPart(nextPart); if (!resourcePaths.contains(path)) { resourcePathsSet.add(path); } } } // copy the resources specified as parameters to the sorted set of paths if (resourcePaths != null) { resourcePathsSet.addAll(ImmutableList.copyOf(resourcePaths)); } // gather all suffix parts in this list List<String> suffixParts = new ArrayList<>(); // now encode all resource paths for (String path : resourcePathsSet) { suffixParts.add(encodeResourcePathPart(path)); } // now encode all entries from the parameter map for (Entry<String, Object> entry : sortedParameterMap.entrySet()) { Object value = entry.getValue(); if (value == null) { // don't add suffix part if value is null continue; } String encodedKey = encodeKeyValuePart(entry.getKey()); String encodedValue = encodeKeyValuePart(value.toString()); suffixParts.add(encodedKey + KEY_VALUE_DELIMITER + encodedValue); } // finally join these parts to a single string return StringUtils.join(suffixParts, SUFFIX_PART_DELIMITER); }
java
public @NotNull String build() { SortedMap<String, Object> sortedParameterMap = new TreeMap<>(parameterMap); // gather resource paths in a treeset (having them in a defined order helps with caching) SortedSet<String> resourcePathsSet = new TreeSet<>(); // iterate over all parts that should be kept from the current request for (String nextPart : initialSuffixParts) { // if this is a key-value-part: if (nextPart.indexOf(KEY_VALUE_DELIMITER) > 0) { String key = decodeKey(nextPart); // decode and keep the part if it is not overridden in the given parameter-map if (!sortedParameterMap.containsKey(key)) { String value = decodeValue(nextPart); sortedParameterMap.put(key, value); } } else { // decode and keep the resource paths (unless they are specified again in resourcePaths) String path = decodeResourcePathPart(nextPart); if (!resourcePaths.contains(path)) { resourcePathsSet.add(path); } } } // copy the resources specified as parameters to the sorted set of paths if (resourcePaths != null) { resourcePathsSet.addAll(ImmutableList.copyOf(resourcePaths)); } // gather all suffix parts in this list List<String> suffixParts = new ArrayList<>(); // now encode all resource paths for (String path : resourcePathsSet) { suffixParts.add(encodeResourcePathPart(path)); } // now encode all entries from the parameter map for (Entry<String, Object> entry : sortedParameterMap.entrySet()) { Object value = entry.getValue(); if (value == null) { // don't add suffix part if value is null continue; } String encodedKey = encodeKeyValuePart(entry.getKey()); String encodedValue = encodeKeyValuePart(value.toString()); suffixParts.add(encodedKey + KEY_VALUE_DELIMITER + encodedValue); } // finally join these parts to a single string return StringUtils.join(suffixParts, SUFFIX_PART_DELIMITER); }
[ "public", "@", "NotNull", "String", "build", "(", ")", "{", "SortedMap", "<", "String", ",", "Object", ">", "sortedParameterMap", "=", "new", "TreeMap", "<>", "(", "parameterMap", ")", ";", "// gather resource paths in a treeset (having them in a defined order helps wit...
Build complete suffix. @return the suffix
[ "Build", "complete", "suffix", "." ]
b0fc1c11a3ceb89efb73826dcfd480d6a00c19af
https://github.com/wcm-io/wcm-io-handler/blob/b0fc1c11a3ceb89efb73826dcfd480d6a00c19af/url/src/main/java/io/wcm/handler/url/suffix/SuffixBuilder.java#L294-L347
train
wcm-io/wcm-io-handler
url/src/main/java/io/wcm/handler/url/integrator/impl/IntegratorHandlerImpl.java
IntegratorHandlerImpl.detectIntegratorTemplateModes
private void detectIntegratorTemplateModes() { // integrator mode cannot be active if no modes defined if (urlHandlerConfig.getIntegratorModes().isEmpty()) { return; } if (request != null && RequestPath.hasSelector(request, SELECTOR_INTEGRATORTEMPLATE_SECURE)) { integratorTemplateSecureMode = true; } else if (request != null && RequestPath.hasSelector(request, SELECTOR_INTEGRATORTEMPLATE)) { integratorTemplateMode = true; } }
java
private void detectIntegratorTemplateModes() { // integrator mode cannot be active if no modes defined if (urlHandlerConfig.getIntegratorModes().isEmpty()) { return; } if (request != null && RequestPath.hasSelector(request, SELECTOR_INTEGRATORTEMPLATE_SECURE)) { integratorTemplateSecureMode = true; } else if (request != null && RequestPath.hasSelector(request, SELECTOR_INTEGRATORTEMPLATE)) { integratorTemplateMode = true; } }
[ "private", "void", "detectIntegratorTemplateModes", "(", ")", "{", "// integrator mode cannot be active if no modes defined", "if", "(", "urlHandlerConfig", ".", "getIntegratorModes", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "return", ";", "}", "if", "(", "requ...
Detect integrator template modes - check selectors in current url.
[ "Detect", "integrator", "template", "modes", "-", "check", "selectors", "in", "current", "url", "." ]
b0fc1c11a3ceb89efb73826dcfd480d6a00c19af
https://github.com/wcm-io/wcm-io-handler/blob/b0fc1c11a3ceb89efb73826dcfd480d6a00c19af/url/src/main/java/io/wcm/handler/url/integrator/impl/IntegratorHandlerImpl.java#L75-L86
train
wcm-io/wcm-io-handler
url/src/main/java/io/wcm/handler/url/integrator/impl/IntegratorHandlerImpl.java
IntegratorHandlerImpl.getIntegratorTemplateSelector
@Override public @NotNull String getIntegratorTemplateSelector() { if (currentPage != null && urlHandlerConfig.isIntegrator(currentPage)) { if (isResourceUrlSecure(currentPage)) { return SELECTOR_INTEGRATORTEMPLATE_SECURE; } else { return SELECTOR_INTEGRATORTEMPLATE; } } if (integratorTemplateSecureMode) { return SELECTOR_INTEGRATORTEMPLATE_SECURE; } else { return SELECTOR_INTEGRATORTEMPLATE; } }
java
@Override public @NotNull String getIntegratorTemplateSelector() { if (currentPage != null && urlHandlerConfig.isIntegrator(currentPage)) { if (isResourceUrlSecure(currentPage)) { return SELECTOR_INTEGRATORTEMPLATE_SECURE; } else { return SELECTOR_INTEGRATORTEMPLATE; } } if (integratorTemplateSecureMode) { return SELECTOR_INTEGRATORTEMPLATE_SECURE; } else { return SELECTOR_INTEGRATORTEMPLATE; } }
[ "@", "Override", "public", "@", "NotNull", "String", "getIntegratorTemplateSelector", "(", ")", "{", "if", "(", "currentPage", "!=", "null", "&&", "urlHandlerConfig", ".", "isIntegrator", "(", "currentPage", ")", ")", "{", "if", "(", "isResourceUrlSecure", "(", ...
Returns selector for integrator template mode. In HTTPS mode the secure selector is returned, otherwise the default selector. HTTPS mode is active if the current page is an integrator page and has simple mode-HTTPs activated, or the secure integrator mode selector is included in the current request. @return Integrator template selector
[ "Returns", "selector", "for", "integrator", "template", "mode", ".", "In", "HTTPS", "mode", "the", "secure", "selector", "is", "returned", "otherwise", "the", "default", "selector", ".", "HTTPS", "mode", "is", "active", "if", "the", "current", "page", "is", ...
b0fc1c11a3ceb89efb73826dcfd480d6a00c19af
https://github.com/wcm-io/wcm-io-handler/blob/b0fc1c11a3ceb89efb73826dcfd480d6a00c19af/url/src/main/java/io/wcm/handler/url/integrator/impl/IntegratorHandlerImpl.java#L113-L129
train
wcm-io/wcm-io-handler
url/src/main/java/io/wcm/handler/url/integrator/impl/IntegratorHandlerImpl.java
IntegratorHandlerImpl.getIntegratorMode
@SuppressWarnings("null") private @NotNull IntegratorMode getIntegratorMode(ValueMap properties) { IntegratorMode mode = null; Collection<IntegratorMode> integratorModes = urlHandlerConfig.getIntegratorModes(); String modeString = properties.get(IntegratorNameConstants.PN_INTEGRATOR_MODE, String.class); if (StringUtils.isNotEmpty(modeString)) { for (IntegratorMode candidate : integratorModes) { if (StringUtils.equals(modeString, candidate.getId())) { mode = candidate; break; } } } // fallback to first mode defined in configuration if (mode == null && !integratorModes.isEmpty()) { mode = integratorModes.iterator().next(); } return mode; }
java
@SuppressWarnings("null") private @NotNull IntegratorMode getIntegratorMode(ValueMap properties) { IntegratorMode mode = null; Collection<IntegratorMode> integratorModes = urlHandlerConfig.getIntegratorModes(); String modeString = properties.get(IntegratorNameConstants.PN_INTEGRATOR_MODE, String.class); if (StringUtils.isNotEmpty(modeString)) { for (IntegratorMode candidate : integratorModes) { if (StringUtils.equals(modeString, candidate.getId())) { mode = candidate; break; } } } // fallback to first mode defined in configuration if (mode == null && !integratorModes.isEmpty()) { mode = integratorModes.iterator().next(); } return mode; }
[ "@", "SuppressWarnings", "(", "\"null\"", ")", "private", "@", "NotNull", "IntegratorMode", "getIntegratorMode", "(", "ValueMap", "properties", ")", "{", "IntegratorMode", "mode", "=", "null", ";", "Collection", "<", "IntegratorMode", ">", "integratorModes", "=", ...
Read integrator mode from content container. Defaults to first integrator mode defined. @param properties Content container @return Integrator mode
[ "Read", "integrator", "mode", "from", "content", "container", ".", "Defaults", "to", "first", "integrator", "mode", "defined", "." ]
b0fc1c11a3ceb89efb73826dcfd480d6a00c19af
https://github.com/wcm-io/wcm-io-handler/blob/b0fc1c11a3ceb89efb73826dcfd480d6a00c19af/url/src/main/java/io/wcm/handler/url/integrator/impl/IntegratorHandlerImpl.java#L152-L170
train
wcm-io/wcm-io-handler
url/src/main/java/io/wcm/handler/url/integrator/impl/IntegratorHandlerImpl.java
IntegratorHandlerImpl.getIntegratorProtocol
@SuppressWarnings("null") private IntegratorProtocol getIntegratorProtocol(ValueMap properties) { IntegratorProtocol protocol = IntegratorProtocol.AUTO; try { String protocolString = properties.get(IntegratorNameConstants.PN_INTEGRATOR_PROTOCOL, String.class); if (StringUtils.isNotEmpty(protocolString)) { protocol = IntegratorProtocol.valueOf(protocolString.toUpperCase()); } } catch (IllegalArgumentException ex) { // ignore } return protocol; }
java
@SuppressWarnings("null") private IntegratorProtocol getIntegratorProtocol(ValueMap properties) { IntegratorProtocol protocol = IntegratorProtocol.AUTO; try { String protocolString = properties.get(IntegratorNameConstants.PN_INTEGRATOR_PROTOCOL, String.class); if (StringUtils.isNotEmpty(protocolString)) { protocol = IntegratorProtocol.valueOf(protocolString.toUpperCase()); } } catch (IllegalArgumentException ex) { // ignore } return protocol; }
[ "@", "SuppressWarnings", "(", "\"null\"", ")", "private", "IntegratorProtocol", "getIntegratorProtocol", "(", "ValueMap", "properties", ")", "{", "IntegratorProtocol", "protocol", "=", "IntegratorProtocol", ".", "AUTO", ";", "try", "{", "String", "protocolString", "="...
Read integrator protocol from content container. Default to AUTO. @param properties Content container @return Integrator protocol
[ "Read", "integrator", "protocol", "from", "content", "container", ".", "Default", "to", "AUTO", "." ]
b0fc1c11a3ceb89efb73826dcfd480d6a00c19af
https://github.com/wcm-io/wcm-io-handler/blob/b0fc1c11a3ceb89efb73826dcfd480d6a00c19af/url/src/main/java/io/wcm/handler/url/integrator/impl/IntegratorHandlerImpl.java#L177-L190
train
wcm-io/wcm-io-handler
url/src/main/java/io/wcm/handler/url/integrator/impl/IntegratorHandlerImpl.java
IntegratorHandlerImpl.isResourceUrlSecure
private boolean isResourceUrlSecure(Page page) { ValueMap props = getPagePropertiesNullSafe(page); IntegratorMode mode = getIntegratorMode(props); if (mode.isDetectProtocol()) { IntegratorProtocol integratorProtocol = getIntegratorProtocol(props); if (integratorProtocol == IntegratorProtocol.HTTPS) { return true; } else if (integratorProtocol == IntegratorProtocol.AUTO) { return RequestPath.hasSelector(request, IntegratorHandler.SELECTOR_INTEGRATORTEMPLATE_SECURE); } } return false; }
java
private boolean isResourceUrlSecure(Page page) { ValueMap props = getPagePropertiesNullSafe(page); IntegratorMode mode = getIntegratorMode(props); if (mode.isDetectProtocol()) { IntegratorProtocol integratorProtocol = getIntegratorProtocol(props); if (integratorProtocol == IntegratorProtocol.HTTPS) { return true; } else if (integratorProtocol == IntegratorProtocol.AUTO) { return RequestPath.hasSelector(request, IntegratorHandler.SELECTOR_INTEGRATORTEMPLATE_SECURE); } } return false; }
[ "private", "boolean", "isResourceUrlSecure", "(", "Page", "page", ")", "{", "ValueMap", "props", "=", "getPagePropertiesNullSafe", "(", "page", ")", ";", "IntegratorMode", "mode", "=", "getIntegratorMode", "(", "props", ")", ";", "if", "(", "mode", ".", "isDet...
Checks whether resource URLs should be rendered in secure mode or not. @return true if resource URLs should be rendered in secure mode
[ "Checks", "whether", "resource", "URLs", "should", "be", "rendered", "in", "secure", "mode", "or", "not", "." ]
b0fc1c11a3ceb89efb73826dcfd480d6a00c19af
https://github.com/wcm-io/wcm-io-handler/blob/b0fc1c11a3ceb89efb73826dcfd480d6a00c19af/url/src/main/java/io/wcm/handler/url/integrator/impl/IntegratorHandlerImpl.java#L196-L210
train
wcm-io/wcm-io-handler
link/src/main/java/io/wcm/handler/link/type/helpers/InternalLinkResolver.java
InternalLinkResolver.getTargetPage
private Page getTargetPage(String targetPath, InternalLinkResolverOptions options) { if (StringUtils.isEmpty(targetPath)) { return null; } // Rewrite target to current site context String rewrittenPath; if (options.isRewritePathToContext() && !useTargetContext(options)) { rewrittenPath = urlHandler.rewritePathToContext(SyntheticNavigatableResource.get(targetPath, resourceResolver)); } else { rewrittenPath = targetPath; } if (StringUtils.isEmpty(rewrittenPath)) { return null; } // Get target page referenced by target path and check for acceptance Page targetPage = pageManager.getPage(rewrittenPath); if (acceptPage(targetPage, options)) { return targetPage; } else { return null; } }
java
private Page getTargetPage(String targetPath, InternalLinkResolverOptions options) { if (StringUtils.isEmpty(targetPath)) { return null; } // Rewrite target to current site context String rewrittenPath; if (options.isRewritePathToContext() && !useTargetContext(options)) { rewrittenPath = urlHandler.rewritePathToContext(SyntheticNavigatableResource.get(targetPath, resourceResolver)); } else { rewrittenPath = targetPath; } if (StringUtils.isEmpty(rewrittenPath)) { return null; } // Get target page referenced by target path and check for acceptance Page targetPage = pageManager.getPage(rewrittenPath); if (acceptPage(targetPage, options)) { return targetPage; } else { return null; } }
[ "private", "Page", "getTargetPage", "(", "String", "targetPath", ",", "InternalLinkResolverOptions", "options", ")", "{", "if", "(", "StringUtils", ".", "isEmpty", "(", "targetPath", ")", ")", "{", "return", "null", ";", "}", "// Rewrite target to current site conte...
Returns the target page for the given internal content link reference. Checks validity of page. @param targetPath Repository path @return Target page or null if target reference is invalid.
[ "Returns", "the", "target", "page", "for", "the", "given", "internal", "content", "link", "reference", ".", "Checks", "validity", "of", "page", "." ]
b0fc1c11a3ceb89efb73826dcfd480d6a00c19af
https://github.com/wcm-io/wcm-io-handler/blob/b0fc1c11a3ceb89efb73826dcfd480d6a00c19af/link/src/main/java/io/wcm/handler/link/type/helpers/InternalLinkResolver.java#L244-L270
train
wcm-io/wcm-io-handler
link/src/main/java/io/wcm/handler/link/type/helpers/InternalLinkResolver.java
InternalLinkResolver.useTargetContext
private boolean useTargetContext(InternalLinkResolverOptions options) { if (options.isUseTargetContext() && !options.isRewritePathToContext()) { return true; } // even is use target context is not activated use it if current page is an experience fragment // otherwise it will be always impossible to resolve internal links else if (currentPage != null && Path.isExperienceFragmentPath(currentPage.getPath())) { return true; } return false; }
java
private boolean useTargetContext(InternalLinkResolverOptions options) { if (options.isUseTargetContext() && !options.isRewritePathToContext()) { return true; } // even is use target context is not activated use it if current page is an experience fragment // otherwise it will be always impossible to resolve internal links else if (currentPage != null && Path.isExperienceFragmentPath(currentPage.getPath())) { return true; } return false; }
[ "private", "boolean", "useTargetContext", "(", "InternalLinkResolverOptions", "options", ")", "{", "if", "(", "options", ".", "isUseTargetContext", "(", ")", "&&", "!", "options", ".", "isRewritePathToContext", "(", ")", ")", "{", "return", "true", ";", "}", "...
Checks if target context should be used. @param options Link resolver options @return true if target context should be used
[ "Checks", "if", "target", "context", "should", "be", "used", "." ]
b0fc1c11a3ceb89efb73826dcfd480d6a00c19af
https://github.com/wcm-io/wcm-io-handler/blob/b0fc1c11a3ceb89efb73826dcfd480d6a00c19af/link/src/main/java/io/wcm/handler/link/type/helpers/InternalLinkResolver.java#L277-L287
train
wcm-io/wcm-io-handler
commons/src/main/java/io/wcm/handler/commons/dom/HtmlElement.java
HtmlElement.addCssClass
public final T addCssClass(String value) { if (StringUtils.isNotEmpty(value)) { return setCssClass(StringUtils.isNotEmpty(getCssClass()) ? getCssClass() + " " + value : value); } else { return (T)this; } }
java
public final T addCssClass(String value) { if (StringUtils.isNotEmpty(value)) { return setCssClass(StringUtils.isNotEmpty(getCssClass()) ? getCssClass() + " " + value : value); } else { return (T)this; } }
[ "public", "final", "T", "addCssClass", "(", "String", "value", ")", "{", "if", "(", "StringUtils", ".", "isNotEmpty", "(", "value", ")", ")", "{", "return", "setCssClass", "(", "StringUtils", ".", "isNotEmpty", "(", "getCssClass", "(", ")", ")", "?", "ge...
Html "class" attribute. Adds a single, space-separated value while preserving existing ones. @param value Value of attribute @return Self reference
[ "Html", "class", "attribute", ".", "Adds", "a", "single", "space", "-", "separated", "value", "while", "preserving", "existing", "ones", "." ]
b0fc1c11a3ceb89efb73826dcfd480d6a00c19af
https://github.com/wcm-io/wcm-io-handler/blob/b0fc1c11a3ceb89efb73826dcfd480d6a00c19af/commons/src/main/java/io/wcm/handler/commons/dom/HtmlElement.java#L131-L138
train
wcm-io/wcm-io-handler
commons/src/main/java/io/wcm/handler/commons/dom/HtmlElement.java
HtmlElement.getStyles
public final Map<String, String> getStyles() { Map<String, String> styleMap = new HashMap<String, String>(); // de-serialize style string, fill style map String styleString = getStyleString(); if (styleString != null) { String[] styles = StringUtils.split(styleString, ";"); for (String styleSubString : styles) { String[] styleParts = StringUtils.split(styleSubString, ":"); if (styleParts.length > 1) { styleMap.put(styleParts[0].trim(), styleParts[1].trim()); } } } return styleMap; }
java
public final Map<String, String> getStyles() { Map<String, String> styleMap = new HashMap<String, String>(); // de-serialize style string, fill style map String styleString = getStyleString(); if (styleString != null) { String[] styles = StringUtils.split(styleString, ";"); for (String styleSubString : styles) { String[] styleParts = StringUtils.split(styleSubString, ":"); if (styleParts.length > 1) { styleMap.put(styleParts[0].trim(), styleParts[1].trim()); } } } return styleMap; }
[ "public", "final", "Map", "<", "String", ",", "String", ">", "getStyles", "(", ")", "{", "Map", "<", "String", ",", "String", ">", "styleMap", "=", "new", "HashMap", "<", "String", ",", "String", ">", "(", ")", ";", "// de-serialize style string, fill styl...
Html "style" attribute. @return Returns map of style key/value pairs.
[ "Html", "style", "attribute", "." ]
b0fc1c11a3ceb89efb73826dcfd480d6a00c19af
https://github.com/wcm-io/wcm-io-handler/blob/b0fc1c11a3ceb89efb73826dcfd480d6a00c19af/commons/src/main/java/io/wcm/handler/commons/dom/HtmlElement.java#L152-L168
train
wcm-io/wcm-io-handler
commons/src/main/java/io/wcm/handler/commons/dom/HtmlElement.java
HtmlElement.setStyle
public final T setStyle(String styleAttribute, String styleValue) { // Add style to style map Map<String, String> styleMap = getStyles(); styleMap.put(styleAttribute, styleValue); // Serialize style string StringBuilder styleString = new StringBuilder(); for (Map.Entry style : styleMap.entrySet()) { styleString.append(style.getKey()); styleString.append(':'); styleString.append(style.getValue()); styleString.append(';'); } setStyleString(styleString.toString()); return (T)this; }
java
public final T setStyle(String styleAttribute, String styleValue) { // Add style to style map Map<String, String> styleMap = getStyles(); styleMap.put(styleAttribute, styleValue); // Serialize style string StringBuilder styleString = new StringBuilder(); for (Map.Entry style : styleMap.entrySet()) { styleString.append(style.getKey()); styleString.append(':'); styleString.append(style.getValue()); styleString.append(';'); } setStyleString(styleString.toString()); return (T)this; }
[ "public", "final", "T", "setStyle", "(", "String", "styleAttribute", ",", "String", "styleValue", ")", "{", "// Add style to style map", "Map", "<", "String", ",", "String", ">", "styleMap", "=", "getStyles", "(", ")", ";", "styleMap", ".", "put", "(", "styl...
Html "style" attribute. Sets single style attribute value. @param styleAttribute Style attribute name @param styleValue Style attribute value @return Self reference
[ "Html", "style", "attribute", ".", "Sets", "single", "style", "attribute", "value", "." ]
b0fc1c11a3ceb89efb73826dcfd480d6a00c19af
https://github.com/wcm-io/wcm-io-handler/blob/b0fc1c11a3ceb89efb73826dcfd480d6a00c19af/commons/src/main/java/io/wcm/handler/commons/dom/HtmlElement.java#L195-L211
train
wcm-io/wcm-io-handler
media/src/main/java/io/wcm/handler/media/format/MediaFormat.java
MediaFormat.guessHumanReadableRatioString
private static String guessHumanReadableRatioString(double ratio, NumberFormat numberFormat) { for (long width = 1; width <= 50; width++) { double height = width / ratio; if (isLong(height)) { return numberFormat.format(width) + ":" + numberFormat.format(height); } } for (long width = 1; width <= 200; width++) { double height = width / 2d / ratio; if (isHalfLong(height)) { return numberFormat.format(width / 2d) + ":" + numberFormat.format(height); } } return null; }
java
private static String guessHumanReadableRatioString(double ratio, NumberFormat numberFormat) { for (long width = 1; width <= 50; width++) { double height = width / ratio; if (isLong(height)) { return numberFormat.format(width) + ":" + numberFormat.format(height); } } for (long width = 1; width <= 200; width++) { double height = width / 2d / ratio; if (isHalfLong(height)) { return numberFormat.format(width / 2d) + ":" + numberFormat.format(height); } } return null; }
[ "private", "static", "String", "guessHumanReadableRatioString", "(", "double", "ratio", ",", "NumberFormat", "numberFormat", ")", "{", "for", "(", "long", "width", "=", "1", ";", "width", "<=", "50", ";", "width", "++", ")", "{", "double", "height", "=", "...
Try to guess a nice human readable ratio string from the given decimal ratio @param ratio Ratio @param numberFormat Number format @return Ratio display string or null if no nice string was found
[ "Try", "to", "guess", "a", "nice", "human", "readable", "ratio", "string", "from", "the", "given", "decimal", "ratio" ]
b0fc1c11a3ceb89efb73826dcfd480d6a00c19af
https://github.com/wcm-io/wcm-io-handler/blob/b0fc1c11a3ceb89efb73826dcfd480d6a00c19af/media/src/main/java/io/wcm/handler/media/format/MediaFormat.java#L265-L279
train
wcm-io/wcm-io-handler
media/src/main/java/io/wcm/handler/media/format/MediaFormat.java
MediaFormat.getMinDimension
public Dimension getMinDimension() { long effWithMin = getEffectiveMinWidth(); long effHeightMin = getEffectiveMinHeight(); double effRatio = getRatio(); if (effWithMin == 0 && effHeightMin > 0 && effRatio > 0) { effWithMin = Math.round(effHeightMin * effRatio); } if (effWithMin > 0 && effHeightMin == 0 && effRatio > 0) { effHeightMin = Math.round(effWithMin / effRatio); } if (effWithMin > 0 || effHeightMin > 0) { return new Dimension(effWithMin, effHeightMin); } else { return null; } }
java
public Dimension getMinDimension() { long effWithMin = getEffectiveMinWidth(); long effHeightMin = getEffectiveMinHeight(); double effRatio = getRatio(); if (effWithMin == 0 && effHeightMin > 0 && effRatio > 0) { effWithMin = Math.round(effHeightMin * effRatio); } if (effWithMin > 0 && effHeightMin == 0 && effRatio > 0) { effHeightMin = Math.round(effWithMin / effRatio); } if (effWithMin > 0 || effHeightMin > 0) { return new Dimension(effWithMin, effHeightMin); } else { return null; } }
[ "public", "Dimension", "getMinDimension", "(", ")", "{", "long", "effWithMin", "=", "getEffectiveMinWidth", "(", ")", ";", "long", "effHeightMin", "=", "getEffectiveMinHeight", "(", ")", ";", "double", "effRatio", "=", "getRatio", "(", ")", ";", "if", "(", "...
Get minimum dimensions for media format. If only with or height is defined the missing dimensions is calculated from the ratio. If no ratio defined either only width or height dimension is returned. If neither width or height are defined null is returned. @return Min. dimensions or null
[ "Get", "minimum", "dimensions", "for", "media", "format", ".", "If", "only", "with", "or", "height", "is", "defined", "the", "missing", "dimensions", "is", "calculated", "from", "the", "ratio", ".", "If", "no", "ratio", "defined", "either", "only", "width", ...
b0fc1c11a3ceb89efb73826dcfd480d6a00c19af
https://github.com/wcm-io/wcm-io-handler/blob/b0fc1c11a3ceb89efb73826dcfd480d6a00c19af/media/src/main/java/io/wcm/handler/media/format/MediaFormat.java#L432-L450
train
wcm-io/wcm-io-handler
media/src/main/java/io/wcm/handler/media/impl/MediaFormatResolver.java
MediaFormatResolver.resolveByNames
private boolean resolveByNames(MediaArgs mediaArgs) { // resolved media formats already set? done. if (mediaArgs.getMediaFormats() != null) { return true; } // no media format names present? done. if (mediaArgs.getMediaFormatNames() == null) { return true; } String[] mediaFormatNames = mediaArgs.getMediaFormatNames(); MediaFormat[] mediaFormats = new MediaFormat[mediaFormatNames.length]; boolean resolutionSuccessful = true; for (int i = 0; i < mediaFormatNames.length; i++) { mediaFormats[i] = mediaFormatHandler.getMediaFormat(mediaFormatNames[i]); if (mediaFormats[i] == null) { log.warn("Media format name '" + mediaFormatNames[i] + "' is invalid."); resolutionSuccessful = false; } } mediaArgs.mediaFormats(mediaFormats); mediaArgs.mediaFormatNames((String[])null); return resolutionSuccessful; }
java
private boolean resolveByNames(MediaArgs mediaArgs) { // resolved media formats already set? done. if (mediaArgs.getMediaFormats() != null) { return true; } // no media format names present? done. if (mediaArgs.getMediaFormatNames() == null) { return true; } String[] mediaFormatNames = mediaArgs.getMediaFormatNames(); MediaFormat[] mediaFormats = new MediaFormat[mediaFormatNames.length]; boolean resolutionSuccessful = true; for (int i = 0; i < mediaFormatNames.length; i++) { mediaFormats[i] = mediaFormatHandler.getMediaFormat(mediaFormatNames[i]); if (mediaFormats[i] == null) { log.warn("Media format name '" + mediaFormatNames[i] + "' is invalid."); resolutionSuccessful = false; } } mediaArgs.mediaFormats(mediaFormats); mediaArgs.mediaFormatNames((String[])null); return resolutionSuccessful; }
[ "private", "boolean", "resolveByNames", "(", "MediaArgs", "mediaArgs", ")", "{", "// resolved media formats already set? done.", "if", "(", "mediaArgs", ".", "getMediaFormats", "(", ")", "!=", "null", ")", "{", "return", "true", ";", "}", "// no media format names pre...
Resolve media format names to media formats so all downstream logic has only to handle the resolved media formats. If resolving fails an exception is thrown. @param mediaArgs Media args @return true if resolution was successful.
[ "Resolve", "media", "format", "names", "to", "media", "formats", "so", "all", "downstream", "logic", "has", "only", "to", "handle", "the", "resolved", "media", "formats", ".", "If", "resolving", "fails", "an", "exception", "is", "thrown", "." ]
b0fc1c11a3ceb89efb73826dcfd480d6a00c19af
https://github.com/wcm-io/wcm-io-handler/blob/b0fc1c11a3ceb89efb73826dcfd480d6a00c19af/media/src/main/java/io/wcm/handler/media/impl/MediaFormatResolver.java#L69-L91
train
wcm-io/wcm-io-handler
media/src/main/java/io/wcm/handler/media/impl/MediaFormatResolver.java
MediaFormatResolver.addResponsiveImageMediaFormats
private boolean addResponsiveImageMediaFormats(MediaArgs mediaArgs) { Map<String, MediaFormat> additionalMediaFormats = new LinkedHashMap<>(); // check if additional on-the-fly generated media formats needs to be added for responsive image handling if (!resolveForImageSizes(mediaArgs, additionalMediaFormats)) { return false; } if (!resolveForResponsivePictureSources(mediaArgs, additionalMediaFormats)) { return false; } // if additional media formats where found add them to the media format list in media args if (!additionalMediaFormats.isEmpty()) { List<MediaFormat> allMediaFormats = new ArrayList<>(); if (mediaArgs.getMediaFormats() != null) { allMediaFormats.addAll(Arrays.asList(mediaArgs.getMediaFormats())); } allMediaFormats.addAll(additionalMediaFormats.values()); mediaArgs.mediaFormats(allMediaFormats.toArray(new MediaFormat[allMediaFormats.size()])); } return true; }
java
private boolean addResponsiveImageMediaFormats(MediaArgs mediaArgs) { Map<String, MediaFormat> additionalMediaFormats = new LinkedHashMap<>(); // check if additional on-the-fly generated media formats needs to be added for responsive image handling if (!resolveForImageSizes(mediaArgs, additionalMediaFormats)) { return false; } if (!resolveForResponsivePictureSources(mediaArgs, additionalMediaFormats)) { return false; } // if additional media formats where found add them to the media format list in media args if (!additionalMediaFormats.isEmpty()) { List<MediaFormat> allMediaFormats = new ArrayList<>(); if (mediaArgs.getMediaFormats() != null) { allMediaFormats.addAll(Arrays.asList(mediaArgs.getMediaFormats())); } allMediaFormats.addAll(additionalMediaFormats.values()); mediaArgs.mediaFormats(allMediaFormats.toArray(new MediaFormat[allMediaFormats.size()])); } return true; }
[ "private", "boolean", "addResponsiveImageMediaFormats", "(", "MediaArgs", "mediaArgs", ")", "{", "Map", "<", "String", ",", "MediaFormat", ">", "additionalMediaFormats", "=", "new", "LinkedHashMap", "<>", "(", ")", ";", "// check if additional on-the-fly generated media f...
Add on-the-fly generated media formats if required for responsive image handling via image sizes or picture sources. @param mediaArgs Media args @return true if resolution was successful
[ "Add", "on", "-", "the", "-", "fly", "generated", "media", "formats", "if", "required", "for", "responsive", "image", "handling", "via", "image", "sizes", "or", "picture", "sources", "." ]
b0fc1c11a3ceb89efb73826dcfd480d6a00c19af
https://github.com/wcm-io/wcm-io-handler/blob/b0fc1c11a3ceb89efb73826dcfd480d6a00c19af/media/src/main/java/io/wcm/handler/media/impl/MediaFormatResolver.java#L99-L121
train
wcm-io/wcm-io-handler
media/src/main/java/io/wcm/handler/mediasource/inline/InlineMediaSource.java
InlineMediaSource.getInlineAsset
private Asset getInlineAsset(Resource ntResourceResource, Media media, String fileName) { return new InlineAsset(ntResourceResource, media, fileName, adaptable); }
java
private Asset getInlineAsset(Resource ntResourceResource, Media media, String fileName) { return new InlineAsset(ntResourceResource, media, fileName, adaptable); }
[ "private", "Asset", "getInlineAsset", "(", "Resource", "ntResourceResource", ",", "Media", "media", ",", "String", "fileName", ")", "{", "return", "new", "InlineAsset", "(", "ntResourceResource", ",", "media", ",", "fileName", ",", "adaptable", ")", ";", "}" ]
Get implementation of inline media item @param ntResourceResource nt:resource node @param media Media metadata @param fileName File name @return Inline media item instance
[ "Get", "implementation", "of", "inline", "media", "item" ]
b0fc1c11a3ceb89efb73826dcfd480d6a00c19af
https://github.com/wcm-io/wcm-io-handler/blob/b0fc1c11a3ceb89efb73826dcfd480d6a00c19af/media/src/main/java/io/wcm/handler/mediasource/inline/InlineMediaSource.java#L170-L172
train
wcm-io/wcm-io-handler
media/src/main/java/io/wcm/handler/mediasource/inline/InlineMediaSource.java
InlineMediaSource.detectFileName
private String detectFileName(Resource referencedResource, Resource ntFileResource, Resource ntResourceResource) { // detect file name String fileName = null; // if referenced resource is not the nt:file node check for <nodename>Name property if (ntFileResource != null && !referencedResource.equals(ntFileResource)) { fileName = referencedResource.getValueMap().get(ntFileResource.getName() + "Name", String.class); } // if not nt:file node exists and the referenced resource is not the nt:resource node check for <nodename>Name property else if (ntFileResource == null && !referencedResource.equals(ntResourceResource)) { fileName = referencedResource.getValueMap().get(ntResourceResource.getName() + "Name", String.class); } // otherwise use node name of nt:file resource if it exists else if (ntFileResource != null) { fileName = ntFileResource.getName(); } // make sure filename has an extension, otherwise build virtual file name if (!StringUtils.contains(fileName, ".")) { fileName = null; } // if no filename found detect extension from mime type and build virtual filename if (StringUtils.isBlank(fileName)) { String fileExtension = null; if (ntResourceResource != null) { String mimeType = ntResourceResource.getValueMap().get(JcrConstants.JCR_MIMETYPE, String.class); if (StringUtils.isNotEmpty(mimeType) && mimeTypeService != null) { fileExtension = mimeTypeService.getExtension(mimeType); } } if (StringUtils.isEmpty(fileExtension)) { fileExtension = "bin"; } fileName = "file." + fileExtension; } return fileName; }
java
private String detectFileName(Resource referencedResource, Resource ntFileResource, Resource ntResourceResource) { // detect file name String fileName = null; // if referenced resource is not the nt:file node check for <nodename>Name property if (ntFileResource != null && !referencedResource.equals(ntFileResource)) { fileName = referencedResource.getValueMap().get(ntFileResource.getName() + "Name", String.class); } // if not nt:file node exists and the referenced resource is not the nt:resource node check for <nodename>Name property else if (ntFileResource == null && !referencedResource.equals(ntResourceResource)) { fileName = referencedResource.getValueMap().get(ntResourceResource.getName() + "Name", String.class); } // otherwise use node name of nt:file resource if it exists else if (ntFileResource != null) { fileName = ntFileResource.getName(); } // make sure filename has an extension, otherwise build virtual file name if (!StringUtils.contains(fileName, ".")) { fileName = null; } // if no filename found detect extension from mime type and build virtual filename if (StringUtils.isBlank(fileName)) { String fileExtension = null; if (ntResourceResource != null) { String mimeType = ntResourceResource.getValueMap().get(JcrConstants.JCR_MIMETYPE, String.class); if (StringUtils.isNotEmpty(mimeType) && mimeTypeService != null) { fileExtension = mimeTypeService.getExtension(mimeType); } } if (StringUtils.isEmpty(fileExtension)) { fileExtension = "bin"; } fileName = "file." + fileExtension; } return fileName; }
[ "private", "String", "detectFileName", "(", "Resource", "referencedResource", ",", "Resource", "ntFileResource", ",", "Resource", "ntResourceResource", ")", "{", "// detect file name", "String", "fileName", "=", "null", ";", "// if referenced resource is not the nt:file node ...
Detect filename for inline binary. @param referencedResource Resource that was referenced in media reference and may contain file name property. @param ntFileResource nt:file resource (optional, null if not existent) @param ntResourceResource nt:resource resource @return Detected or virtual filename. Never null.
[ "Detect", "filename", "for", "inline", "binary", "." ]
b0fc1c11a3ceb89efb73826dcfd480d6a00c19af
https://github.com/wcm-io/wcm-io-handler/blob/b0fc1c11a3ceb89efb73826dcfd480d6a00c19af/media/src/main/java/io/wcm/handler/mediasource/inline/InlineMediaSource.java#L181-L218
train
wcm-io/wcm-io-handler
media/src/main/java/io/wcm/handler/mediasource/inline/InlineMediaSource.java
InlineMediaSource.cleanupFileName
private String cleanupFileName(String fileName) { String processedFileName = fileName; // strip off path parts if (StringUtils.contains(processedFileName, "/")) { processedFileName = StringUtils.substringAfterLast(processedFileName, "/"); } if (StringUtils.contains(processedFileName, "\\")) { processedFileName = StringUtils.substringAfterLast(processedFileName, "\\"); } // make sure filename does not contain any invalid characters processedFileName = Escape.validFilename(processedFileName); return processedFileName; }
java
private String cleanupFileName(String fileName) { String processedFileName = fileName; // strip off path parts if (StringUtils.contains(processedFileName, "/")) { processedFileName = StringUtils.substringAfterLast(processedFileName, "/"); } if (StringUtils.contains(processedFileName, "\\")) { processedFileName = StringUtils.substringAfterLast(processedFileName, "\\"); } // make sure filename does not contain any invalid characters processedFileName = Escape.validFilename(processedFileName); return processedFileName; }
[ "private", "String", "cleanupFileName", "(", "String", "fileName", ")", "{", "String", "processedFileName", "=", "fileName", ";", "// strip off path parts", "if", "(", "StringUtils", ".", "contains", "(", "processedFileName", ",", "\"/\"", ")", ")", "{", "processe...
Make sure filename contains no invalid characters or path parts @param fileName File name @return Cleaned up file name
[ "Make", "sure", "filename", "contains", "no", "invalid", "characters", "or", "path", "parts" ]
b0fc1c11a3ceb89efb73826dcfd480d6a00c19af
https://github.com/wcm-io/wcm-io-handler/blob/b0fc1c11a3ceb89efb73826dcfd480d6a00c19af/media/src/main/java/io/wcm/handler/mediasource/inline/InlineMediaSource.java#L225-L240
train
wcm-io/wcm-io-handler
media/src/main/java/io/wcm/handler/media/format/impl/MediaFormatHandlerImpl.java
MediaFormatHandlerImpl.isRenditionMatchSizeSameBigger
private boolean isRenditionMatchSizeSameBigger(MediaFormat mediaFormat, MediaFormat mediaFormatRequested) { long widthRequested = mediaFormatRequested.getEffectiveMinWidth(); long heightRequested = mediaFormatRequested.getEffectiveMinHeight(); long widthMax = mediaFormat.getEffectiveMaxWidth(); long heightMax = mediaFormat.getEffectiveMaxHeight(); return ((widthMax >= widthRequested) || (widthMax == 0)) && ((heightMax >= heightRequested) || (heightMax == 0)); }
java
private boolean isRenditionMatchSizeSameBigger(MediaFormat mediaFormat, MediaFormat mediaFormatRequested) { long widthRequested = mediaFormatRequested.getEffectiveMinWidth(); long heightRequested = mediaFormatRequested.getEffectiveMinHeight(); long widthMax = mediaFormat.getEffectiveMaxWidth(); long heightMax = mediaFormat.getEffectiveMaxHeight(); return ((widthMax >= widthRequested) || (widthMax == 0)) && ((heightMax >= heightRequested) || (heightMax == 0)); }
[ "private", "boolean", "isRenditionMatchSizeSameBigger", "(", "MediaFormat", "mediaFormat", ",", "MediaFormat", "mediaFormatRequested", ")", "{", "long", "widthRequested", "=", "mediaFormatRequested", ".", "getEffectiveMinWidth", "(", ")", ";", "long", "heightRequested", "...
Checks if the given media format size is same size or bigger than the requested one. @param mediaFormat Media format @param mediaFormatRequested Requested media format @return true if media format is same size or bigger
[ "Checks", "if", "the", "given", "media", "format", "size", "is", "same", "size", "or", "bigger", "than", "the", "requested", "one", "." ]
b0fc1c11a3ceb89efb73826dcfd480d6a00c19af
https://github.com/wcm-io/wcm-io-handler/blob/b0fc1c11a3ceb89efb73826dcfd480d6a00c19af/media/src/main/java/io/wcm/handler/media/format/impl/MediaFormatHandlerImpl.java#L211-L220
train
wcm-io/wcm-io-handler
media/src/main/java/io/wcm/handler/media/format/impl/MediaFormatHandlerImpl.java
MediaFormatHandlerImpl.isRenditionMatchSizeSameSmaller
private boolean isRenditionMatchSizeSameSmaller(MediaFormat mediaFormat, MediaFormat mediaFormatRequested) { long widthRequested = mediaFormatRequested.getEffectiveMinWidth(); long heightRequested = mediaFormatRequested.getEffectiveMinHeight(); long widthMin = mediaFormat.getEffectiveMinWidth(); long heightMin = mediaFormat.getEffectiveMinHeight(); return widthMin <= widthRequested && heightMin <= heightRequested; }
java
private boolean isRenditionMatchSizeSameSmaller(MediaFormat mediaFormat, MediaFormat mediaFormatRequested) { long widthRequested = mediaFormatRequested.getEffectiveMinWidth(); long heightRequested = mediaFormatRequested.getEffectiveMinHeight(); long widthMin = mediaFormat.getEffectiveMinWidth(); long heightMin = mediaFormat.getEffectiveMinHeight(); return widthMin <= widthRequested && heightMin <= heightRequested; }
[ "private", "boolean", "isRenditionMatchSizeSameSmaller", "(", "MediaFormat", "mediaFormat", ",", "MediaFormat", "mediaFormatRequested", ")", "{", "long", "widthRequested", "=", "mediaFormatRequested", ".", "getEffectiveMinWidth", "(", ")", ";", "long", "heightRequested", ...
Checks if the given media format size is same size or smaller than the requested one. @param mediaFormat Media format @param mediaFormatRequested Requested media format @return true if media format is same size or smaller
[ "Checks", "if", "the", "given", "media", "format", "size", "is", "same", "size", "or", "smaller", "than", "the", "requested", "one", "." ]
b0fc1c11a3ceb89efb73826dcfd480d6a00c19af
https://github.com/wcm-io/wcm-io-handler/blob/b0fc1c11a3ceb89efb73826dcfd480d6a00c19af/media/src/main/java/io/wcm/handler/media/format/impl/MediaFormatHandlerImpl.java#L228-L236
train
wcm-io/wcm-io-handler
media/src/main/java/io/wcm/handler/media/format/impl/MediaFormatHandlerImpl.java
MediaFormatHandlerImpl.isRenditionMatchExtension
private boolean isRenditionMatchExtension(MediaFormat mediaFormat) { for (String extension : mediaFormat.getExtensions()) { if (FileExtension.isImage(extension)) { return true; } } return false; }
java
private boolean isRenditionMatchExtension(MediaFormat mediaFormat) { for (String extension : mediaFormat.getExtensions()) { if (FileExtension.isImage(extension)) { return true; } } return false; }
[ "private", "boolean", "isRenditionMatchExtension", "(", "MediaFormat", "mediaFormat", ")", "{", "for", "(", "String", "extension", ":", "mediaFormat", ".", "getExtensions", "(", ")", ")", "{", "if", "(", "FileExtension", ".", "isImage", "(", "extension", ")", ...
Checks if one of the extensions of the given media format are supported for renditions. @param mediaFormat Media format @return true if supported extension found
[ "Checks", "if", "one", "of", "the", "extensions", "of", "the", "given", "media", "format", "are", "supported", "for", "renditions", "." ]
b0fc1c11a3ceb89efb73826dcfd480d6a00c19af
https://github.com/wcm-io/wcm-io-handler/blob/b0fc1c11a3ceb89efb73826dcfd480d6a00c19af/media/src/main/java/io/wcm/handler/media/format/impl/MediaFormatHandlerImpl.java#L243-L250
train
wcm-io/wcm-io-handler
media/src/main/java/io/wcm/handler/mediasource/dam/impl/TransformedRenditionHandler.java
TransformedRenditionHandler.rotateSourceRenditions
private NavigableSet<RenditionMetadata> rotateSourceRenditions(Set<RenditionMetadata> candidates) { if (rotation == null) { return new TreeSet<>(candidates); } return candidates.stream() .map(rendition -> new VirtualTransformedRenditionMetadata(rendition.getRendition(), rotateMapWidth(rendition.getWidth(), rendition.getHeight()), rotateMapHeight(rendition.getWidth(), rendition.getHeight()), null, rotation)) .collect(Collectors.toCollection(TreeSet::new)); }
java
private NavigableSet<RenditionMetadata> rotateSourceRenditions(Set<RenditionMetadata> candidates) { if (rotation == null) { return new TreeSet<>(candidates); } return candidates.stream() .map(rendition -> new VirtualTransformedRenditionMetadata(rendition.getRendition(), rotateMapWidth(rendition.getWidth(), rendition.getHeight()), rotateMapHeight(rendition.getWidth(), rendition.getHeight()), null, rotation)) .collect(Collectors.toCollection(TreeSet::new)); }
[ "private", "NavigableSet", "<", "RenditionMetadata", ">", "rotateSourceRenditions", "(", "Set", "<", "RenditionMetadata", ">", "candidates", ")", "{", "if", "(", "rotation", "==", "null", ")", "{", "return", "new", "TreeSet", "<>", "(", "candidates", ")", ";",...
Rotates all source renditions if configured. @param candidates Candidate renditions @return Virtual-rotated and sorted candidate renditions
[ "Rotates", "all", "source", "renditions", "if", "configured", "." ]
b0fc1c11a3ceb89efb73826dcfd480d6a00c19af
https://github.com/wcm-io/wcm-io-handler/blob/b0fc1c11a3ceb89efb73826dcfd480d6a00c19af/media/src/main/java/io/wcm/handler/mediasource/dam/impl/TransformedRenditionHandler.java#L80-L90
train
wcm-io/wcm-io-handler
media/src/main/java/io/wcm/handler/mediasource/dam/impl/TransformedRenditionHandler.java
TransformedRenditionHandler.getCropRendition
private VirtualTransformedRenditionMetadata getCropRendition(NavigableSet<RenditionMetadata> candidates) { RenditionMetadata original = getOriginalRendition(); if (original == null) { return null; } Double scaleFactor = getCropScaleFactor(); CropDimension scaledCropDimension = new CropDimension( Math.round(cropDimension.getLeft() * scaleFactor), Math.round(cropDimension.getTop() * scaleFactor), Math.round(cropDimension.getWidth() * scaleFactor), Math.round(cropDimension.getHeight() * scaleFactor)); return new VirtualTransformedRenditionMetadata(original.getRendition(), rotateMapWidth(scaledCropDimension.getWidth(), scaledCropDimension.getHeight()), rotateMapHeight(scaledCropDimension.getWidth(), scaledCropDimension.getHeight()), scaledCropDimension, rotation); }
java
private VirtualTransformedRenditionMetadata getCropRendition(NavigableSet<RenditionMetadata> candidates) { RenditionMetadata original = getOriginalRendition(); if (original == null) { return null; } Double scaleFactor = getCropScaleFactor(); CropDimension scaledCropDimension = new CropDimension( Math.round(cropDimension.getLeft() * scaleFactor), Math.round(cropDimension.getTop() * scaleFactor), Math.round(cropDimension.getWidth() * scaleFactor), Math.round(cropDimension.getHeight() * scaleFactor)); return new VirtualTransformedRenditionMetadata(original.getRendition(), rotateMapWidth(scaledCropDimension.getWidth(), scaledCropDimension.getHeight()), rotateMapHeight(scaledCropDimension.getWidth(), scaledCropDimension.getHeight()), scaledCropDimension, rotation); }
[ "private", "VirtualTransformedRenditionMetadata", "getCropRendition", "(", "NavigableSet", "<", "RenditionMetadata", ">", "candidates", ")", "{", "RenditionMetadata", "original", "=", "getOriginalRendition", "(", ")", ";", "if", "(", "original", "==", "null", ")", "{"...
Searches for the biggest web-enabled rendition that matches the crop dimensions width and height or is bigger. @param candidates @return Rendition or null if no match found
[ "Searches", "for", "the", "biggest", "web", "-", "enabled", "rendition", "that", "matches", "the", "crop", "dimensions", "width", "and", "height", "or", "is", "bigger", "." ]
b0fc1c11a3ceb89efb73826dcfd480d6a00c19af
https://github.com/wcm-io/wcm-io-handler/blob/b0fc1c11a3ceb89efb73826dcfd480d6a00c19af/media/src/main/java/io/wcm/handler/mediasource/dam/impl/TransformedRenditionHandler.java#L97-L112
train
wcm-io/wcm-io-handler
media/src/main/java/io/wcm/handler/mediasource/dam/impl/TransformedRenditionHandler.java
TransformedRenditionHandler.getCropScaleFactor
private double getCropScaleFactor() { RenditionMetadata original = getOriginalRendition(); RenditionMetadata webEnabled = AutoCropping.getWebRenditionForCropping(getAsset()); if (original == null || webEnabled == null || original.getWidth() == 0 || webEnabled.getWidth() == 0) { return 1d; } return (double)original.getWidth() / (double)webEnabled.getWidth(); }
java
private double getCropScaleFactor() { RenditionMetadata original = getOriginalRendition(); RenditionMetadata webEnabled = AutoCropping.getWebRenditionForCropping(getAsset()); if (original == null || webEnabled == null || original.getWidth() == 0 || webEnabled.getWidth() == 0) { return 1d; } return (double)original.getWidth() / (double)webEnabled.getWidth(); }
[ "private", "double", "getCropScaleFactor", "(", ")", "{", "RenditionMetadata", "original", "=", "getOriginalRendition", "(", ")", ";", "RenditionMetadata", "webEnabled", "=", "AutoCropping", ".", "getWebRenditionForCropping", "(", "getAsset", "(", ")", ")", ";", "if...
The cropping coordinates are stored with coordinates relating to the web-enabled rendition. But we want to crop the original image, so we have to scale those values to match the coordinates in the original image. @return Scale factor
[ "The", "cropping", "coordinates", "are", "stored", "with", "coordinates", "relating", "to", "the", "web", "-", "enabled", "rendition", ".", "But", "we", "want", "to", "crop", "the", "original", "image", "so", "we", "have", "to", "scale", "those", "values", ...
b0fc1c11a3ceb89efb73826dcfd480d6a00c19af
https://github.com/wcm-io/wcm-io-handler/blob/b0fc1c11a3ceb89efb73826dcfd480d6a00c19af/media/src/main/java/io/wcm/handler/mediasource/dam/impl/TransformedRenditionHandler.java#L119-L126
train
wcm-io/wcm-io-handler
link/src/main/java/io/wcm/handler/link/type/helpers/SyntheticNavigatableResource.java
SyntheticNavigatableResource.get
static @NotNull Resource get(String path, ResourceResolver resolver) { Resource resource = resolver.getResource(path); if (resource != null) { return resource; } return new SyntheticNavigatableResource(path, resolver); }
java
static @NotNull Resource get(String path, ResourceResolver resolver) { Resource resource = resolver.getResource(path); if (resource != null) { return resource; } return new SyntheticNavigatableResource(path, resolver); }
[ "static", "@", "NotNull", "Resource", "get", "(", "String", "path", ",", "ResourceResolver", "resolver", ")", "{", "Resource", "resource", "=", "resolver", ".", "getResource", "(", "path", ")", ";", "if", "(", "resource", "!=", "null", ")", "{", "return", ...
Get resource for path. If the path does not exist a synthetic resource is created which supports navigation over it's parents until it reaches a resource that exists. @param path Path @return Resource (never null)
[ "Get", "resource", "for", "path", ".", "If", "the", "path", "does", "not", "exist", "a", "synthetic", "resource", "is", "created", "which", "supports", "navigation", "over", "it", "s", "parents", "until", "it", "reaches", "a", "resource", "that", "exists", ...
b0fc1c11a3ceb89efb73826dcfd480d6a00c19af
https://github.com/wcm-io/wcm-io-handler/blob/b0fc1c11a3ceb89efb73826dcfd480d6a00c19af/link/src/main/java/io/wcm/handler/link/type/helpers/SyntheticNavigatableResource.java#L87-L93
train
wcm-io/wcm-io-handler
media/src/main/java/io/wcm/handler/media/MediaArgs.java
MediaArgs.dragDropSupport
public @NotNull MediaArgs dragDropSupport(DragDropSupport value) { if (value == null) { throw new IllegalArgumentException("No null value allowed for drag&drop support."); } this.dragDropSupport = value; return this; }
java
public @NotNull MediaArgs dragDropSupport(DragDropSupport value) { if (value == null) { throw new IllegalArgumentException("No null value allowed for drag&drop support."); } this.dragDropSupport = value; return this; }
[ "public", "@", "NotNull", "MediaArgs", "dragDropSupport", "(", "DragDropSupport", "value", ")", "{", "if", "(", "value", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"No null value allowed for drag&drop support.\"", ")", ";", "}", "this...
Drag&amp;Drop support for media builder. @param value Drag&amp;Drop support @return this
[ "Drag&amp", ";", "Drop", "support", "for", "media", "builder", "." ]
b0fc1c11a3ceb89efb73826dcfd480d6a00c19af
https://github.com/wcm-io/wcm-io-handler/blob/b0fc1c11a3ceb89efb73826dcfd480d6a00c19af/media/src/main/java/io/wcm/handler/media/MediaArgs.java#L498-L504
train
wcm-io/wcm-io-handler
media/src/main/java/io/wcm/handler/media/impl/ImageFileServlet.java
ImageFileServlet.getImageFileName
public static String getImageFileName(String originalFilename) { String namePart = StringUtils.substringBeforeLast(originalFilename, "."); String extensionPart = StringUtils.substringAfterLast(originalFilename, "."); // use PNG format if original image is PNG, otherwise always use JPEG if (StringUtils.equalsIgnoreCase(extensionPart, FileExtension.PNG)) { extensionPart = FileExtension.PNG; } else { extensionPart = FileExtension.JPEG; } return namePart + "." + extensionPart; }
java
public static String getImageFileName(String originalFilename) { String namePart = StringUtils.substringBeforeLast(originalFilename, "."); String extensionPart = StringUtils.substringAfterLast(originalFilename, "."); // use PNG format if original image is PNG, otherwise always use JPEG if (StringUtils.equalsIgnoreCase(extensionPart, FileExtension.PNG)) { extensionPart = FileExtension.PNG; } else { extensionPart = FileExtension.JPEG; } return namePart + "." + extensionPart; }
[ "public", "static", "String", "getImageFileName", "(", "String", "originalFilename", ")", "{", "String", "namePart", "=", "StringUtils", ".", "substringBeforeLast", "(", "originalFilename", ",", "\".\"", ")", ";", "String", "extensionPart", "=", "StringUtils", ".", ...
Get image filename to be used for the URL with file extension matching the image format which is produced by this servlet. @param originalFilename Original filename of the image to render. @return Filename to be used for URL.
[ "Get", "image", "filename", "to", "be", "used", "for", "the", "URL", "with", "file", "extension", "matching", "the", "image", "format", "which", "is", "produced", "by", "this", "servlet", "." ]
b0fc1c11a3ceb89efb73826dcfd480d6a00c19af
https://github.com/wcm-io/wcm-io-handler/blob/b0fc1c11a3ceb89efb73826dcfd480d6a00c19af/media/src/main/java/io/wcm/handler/media/impl/ImageFileServlet.java#L155-L167
train
wcm-io/wcm-io-handler
richtext/src/main/java/io/wcm/handler/richtext/impl/DataPropertyUtil.java
DataPropertyUtil.toHtml5DataName
public static String toHtml5DataName(String headlessCamelCaseName) { if (StringUtils.isEmpty(headlessCamelCaseName)) { throw new IllegalArgumentException("Property name is empty."); } if (!isHeadlessCamelCaseName(headlessCamelCaseName)) { throw new IllegalArgumentException("This is not a valid headless camel case property name: " + headlessCamelCaseName); } StringBuilder html5DataName = new StringBuilder(HTML5_DATA_PREFIX); for (int i = 0; i < headlessCamelCaseName.length(); i++) { char c = headlessCamelCaseName.charAt(i); if (CharUtils.isAsciiAlphaUpper(c)) { html5DataName.append('-'); } html5DataName.append(Character.toLowerCase(c)); } return html5DataName.toString(); }
java
public static String toHtml5DataName(String headlessCamelCaseName) { if (StringUtils.isEmpty(headlessCamelCaseName)) { throw new IllegalArgumentException("Property name is empty."); } if (!isHeadlessCamelCaseName(headlessCamelCaseName)) { throw new IllegalArgumentException("This is not a valid headless camel case property name: " + headlessCamelCaseName); } StringBuilder html5DataName = new StringBuilder(HTML5_DATA_PREFIX); for (int i = 0; i < headlessCamelCaseName.length(); i++) { char c = headlessCamelCaseName.charAt(i); if (CharUtils.isAsciiAlphaUpper(c)) { html5DataName.append('-'); } html5DataName.append(Character.toLowerCase(c)); } return html5DataName.toString(); }
[ "public", "static", "String", "toHtml5DataName", "(", "String", "headlessCamelCaseName", ")", "{", "if", "(", "StringUtils", ".", "isEmpty", "(", "headlessCamelCaseName", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Property name is empty.\"", ")...
Converts a headless camel case property name to a HTML5 data attribute name including "data-" prefix. @param headlessCamelCaseName Headless camel case name @return HTML5 data attribute name @throws IllegalArgumentException If parameter name is not valid
[ "Converts", "a", "headless", "camel", "case", "property", "name", "to", "a", "HTML5", "data", "attribute", "name", "including", "data", "-", "prefix", "." ]
b0fc1c11a3ceb89efb73826dcfd480d6a00c19af
https://github.com/wcm-io/wcm-io-handler/blob/b0fc1c11a3ceb89efb73826dcfd480d6a00c19af/richtext/src/main/java/io/wcm/handler/richtext/impl/DataPropertyUtil.java#L47-L65
train
wcm-io/wcm-io-handler
richtext/src/main/java/io/wcm/handler/richtext/impl/DataPropertyUtil.java
DataPropertyUtil.toHeadlessCamelCaseName
public static String toHeadlessCamelCaseName(String html5DataName) { if (StringUtils.isEmpty(html5DataName)) { throw new IllegalArgumentException("Property name is empty."); } if (!isHtml5DataName(html5DataName)) { throw new IllegalArgumentException("This is not a valid HTML5 data property name: " + html5DataName); } String html5DataNameWithoutSuffix = StringUtils.substringAfter(html5DataName, HTML5_DATA_PREFIX); StringBuilder headlessCamelCaseName = new StringBuilder(); boolean upperCaseNext = false; for (int i = 0; i < html5DataNameWithoutSuffix.length(); i++) { char c = html5DataNameWithoutSuffix.charAt(i); if (c == '-') { upperCaseNext = true; } else if (upperCaseNext) { headlessCamelCaseName.append(Character.toUpperCase(c)); upperCaseNext = false; } else { headlessCamelCaseName.append(c); } } return headlessCamelCaseName.toString(); }
java
public static String toHeadlessCamelCaseName(String html5DataName) { if (StringUtils.isEmpty(html5DataName)) { throw new IllegalArgumentException("Property name is empty."); } if (!isHtml5DataName(html5DataName)) { throw new IllegalArgumentException("This is not a valid HTML5 data property name: " + html5DataName); } String html5DataNameWithoutSuffix = StringUtils.substringAfter(html5DataName, HTML5_DATA_PREFIX); StringBuilder headlessCamelCaseName = new StringBuilder(); boolean upperCaseNext = false; for (int i = 0; i < html5DataNameWithoutSuffix.length(); i++) { char c = html5DataNameWithoutSuffix.charAt(i); if (c == '-') { upperCaseNext = true; } else if (upperCaseNext) { headlessCamelCaseName.append(Character.toUpperCase(c)); upperCaseNext = false; } else { headlessCamelCaseName.append(c); } } return headlessCamelCaseName.toString(); }
[ "public", "static", "String", "toHeadlessCamelCaseName", "(", "String", "html5DataName", ")", "{", "if", "(", "StringUtils", ".", "isEmpty", "(", "html5DataName", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Property name is empty.\"", ")", ";"...
Converts a HTML5 data attribute name including "data-" prefix to a headless camel case name. @param html5DataName Html5 data attribute name @return Headless camel case name @throws IllegalArgumentException If parameter name is not valid
[ "Converts", "a", "HTML5", "data", "attribute", "name", "including", "data", "-", "prefix", "to", "a", "headless", "camel", "case", "name", "." ]
b0fc1c11a3ceb89efb73826dcfd480d6a00c19af
https://github.com/wcm-io/wcm-io-handler/blob/b0fc1c11a3ceb89efb73826dcfd480d6a00c19af/richtext/src/main/java/io/wcm/handler/richtext/impl/DataPropertyUtil.java#L73-L99
train
wcm-io/wcm-io-handler
commons/src/main/java/io/wcm/handler/commons/dom/AbstractElement.java
AbstractElement.setName
@Override @Deprecated public final org.jdom2.Element setName(String value) { return super.setName(value); }
java
@Override @Deprecated public final org.jdom2.Element setName(String value) { return super.setName(value); }
[ "@", "Override", "@", "Deprecated", "public", "final", "org", ".", "jdom2", ".", "Element", "setName", "(", "String", "value", ")", "{", "return", "super", ".", "setName", "(", "value", ")", ";", "}" ]
Sets element name - should not be used for HtmlElement-derived classes! @param value Element name @return Self reference @deprecated Deprecated
[ "Sets", "element", "name", "-", "should", "not", "be", "used", "for", "HtmlElement", "-", "derived", "classes!" ]
b0fc1c11a3ceb89efb73826dcfd480d6a00c19af
https://github.com/wcm-io/wcm-io-handler/blob/b0fc1c11a3ceb89efb73826dcfd480d6a00c19af/commons/src/main/java/io/wcm/handler/commons/dom/AbstractElement.java#L60-L64
train
wcm-io/wcm-io-handler
commons/src/main/java/io/wcm/handler/commons/dom/AbstractElement.java
AbstractElement.getAttributeValueAsInteger
public final int getAttributeValueAsInteger(String attributeName) { Attribute attribute = getAttribute(attributeName); if (attribute == null) { return 0; } else { try { return attribute.getIntValue(); } catch (DataConversionException ex) { return 0; } } }
java
public final int getAttributeValueAsInteger(String attributeName) { Attribute attribute = getAttribute(attributeName); if (attribute == null) { return 0; } else { try { return attribute.getIntValue(); } catch (DataConversionException ex) { return 0; } } }
[ "public", "final", "int", "getAttributeValueAsInteger", "(", "String", "attributeName", ")", "{", "Attribute", "attribute", "=", "getAttribute", "(", "attributeName", ")", ";", "if", "(", "attribute", "==", "null", ")", "{", "return", "0", ";", "}", "else", ...
Gets attribute value as integer. @param attributeName Attribute name @return Attribute value as integer or 0 if not set.
[ "Gets", "attribute", "value", "as", "integer", "." ]
b0fc1c11a3ceb89efb73826dcfd480d6a00c19af
https://github.com/wcm-io/wcm-io-handler/blob/b0fc1c11a3ceb89efb73826dcfd480d6a00c19af/commons/src/main/java/io/wcm/handler/commons/dom/AbstractElement.java#L71-L84
train
wcm-io/wcm-io-handler
commons/src/main/java/io/wcm/handler/commons/dom/AbstractElement.java
AbstractElement.setAttributeValueAsLong
public final T setAttributeValueAsLong(String name, long value) { setAttribute(name, Long.toString(value)); return (T)this; }
java
public final T setAttributeValueAsLong(String name, long value) { setAttribute(name, Long.toString(value)); return (T)this; }
[ "public", "final", "T", "setAttributeValueAsLong", "(", "String", "name", ",", "long", "value", ")", "{", "setAttribute", "(", "name", ",", "Long", ".", "toString", "(", "value", ")", ")", ";", "return", "(", "T", ")", "this", ";", "}" ]
Sets attribute value as long. @param name Attribute name @param value Attribute value as long @return Self reference
[ "Sets", "attribute", "value", "as", "long", "." ]
b0fc1c11a3ceb89efb73826dcfd480d6a00c19af
https://github.com/wcm-io/wcm-io-handler/blob/b0fc1c11a3ceb89efb73826dcfd480d6a00c19af/commons/src/main/java/io/wcm/handler/commons/dom/AbstractElement.java#L92-L95
train
wcm-io/wcm-io-handler
commons/src/main/java/io/wcm/handler/commons/dom/AbstractElement.java
AbstractElement.getAttributeValueAsLong
public final long getAttributeValueAsLong(String attributeName) { Attribute attribute = getAttribute(attributeName); if (attribute == null) { return 0; } else { try { return attribute.getLongValue(); } catch (DataConversionException ex) { return 0; } } }
java
public final long getAttributeValueAsLong(String attributeName) { Attribute attribute = getAttribute(attributeName); if (attribute == null) { return 0; } else { try { return attribute.getLongValue(); } catch (DataConversionException ex) { return 0; } } }
[ "public", "final", "long", "getAttributeValueAsLong", "(", "String", "attributeName", ")", "{", "Attribute", "attribute", "=", "getAttribute", "(", "attributeName", ")", ";", "if", "(", "attribute", "==", "null", ")", "{", "return", "0", ";", "}", "else", "{...
Gets attribute value as long. @param attributeName Attribute name @return Attribute value as long or 0 if not set.
[ "Gets", "attribute", "value", "as", "long", "." ]
b0fc1c11a3ceb89efb73826dcfd480d6a00c19af
https://github.com/wcm-io/wcm-io-handler/blob/b0fc1c11a3ceb89efb73826dcfd480d6a00c19af/commons/src/main/java/io/wcm/handler/commons/dom/AbstractElement.java#L102-L115
train
wcm-io/wcm-io-handler
commons/src/main/java/io/wcm/handler/commons/dom/AbstractElement.java
AbstractElement.setAttributeValueAsInteger
public final T setAttributeValueAsInteger(String name, int value) { setAttribute(name, Integer.toString(value)); return (T)this; }
java
public final T setAttributeValueAsInteger(String name, int value) { setAttribute(name, Integer.toString(value)); return (T)this; }
[ "public", "final", "T", "setAttributeValueAsInteger", "(", "String", "name", ",", "int", "value", ")", "{", "setAttribute", "(", "name", ",", "Integer", ".", "toString", "(", "value", ")", ")", ";", "return", "(", "T", ")", "this", ";", "}" ]
Sets attribute value as integer. @param name Attribute name @param value Attribute value as integer @return Self reference
[ "Sets", "attribute", "value", "as", "integer", "." ]
b0fc1c11a3ceb89efb73826dcfd480d6a00c19af
https://github.com/wcm-io/wcm-io-handler/blob/b0fc1c11a3ceb89efb73826dcfd480d6a00c19af/commons/src/main/java/io/wcm/handler/commons/dom/AbstractElement.java#L123-L126
train
wcm-io/wcm-io-handler
commons/src/main/java/io/wcm/handler/commons/dom/AbstractElement.java
AbstractElement.addContent
@Override public final org.jdom2.Element addContent(Content content) { // ignore empty elements if (content == null) { return null; } return super.addContent(content); }
java
@Override public final org.jdom2.Element addContent(Content content) { // ignore empty elements if (content == null) { return null; } return super.addContent(content); }
[ "@", "Override", "public", "final", "org", ".", "jdom2", ".", "Element", "addContent", "(", "Content", "content", ")", "{", "// ignore empty elements", "if", "(", "content", "==", "null", ")", "{", "return", "null", ";", "}", "return", "super", ".", "addCo...
Appends the child to the end of the element's content list @param content Child to append to end of content list. Null values are ignored. @return The element on which the method was called.
[ "Appends", "the", "child", "to", "the", "end", "of", "the", "element", "s", "content", "list" ]
b0fc1c11a3ceb89efb73826dcfd480d6a00c19af
https://github.com/wcm-io/wcm-io-handler/blob/b0fc1c11a3ceb89efb73826dcfd480d6a00c19af/commons/src/main/java/io/wcm/handler/commons/dom/AbstractElement.java#L133-L140
train
wcm-io/wcm-io-handler
commons/src/main/java/io/wcm/handler/commons/dom/AbstractElement.java
AbstractElement.addContent
@Override public final org.jdom2.Element addContent(Collection collection) { // ignore empty elements if (collection == null) { return null; } return super.addContent(collection); }
java
@Override public final org.jdom2.Element addContent(Collection collection) { // ignore empty elements if (collection == null) { return null; } return super.addContent(collection); }
[ "@", "Override", "public", "final", "org", ".", "jdom2", ".", "Element", "addContent", "(", "Collection", "collection", ")", "{", "// ignore empty elements", "if", "(", "collection", "==", "null", ")", "{", "return", "null", ";", "}", "return", "super", ".",...
Appends all children in the given collection to the end of the content list. In event of an exception during add the original content will be unchanged and the objects in the supplied collection will be unaltered. @param collection Collection to append. Null values are ignored. @return the element on which the method was called
[ "Appends", "all", "children", "in", "the", "given", "collection", "to", "the", "end", "of", "the", "content", "list", ".", "In", "event", "of", "an", "exception", "during", "add", "the", "original", "content", "will", "be", "unchanged", "and", "the", "obje...
b0fc1c11a3ceb89efb73826dcfd480d6a00c19af
https://github.com/wcm-io/wcm-io-handler/blob/b0fc1c11a3ceb89efb73826dcfd480d6a00c19af/commons/src/main/java/io/wcm/handler/commons/dom/AbstractElement.java#L177-L184
train
wcm-io/wcm-io-handler
richtext/src/main/java/io/wcm/handler/richtext/util/XHtmlEntityResolver.java
XHtmlEntityResolver.resolveEntity
@Override public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { String filename = xhtmlResourceMap.get(publicId); if (filename != null) { String resourceName = resourceFolder + "/" + filename; InputStream is = XHtmlEntityResolver.class.getResourceAsStream(resourceName); if (is == null) { throw new IOException("Resource '" + resourceName + "' not found in class path."); } return new InputSource(is); } return null; }
java
@Override public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { String filename = xhtmlResourceMap.get(publicId); if (filename != null) { String resourceName = resourceFolder + "/" + filename; InputStream is = XHtmlEntityResolver.class.getResourceAsStream(resourceName); if (is == null) { throw new IOException("Resource '" + resourceName + "' not found in class path."); } return new InputSource(is); } return null; }
[ "@", "Override", "public", "InputSource", "resolveEntity", "(", "String", "publicId", ",", "String", "systemId", ")", "throws", "SAXException", ",", "IOException", "{", "String", "filename", "=", "xhtmlResourceMap", ".", "get", "(", "publicId", ")", ";", "if", ...
Resolve XHtml resource entities, load from classpath resources.
[ "Resolve", "XHtml", "resource", "entities", "load", "from", "classpath", "resources", "." ]
b0fc1c11a3ceb89efb73826dcfd480d6a00c19af
https://github.com/wcm-io/wcm-io-handler/blob/b0fc1c11a3ceb89efb73826dcfd480d6a00c19af/richtext/src/main/java/io/wcm/handler/richtext/util/XHtmlEntityResolver.java#L61-L77
train
jenkinsci/favorite-plugin
src/main/java/hudson/plugins/favorite/user/FavoriteUserProperty.java
FavoriteUserProperty.readResolve
Object readResolve() { if (favorites != null) { data = Maps.newConcurrentMap(); for (String job : favorites) { data.put(job, true); } favorites = null; } return this; }
java
Object readResolve() { if (favorites != null) { data = Maps.newConcurrentMap(); for (String job : favorites) { data.put(job, true); } favorites = null; } return this; }
[ "Object", "readResolve", "(", ")", "{", "if", "(", "favorites", "!=", "null", ")", "{", "data", "=", "Maps", ".", "newConcurrentMap", "(", ")", ";", "for", "(", "String", "job", ":", "favorites", ")", "{", "data", ".", "put", "(", "job", ",", "true...
Migrates this properties storage from favourite's list to a map of booleans @return this
[ "Migrates", "this", "properties", "storage", "from", "favourite", "s", "list", "to", "a", "map", "of", "booleans" ]
4ce9b195b4d888190fe12c92d546d64f22728c22
https://github.com/jenkinsci/favorite-plugin/blob/4ce9b195b4d888190fe12c92d546d64f22728c22/src/main/java/hudson/plugins/favorite/user/FavoriteUserProperty.java#L129-L138
train
phax/peppol-directory
peppol-directory-indexer/src/main/java/com/helger/pd/indexer/index/IndexerWorkItemQueue.java
IndexerWorkItemQueue.stop
@Nonnull @ReturnsMutableCopy public ICommonsList <IIndexerWorkItem> stop () { // don't take any more actions m_aImmediateCollector.stopQueuingNewObjects (); // Get all remaining objects and save them for late reuse final ICommonsList <IIndexerWorkItem> aRemainingItems = m_aImmediateCollector.drainQueue (); // Shutdown the thread pool afterwards ExecutorServiceHelper.shutdownAndWaitUntilAllTasksAreFinished (m_aSenderThreadPool); return aRemainingItems; }
java
@Nonnull @ReturnsMutableCopy public ICommonsList <IIndexerWorkItem> stop () { // don't take any more actions m_aImmediateCollector.stopQueuingNewObjects (); // Get all remaining objects and save them for late reuse final ICommonsList <IIndexerWorkItem> aRemainingItems = m_aImmediateCollector.drainQueue (); // Shutdown the thread pool afterwards ExecutorServiceHelper.shutdownAndWaitUntilAllTasksAreFinished (m_aSenderThreadPool); return aRemainingItems; }
[ "@", "Nonnull", "@", "ReturnsMutableCopy", "public", "ICommonsList", "<", "IIndexerWorkItem", ">", "stop", "(", ")", "{", "// don't take any more actions", "m_aImmediateCollector", ".", "stopQueuingNewObjects", "(", ")", ";", "// Get all remaining objects and save them for la...
Stop the indexer work queue immediately. @return The list of all remaining objects in the queue. Never <code>null</code>.
[ "Stop", "the", "indexer", "work", "queue", "immediately", "." ]
98da26da29fb7178371d6b029516cbf01be223fb
https://github.com/phax/peppol-directory/blob/98da26da29fb7178371d6b029516cbf01be223fb/peppol-directory-indexer/src/main/java/com/helger/pd/indexer/index/IndexerWorkItemQueue.java#L83-L97
train
phax/peppol-directory
peppol-directory-indexer/src/main/java/com/helger/pd/indexer/index/IndexerWorkItemQueue.java
IndexerWorkItemQueue.queueObject
public void queueObject (@Nonnull final IIndexerWorkItem aItem) { ValueEnforcer.notNull (aItem, "Item"); m_aImmediateCollector.queueObject (aItem); }
java
public void queueObject (@Nonnull final IIndexerWorkItem aItem) { ValueEnforcer.notNull (aItem, "Item"); m_aImmediateCollector.queueObject (aItem); }
[ "public", "void", "queueObject", "(", "@", "Nonnull", "final", "IIndexerWorkItem", "aItem", ")", "{", "ValueEnforcer", ".", "notNull", "(", "aItem", ",", "\"Item\"", ")", ";", "m_aImmediateCollector", ".", "queueObject", "(", "aItem", ")", ";", "}" ]
Queue a work item and handle it asynchronously. @param aItem The item to be added. May not be <code>null</code>.
[ "Queue", "a", "work", "item", "and", "handle", "it", "asynchronously", "." ]
98da26da29fb7178371d6b029516cbf01be223fb
https://github.com/phax/peppol-directory/blob/98da26da29fb7178371d6b029516cbf01be223fb/peppol-directory-indexer/src/main/java/com/helger/pd/indexer/index/IndexerWorkItemQueue.java#L105-L109
train
phax/peppol-directory
peppol-directory-indexer/src/main/java/com/helger/pd/indexer/reindex/ReIndexWorkItemList.java
ReIndexWorkItemList.addItem
public void addItem (@Nonnull final ReIndexWorkItem aItem) throws IllegalStateException { ValueEnforcer.notNull (aItem, "Item"); m_aRWLock.writeLocked ( () -> { internalCreateItem (aItem); }); LOGGER.info ("Added " + aItem.getLogText () + " to re-try list for retry #" + (aItem.getRetryCount () + 1)); }
java
public void addItem (@Nonnull final ReIndexWorkItem aItem) throws IllegalStateException { ValueEnforcer.notNull (aItem, "Item"); m_aRWLock.writeLocked ( () -> { internalCreateItem (aItem); }); LOGGER.info ("Added " + aItem.getLogText () + " to re-try list for retry #" + (aItem.getRetryCount () + 1)); }
[ "public", "void", "addItem", "(", "@", "Nonnull", "final", "ReIndexWorkItem", "aItem", ")", "throws", "IllegalStateException", "{", "ValueEnforcer", ".", "notNull", "(", "aItem", ",", "\"Item\"", ")", ";", "m_aRWLock", ".", "writeLocked", "(", "(", ")", "->", ...
Add a unique item to the list. @param aItem The item to be added. May not be <code>null</code>. @throws IllegalStateException If an item with the same ID is already contained
[ "Add", "a", "unique", "item", "to", "the", "list", "." ]
98da26da29fb7178371d6b029516cbf01be223fb
https://github.com/phax/peppol-directory/blob/98da26da29fb7178371d6b029516cbf01be223fb/peppol-directory-indexer/src/main/java/com/helger/pd/indexer/reindex/ReIndexWorkItemList.java#L63-L70
train
phax/peppol-directory
peppol-directory-indexer/src/main/java/com/helger/pd/indexer/mgr/PDIndexerManager.java
PDIndexerManager._queueUniqueWorkItem
@Nonnull private EChange _queueUniqueWorkItem (@Nonnull final IIndexerWorkItem aWorkItem) { ValueEnforcer.notNull (aWorkItem, "WorkItem"); // Check for duplicate m_aRWLock.writeLock ().lock (); try { if (!m_aUniqueItems.add (aWorkItem)) { LOGGER.info ("Ignoring work item " + aWorkItem.getLogText () + " because it is already in the queue/re-index list!"); return EChange.UNCHANGED; } } finally { m_aRWLock.writeLock ().unlock (); } // Queue it m_aIndexerWorkQueue.queueObject (aWorkItem); LOGGER.info ("Queued work item " + aWorkItem.getLogText ()); // Remove the entry from the dead list to avoid spamming the dead list if (m_aDeadList.getAndRemoveEntry (x -> x.getWorkItem ().equals (aWorkItem)) != null) LOGGER.info ("Removed the new work item " + aWorkItem.getLogText () + " from the dead list"); return EChange.CHANGED; }
java
@Nonnull private EChange _queueUniqueWorkItem (@Nonnull final IIndexerWorkItem aWorkItem) { ValueEnforcer.notNull (aWorkItem, "WorkItem"); // Check for duplicate m_aRWLock.writeLock ().lock (); try { if (!m_aUniqueItems.add (aWorkItem)) { LOGGER.info ("Ignoring work item " + aWorkItem.getLogText () + " because it is already in the queue/re-index list!"); return EChange.UNCHANGED; } } finally { m_aRWLock.writeLock ().unlock (); } // Queue it m_aIndexerWorkQueue.queueObject (aWorkItem); LOGGER.info ("Queued work item " + aWorkItem.getLogText ()); // Remove the entry from the dead list to avoid spamming the dead list if (m_aDeadList.getAndRemoveEntry (x -> x.getWorkItem ().equals (aWorkItem)) != null) LOGGER.info ("Removed the new work item " + aWorkItem.getLogText () + " from the dead list"); return EChange.CHANGED; }
[ "@", "Nonnull", "private", "EChange", "_queueUniqueWorkItem", "(", "@", "Nonnull", "final", "IIndexerWorkItem", "aWorkItem", ")", "{", "ValueEnforcer", ".", "notNull", "(", "aWorkItem", ",", "\"WorkItem\"", ")", ";", "// Check for duplicate", "m_aRWLock", ".", "writ...
Queue a single work item of any type. If the item is already in the queue, it is ignored. @param aWorkItem Work item to be queued. May not be <code>null</code>. @return {@link EChange#CHANGED} if it was queued
[ "Queue", "a", "single", "work", "item", "of", "any", "type", ".", "If", "the", "item", "is", "already", "in", "the", "queue", "it", "is", "ignored", "." ]
98da26da29fb7178371d6b029516cbf01be223fb
https://github.com/phax/peppol-directory/blob/98da26da29fb7178371d6b029516cbf01be223fb/peppol-directory-indexer/src/main/java/com/helger/pd/indexer/mgr/PDIndexerManager.java#L209-L240
train
phax/peppol-directory
peppol-directory-indexer/src/main/java/com/helger/pd/indexer/mgr/PDIndexerManager.java
PDIndexerManager.queueWorkItem
@Nonnull public EChange queueWorkItem (@Nonnull final IParticipantIdentifier aParticipantID, @Nonnull final EIndexerWorkItemType eType, @Nonnull @Nonempty final String sOwnerID, @Nonnull @Nonempty final String sRequestingHost) { // Build item final IIndexerWorkItem aWorkItem = new IndexerWorkItem (aParticipantID, eType, sOwnerID, sRequestingHost); // And queue it return _queueUniqueWorkItem (aWorkItem); }
java
@Nonnull public EChange queueWorkItem (@Nonnull final IParticipantIdentifier aParticipantID, @Nonnull final EIndexerWorkItemType eType, @Nonnull @Nonempty final String sOwnerID, @Nonnull @Nonempty final String sRequestingHost) { // Build item final IIndexerWorkItem aWorkItem = new IndexerWorkItem (aParticipantID, eType, sOwnerID, sRequestingHost); // And queue it return _queueUniqueWorkItem (aWorkItem); }
[ "@", "Nonnull", "public", "EChange", "queueWorkItem", "(", "@", "Nonnull", "final", "IParticipantIdentifier", "aParticipantID", ",", "@", "Nonnull", "final", "EIndexerWorkItemType", "eType", ",", "@", "Nonnull", "@", "Nonempty", "final", "String", "sOwnerID", ",", ...
Queue a new work item @param aParticipantID Participant ID to use. @param eType Action type. @param sOwnerID Owner of this action @param sRequestingHost Requesting host (IP address) @return {@link EChange#UNCHANGED} if the item was queued, {@link EChange#UNCHANGED} if this item is already in the queue!
[ "Queue", "a", "new", "work", "item" ]
98da26da29fb7178371d6b029516cbf01be223fb
https://github.com/phax/peppol-directory/blob/98da26da29fb7178371d6b029516cbf01be223fb/peppol-directory-indexer/src/main/java/com/helger/pd/indexer/mgr/PDIndexerManager.java#L256-L266
train
phax/peppol-directory
peppol-directory-indexer/src/main/java/com/helger/pd/indexer/mgr/PDIndexerManager.java
PDIndexerManager.expireOldEntries
public void expireOldEntries () { // Expire old entries final ICommonsList <IReIndexWorkItem> aExpiredItems = m_aReIndexList.getAndRemoveAllEntries (IReIndexWorkItem::isExpired); if (aExpiredItems.isNotEmpty ()) { LOGGER.info ("Expiring " + aExpiredItems.size () + " re-index work items and move them to the dead list"); for (final IReIndexWorkItem aItem : aExpiredItems) { // remove them from the overall list but move to dead item list m_aRWLock.writeLocked ( () -> m_aUniqueItems.remove (aItem.getWorkItem ())); // move all to the dead item list m_aDeadList.addItem ((ReIndexWorkItem) aItem); LOGGER.info ("Added " + aItem.getLogText () + " to the dead list"); } } }
java
public void expireOldEntries () { // Expire old entries final ICommonsList <IReIndexWorkItem> aExpiredItems = m_aReIndexList.getAndRemoveAllEntries (IReIndexWorkItem::isExpired); if (aExpiredItems.isNotEmpty ()) { LOGGER.info ("Expiring " + aExpiredItems.size () + " re-index work items and move them to the dead list"); for (final IReIndexWorkItem aItem : aExpiredItems) { // remove them from the overall list but move to dead item list m_aRWLock.writeLocked ( () -> m_aUniqueItems.remove (aItem.getWorkItem ())); // move all to the dead item list m_aDeadList.addItem ((ReIndexWorkItem) aItem); LOGGER.info ("Added " + aItem.getLogText () + " to the dead list"); } } }
[ "public", "void", "expireOldEntries", "(", ")", "{", "// Expire old entries", "final", "ICommonsList", "<", "IReIndexWorkItem", ">", "aExpiredItems", "=", "m_aReIndexList", ".", "getAndRemoveAllEntries", "(", "IReIndexWorkItem", "::", "isExpired", ")", ";", "if", "(",...
Expire all re-index entries that are in the list for a too long time. This is called from a scheduled job only. All respective items are move from the re-index list to the dead list.
[ "Expire", "all", "re", "-", "index", "entries", "that", "are", "in", "the", "list", "for", "a", "too", "long", "time", ".", "This", "is", "called", "from", "a", "scheduled", "job", "only", ".", "All", "respective", "items", "are", "move", "from", "the"...
98da26da29fb7178371d6b029516cbf01be223fb
https://github.com/phax/peppol-directory/blob/98da26da29fb7178371d6b029516cbf01be223fb/peppol-directory-indexer/src/main/java/com/helger/pd/indexer/mgr/PDIndexerManager.java#L273-L291
train
phax/peppol-directory
peppol-directory-indexer/src/main/java/com/helger/pd/indexer/mgr/PDIndexerManager.java
PDIndexerManager.reIndexParticipantData
public void reIndexParticipantData () { final LocalDateTime aNow = PDTFactory.getCurrentLocalDateTime (); // Get and remove all items to re-index "now" final List <IReIndexWorkItem> aReIndexNowItems = m_aReIndexList.getAndRemoveAllEntries (aWorkItem -> aWorkItem.isRetryPossible (aNow)); if (LOGGER.isDebugEnabled ()) LOGGER.debug ("Re-indexing " + aReIndexNowItems.size () + " work items"); for (final IReIndexWorkItem aReIndexItem : aReIndexNowItems) { LOGGER.info ("Try to re-index " + aReIndexItem.getLogText ()); PDIndexExecutor.executeWorkItem (m_aStorageMgr, aReIndexItem.getWorkItem (), 1 + aReIndexItem.getRetryCount (), aSuccessItem -> _onReIndexSuccess (aSuccessItem), aFailureItem -> _onReIndexFailure (aReIndexItem)); } }
java
public void reIndexParticipantData () { final LocalDateTime aNow = PDTFactory.getCurrentLocalDateTime (); // Get and remove all items to re-index "now" final List <IReIndexWorkItem> aReIndexNowItems = m_aReIndexList.getAndRemoveAllEntries (aWorkItem -> aWorkItem.isRetryPossible (aNow)); if (LOGGER.isDebugEnabled ()) LOGGER.debug ("Re-indexing " + aReIndexNowItems.size () + " work items"); for (final IReIndexWorkItem aReIndexItem : aReIndexNowItems) { LOGGER.info ("Try to re-index " + aReIndexItem.getLogText ()); PDIndexExecutor.executeWorkItem (m_aStorageMgr, aReIndexItem.getWorkItem (), 1 + aReIndexItem.getRetryCount (), aSuccessItem -> _onReIndexSuccess (aSuccessItem), aFailureItem -> _onReIndexFailure (aReIndexItem)); } }
[ "public", "void", "reIndexParticipantData", "(", ")", "{", "final", "LocalDateTime", "aNow", "=", "PDTFactory", ".", "getCurrentLocalDateTime", "(", ")", ";", "// Get and remove all items to re-index \"now\"", "final", "List", "<", "IReIndexWorkItem", ">", "aReIndexNowIte...
Re-index all entries that are ready to be re-indexed now. This is called from a scheduled job only.
[ "Re", "-", "index", "all", "entries", "that", "are", "ready", "to", "be", "re", "-", "indexed", "now", ".", "This", "is", "called", "from", "a", "scheduled", "job", "only", "." ]
98da26da29fb7178371d6b029516cbf01be223fb
https://github.com/phax/peppol-directory/blob/98da26da29fb7178371d6b029516cbf01be223fb/peppol-directory-indexer/src/main/java/com/helger/pd/indexer/mgr/PDIndexerManager.java#L297-L317
train
phax/peppol-directory
peppol-directory-indexer/src/main/java/com/helger/pd/indexer/clientcert/ClientCertificateValidator.java
ClientCertificateValidator.verifyClientCertificate
@Nonnull public static ClientCertificateValidationResult verifyClientCertificate (@Nonnull final HttpServletRequest aHttpRequest, @Nonnull final String sLogPrefix) { if (s_bIsCheckDisabled.get ()) { if (LOGGER.isDebugEnabled ()) LOGGER.debug (sLogPrefix + "Client certificate is considered valid because the 'allow all' for tests is set!"); return ClientCertificateValidationResult.createSuccess (INSECURE_DEBUG_CLIENT); } // This is how to get client certificate from request final Object aValue = aHttpRequest.getAttribute ("javax.servlet.request.X509Certificate"); if (aValue == null) { if (LOGGER.isWarnEnabled ()) LOGGER.warn (sLogPrefix + "No client certificates present in the request"); return ClientCertificateValidationResult.createFailure (); } // type check if (!(aValue instanceof X509Certificate [])) throw new IllegalStateException ("Request value is not of type X509Certificate[] but of " + aValue.getClass ()); // Main checking final X509Certificate [] aRequestCerts = (X509Certificate []) aValue; if (ArrayHelper.isEmpty (aRequestCerts)) { // Empty array if (LOGGER.isWarnEnabled ()) LOGGER.warn (sLogPrefix + "No client certificates passed for validation"); return ClientCertificateValidationResult.createFailure (); } // OK, we have a non-empty, type checked Certificate array // TODO: determine CRLs final ICommonsList <CRL> aCRLs = new CommonsArrayList <> (); // Verify for "now" final LocalDateTime aVerificationDate = PDTFactory.getCurrentLocalDateTime (); // Search the certificate from the request matching our required issuers X509Certificate aClientCertToVerify = null; { for (final X509Certificate aCert : aRequestCerts) { final X500Principal aIssuer = aCert.getIssuerX500Principal (); if (s_aSearchIssuers.contains (aIssuer)) { if (LOGGER.isInfoEnabled ()) LOGGER.info (sLogPrefix + " Using the following client certificate issuer for verification: '" + aIssuer + "'"); aClientCertToVerify = aCert; break; } } // Do we have a certificate to verify? if (aClientCertToVerify == null) { throw new IllegalStateException ("Found no client certificate that was issued by one of the " + s_aSearchIssuers.size () + " required issuers. Provided certs are: " + Arrays.toString (aRequestCerts)); } } final String sClientID = getClientUniqueID (aClientCertToVerify); // This is the main verification process against the PEPPOL SMP root // certificate for (final X509Certificate aRootCert : s_aPeppolSMPRootCerts) { final String sVerifyErrorMsg = _verifyCertificate (aClientCertToVerify, aRootCert, aCRLs, aVerificationDate); if (sVerifyErrorMsg == null) { if (LOGGER.isInfoEnabled ()) LOGGER.info (sLogPrefix + " Passed client certificate is valid"); return ClientCertificateValidationResult.createSuccess (sClientID); } } if (LOGGER.isWarnEnabled ()) LOGGER.warn ("Client certificate is invalid: " + sClientID); return ClientCertificateValidationResult.createFailure (); }
java
@Nonnull public static ClientCertificateValidationResult verifyClientCertificate (@Nonnull final HttpServletRequest aHttpRequest, @Nonnull final String sLogPrefix) { if (s_bIsCheckDisabled.get ()) { if (LOGGER.isDebugEnabled ()) LOGGER.debug (sLogPrefix + "Client certificate is considered valid because the 'allow all' for tests is set!"); return ClientCertificateValidationResult.createSuccess (INSECURE_DEBUG_CLIENT); } // This is how to get client certificate from request final Object aValue = aHttpRequest.getAttribute ("javax.servlet.request.X509Certificate"); if (aValue == null) { if (LOGGER.isWarnEnabled ()) LOGGER.warn (sLogPrefix + "No client certificates present in the request"); return ClientCertificateValidationResult.createFailure (); } // type check if (!(aValue instanceof X509Certificate [])) throw new IllegalStateException ("Request value is not of type X509Certificate[] but of " + aValue.getClass ()); // Main checking final X509Certificate [] aRequestCerts = (X509Certificate []) aValue; if (ArrayHelper.isEmpty (aRequestCerts)) { // Empty array if (LOGGER.isWarnEnabled ()) LOGGER.warn (sLogPrefix + "No client certificates passed for validation"); return ClientCertificateValidationResult.createFailure (); } // OK, we have a non-empty, type checked Certificate array // TODO: determine CRLs final ICommonsList <CRL> aCRLs = new CommonsArrayList <> (); // Verify for "now" final LocalDateTime aVerificationDate = PDTFactory.getCurrentLocalDateTime (); // Search the certificate from the request matching our required issuers X509Certificate aClientCertToVerify = null; { for (final X509Certificate aCert : aRequestCerts) { final X500Principal aIssuer = aCert.getIssuerX500Principal (); if (s_aSearchIssuers.contains (aIssuer)) { if (LOGGER.isInfoEnabled ()) LOGGER.info (sLogPrefix + " Using the following client certificate issuer for verification: '" + aIssuer + "'"); aClientCertToVerify = aCert; break; } } // Do we have a certificate to verify? if (aClientCertToVerify == null) { throw new IllegalStateException ("Found no client certificate that was issued by one of the " + s_aSearchIssuers.size () + " required issuers. Provided certs are: " + Arrays.toString (aRequestCerts)); } } final String sClientID = getClientUniqueID (aClientCertToVerify); // This is the main verification process against the PEPPOL SMP root // certificate for (final X509Certificate aRootCert : s_aPeppolSMPRootCerts) { final String sVerifyErrorMsg = _verifyCertificate (aClientCertToVerify, aRootCert, aCRLs, aVerificationDate); if (sVerifyErrorMsg == null) { if (LOGGER.isInfoEnabled ()) LOGGER.info (sLogPrefix + " Passed client certificate is valid"); return ClientCertificateValidationResult.createSuccess (sClientID); } } if (LOGGER.isWarnEnabled ()) LOGGER.warn ("Client certificate is invalid: " + sClientID); return ClientCertificateValidationResult.createFailure (); }
[ "@", "Nonnull", "public", "static", "ClientCertificateValidationResult", "verifyClientCertificate", "(", "@", "Nonnull", "final", "HttpServletRequest", "aHttpRequest", ",", "@", "Nonnull", "final", "String", "sLogPrefix", ")", "{", "if", "(", "s_bIsCheckDisabled", ".", ...
Extract certificates from request and validate them. @param aHttpRequest The HTTP request to use. May not be <code>null</code>. @param sLogPrefix The context - for logging only. May not be <code>null</code>. @return Never <code>null</code>.
[ "Extract", "certificates", "from", "request", "and", "validate", "them", "." ]
98da26da29fb7178371d6b029516cbf01be223fb
https://github.com/phax/peppol-directory/blob/98da26da29fb7178371d6b029516cbf01be223fb/peppol-directory-indexer/src/main/java/com/helger/pd/indexer/clientcert/ClientCertificateValidator.java#L264-L351
train
phax/peppol-directory
peppol-directory-indexer/src/main/java/com/helger/pd/indexer/storage/PDStorageManager.java
PDStorageManager.getGroupedByParticipantID
@Nonnull @ReturnsMutableCopy public static IMultiMapListBased <IParticipantIdentifier, PDStoredBusinessEntity> getGroupedByParticipantID (@Nonnull final Iterable <PDStoredBusinessEntity> aDocs) { final MultiLinkedHashMapArrayListBased <IParticipantIdentifier, PDStoredBusinessEntity> ret = new MultiLinkedHashMapArrayListBased <> (); for (final PDStoredBusinessEntity aDoc : aDocs) ret.putSingle (aDoc.getParticipantID (), aDoc); return ret; }
java
@Nonnull @ReturnsMutableCopy public static IMultiMapListBased <IParticipantIdentifier, PDStoredBusinessEntity> getGroupedByParticipantID (@Nonnull final Iterable <PDStoredBusinessEntity> aDocs) { final MultiLinkedHashMapArrayListBased <IParticipantIdentifier, PDStoredBusinessEntity> ret = new MultiLinkedHashMapArrayListBased <> (); for (final PDStoredBusinessEntity aDoc : aDocs) ret.putSingle (aDoc.getParticipantID (), aDoc); return ret; }
[ "@", "Nonnull", "@", "ReturnsMutableCopy", "public", "static", "IMultiMapListBased", "<", "IParticipantIdentifier", ",", "PDStoredBusinessEntity", ">", "getGroupedByParticipantID", "(", "@", "Nonnull", "final", "Iterable", "<", "PDStoredBusinessEntity", ">", "aDocs", ")",...
Group the passed document list by participant ID @param aDocs The document list to group. @return A non-<code>null</code> ordered map with the results. Order is like the order of the input list.
[ "Group", "the", "passed", "document", "list", "by", "participant", "ID" ]
98da26da29fb7178371d6b029516cbf01be223fb
https://github.com/phax/peppol-directory/blob/98da26da29fb7178371d6b029516cbf01be223fb/peppol-directory-indexer/src/main/java/com/helger/pd/indexer/storage/PDStorageManager.java#L562-L570
train
phax/peppol-directory
peppol-directory-indexer/src/main/java/com/helger/pd/indexer/rest/IndexerResource.java
IndexerResource._checkClientCertificate
@Nonnull private static ClientCertificateValidationResult _checkClientCertificate (@Nonnull final HttpServletRequest aHttpServletRequest, @Nonnull final String sLogPrefix) { try { return ClientCertificateValidator.verifyClientCertificate (aHttpServletRequest, sLogPrefix); } catch (final RuntimeException ex) { if (LOGGER.isWarnEnabled ()) LOGGER.warn (sLogPrefix + "Error validating client certificate", ex); } return ClientCertificateValidationResult.createFailure (); }
java
@Nonnull private static ClientCertificateValidationResult _checkClientCertificate (@Nonnull final HttpServletRequest aHttpServletRequest, @Nonnull final String sLogPrefix) { try { return ClientCertificateValidator.verifyClientCertificate (aHttpServletRequest, sLogPrefix); } catch (final RuntimeException ex) { if (LOGGER.isWarnEnabled ()) LOGGER.warn (sLogPrefix + "Error validating client certificate", ex); } return ClientCertificateValidationResult.createFailure (); }
[ "@", "Nonnull", "private", "static", "ClientCertificateValidationResult", "_checkClientCertificate", "(", "@", "Nonnull", "final", "HttpServletRequest", "aHttpServletRequest", ",", "@", "Nonnull", "final", "String", "sLogPrefix", ")", "{", "try", "{", "return", "ClientC...
Check if the current request contains a client certificate and whether it is valid. @param aHttpServletRequest The current servlet request. May not be <code>null</code>. @param sLogPrefix The context - for logging only. May not be <code>null</code>. @return The validation result
[ "Check", "if", "the", "current", "request", "contains", "a", "client", "certificate", "and", "whether", "it", "is", "valid", "." ]
98da26da29fb7178371d6b029516cbf01be223fb
https://github.com/phax/peppol-directory/blob/98da26da29fb7178371d6b029516cbf01be223fb/peppol-directory-indexer/src/main/java/com/helger/pd/indexer/rest/IndexerResource.java#L64-L78
train
phax/peppol-directory
peppol-directory-indexer/src/main/java/com/helger/pd/indexer/reindex/ReIndexWorkItem.java
ReIndexWorkItem.incRetryCount
public void incRetryCount () { m_nRetries++; m_aPreviousRetryDT = PDTFactory.getCurrentLocalDateTime (); m_aNextRetryDT = m_aPreviousRetryDT.plusMinutes (PDServerConfiguration.getReIndexRetryMinutes ()); }
java
public void incRetryCount () { m_nRetries++; m_aPreviousRetryDT = PDTFactory.getCurrentLocalDateTime (); m_aNextRetryDT = m_aPreviousRetryDT.plusMinutes (PDServerConfiguration.getReIndexRetryMinutes ()); }
[ "public", "void", "incRetryCount", "(", ")", "{", "m_nRetries", "++", ";", "m_aPreviousRetryDT", "=", "PDTFactory", ".", "getCurrentLocalDateTime", "(", ")", ";", "m_aNextRetryDT", "=", "m_aPreviousRetryDT", ".", "plusMinutes", "(", "PDServerConfiguration", ".", "ge...
Increment the number of retries and update the previous and the next retry datetime.
[ "Increment", "the", "number", "of", "retries", "and", "update", "the", "previous", "and", "the", "next", "retry", "datetime", "." ]
98da26da29fb7178371d6b029516cbf01be223fb
https://github.com/phax/peppol-directory/blob/98da26da29fb7178371d6b029516cbf01be223fb/peppol-directory-indexer/src/main/java/com/helger/pd/indexer/reindex/ReIndexWorkItem.java#L138-L143
train
phax/peppol-directory
peppol-directory-indexer/src/main/java/com/helger/pd/indexer/lucene/PDLucene.java
PDLucene.getSearcher
@Nullable public IndexSearcher getSearcher () throws IOException { _checkClosing (); final IndexReader aReader = getReader (); if (aReader == null) { // Index not readable LOGGER.warn ("Index not readable"); return null; } if (m_aSearchReader == aReader) { // Reader did not change - use cached searcher assert m_aSearcher != null; } else { // Create new searcher only if necessary m_aSearchReader = aReader; m_aSearcher = new IndexSearcher (aReader); } return m_aSearcher; }
java
@Nullable public IndexSearcher getSearcher () throws IOException { _checkClosing (); final IndexReader aReader = getReader (); if (aReader == null) { // Index not readable LOGGER.warn ("Index not readable"); return null; } if (m_aSearchReader == aReader) { // Reader did not change - use cached searcher assert m_aSearcher != null; } else { // Create new searcher only if necessary m_aSearchReader = aReader; m_aSearcher = new IndexSearcher (aReader); } return m_aSearcher; }
[ "@", "Nullable", "public", "IndexSearcher", "getSearcher", "(", ")", "throws", "IOException", "{", "_checkClosing", "(", ")", ";", "final", "IndexReader", "aReader", "=", "getReader", "(", ")", ";", "if", "(", "aReader", "==", "null", ")", "{", "// Index not...
Get a searcher on this index. @return <code>null</code> if no reader or no searcher could be obtained @throws IOException On IO error
[ "Get", "a", "searcher", "on", "this", "index", "." ]
98da26da29fb7178371d6b029516cbf01be223fb
https://github.com/phax/peppol-directory/blob/98da26da29fb7178371d6b029516cbf01be223fb/peppol-directory-indexer/src/main/java/com/helger/pd/indexer/lucene/PDLucene.java#L264-L288
train
phax/peppol-directory
peppol-directory-indexer/src/main/java/com/helger/pd/indexer/lucene/PDLucene.java
PDLucene.updateDocuments
@MustBeLocked (ELockType.WRITE) public void updateDocuments (@Nullable final Term aDelTerm, @Nonnull final Iterable <? extends Iterable <? extends IndexableField>> aDocs) throws IOException { long nSeqNum; if (false) { // Delete and than add nSeqNum = _getWriter ().deleteDocuments (aDelTerm); nSeqNum = _getWriter ().updateDocuments (null, aDocs); } else { // Update directly nSeqNum = _getWriter ().updateDocuments (aDelTerm, aDocs); } if (LOGGER.isDebugEnabled ()) LOGGER.debug ("Last seq# after updateDocuments is " + nSeqNum); m_aWriterChanges.incrementAndGet (); }
java
@MustBeLocked (ELockType.WRITE) public void updateDocuments (@Nullable final Term aDelTerm, @Nonnull final Iterable <? extends Iterable <? extends IndexableField>> aDocs) throws IOException { long nSeqNum; if (false) { // Delete and than add nSeqNum = _getWriter ().deleteDocuments (aDelTerm); nSeqNum = _getWriter ().updateDocuments (null, aDocs); } else { // Update directly nSeqNum = _getWriter ().updateDocuments (aDelTerm, aDocs); } if (LOGGER.isDebugEnabled ()) LOGGER.debug ("Last seq# after updateDocuments is " + nSeqNum); m_aWriterChanges.incrementAndGet (); }
[ "@", "MustBeLocked", "(", "ELockType", ".", "WRITE", ")", "public", "void", "updateDocuments", "(", "@", "Nullable", "final", "Term", "aDelTerm", ",", "@", "Nonnull", "final", "Iterable", "<", "?", "extends", "Iterable", "<", "?", "extends", "IndexableField", ...
Atomically deletes documents matching the provided delTerm and adds a block of documents with sequentially assigned document IDs, such that an external reader will see all or none of the documents. @param aDelTerm the term to identify the document(s) to be deleted. May be <code>null</code>. @param aDocs the documents to be added. May not be <code>null</code>. @throws CorruptIndexException if the index is corrupt @throws IOException if there is a low-level IO error
[ "Atomically", "deletes", "documents", "matching", "the", "provided", "delTerm", "and", "adds", "a", "block", "of", "documents", "with", "sequentially", "assigned", "document", "IDs", "such", "that", "an", "external", "reader", "will", "see", "all", "or", "none",...
98da26da29fb7178371d6b029516cbf01be223fb
https://github.com/phax/peppol-directory/blob/98da26da29fb7178371d6b029516cbf01be223fb/peppol-directory-indexer/src/main/java/com/helger/pd/indexer/lucene/PDLucene.java#L331-L350
train
phax/peppol-directory
peppol-directory-indexer/src/main/java/com/helger/pd/indexer/lucene/PDLucene.java
PDLucene.writeLockedAtomic
@Nonnull public ESuccess writeLockedAtomic (@Nonnull final IThrowingRunnable <IOException> aRunnable) throws IOException { m_aRWLock.writeLock ().lock (); try { if (isClosing ()) { LOGGER.info ("Cannot executed something write locked, because Lucene is shutting down"); return ESuccess.FAILURE; } aRunnable.run (); } finally { m_aRWLock.writeLock ().unlock (); } return ESuccess.SUCCESS; }
java
@Nonnull public ESuccess writeLockedAtomic (@Nonnull final IThrowingRunnable <IOException> aRunnable) throws IOException { m_aRWLock.writeLock ().lock (); try { if (isClosing ()) { LOGGER.info ("Cannot executed something write locked, because Lucene is shutting down"); return ESuccess.FAILURE; } aRunnable.run (); } finally { m_aRWLock.writeLock ().unlock (); } return ESuccess.SUCCESS; }
[ "@", "Nonnull", "public", "ESuccess", "writeLockedAtomic", "(", "@", "Nonnull", "final", "IThrowingRunnable", "<", "IOException", ">", "aRunnable", ")", "throws", "IOException", "{", "m_aRWLock", ".", "writeLock", "(", ")", ".", "lock", "(", ")", ";", "try", ...
Run the provided action within a locked section. @param aRunnable Callback to be executed @return {@link ESuccess#FAILURE} if the index is just closing @throws IOException may be thrown by the callback
[ "Run", "the", "provided", "action", "within", "a", "locked", "section", "." ]
98da26da29fb7178371d6b029516cbf01be223fb
https://github.com/phax/peppol-directory/blob/98da26da29fb7178371d6b029516cbf01be223fb/peppol-directory-indexer/src/main/java/com/helger/pd/indexer/lucene/PDLucene.java#L381-L399
train
phax/peppol-directory
peppol-directory-indexer/src/main/java/com/helger/pd/indexer/storage/field/AbstractPDField.java
AbstractPDField.getDocValue
@Nullable public final NATIVE_TYPE getDocValue (@Nonnull final Document aDoc) { final IndexableField aField = getDocField (aDoc); if (aField != null) return getFieldNativeValue (aField); return null; }
java
@Nullable public final NATIVE_TYPE getDocValue (@Nonnull final Document aDoc) { final IndexableField aField = getDocField (aDoc); if (aField != null) return getFieldNativeValue (aField); return null; }
[ "@", "Nullable", "public", "final", "NATIVE_TYPE", "getDocValue", "(", "@", "Nonnull", "final", "Document", "aDoc", ")", "{", "final", "IndexableField", "aField", "=", "getDocField", "(", "aDoc", ")", ";", "if", "(", "aField", "!=", "null", ")", "return", ...
Get the value of this field in the provided document @param aDoc The Lucene result document @return <code>null</code> if no such field is present, the stored value otherwise.
[ "Get", "the", "value", "of", "this", "field", "in", "the", "provided", "document" ]
98da26da29fb7178371d6b029516cbf01be223fb
https://github.com/phax/peppol-directory/blob/98da26da29fb7178371d6b029516cbf01be223fb/peppol-directory-indexer/src/main/java/com/helger/pd/indexer/storage/field/AbstractPDField.java#L142-L149
train
phax/peppol-directory
peppol-directory-businesscard/src/main/java/com/helger/pd/businesscard/helper/PDBusinessCardHelper.java
PDBusinessCardHelper.parseBusinessCard
@Nullable public static PDBusinessCard parseBusinessCard (@Nonnull final byte [] aData, @Nullable final Charset aCharset) { ValueEnforcer.notNull (aData, "Data"); { // Read version 1 final PD1BusinessCardMarshaller aMarshaller1 = new PD1BusinessCardMarshaller (); aMarshaller1.readExceptionCallbacks ().removeAll (); if (aCharset != null) aMarshaller1.setCharset (aCharset); final PD1BusinessCardType aBC1 = aMarshaller1.read (aData); if (aBC1 != null) try { return PD1APIHelper.createBusinessCard (aBC1); } catch (final IllegalArgumentException ex) { // If the BC does not adhere to the XSD // Happens if e.g. name is null return null; } } { // Read as version 2 final PD2BusinessCardMarshaller aMarshaller2 = new PD2BusinessCardMarshaller (); aMarshaller2.readExceptionCallbacks ().removeAll (); if (aCharset != null) aMarshaller2.setCharset (aCharset); final PD2BusinessCardType aBC2 = aMarshaller2.read (aData); if (aBC2 != null) try { return PD2APIHelper.createBusinessCard (aBC2); } catch (final IllegalArgumentException ex) { // If the BC does not adhere to the XSD // Happens if e.g. name is null return null; } } { // Read as version 3 final PD3BusinessCardMarshaller aMarshaller3 = new PD3BusinessCardMarshaller (); aMarshaller3.readExceptionCallbacks ().removeAll (); if (aCharset != null) aMarshaller3.setCharset (aCharset); final PD3BusinessCardType aBC3 = aMarshaller3.read (aData); if (aBC3 != null) try { return PD3APIHelper.createBusinessCard (aBC3); } catch (final IllegalArgumentException ex) { // If the BC does not adhere to the XSD // Happens if e.g. name is null return null; } } // Unsupported version return null; }
java
@Nullable public static PDBusinessCard parseBusinessCard (@Nonnull final byte [] aData, @Nullable final Charset aCharset) { ValueEnforcer.notNull (aData, "Data"); { // Read version 1 final PD1BusinessCardMarshaller aMarshaller1 = new PD1BusinessCardMarshaller (); aMarshaller1.readExceptionCallbacks ().removeAll (); if (aCharset != null) aMarshaller1.setCharset (aCharset); final PD1BusinessCardType aBC1 = aMarshaller1.read (aData); if (aBC1 != null) try { return PD1APIHelper.createBusinessCard (aBC1); } catch (final IllegalArgumentException ex) { // If the BC does not adhere to the XSD // Happens if e.g. name is null return null; } } { // Read as version 2 final PD2BusinessCardMarshaller aMarshaller2 = new PD2BusinessCardMarshaller (); aMarshaller2.readExceptionCallbacks ().removeAll (); if (aCharset != null) aMarshaller2.setCharset (aCharset); final PD2BusinessCardType aBC2 = aMarshaller2.read (aData); if (aBC2 != null) try { return PD2APIHelper.createBusinessCard (aBC2); } catch (final IllegalArgumentException ex) { // If the BC does not adhere to the XSD // Happens if e.g. name is null return null; } } { // Read as version 3 final PD3BusinessCardMarshaller aMarshaller3 = new PD3BusinessCardMarshaller (); aMarshaller3.readExceptionCallbacks ().removeAll (); if (aCharset != null) aMarshaller3.setCharset (aCharset); final PD3BusinessCardType aBC3 = aMarshaller3.read (aData); if (aBC3 != null) try { return PD3APIHelper.createBusinessCard (aBC3); } catch (final IllegalArgumentException ex) { // If the BC does not adhere to the XSD // Happens if e.g. name is null return null; } } // Unsupported version return null; }
[ "@", "Nullable", "public", "static", "PDBusinessCard", "parseBusinessCard", "(", "@", "Nonnull", "final", "byte", "[", "]", "aData", ",", "@", "Nullable", "final", "Charset", "aCharset", ")", "{", "ValueEnforcer", ".", "notNull", "(", "aData", ",", "\"Data\"",...
A generic reading API to read all supported versions of the BusinessCard from a byte array and an optional character set. @param aData Bytes to read. May not be <code>null</code>. @param aCharset Character set to use. May be <code>null</code> in which case the XML character set determination takes place. @return <code>null</code> if parsing fails.
[ "A", "generic", "reading", "API", "to", "read", "all", "supported", "versions", "of", "the", "BusinessCard", "from", "a", "byte", "array", "and", "an", "optional", "character", "set", "." ]
98da26da29fb7178371d6b029516cbf01be223fb
https://github.com/phax/peppol-directory/blob/98da26da29fb7178371d6b029516cbf01be223fb/peppol-directory-businesscard/src/main/java/com/helger/pd/businesscard/helper/PDBusinessCardHelper.java#L61-L128
train
phax/peppol-directory
peppol-directory-businesscard/src/main/java/com/helger/pd/businesscard/helper/PDBusinessCardHelper.java
PDBusinessCardHelper.parseBusinessCard
@Nullable public static PDBusinessCard parseBusinessCard (@Nonnull final Node aNode) { ValueEnforcer.notNull (aNode, "Node"); { // Read version 1 final PD1BusinessCardMarshaller aMarshaller1 = new PD1BusinessCardMarshaller (); aMarshaller1.readExceptionCallbacks ().removeAll (); final PD1BusinessCardType aBC1 = aMarshaller1.read (aNode); if (aBC1 != null) try { return PD1APIHelper.createBusinessCard (aBC1); } catch (final IllegalArgumentException ex) { // If the BC does not adhere to the XSD // Happens if e.g. name is null return null; } } { // Read as version 2 final PD2BusinessCardMarshaller aMarshaller2 = new PD2BusinessCardMarshaller (); aMarshaller2.readExceptionCallbacks ().removeAll (); final PD2BusinessCardType aBC2 = aMarshaller2.read (aNode); if (aBC2 != null) try { return PD2APIHelper.createBusinessCard (aBC2); } catch (final IllegalArgumentException ex) { // If the BC does not adhere to the XSD // Happens if e.g. name is null return null; } } { // Read as version 3 final PD3BusinessCardMarshaller aMarshaller3 = new PD3BusinessCardMarshaller (); aMarshaller3.readExceptionCallbacks ().removeAll (); final PD3BusinessCardType aBC3 = aMarshaller3.read (aNode); if (aBC3 != null) try { return PD3APIHelper.createBusinessCard (aBC3); } catch (final IllegalArgumentException ex) { // If the BC does not adhere to the XSD // Happens if e.g. name is null return null; } } // Unsupported version return null; }
java
@Nullable public static PDBusinessCard parseBusinessCard (@Nonnull final Node aNode) { ValueEnforcer.notNull (aNode, "Node"); { // Read version 1 final PD1BusinessCardMarshaller aMarshaller1 = new PD1BusinessCardMarshaller (); aMarshaller1.readExceptionCallbacks ().removeAll (); final PD1BusinessCardType aBC1 = aMarshaller1.read (aNode); if (aBC1 != null) try { return PD1APIHelper.createBusinessCard (aBC1); } catch (final IllegalArgumentException ex) { // If the BC does not adhere to the XSD // Happens if e.g. name is null return null; } } { // Read as version 2 final PD2BusinessCardMarshaller aMarshaller2 = new PD2BusinessCardMarshaller (); aMarshaller2.readExceptionCallbacks ().removeAll (); final PD2BusinessCardType aBC2 = aMarshaller2.read (aNode); if (aBC2 != null) try { return PD2APIHelper.createBusinessCard (aBC2); } catch (final IllegalArgumentException ex) { // If the BC does not adhere to the XSD // Happens if e.g. name is null return null; } } { // Read as version 3 final PD3BusinessCardMarshaller aMarshaller3 = new PD3BusinessCardMarshaller (); aMarshaller3.readExceptionCallbacks ().removeAll (); final PD3BusinessCardType aBC3 = aMarshaller3.read (aNode); if (aBC3 != null) try { return PD3APIHelper.createBusinessCard (aBC3); } catch (final IllegalArgumentException ex) { // If the BC does not adhere to the XSD // Happens if e.g. name is null return null; } } // Unsupported version return null; }
[ "@", "Nullable", "public", "static", "PDBusinessCard", "parseBusinessCard", "(", "@", "Nonnull", "final", "Node", "aNode", ")", "{", "ValueEnforcer", ".", "notNull", "(", "aNode", ",", "\"Node\"", ")", ";", "{", "// Read version 1", "final", "PD1BusinessCardMarsha...
A generic reading API to read all supported versions of the BusinessCard from a DOM node. @param aNode Pre-parsed XML node to read. May not be <code>null</code>. @return <code>null</code> if parsing fails. @since 0.7.2
[ "A", "generic", "reading", "API", "to", "read", "all", "supported", "versions", "of", "the", "BusinessCard", "from", "a", "DOM", "node", "." ]
98da26da29fb7178371d6b029516cbf01be223fb
https://github.com/phax/peppol-directory/blob/98da26da29fb7178371d6b029516cbf01be223fb/peppol-directory-businesscard/src/main/java/com/helger/pd/businesscard/helper/PDBusinessCardHelper.java#L139-L200
train
phax/peppol-directory
peppol-directory-indexer/src/main/java/com/helger/pd/indexer/clientcert/ClientCertificateValidationResult.java
ClientCertificateValidationResult.createSuccess
@Nonnull public static ClientCertificateValidationResult createSuccess (@Nonnull @Nonempty final String sClientID) { ValueEnforcer.notEmpty (sClientID, "ClientID"); return new ClientCertificateValidationResult (true, sClientID); }
java
@Nonnull public static ClientCertificateValidationResult createSuccess (@Nonnull @Nonempty final String sClientID) { ValueEnforcer.notEmpty (sClientID, "ClientID"); return new ClientCertificateValidationResult (true, sClientID); }
[ "@", "Nonnull", "public", "static", "ClientCertificateValidationResult", "createSuccess", "(", "@", "Nonnull", "@", "Nonempty", "final", "String", "sClientID", ")", "{", "ValueEnforcer", ".", "notEmpty", "(", "sClientID", ",", "\"ClientID\"", ")", ";", "return", "...
Create client certificate validation success @param sClientID Client ID to use. May neither be <code>null</code> nor empty. @return Never <code>null</code>.
[ "Create", "client", "certificate", "validation", "success" ]
98da26da29fb7178371d6b029516cbf01be223fb
https://github.com/phax/peppol-directory/blob/98da26da29fb7178371d6b029516cbf01be223fb/peppol-directory-indexer/src/main/java/com/helger/pd/indexer/clientcert/ClientCertificateValidationResult.java#L76-L81
train
phax/peppol-directory
peppol-directory-client/src/main/java/com/helger/pd/client/PDClient.java
PDClient.executeRequest
@Nonnull @OverrideOnDemand protected <T> T executeRequest (@Nonnull final HttpRequestBase aRequest, @Nonnull final ResponseHandler <T> aHandler) throws IOException { // Contextual attributes set the local context level will take // precedence over those set at the client level. final HttpContext aContext = HttpClientHelper.createHttpContext (m_aProxy, m_aProxyCredentials); return m_aHttpClientMgr.execute (aRequest, aContext, aHandler); }
java
@Nonnull @OverrideOnDemand protected <T> T executeRequest (@Nonnull final HttpRequestBase aRequest, @Nonnull final ResponseHandler <T> aHandler) throws IOException { // Contextual attributes set the local context level will take // precedence over those set at the client level. final HttpContext aContext = HttpClientHelper.createHttpContext (m_aProxy, m_aProxyCredentials); return m_aHttpClientMgr.execute (aRequest, aContext, aHandler); }
[ "@", "Nonnull", "@", "OverrideOnDemand", "protected", "<", "T", ">", "T", "executeRequest", "(", "@", "Nonnull", "final", "HttpRequestBase", "aRequest", ",", "@", "Nonnull", "final", "ResponseHandler", "<", "T", ">", "aHandler", ")", "throws", "IOException", "...
The main execution routine. Overwrite this method to add additional properties to the call. @param aRequest The request to be executed. Never <code>null</code>. @param aHandler The response handler to be used. May not be <code>null</code>. @return The return value of the response handler. Never <code>null</code>. @throws IOException On HTTP error @param <T> Response type
[ "The", "main", "execution", "routine", ".", "Overwrite", "this", "method", "to", "add", "additional", "properties", "to", "the", "call", "." ]
98da26da29fb7178371d6b029516cbf01be223fb
https://github.com/phax/peppol-directory/blob/98da26da29fb7178371d6b029516cbf01be223fb/peppol-directory-client/src/main/java/com/helger/pd/client/PDClient.java#L245-L254
train
phax/peppol-directory
peppol-directory-client/src/main/java/com/helger/pd/client/PDClient.java
PDClient.isServiceGroupRegistered
@Nonnull public boolean isServiceGroupRegistered (@Nonnull final IParticipantIdentifier aParticipantID) { ValueEnforcer.notNull (aParticipantID, "ParticipantID"); final HttpGet aGet = new HttpGet (m_sPDIndexerURL + aParticipantID.getURIPercentEncoded ()); try { return executeRequest (aGet, new PDClientResponseHandler ()).isSuccess (); } catch (final Throwable t) { m_aExceptionHdl.onException (aParticipantID, "isServiceGroupRegistered", t); } return false; }
java
@Nonnull public boolean isServiceGroupRegistered (@Nonnull final IParticipantIdentifier aParticipantID) { ValueEnforcer.notNull (aParticipantID, "ParticipantID"); final HttpGet aGet = new HttpGet (m_sPDIndexerURL + aParticipantID.getURIPercentEncoded ()); try { return executeRequest (aGet, new PDClientResponseHandler ()).isSuccess (); } catch (final Throwable t) { m_aExceptionHdl.onException (aParticipantID, "isServiceGroupRegistered", t); } return false; }
[ "@", "Nonnull", "public", "boolean", "isServiceGroupRegistered", "(", "@", "Nonnull", "final", "IParticipantIdentifier", "aParticipantID", ")", "{", "ValueEnforcer", ".", "notNull", "(", "aParticipantID", ",", "\"ParticipantID\"", ")", ";", "final", "HttpGet", "aGet",...
Gets a list of references to the CompleteServiceGroup's owned by the specified userId. This is a non-specification compliant method. @param aParticipantID Participant ID to query for existence. May not be <code>null</code>. @return <code>true</code> if the participant is in the index, <code>false</code> otherwise.
[ "Gets", "a", "list", "of", "references", "to", "the", "CompleteServiceGroup", "s", "owned", "by", "the", "specified", "userId", ".", "This", "is", "a", "non", "-", "specification", "compliant", "method", "." ]
98da26da29fb7178371d6b029516cbf01be223fb
https://github.com/phax/peppol-directory/blob/98da26da29fb7178371d6b029516cbf01be223fb/peppol-directory-client/src/main/java/com/helger/pd/client/PDClient.java#L265-L280
train
phax/peppol-directory
peppol-directory-publisher/src/main/java/com/helger/pd/publisher/exportall/ExportAllManager.java
ExportAllManager.streamFileXMLTo
public static void streamFileXMLTo (@Nonnull final UnifiedResponse aUR) { // Do it in a read lock! s_aRWLock.readLock ().lock (); try { final File f = _getFileXML (); // setContent(IReadableResource) is lazy aUR.setContent (new FileSystemResource (f)); } finally { s_aRWLock.readLock ().unlock (); } }
java
public static void streamFileXMLTo (@Nonnull final UnifiedResponse aUR) { // Do it in a read lock! s_aRWLock.readLock ().lock (); try { final File f = _getFileXML (); // setContent(IReadableResource) is lazy aUR.setContent (new FileSystemResource (f)); } finally { s_aRWLock.readLock ().unlock (); } }
[ "public", "static", "void", "streamFileXMLTo", "(", "@", "Nonnull", "final", "UnifiedResponse", "aUR", ")", "{", "// Do it in a read lock!", "s_aRWLock", ".", "readLock", "(", ")", ".", "lock", "(", ")", ";", "try", "{", "final", "File", "f", "=", "_getFileX...
Stream the stored XML file to the provided HTTP response @param aUR The response to stream to. May not be <code>null</code>.
[ "Stream", "the", "stored", "XML", "file", "to", "the", "provided", "HTTP", "response" ]
98da26da29fb7178371d6b029516cbf01be223fb
https://github.com/phax/peppol-directory/blob/98da26da29fb7178371d6b029516cbf01be223fb/peppol-directory-publisher/src/main/java/com/helger/pd/publisher/exportall/ExportAllManager.java#L135-L149
train
phax/peppol-directory
peppol-directory-publisher/src/main/java/com/helger/pd/publisher/exportall/ExportAllManager.java
ExportAllManager.streamFileExcelTo
public static void streamFileExcelTo (@Nonnull final UnifiedResponse aUR) { // Do it in a read lock! s_aRWLock.readLock ().lock (); try { final File f = _getFileExcel (); // setContent(IReadableResource) is lazy aUR.setContent (new FileSystemResource (f)); } finally { s_aRWLock.readLock ().unlock (); } }
java
public static void streamFileExcelTo (@Nonnull final UnifiedResponse aUR) { // Do it in a read lock! s_aRWLock.readLock ().lock (); try { final File f = _getFileExcel (); // setContent(IReadableResource) is lazy aUR.setContent (new FileSystemResource (f)); } finally { s_aRWLock.readLock ().unlock (); } }
[ "public", "static", "void", "streamFileExcelTo", "(", "@", "Nonnull", "final", "UnifiedResponse", "aUR", ")", "{", "// Do it in a read lock!", "s_aRWLock", ".", "readLock", "(", ")", ".", "lock", "(", ")", ";", "try", "{", "final", "File", "f", "=", "_getFil...
Stream the stored Excel file to the provided HTTP response @param aUR The response to stream to. May not be <code>null</code>.
[ "Stream", "the", "stored", "Excel", "file", "to", "the", "provided", "HTTP", "response" ]
98da26da29fb7178371d6b029516cbf01be223fb
https://github.com/phax/peppol-directory/blob/98da26da29fb7178371d6b029516cbf01be223fb/peppol-directory-publisher/src/main/java/com/helger/pd/publisher/exportall/ExportAllManager.java#L246-L260
train
phax/peppol-directory
peppol-directory-indexer/src/main/java/com/helger/pd/indexer/mgr/PDIndexExecutor.java
PDIndexExecutor.executeWorkItem
@Nonnull public static ESuccess executeWorkItem (@Nonnull final IPDStorageManager aStorageMgr, @Nonnull final IIndexerWorkItem aWorkItem, @Nonnegative final int nRetryCount, @Nonnull final Consumer <? super IIndexerWorkItem> aSuccessHandler, @Nonnull final Consumer <? super IIndexerWorkItem> aFailureHandler) { LOGGER.info ("Execute work item " + aWorkItem.getLogText () + " - " + (nRetryCount > 0 ? "retry #" + nRetryCount : "initial try")); try { final IParticipantIdentifier aParticipantID = aWorkItem.getParticipantID (); ESuccess eSuccess; switch (aWorkItem.getType ()) { case CREATE_UPDATE: { // Get BI from participant (e.g. from SMP) final PDExtendedBusinessCard aBI = PDMetaManager.getBusinessCardProvider ().getBusinessCard (aParticipantID); if (aBI == null) { // No/invalid extension present - no need to try again eSuccess = ESuccess.FAILURE; } else { // Got data - put in storage eSuccess = aStorageMgr.createOrUpdateEntry (aParticipantID, aBI, aWorkItem.getAsMetaData ()); } break; } case DELETE: { // Only mark as deleted eSuccess = aStorageMgr.markEntryDeleted (aParticipantID, aWorkItem.getAsMetaData ()); break; } case SYNC: { // Get BI from participant (e.g. from SMP) final PDExtendedBusinessCard aBI = PDMetaManager.getBusinessCardProvider ().getBusinessCard (aParticipantID); if (aBI == null) { // No/invalid extension present - delete from index eSuccess = aStorageMgr.markEntryDeleted (aParticipantID, aWorkItem.getAsMetaData ()); } else { // Got data - put in storage eSuccess = aStorageMgr.createOrUpdateEntry (aParticipantID, aBI, aWorkItem.getAsMetaData ()); } break; } default: throw new IllegalStateException ("Unsupported work item type: " + aWorkItem); } if (eSuccess.isSuccess ()) { // Item handled - remove from overall list aSuccessHandler.accept (aWorkItem); // And we're done return ESuccess.SUCCESS; } // else error storing data } catch (final Exception ex) { LOGGER.error ("Error in executing work item " + aWorkItem.getLogText (), ex); // Fall through } // Invoke failure handler aFailureHandler.accept (aWorkItem); return ESuccess.FAILURE; }
java
@Nonnull public static ESuccess executeWorkItem (@Nonnull final IPDStorageManager aStorageMgr, @Nonnull final IIndexerWorkItem aWorkItem, @Nonnegative final int nRetryCount, @Nonnull final Consumer <? super IIndexerWorkItem> aSuccessHandler, @Nonnull final Consumer <? super IIndexerWorkItem> aFailureHandler) { LOGGER.info ("Execute work item " + aWorkItem.getLogText () + " - " + (nRetryCount > 0 ? "retry #" + nRetryCount : "initial try")); try { final IParticipantIdentifier aParticipantID = aWorkItem.getParticipantID (); ESuccess eSuccess; switch (aWorkItem.getType ()) { case CREATE_UPDATE: { // Get BI from participant (e.g. from SMP) final PDExtendedBusinessCard aBI = PDMetaManager.getBusinessCardProvider ().getBusinessCard (aParticipantID); if (aBI == null) { // No/invalid extension present - no need to try again eSuccess = ESuccess.FAILURE; } else { // Got data - put in storage eSuccess = aStorageMgr.createOrUpdateEntry (aParticipantID, aBI, aWorkItem.getAsMetaData ()); } break; } case DELETE: { // Only mark as deleted eSuccess = aStorageMgr.markEntryDeleted (aParticipantID, aWorkItem.getAsMetaData ()); break; } case SYNC: { // Get BI from participant (e.g. from SMP) final PDExtendedBusinessCard aBI = PDMetaManager.getBusinessCardProvider ().getBusinessCard (aParticipantID); if (aBI == null) { // No/invalid extension present - delete from index eSuccess = aStorageMgr.markEntryDeleted (aParticipantID, aWorkItem.getAsMetaData ()); } else { // Got data - put in storage eSuccess = aStorageMgr.createOrUpdateEntry (aParticipantID, aBI, aWorkItem.getAsMetaData ()); } break; } default: throw new IllegalStateException ("Unsupported work item type: " + aWorkItem); } if (eSuccess.isSuccess ()) { // Item handled - remove from overall list aSuccessHandler.accept (aWorkItem); // And we're done return ESuccess.SUCCESS; } // else error storing data } catch (final Exception ex) { LOGGER.error ("Error in executing work item " + aWorkItem.getLogText (), ex); // Fall through } // Invoke failure handler aFailureHandler.accept (aWorkItem); return ESuccess.FAILURE; }
[ "@", "Nonnull", "public", "static", "ESuccess", "executeWorkItem", "(", "@", "Nonnull", "final", "IPDStorageManager", "aStorageMgr", ",", "@", "Nonnull", "final", "IIndexerWorkItem", "aWorkItem", ",", "@", "Nonnegative", "final", "int", "nRetryCount", ",", "@", "N...
This method is responsible for executing the specified work item depending on its type. @param aStorageMgr Storage manager. @param aWorkItem The work item to be executed. May not be <code>null</code>. @param nRetryCount The retry count. For the initial indexing it is 0, for the first retry 1 etc. @param aSuccessHandler A callback that is invoked upon success only. @param aFailureHandler A callback that is invoked upon failure only. @return {@link ESuccess}
[ "This", "method", "is", "responsible", "for", "executing", "the", "specified", "work", "item", "depending", "on", "its", "type", "." ]
98da26da29fb7178371d6b029516cbf01be223fb
https://github.com/phax/peppol-directory/blob/98da26da29fb7178371d6b029516cbf01be223fb/peppol-directory-indexer/src/main/java/com/helger/pd/indexer/mgr/PDIndexExecutor.java#L62-L144
train
vorburger/ch.vorburger.exec
src/main/java/ch/vorburger/exec/ManagedProcess.java
ManagedProcess.buffer
protected BufferedInputStream buffer(final InputStream inputStream) { // reject null early on rather than waiting for IO operation to fail if (inputStream == null) { // not checked by BufferedInputStream throw new NullPointerException("inputStream == null"); } return inputStream instanceof BufferedInputStream ? (BufferedInputStream) inputStream : new BufferedInputStream(inputStream); }
java
protected BufferedInputStream buffer(final InputStream inputStream) { // reject null early on rather than waiting for IO operation to fail if (inputStream == null) { // not checked by BufferedInputStream throw new NullPointerException("inputStream == null"); } return inputStream instanceof BufferedInputStream ? (BufferedInputStream) inputStream : new BufferedInputStream(inputStream); }
[ "protected", "BufferedInputStream", "buffer", "(", "final", "InputStream", "inputStream", ")", "{", "// reject null early on rather than waiting for IO operation to fail", "if", "(", "inputStream", "==", "null", ")", "{", "// not checked by BufferedInputStream", "throw", "new",...
stolen from commons-io IOUtiles (@since v2.5)
[ "stolen", "from", "commons", "-", "io", "IOUtiles", "(" ]
98853c55c8dfb3a6185019b8928df2a091baa471
https://github.com/vorburger/ch.vorburger.exec/blob/98853c55c8dfb3a6185019b8928df2a091baa471/src/main/java/ch/vorburger/exec/ManagedProcess.java#L136-L143
train
vorburger/ch.vorburger.exec
src/main/java/ch/vorburger/exec/ManagedProcess.java
ManagedProcess.exitValue
@Override public int exitValue() throws ManagedProcessException { try { return resultHandler.getExitValue(); } catch (IllegalStateException e) { throw new ManagedProcessException("Exit Value not (yet) available for " + getProcLongName(), e); } }
java
@Override public int exitValue() throws ManagedProcessException { try { return resultHandler.getExitValue(); } catch (IllegalStateException e) { throw new ManagedProcessException("Exit Value not (yet) available for " + getProcLongName(), e); } }
[ "@", "Override", "public", "int", "exitValue", "(", ")", "throws", "ManagedProcessException", "{", "try", "{", "return", "resultHandler", ".", "getExitValue", "(", ")", ";", "}", "catch", "(", "IllegalStateException", "e", ")", "{", "throw", "new", "ManagedPro...
Returns the exit value for the subprocess. @return the exit value of the subprocess represented by this <code>Process</code> object. by convention, the value <code>0</code> indicates normal termination. @exception ManagedProcessException if the subprocess represented by this <code>ManagedProcess</code> object has not yet terminated.
[ "Returns", "the", "exit", "value", "for", "the", "subprocess", "." ]
98853c55c8dfb3a6185019b8928df2a091baa471
https://github.com/vorburger/ch.vorburger.exec/blob/98853c55c8dfb3a6185019b8928df2a091baa471/src/main/java/ch/vorburger/exec/ManagedProcess.java#L387-L395
train
milaboratory/milib
src/main/java/com/milaboratory/core/io/sequence/fastq/FastqRecordsReader.java
FastqRecordsReader.close
@Override public void close() { if (!closed.compareAndSet(false, true)) return; //is synchronized with itself and _next calls, //so no synchronization on inner reader is needed try { synchronized (inputStream) { inputStream.close(); } } catch (IOException ex) { throw new RuntimeException(ex); } }
java
@Override public void close() { if (!closed.compareAndSet(false, true)) return; //is synchronized with itself and _next calls, //so no synchronization on inner reader is needed try { synchronized (inputStream) { inputStream.close(); } } catch (IOException ex) { throw new RuntimeException(ex); } }
[ "@", "Override", "public", "void", "close", "(", ")", "{", "if", "(", "!", "closed", ".", "compareAndSet", "(", "false", ",", "true", ")", ")", "return", ";", "//is synchronized with itself and _next calls,", "//so no synchronization on inner reader is needed", "try",...
Closes the output port
[ "Closes", "the", "output", "port" ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/io/sequence/fastq/FastqRecordsReader.java#L221-L235
train
milaboratory/milib
src/main/java/com/milaboratory/core/io/util/FileIndex.java
FileIndex.write
public void write(OutputStream stream) throws IOException { //Creating buffer ByteArrayOutputStream bos = new ByteArrayOutputStream(); //Creating compressed output data stream DeflaterOutputStream deflate = new DeflaterOutputStream(bos); DataOutputStream dataStream = new DataOutputStream(deflate); //Writing index step dataStream.writeLong(step); //Writing boundaries of index dataStream.writeLong(getStartingRecordNumber()); dataStream.writeLong(getLastRecordNumber()); //Writing number of meta-records dataStream.writeInt(metadata.size()); //Writing meta records for (Map.Entry<String, String> e : metadata.entrySet()) { dataStream.writeUTF(e.getKey()); dataStream.writeUTF(e.getValue()); } //Writing number of entries dataStream.writeInt(index.size()); //Writing index long lastValue = 0, v; for (int i = 0; i < index.size(); ++i) { IOUtil.writeRawVarint64(dataStream, (v = index.get(i)) - lastValue); lastValue = v; } //Flushing gzip output stream to underlying stream deflate.finish(); //Creating raw output stream DataOutputStream raw = new DataOutputStream(stream); //Writing non-compressed magic number raw.writeInt(MAGIC); //Writing index size raw.writeInt(bos.size()); //Writes index raw.write(bos.toByteArray()); }
java
public void write(OutputStream stream) throws IOException { //Creating buffer ByteArrayOutputStream bos = new ByteArrayOutputStream(); //Creating compressed output data stream DeflaterOutputStream deflate = new DeflaterOutputStream(bos); DataOutputStream dataStream = new DataOutputStream(deflate); //Writing index step dataStream.writeLong(step); //Writing boundaries of index dataStream.writeLong(getStartingRecordNumber()); dataStream.writeLong(getLastRecordNumber()); //Writing number of meta-records dataStream.writeInt(metadata.size()); //Writing meta records for (Map.Entry<String, String> e : metadata.entrySet()) { dataStream.writeUTF(e.getKey()); dataStream.writeUTF(e.getValue()); } //Writing number of entries dataStream.writeInt(index.size()); //Writing index long lastValue = 0, v; for (int i = 0; i < index.size(); ++i) { IOUtil.writeRawVarint64(dataStream, (v = index.get(i)) - lastValue); lastValue = v; } //Flushing gzip output stream to underlying stream deflate.finish(); //Creating raw output stream DataOutputStream raw = new DataOutputStream(stream); //Writing non-compressed magic number raw.writeInt(MAGIC); //Writing index size raw.writeInt(bos.size()); //Writes index raw.write(bos.toByteArray()); }
[ "public", "void", "write", "(", "OutputStream", "stream", ")", "throws", "IOException", "{", "//Creating buffer", "ByteArrayOutputStream", "bos", "=", "new", "ByteArrayOutputStream", "(", ")", ";", "//Creating compressed output data stream", "DeflaterOutputStream", "deflate...
Writes this index to specified output stream. @param stream output stream @throws IOException
[ "Writes", "this", "index", "to", "specified", "output", "stream", "." ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/io/util/FileIndex.java#L151-L199
train
milaboratory/milib
src/main/java/com/milaboratory/core/io/util/FileIndex.java
FileIndex.read
public static FileIndex read(InputStream stream) throws IOException { //Creating raw input stream DataInputStream raw = new DataInputStream(stream); //Reading magic number int magic = raw.readInt(); if (magic != MAGIC) throw new IOException("Wrong magic number"); //Reading length int length = raw.readInt(); //Reading whole index byte[] buffer = new byte[length]; raw.read(buffer); //Creating uncompressed stream InflaterInputStream inflater = new InflaterInputStream(new ByteArrayInputStream(buffer)); DataInputStream dataStream = new DataInputStream(inflater); //Reading step long step = dataStream.readLong(); long startingRecordNumner = dataStream.readLong(); long lastRecordNumber = dataStream.readLong(); //Reading meta record count int metaRecordsCount = dataStream.readInt(); //Reading meta records Map<String, String> metadata = new HashMap<>(); String key, value; while (--metaRecordsCount >= 0) { key = dataStream.readUTF(); value = dataStream.readUTF(); metadata.put(key, value); } //Reading entries number int size = dataStream.readInt(); //Creating array for index TLongArrayList index = new TLongArrayList(size); //Reading index long last = 0, val; for (int i = 0; i < size; ++i) { val = IOUtil.readRawVarint64(dataStream, -1); if (val == -1) throw new IOException("Wrong file format"); last += val; index.add(last); } return new FileIndex(step, metadata, index, startingRecordNumner, lastRecordNumber); }
java
public static FileIndex read(InputStream stream) throws IOException { //Creating raw input stream DataInputStream raw = new DataInputStream(stream); //Reading magic number int magic = raw.readInt(); if (magic != MAGIC) throw new IOException("Wrong magic number"); //Reading length int length = raw.readInt(); //Reading whole index byte[] buffer = new byte[length]; raw.read(buffer); //Creating uncompressed stream InflaterInputStream inflater = new InflaterInputStream(new ByteArrayInputStream(buffer)); DataInputStream dataStream = new DataInputStream(inflater); //Reading step long step = dataStream.readLong(); long startingRecordNumner = dataStream.readLong(); long lastRecordNumber = dataStream.readLong(); //Reading meta record count int metaRecordsCount = dataStream.readInt(); //Reading meta records Map<String, String> metadata = new HashMap<>(); String key, value; while (--metaRecordsCount >= 0) { key = dataStream.readUTF(); value = dataStream.readUTF(); metadata.put(key, value); } //Reading entries number int size = dataStream.readInt(); //Creating array for index TLongArrayList index = new TLongArrayList(size); //Reading index long last = 0, val; for (int i = 0; i < size; ++i) { val = IOUtil.readRawVarint64(dataStream, -1); if (val == -1) throw new IOException("Wrong file format"); last += val; index.add(last); } return new FileIndex(step, metadata, index, startingRecordNumner, lastRecordNumber); }
[ "public", "static", "FileIndex", "read", "(", "InputStream", "stream", ")", "throws", "IOException", "{", "//Creating raw input stream", "DataInputStream", "raw", "=", "new", "DataInputStream", "(", "stream", ")", ";", "//Reading magic number", "int", "magic", "=", ...
Reads index from input stream. @param stream input stream @return {@code FileIndex} @throws IOException
[ "Reads", "index", "from", "input", "stream", "." ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/io/util/FileIndex.java#L230-L284
train
milaboratory/milib
src/main/java/com/milaboratory/core/sequence/Alphabets.java
Alphabets.register
public static void register(Alphabet alphabet) { if (alphabetsByName.put(alphabet.getAlphabetName(), alphabet) != null) throw new IllegalStateException("Alphabet with this name is already registered."); if (alphabetsById.put(alphabet.getId(), alphabet) != null) throw new IllegalStateException("Alphabet with this id is already registered."); }
java
public static void register(Alphabet alphabet) { if (alphabetsByName.put(alphabet.getAlphabetName(), alphabet) != null) throw new IllegalStateException("Alphabet with this name is already registered."); if (alphabetsById.put(alphabet.getId(), alphabet) != null) throw new IllegalStateException("Alphabet with this id is already registered."); }
[ "public", "static", "void", "register", "(", "Alphabet", "alphabet", ")", "{", "if", "(", "alphabetsByName", ".", "put", "(", "alphabet", ".", "getAlphabetName", "(", ")", ",", "alphabet", ")", "!=", "null", ")", "throw", "new", "IllegalStateException", "(",...
Register new alphabet @param alphabet alphabet
[ "Register", "new", "alphabet" ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/sequence/Alphabets.java#L49-L55
train
milaboratory/milib
src/main/java/com/milaboratory/util/Sorter.java
Sorter.sort
public static <T> OutputPortCloseable<T> sort( OutputPort<T> initialSource, Comparator<T> comparator, int chunkSize, Class<T> clazz, File tempFile) throws IOException { return sort(initialSource, comparator, chunkSize, new ObjectSerializer.PrimitivIOObjectSerializer<>(clazz), tempFile); }
java
public static <T> OutputPortCloseable<T> sort( OutputPort<T> initialSource, Comparator<T> comparator, int chunkSize, Class<T> clazz, File tempFile) throws IOException { return sort(initialSource, comparator, chunkSize, new ObjectSerializer.PrimitivIOObjectSerializer<>(clazz), tempFile); }
[ "public", "static", "<", "T", ">", "OutputPortCloseable", "<", "T", ">", "sort", "(", "OutputPort", "<", "T", ">", "initialSource", ",", "Comparator", "<", "T", ">", "comparator", ",", "int", "chunkSize", ",", "Class", "<", "T", ">", "clazz", ",", "Fil...
Sort objects supporting PrimitivIO serialization.
[ "Sort", "objects", "supporting", "PrimitivIO", "serialization", "." ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/util/Sorter.java#L52-L60
train
milaboratory/milib
src/main/java/com/milaboratory/core/tree/BranchingEnumerator.java
BranchingEnumerator.move1
private void move1() { if (node == null) return; if (position >= reference.size()) { node = null; return; } node = node.links[reference.codeAt(position++)]; }
java
private void move1() { if (node == null) return; if (position >= reference.size()) { node = null; return; } node = node.links[reference.codeAt(position++)]; }
[ "private", "void", "move1", "(", ")", "{", "if", "(", "node", "==", "null", ")", "return", ";", "if", "(", "position", ">=", "reference", ".", "size", "(", ")", ")", "{", "node", "=", "null", ";", "return", ";", "}", "node", "=", "node", ".", "...
Move the pointer one step forward. Move is made exactly matching the corresponding nucleotide in the reference sequence, so this method prevents branching in the current position.
[ "Move", "the", "pointer", "one", "step", "forward", ".", "Move", "is", "made", "exactly", "matching", "the", "corresponding", "nucleotide", "in", "the", "reference", "sequence", "so", "this", "method", "prevents", "branching", "in", "the", "current", "position",...
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/tree/BranchingEnumerator.java#L67-L77
train
milaboratory/milib
src/main/java/com/milaboratory/core/io/util/AbstractRandomAccessReader.java
AbstractRandomAccessReader.seekToRecord
public void seekToRecord(long recordNumber) throws IOException { if (currentRecordNumber == recordNumber) return; long skip; if (recordNumber < fileIndex.getStartingRecordNumber()) { if (currentRecordNumber < recordNumber) skip = recordNumber - currentRecordNumber; else { skip = recordNumber; seek0(0); } } else if (recordNumber > fileIndex.getLastRecordNumber()) { if (currentRecordNumber < recordNumber) skip = recordNumber - currentRecordNumber; else { long record = fileIndex.getLastRecordNumber(); skip = recordNumber - record; seek0(fileIndex.getNearestPosition(record)); } } else if (recordNumber > currentRecordNumber && recordNumber - currentRecordNumber < fileIndex.getStep()) { skip = recordNumber - currentRecordNumber; } else { seek0(fileIndex.getNearestPosition(recordNumber)); skip = recordNumber - fileIndex.getNearestRecordNumber(recordNumber); } for (; skip > 0; --skip) skip(); currentRecordNumber = recordNumber; }
java
public void seekToRecord(long recordNumber) throws IOException { if (currentRecordNumber == recordNumber) return; long skip; if (recordNumber < fileIndex.getStartingRecordNumber()) { if (currentRecordNumber < recordNumber) skip = recordNumber - currentRecordNumber; else { skip = recordNumber; seek0(0); } } else if (recordNumber > fileIndex.getLastRecordNumber()) { if (currentRecordNumber < recordNumber) skip = recordNumber - currentRecordNumber; else { long record = fileIndex.getLastRecordNumber(); skip = recordNumber - record; seek0(fileIndex.getNearestPosition(record)); } } else if (recordNumber > currentRecordNumber && recordNumber - currentRecordNumber < fileIndex.getStep()) { skip = recordNumber - currentRecordNumber; } else { seek0(fileIndex.getNearestPosition(recordNumber)); skip = recordNumber - fileIndex.getNearestRecordNumber(recordNumber); } for (; skip > 0; --skip) skip(); currentRecordNumber = recordNumber; }
[ "public", "void", "seekToRecord", "(", "long", "recordNumber", ")", "throws", "IOException", "{", "if", "(", "currentRecordNumber", "==", "recordNumber", ")", "return", ";", "long", "skip", ";", "if", "(", "recordNumber", "<", "fileIndex", ".", "getStartingRecor...
Sets the file-pointer offset, measured from the beginning of this file, at which the next record occurs. @param recordNumber number of record, at which to set the file pointer. @throws IOException if {@code pos} is less than {@code 0} or if an I/O error occurs.
[ "Sets", "the", "file", "-", "pointer", "offset", "measured", "from", "the", "beginning", "of", "this", "file", "at", "which", "the", "next", "record", "occurs", "." ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/io/util/AbstractRandomAccessReader.java#L62-L92
train
milaboratory/milib
src/main/java/com/milaboratory/core/io/util/AbstractRandomAccessReader.java
AbstractRandomAccessReader.take
@Override public T take() { T t = take0(); if (t != null) ++currentRecordNumber; return t; }
java
@Override public T take() { T t = take0(); if (t != null) ++currentRecordNumber; return t; }
[ "@", "Override", "public", "T", "take", "(", ")", "{", "T", "t", "=", "take0", "(", ")", ";", "if", "(", "t", "!=", "null", ")", "++", "currentRecordNumber", ";", "return", "t", ";", "}" ]
Returns the next record or null if no more records exist. @return next record or null if no more records exist
[ "Returns", "the", "next", "record", "or", "null", "if", "no", "more", "records", "exist", "." ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/io/util/AbstractRandomAccessReader.java#L115-L121
train
milaboratory/milib
src/main/java/com/milaboratory/core/mutations/Mutations.java
Mutations.getLengthDelta
public int getLengthDelta() { int delta = 0; for (int mut : mutations) switch (mut & MUTATION_TYPE_MASK) { case RAW_MUTATION_TYPE_DELETION: --delta; break; case RAW_MUTATION_TYPE_INSERTION: ++delta; break; } return delta; }
java
public int getLengthDelta() { int delta = 0; for (int mut : mutations) switch (mut & MUTATION_TYPE_MASK) { case RAW_MUTATION_TYPE_DELETION: --delta; break; case RAW_MUTATION_TYPE_INSERTION: ++delta; break; } return delta; }
[ "public", "int", "getLengthDelta", "(", ")", "{", "int", "delta", "=", "0", ";", "for", "(", "int", "mut", ":", "mutations", ")", "switch", "(", "mut", "&", "MUTATION_TYPE_MASK", ")", "{", "case", "RAW_MUTATION_TYPE_DELETION", ":", "--", "delta", ";", "b...
Returns the difference between the length of initial sequence and length of mutated sequence. Negative values denotes that mutated sequence is shorter. @return difference between the length of initial sequence and mutated sequence
[ "Returns", "the", "difference", "between", "the", "length", "of", "initial", "sequence", "and", "length", "of", "mutated", "sequence", ".", "Negative", "values", "denotes", "that", "mutated", "sequence", "is", "shorter", "." ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/mutations/Mutations.java#L248-L262
train
milaboratory/milib
src/main/java/com/milaboratory/core/mutations/Mutations.java
Mutations.concat
public Mutations<S> concat(final Mutations<S> other) { return new MutationsBuilder<>(alphabet, false) .ensureCapacity(this.size() + other.size()) .append(this) .append(other) .createAndDestroy(); }
java
public Mutations<S> concat(final Mutations<S> other) { return new MutationsBuilder<>(alphabet, false) .ensureCapacity(this.size() + other.size()) .append(this) .append(other) .createAndDestroy(); }
[ "public", "Mutations", "<", "S", ">", "concat", "(", "final", "Mutations", "<", "S", ">", "other", ")", "{", "return", "new", "MutationsBuilder", "<>", "(", "alphabet", ",", "false", ")", ".", "ensureCapacity", "(", "this", ".", "size", "(", ")", "+", ...
Concatenates this and other
[ "Concatenates", "this", "and", "other" ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/mutations/Mutations.java#L267-L273
train
milaboratory/milib
src/main/java/com/milaboratory/core/mutations/Mutations.java
Mutations.move
public Mutations<S> move(int offset) { int[] newMutations = new int[mutations.length]; for (int i = 0; i < mutations.length; ++i) newMutations[i] = Mutation.move(mutations[i], offset); return new Mutations<S>(alphabet, newMutations, true); }
java
public Mutations<S> move(int offset) { int[] newMutations = new int[mutations.length]; for (int i = 0; i < mutations.length; ++i) newMutations[i] = Mutation.move(mutations[i], offset); return new Mutations<S>(alphabet, newMutations, true); }
[ "public", "Mutations", "<", "S", ">", "move", "(", "int", "offset", ")", "{", "int", "[", "]", "newMutations", "=", "new", "int", "[", "mutations", ".", "length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "mutations", ".", "lengt...
Moves positions of mutations by specified offset @param offset offset @return relocated positions
[ "Moves", "positions", "of", "mutations", "by", "specified", "offset" ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/mutations/Mutations.java#L351-L356
train
milaboratory/milib
src/main/java/com/milaboratory/core/mutations/Mutations.java
Mutations.removeMutationsInRange
public Mutations<S> removeMutationsInRange(int from, int to) { if (to < from) throw new IllegalArgumentException("Reversed ranges are not supported."); // If range is empty return untouched mutations object if (from == to) return this; // Determine range in mutations to remove long indexRange = getIndexRange(from, to); // Unpacking int fromIndex = (int) (indexRange >>> 32), toIndex = (int) (indexRange & 0xFFFFFFFF); if (fromIndex == 0 && toIndex == mutations.length) return empty(alphabet); // Creating result int[] result = new int[mutations.length - (toIndex - fromIndex)]; // Constant to move positions in the output array int offset = (from - to) << POSITION_OFFSET; // Negative value // Copy and move mutations int i = 0; for (int j = 0; j < fromIndex; ++j) result[i++] = mutations[j]; for (int j = toIndex; j < mutations.length; ++j) result[i++] = mutations[j] + offset; assert i == result.length; return new Mutations<>(alphabet, result, true); }
java
public Mutations<S> removeMutationsInRange(int from, int to) { if (to < from) throw new IllegalArgumentException("Reversed ranges are not supported."); // If range is empty return untouched mutations object if (from == to) return this; // Determine range in mutations to remove long indexRange = getIndexRange(from, to); // Unpacking int fromIndex = (int) (indexRange >>> 32), toIndex = (int) (indexRange & 0xFFFFFFFF); if (fromIndex == 0 && toIndex == mutations.length) return empty(alphabet); // Creating result int[] result = new int[mutations.length - (toIndex - fromIndex)]; // Constant to move positions in the output array int offset = (from - to) << POSITION_OFFSET; // Negative value // Copy and move mutations int i = 0; for (int j = 0; j < fromIndex; ++j) result[i++] = mutations[j]; for (int j = toIndex; j < mutations.length; ++j) result[i++] = mutations[j] + offset; assert i == result.length; return new Mutations<>(alphabet, result, true); }
[ "public", "Mutations", "<", "S", ">", "removeMutationsInRange", "(", "int", "from", ",", "int", "to", ")", "{", "if", "(", "to", "<", "from", ")", "throw", "new", "IllegalArgumentException", "(", "\"Reversed ranges are not supported.\"", ")", ";", "// If range i...
Removes mutations for a range of positions in the original sequence and performs shift of corresponding positions of mutations. <p>Insertions before {@code from} will be left untouched. Insertions after {@code (to - 1)} will be removed.</p> <p> <b>Important:</b> to remove leftmost insertions (left trailing insertions) use {@code from = -1}. E.g. {@code extractRelativeMutationsForRange(mut, -1, seqLength) == mut}. </p> @param from left bound of range, inclusive. Use -1 to extract leftmost insertions. @param to right bound of range, exclusive @return mutations for a range of positions
[ "Removes", "mutations", "for", "a", "range", "of", "positions", "in", "the", "original", "sequence", "and", "performs", "shift", "of", "corresponding", "positions", "of", "mutations", "." ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/mutations/Mutations.java#L518-L552
train
milaboratory/milib
src/main/java/com/milaboratory/util/ArraysUtils.java
ArraysUtils.getSortedDistinct
public static long[] getSortedDistinct(long[] values) { if (values.length == 0) return values; Arrays.sort(values); int shift = 0; int i = 0; while (i + shift + 1 < values.length) if (values[i + shift] == values[i + shift + 1]) ++shift; else { values[i] = values[i + shift]; ++i; } values[i] = values[i + shift]; return Arrays.copyOf(values, i + 1); }
java
public static long[] getSortedDistinct(long[] values) { if (values.length == 0) return values; Arrays.sort(values); int shift = 0; int i = 0; while (i + shift + 1 < values.length) if (values[i + shift] == values[i + shift + 1]) ++shift; else { values[i] = values[i + shift]; ++i; } values[i] = values[i + shift]; return Arrays.copyOf(values, i + 1); }
[ "public", "static", "long", "[", "]", "getSortedDistinct", "(", "long", "[", "]", "values", ")", "{", "if", "(", "values", ".", "length", "==", "0", ")", "return", "values", ";", "Arrays", ".", "sort", "(", "values", ")", ";", "int", "shift", "=", ...
Sort array & return array with removed repetitive values. @param values input array (this method will quickSort this array) @return sorted array of distinct values
[ "Sort", "array", "&", "return", "array", "with", "removed", "repetitive", "values", "." ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/util/ArraysUtils.java#L60-L75
train
milaboratory/milib
src/main/java/com/milaboratory/core/sequence/SequenceWithQuality.java
SequenceWithQuality.toPrettyString
public String toPrettyString() { String seq = sequence.toString(); String qual = quality.toString(); return seq + '\n' + qual; }
java
public String toPrettyString() { String seq = sequence.toString(); String qual = quality.toString(); return seq + '\n' + qual; }
[ "public", "String", "toPrettyString", "(", ")", "{", "String", "seq", "=", "sequence", ".", "toString", "(", ")", ";", "String", "qual", "=", "quality", ".", "toString", "(", ")", ";", "return", "seq", "+", "'", "'", "+", "qual", ";", "}" ]
Returns a pretty string representation of this. @return pretty string representation of this
[ "Returns", "a", "pretty", "string", "representation", "of", "this", "." ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/sequence/SequenceWithQuality.java#L127-L131
train
milaboratory/milib
src/main/java/com/milaboratory/core/tree/NeighborhoodIterator.java
NeighborhoodIterator.ensureCapacity
private void ensureCapacity(int newSize) { int oldSize; if ((oldSize = branchingEnumerators.length) < newSize) { branchingEnumerators = Arrays.copyOfRange(branchingEnumerators, 0, newSize); for (int i = oldSize; i < newSize; ++i) branchingEnumerators[i] = new BranchingEnumerator<>(reference, guide); } }
java
private void ensureCapacity(int newSize) { int oldSize; if ((oldSize = branchingEnumerators.length) < newSize) { branchingEnumerators = Arrays.copyOfRange(branchingEnumerators, 0, newSize); for (int i = oldSize; i < newSize; ++i) branchingEnumerators[i] = new BranchingEnumerator<>(reference, guide); } }
[ "private", "void", "ensureCapacity", "(", "int", "newSize", ")", "{", "int", "oldSize", ";", "if", "(", "(", "oldSize", "=", "branchingEnumerators", ".", "length", ")", "<", "newSize", ")", "{", "branchingEnumerators", "=", "Arrays", ".", "copyOfRange", "(",...
Ensures capacity for storing BranchingEnumerators. @param newSize desired size
[ "Ensures", "capacity", "for", "storing", "BranchingEnumerators", "." ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/tree/NeighborhoodIterator.java#L70-L77
train
milaboratory/milib
src/main/java/com/milaboratory/core/tree/NeighborhoodIterator.java
NeighborhoodIterator.setupBranchingEnumerators
private void setupBranchingEnumerators() { //Getting required sequence of differences (mutations) final byte[] bSequence = branchingSequences[branchingSequenceIndex]; //Ensure number of branching enumerators ensureCapacity(bSequence.length); //Setting up initial branching enumerators byte previous = -1, current; for (int i = 0; i < bSequence.length; ++i) { current = bSequence[i]; boolean autoMove1 = (previous == 1 && current == 2); // prevents insertion right after deletion if (parameters.isGreedy()) { // prevent some other 'redundant' cases autoMove1 = autoMove1 || (previous == 2 && current == 1) || // prevents deletion right after insertion (previous == 2 && current == 0); // prevents mismatch right after insertion } branchingEnumerators[i].setup(current, autoMove1); previous = bSequence[i]; } branchingEnumerators[0].reset(0, root); lastEnumerator = bSequence.length - 1; }
java
private void setupBranchingEnumerators() { //Getting required sequence of differences (mutations) final byte[] bSequence = branchingSequences[branchingSequenceIndex]; //Ensure number of branching enumerators ensureCapacity(bSequence.length); //Setting up initial branching enumerators byte previous = -1, current; for (int i = 0; i < bSequence.length; ++i) { current = bSequence[i]; boolean autoMove1 = (previous == 1 && current == 2); // prevents insertion right after deletion if (parameters.isGreedy()) { // prevent some other 'redundant' cases autoMove1 = autoMove1 || (previous == 2 && current == 1) || // prevents deletion right after insertion (previous == 2 && current == 0); // prevents mismatch right after insertion } branchingEnumerators[i].setup(current, autoMove1); previous = bSequence[i]; } branchingEnumerators[0].reset(0, root); lastEnumerator = bSequence.length - 1; }
[ "private", "void", "setupBranchingEnumerators", "(", ")", "{", "//Getting required sequence of differences (mutations)", "final", "byte", "[", "]", "bSequence", "=", "branchingSequences", "[", "branchingSequenceIndex", "]", ";", "//Ensure number of branching enumerators", "ensu...
Setts up BranchingEnumerators for current branching sequence
[ "Setts", "up", "BranchingEnumerators", "for", "current", "branching", "sequence" ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/tree/NeighborhoodIterator.java#L82-L111
train
milaboratory/milib
src/main/java/com/milaboratory/core/alignment/LinearGapAlignmentScoring.java
LinearGapAlignmentScoring.getAminoAcidBLASTScoring
public static LinearGapAlignmentScoring<AminoAcidSequence> getAminoAcidBLASTScoring(BLASTMatrix matrix, int gapPenalty) { return new LinearGapAlignmentScoring<>(AminoAcidSequence.ALPHABET, matrix.getMatrix(), gapPenalty); }
java
public static LinearGapAlignmentScoring<AminoAcidSequence> getAminoAcidBLASTScoring(BLASTMatrix matrix, int gapPenalty) { return new LinearGapAlignmentScoring<>(AminoAcidSequence.ALPHABET, matrix.getMatrix(), gapPenalty); }
[ "public", "static", "LinearGapAlignmentScoring", "<", "AminoAcidSequence", ">", "getAminoAcidBLASTScoring", "(", "BLASTMatrix", "matrix", ",", "int", "gapPenalty", ")", "{", "return", "new", "LinearGapAlignmentScoring", "<>", "(", "AminoAcidSequence", ".", "ALPHABET", "...
Returns standard amino acid BLAST scoring @param matrix BLAST substitution matrix @param gapPenalty penalty for gap, must be < 0 @return standard amino acid BLAST scoring
[ "Returns", "standard", "amino", "acid", "BLAST", "scoring" ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/alignment/LinearGapAlignmentScoring.java#L153-L157
train
milaboratory/milib
src/main/java/com/milaboratory/core/io/sequence/fasta/RandomAccessFastaIndex.java
RandomAccessFastaIndex.index
public static RandomAccessFastaIndex index(Path file, int indexStep, boolean save, LongProcessReporter reporter) { Path indexFile = file.resolveSibling(file.getFileName() + INDEX_SUFFIX); if (Files.exists(indexFile)) try (FileInputStream fis = new FileInputStream(indexFile.toFile())) { RandomAccessFastaIndex index = RandomAccessFastaIndex.read(new BufferedInputStream(fis)); if (index.getIndexStep() != indexStep) throw new IllegalArgumentException("Mismatched index step in " + indexFile + ". Remove the file to recreate the index."); return index; } catch (IOException e) { throw new RuntimeException(e); } try (LongProcess lp = reporter.start("Indexing " + file.getFileName()); FileChannel fc = FileChannel.open(file, StandardOpenOption.READ)) { // Requesting file size to correctly report status long size = Files.size(file); // Allocating buffer ByteBuffer buffer = ByteBuffer.allocate(65536); // Extracting backing byte array byte[] bufferArray = buffer.array(); // Creating builder StreamIndexBuilder builder = new StreamIndexBuilder(indexStep); // Indexing file int read; long done = 0; while ((read = fc.read((ByteBuffer) buffer.clear())) > 0) { builder.processBuffer(bufferArray, 0, read); lp.reportStatus(1.0 * (done += read) / size); } // Build index RandomAccessFastaIndex index = builder.build(); if (save) try (FileOutputStream fos = new FileOutputStream(indexFile.toFile())) { index.write(new BufferedOutputStream(fos)); } return index; } catch (IOException ioe) { throw new RuntimeException(ioe); } }
java
public static RandomAccessFastaIndex index(Path file, int indexStep, boolean save, LongProcessReporter reporter) { Path indexFile = file.resolveSibling(file.getFileName() + INDEX_SUFFIX); if (Files.exists(indexFile)) try (FileInputStream fis = new FileInputStream(indexFile.toFile())) { RandomAccessFastaIndex index = RandomAccessFastaIndex.read(new BufferedInputStream(fis)); if (index.getIndexStep() != indexStep) throw new IllegalArgumentException("Mismatched index step in " + indexFile + ". Remove the file to recreate the index."); return index; } catch (IOException e) { throw new RuntimeException(e); } try (LongProcess lp = reporter.start("Indexing " + file.getFileName()); FileChannel fc = FileChannel.open(file, StandardOpenOption.READ)) { // Requesting file size to correctly report status long size = Files.size(file); // Allocating buffer ByteBuffer buffer = ByteBuffer.allocate(65536); // Extracting backing byte array byte[] bufferArray = buffer.array(); // Creating builder StreamIndexBuilder builder = new StreamIndexBuilder(indexStep); // Indexing file int read; long done = 0; while ((read = fc.read((ByteBuffer) buffer.clear())) > 0) { builder.processBuffer(bufferArray, 0, read); lp.reportStatus(1.0 * (done += read) / size); } // Build index RandomAccessFastaIndex index = builder.build(); if (save) try (FileOutputStream fos = new FileOutputStream(indexFile.toFile())) { index.write(new BufferedOutputStream(fos)); } return index; } catch (IOException ioe) { throw new RuntimeException(ioe); } }
[ "public", "static", "RandomAccessFastaIndex", "index", "(", "Path", "file", ",", "int", "indexStep", ",", "boolean", "save", ",", "LongProcessReporter", "reporter", ")", "{", "Path", "indexFile", "=", "file", ".", "resolveSibling", "(", "file", ".", "getFileName...
Index fasta file or loads previously created index @param file file to index @param indexStep index step @param save whether to save index to {input_file_name}.mifdx file @param reporter reporter @return index
[ "Index", "fasta", "file", "or", "loads", "previously", "created", "index" ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/io/sequence/fasta/RandomAccessFastaIndex.java#L321-L366
train
milaboratory/milib
src/main/java/com/milaboratory/core/alignment/kaligner1/KAlignerParameters.java
KAlignerParameters.getByName
public static KAlignerParameters getByName(String name) { KAlignerParameters params = knownParameters.get(name); if (params == null) return null; return params.clone(); }
java
public static KAlignerParameters getByName(String name) { KAlignerParameters params = knownParameters.get(name); if (params == null) return null; return params.clone(); }
[ "public", "static", "KAlignerParameters", "getByName", "(", "String", "name", ")", "{", "KAlignerParameters", "params", "=", "knownParameters", ".", "get", "(", "name", ")", ";", "if", "(", "params", "==", "null", ")", "return", "null", ";", "return", "param...
Returns parameters by specified preset name @param name parameters preset name @return parameters with specified preset name
[ "Returns", "parameters", "by", "specified", "preset", "name" ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/alignment/kaligner1/KAlignerParameters.java#L60-L65
train
milaboratory/milib
src/main/java/com/milaboratory/core/io/sequence/fasta/FastaReader.java
FastaReader.asRawRecordsPort
public OutputPortCloseable<RawFastaRecord> asRawRecordsPort() { return new OutputPortCloseable<RawFastaRecord>() { @Override public void close() { FastaReader.this.close(); } @Override public RawFastaRecord take() { return takeRawRecord(); } }; }
java
public OutputPortCloseable<RawFastaRecord> asRawRecordsPort() { return new OutputPortCloseable<RawFastaRecord>() { @Override public void close() { FastaReader.this.close(); } @Override public RawFastaRecord take() { return takeRawRecord(); } }; }
[ "public", "OutputPortCloseable", "<", "RawFastaRecord", ">", "asRawRecordsPort", "(", ")", "{", "return", "new", "OutputPortCloseable", "<", "RawFastaRecord", ">", "(", ")", "{", "@", "Override", "public", "void", "close", "(", ")", "{", "FastaReader", ".", "t...
Returns output port of raw records. @return output port of raw records
[ "Returns", "output", "port", "of", "raw", "records", "." ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/io/sequence/fasta/FastaReader.java#L159-L171
train
librato/metrics-librato
src/main/java/com/librato/metrics/reporter/SourceInformation.java
SourceInformation.from
public static SourceInformation from(Pattern sourceRegex, String name) { if (sourceRegex == null) { return new SourceInformation(null, name); } Matcher matcher = sourceRegex.matcher(name); if (matcher.groupCount() != 1) { log.error("Source regex matcher must define a group"); return new SourceInformation(null, name); } if (!matcher.find()) { return new SourceInformation(null, name); } String source = matcher.group(1); int endPos = matcher.toMatchResult().end(); if (endPos >= name.length()) { // the source matched the whole metric name, probably in error. log.error("Source '{}' matched the whole metric name. Metric name cannot be empty"); return new SourceInformation(null, name); } String newName = name.substring(endPos); return new SourceInformation(source, newName); }
java
public static SourceInformation from(Pattern sourceRegex, String name) { if (sourceRegex == null) { return new SourceInformation(null, name); } Matcher matcher = sourceRegex.matcher(name); if (matcher.groupCount() != 1) { log.error("Source regex matcher must define a group"); return new SourceInformation(null, name); } if (!matcher.find()) { return new SourceInformation(null, name); } String source = matcher.group(1); int endPos = matcher.toMatchResult().end(); if (endPos >= name.length()) { // the source matched the whole metric name, probably in error. log.error("Source '{}' matched the whole metric name. Metric name cannot be empty"); return new SourceInformation(null, name); } String newName = name.substring(endPos); return new SourceInformation(source, newName); }
[ "public", "static", "SourceInformation", "from", "(", "Pattern", "sourceRegex", ",", "String", "name", ")", "{", "if", "(", "sourceRegex", "==", "null", ")", "{", "return", "new", "SourceInformation", "(", "null", ",", "name", ")", ";", "}", "Matcher", "ma...
If the pattern is not null, it will attempt to match against the supplied name to pull out the source.
[ "If", "the", "pattern", "is", "not", "null", "it", "will", "attempt", "to", "match", "against", "the", "supplied", "name", "to", "pull", "out", "the", "source", "." ]
10713643cf7d80e0f9741a7e1e81d1f6d68dc3f6
https://github.com/librato/metrics-librato/blob/10713643cf7d80e0f9741a7e1e81d1f6d68dc3f6/src/main/java/com/librato/metrics/reporter/SourceInformation.java#L18-L39
train
milaboratory/milib
src/main/java/com/milaboratory/core/clustering/Clustering.java
Clustering.performClustering
public static <T, S extends Sequence<S>> List<Cluster<T>> performClustering(Collection<T> inputObjects, SequenceExtractor<T, S> sequenceExtractor, ClusteringStrategy<T, S> strategy) { return new Clustering<>(inputObjects, sequenceExtractor, strategy).performClustering(); }
java
public static <T, S extends Sequence<S>> List<Cluster<T>> performClustering(Collection<T> inputObjects, SequenceExtractor<T, S> sequenceExtractor, ClusteringStrategy<T, S> strategy) { return new Clustering<>(inputObjects, sequenceExtractor, strategy).performClustering(); }
[ "public", "static", "<", "T", ",", "S", "extends", "Sequence", "<", "S", ">", ">", "List", "<", "Cluster", "<", "T", ">", ">", "performClustering", "(", "Collection", "<", "T", ">", "inputObjects", ",", "SequenceExtractor", "<", "T", ",", "S", ">", "...
Helper method. See class description.
[ "Helper", "method", ".", "See", "class", "description", "." ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/clustering/Clustering.java#L262-L266
train
milaboratory/milib
src/main/java/com/milaboratory/core/alignment/Alignment.java
Alignment.calculateScore
public int calculateScore(AlignmentScoring<S> scoring) { return AlignmentUtils.calculateScore(sequence1, sequence1Range, mutations, scoring); }
java
public int calculateScore(AlignmentScoring<S> scoring) { return AlignmentUtils.calculateScore(sequence1, sequence1Range, mutations, scoring); }
[ "public", "int", "calculateScore", "(", "AlignmentScoring", "<", "S", ">", "scoring", ")", "{", "return", "AlignmentUtils", ".", "calculateScore", "(", "sequence1", ",", "sequence1Range", ",", "mutations", ",", "scoring", ")", ";", "}" ]
Calculates score for this alignment using another scoring. @param scoring scoring @return alignment score
[ "Calculates", "score", "for", "this", "alignment", "using", "another", "scoring", "." ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/alignment/Alignment.java#L107-L109
train
milaboratory/milib
src/main/java/com/milaboratory/core/alignment/Alignment.java
Alignment.convertToSeq1Range
public Range convertToSeq1Range(Range rangeInSeq2) { int from = aabs(convertToSeq1Position(rangeInSeq2.getFrom())); int to = aabs(convertToSeq1Position(rangeInSeq2.getTo())); if (from == -1 || to == -1) return null; return new Range(from, to); }
java
public Range convertToSeq1Range(Range rangeInSeq2) { int from = aabs(convertToSeq1Position(rangeInSeq2.getFrom())); int to = aabs(convertToSeq1Position(rangeInSeq2.getTo())); if (from == -1 || to == -1) return null; return new Range(from, to); }
[ "public", "Range", "convertToSeq1Range", "(", "Range", "rangeInSeq2", ")", "{", "int", "from", "=", "aabs", "(", "convertToSeq1Position", "(", "rangeInSeq2", ".", "getFrom", "(", ")", ")", ")", ";", "int", "to", "=", "aabs", "(", "convertToSeq1Position", "("...
Converts range in sequence2 to range in sequence1, or returns null if input range is not fully covered by alignment @param rangeInSeq2 range in sequence 2 @return range in sequence1 or null if rangeInSeq2 is not fully covered by alignment
[ "Converts", "range", "in", "sequence2", "to", "range", "in", "sequence1", "or", "returns", "null", "if", "input", "range", "is", "not", "fully", "covered", "by", "alignment" ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/alignment/Alignment.java#L231-L239
train
milaboratory/milib
src/main/java/com/milaboratory/core/alignment/Alignment.java
Alignment.convertToSeq2Range
public Range convertToSeq2Range(Range rangeInSeq1) { int from = aabs(convertToSeq2Position(rangeInSeq1.getFrom())); int to = aabs(convertToSeq2Position(rangeInSeq1.getTo())); if (from == -1 || to == -1) return null; return new Range(from, to); }
java
public Range convertToSeq2Range(Range rangeInSeq1) { int from = aabs(convertToSeq2Position(rangeInSeq1.getFrom())); int to = aabs(convertToSeq2Position(rangeInSeq1.getTo())); if (from == -1 || to == -1) return null; return new Range(from, to); }
[ "public", "Range", "convertToSeq2Range", "(", "Range", "rangeInSeq1", ")", "{", "int", "from", "=", "aabs", "(", "convertToSeq2Position", "(", "rangeInSeq1", ".", "getFrom", "(", ")", ")", ")", ";", "int", "to", "=", "aabs", "(", "convertToSeq2Position", "("...
Converts range in sequence1 to range in sequence2, or returns null if input range is not fully covered by alignment @param rangeInSeq1 range in sequence 1 @return range in sequence2 or null if rangeInSeq1 is not fully covered by alignment
[ "Converts", "range", "in", "sequence1", "to", "range", "in", "sequence2", "or", "returns", "null", "if", "input", "range", "is", "not", "fully", "covered", "by", "alignment" ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/alignment/Alignment.java#L248-L256
train
milaboratory/milib
src/main/java/com/milaboratory/core/alignment/Alignment.java
Alignment.invert
public Alignment<S> invert(S sequence2) { return new Alignment<>(sequence2, getRelativeMutations().invert().move(sequence2Range.getFrom()), sequence2Range, sequence1Range, score); }
java
public Alignment<S> invert(S sequence2) { return new Alignment<>(sequence2, getRelativeMutations().invert().move(sequence2Range.getFrom()), sequence2Range, sequence1Range, score); }
[ "public", "Alignment", "<", "S", ">", "invert", "(", "S", "sequence2", ")", "{", "return", "new", "Alignment", "<>", "(", "sequence2", ",", "getRelativeMutations", "(", ")", ".", "invert", "(", ")", ".", "move", "(", "sequence2Range", ".", "getFrom", "("...
Having sequence2 creates alignment from sequence2 to sequence1 @param sequence2 sequence2 @return inverted alignment
[ "Having", "sequence2", "creates", "alignment", "from", "sequence2", "to", "sequence1" ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/alignment/Alignment.java#L273-L276
train
milaboratory/milib
src/main/java/com/milaboratory/core/alignment/Alignment.java
Alignment.similarity
public float similarity() { int match = 0, mismatch = 0; AlignmentIteratorForward<S> iterator = forwardIterator(); while (iterator.advance()) { final int mut = iterator.getCurrentMutation(); if (mut == NON_MUTATION) ++match; else ++mismatch; } return 1.0f * match / (match + mismatch); }
java
public float similarity() { int match = 0, mismatch = 0; AlignmentIteratorForward<S> iterator = forwardIterator(); while (iterator.advance()) { final int mut = iterator.getCurrentMutation(); if (mut == NON_MUTATION) ++match; else ++mismatch; } return 1.0f * match / (match + mismatch); }
[ "public", "float", "similarity", "(", ")", "{", "int", "match", "=", "0", ",", "mismatch", "=", "0", ";", "AlignmentIteratorForward", "<", "S", ">", "iterator", "=", "forwardIterator", "(", ")", ";", "while", "(", "iterator", ".", "advance", "(", ")", ...
Returns number of matches divided by sum of number of matches and mismatches. @return number of matches divided by sum of number of matches and mismatches
[ "Returns", "number", "of", "matches", "divided", "by", "sum", "of", "number", "of", "matches", "and", "mismatches", "." ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/alignment/Alignment.java#L283-L296
train
librato/metrics-librato
src/main/java/com/librato/metrics/reporter/DeltaTracker.java
DeltaTracker.peekDelta
public Long peekDelta(String name, long count) { Long previous = lookup.get(name); return calculateDelta(name, previous, count); }
java
public Long peekDelta(String name, long count) { Long previous = lookup.get(name); return calculateDelta(name, previous, count); }
[ "public", "Long", "peekDelta", "(", "String", "name", ",", "long", "count", ")", "{", "Long", "previous", "=", "lookup", ".", "get", "(", "name", ")", ";", "return", "calculateDelta", "(", "name", ",", "previous", ",", "count", ")", ";", "}" ]
Gets the delta without updating the internal data store
[ "Gets", "the", "delta", "without", "updating", "the", "internal", "data", "store" ]
10713643cf7d80e0f9741a7e1e81d1f6d68dc3f6
https://github.com/librato/metrics-librato/blob/10713643cf7d80e0f9741a7e1e81d1f6d68dc3f6/src/main/java/com/librato/metrics/reporter/DeltaTracker.java#L49-L52
train
librato/metrics-librato
src/main/java/com/librato/metrics/reporter/DeltaTracker.java
DeltaTracker.getDelta
public Long getDelta(String name, long count) { Long previous = lookup.put(name, count); return calculateDelta(name, previous, count); }
java
public Long getDelta(String name, long count) { Long previous = lookup.put(name, count); return calculateDelta(name, previous, count); }
[ "public", "Long", "getDelta", "(", "String", "name", ",", "long", "count", ")", "{", "Long", "previous", "=", "lookup", ".", "put", "(", "name", ",", "count", ")", ";", "return", "calculateDelta", "(", "name", ",", "previous", ",", "count", ")", ";", ...
Calculates the delta. If this is a new value that has not been seen before, zero will be assumed to be the initial value. Updates the internal map with the supplied count. @param name the name of the counter @param count the counter value @return the delta
[ "Calculates", "the", "delta", ".", "If", "this", "is", "a", "new", "value", "that", "has", "not", "been", "seen", "before", "zero", "will", "be", "assumed", "to", "be", "the", "initial", "value", ".", "Updates", "the", "internal", "map", "with", "the", ...
10713643cf7d80e0f9741a7e1e81d1f6d68dc3f6
https://github.com/librato/metrics-librato/blob/10713643cf7d80e0f9741a7e1e81d1f6d68dc3f6/src/main/java/com/librato/metrics/reporter/DeltaTracker.java#L62-L65
train
milaboratory/milib
src/main/java/com/milaboratory/core/sequence/quality/QualityTrimmer.java
QualityTrimmer.extendRange
public static Range extendRange(SequenceQuality quality, QualityTrimmerParameters parameters, Range initialRange) { int lower = pabs(trim(quality, 0, initialRange.getLower(), -1, false, parameters)); int upper = pabs(trim(quality, initialRange.getUpper(), quality.size(), +1, false, parameters)) + 1; return new Range(lower, upper, initialRange.isReverse()); }
java
public static Range extendRange(SequenceQuality quality, QualityTrimmerParameters parameters, Range initialRange) { int lower = pabs(trim(quality, 0, initialRange.getLower(), -1, false, parameters)); int upper = pabs(trim(quality, initialRange.getUpper(), quality.size(), +1, false, parameters)) + 1; return new Range(lower, upper, initialRange.isReverse()); }
[ "public", "static", "Range", "extendRange", "(", "SequenceQuality", "quality", ",", "QualityTrimmerParameters", "parameters", ",", "Range", "initialRange", ")", "{", "int", "lower", "=", "pabs", "(", "trim", "(", "quality", ",", "0", ",", "initialRange", ".", ...
Extend initialRange to the biggest possible range that fulfils the criteria of QualityTrimmer along the whole extended region. The criteria may not be fulfilled for the initial range. @param quality quality values @param parameters trimming parameters @param initialRange initial range to extend @return
[ "Extend", "initialRange", "to", "the", "biggest", "possible", "range", "that", "fulfils", "the", "criteria", "of", "QualityTrimmer", "along", "the", "whole", "extended", "region", "." ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/sequence/quality/QualityTrimmer.java#L158-L162
train
milaboratory/milib
src/main/java/com/milaboratory/core/sequence/quality/QualityTrimmer.java
QualityTrimmer.trim
public static Range trim(SequenceQuality quality, QualityTrimmerParameters parameters) { return trim(quality, parameters, new Range(0, quality.size())); }
java
public static Range trim(SequenceQuality quality, QualityTrimmerParameters parameters) { return trim(quality, parameters, new Range(0, quality.size())); }
[ "public", "static", "Range", "trim", "(", "SequenceQuality", "quality", ",", "QualityTrimmerParameters", "parameters", ")", "{", "return", "trim", "(", "quality", ",", "parameters", ",", "new", "Range", "(", "0", ",", "quality", ".", "size", "(", ")", ")", ...
Trims the quality string by cutting off low quality nucleotides on both edges. The criteria of QualityTrimmer may not be fulfilled for the resulting range. This method detects beginning of the region with stably high quality, once the beginning of the region is detected the algorithm stops. Detected stop positions are "from" and "to" of the output range. @param quality quality values @param parameters trimming parameters @return trimmed range
[ "Trims", "the", "quality", "string", "by", "cutting", "off", "low", "quality", "nucleotides", "on", "both", "edges", "." ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/sequence/quality/QualityTrimmer.java#L175-L177
train
milaboratory/milib
src/main/java/com/milaboratory/core/sequence/quality/QualityTrimmer.java
QualityTrimmer.trim
public static Range trim(SequenceQuality quality, QualityTrimmerParameters parameters, Range initialRange) { int lower = pabs(trim(quality, initialRange.getLower(), initialRange.getUpper(), +1, true, parameters)) + 1; assert lower >= initialRange.getLower(); if (lower == initialRange.getUpper()) return null; int upper = pabs(trim(quality, lower, initialRange.getUpper(), -1, true, parameters)); if (upper == lower) // Should not happen, just in case return null; return new Range(lower, upper, initialRange.isReverse()); }
java
public static Range trim(SequenceQuality quality, QualityTrimmerParameters parameters, Range initialRange) { int lower = pabs(trim(quality, initialRange.getLower(), initialRange.getUpper(), +1, true, parameters)) + 1; assert lower >= initialRange.getLower(); if (lower == initialRange.getUpper()) return null; int upper = pabs(trim(quality, lower, initialRange.getUpper(), -1, true, parameters)); if (upper == lower) // Should not happen, just in case return null; return new Range(lower, upper, initialRange.isReverse()); }
[ "public", "static", "Range", "trim", "(", "SequenceQuality", "quality", ",", "QualityTrimmerParameters", "parameters", ",", "Range", "initialRange", ")", "{", "int", "lower", "=", "pabs", "(", "trim", "(", "quality", ",", "initialRange", ".", "getLower", "(", ...
Trims the initialRange by cutting off low quality nucleotides on both edges. The criteria of QualityTrimmer may not be fulfilled for the resulting range. This method detects beginning of the region with stably high quality, once the beginning of the region is detected the algorithm stops. Detected stop positions are "from" and "to" of the output range. @param quality quality values @param parameters trimming parameters @param initialRange initial range to trim @return trimmed range, or null in case the whole sequence should be trimmed
[ "Trims", "the", "initialRange", "by", "cutting", "off", "low", "quality", "nucleotides", "on", "both", "edges", "." ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/sequence/quality/QualityTrimmer.java#L191-L201
train
milaboratory/milib
src/main/java/com/milaboratory/core/sequence/AminoAcidSequence.java
AminoAcidSequence.translate
public static AminoAcidSequence translate(NucleotideSequence sequence) { if (sequence.size() % 3 != 0) throw new IllegalArgumentException("Only nucleotide sequences with size multiple " + "of three are supported (in-frame)."); byte[] aaData = new byte[sequence.size() / 3]; GeneticCode.translate(aaData, 0, sequence, 0, sequence.size()); return new AminoAcidSequence(aaData, true); }
java
public static AminoAcidSequence translate(NucleotideSequence sequence) { if (sequence.size() % 3 != 0) throw new IllegalArgumentException("Only nucleotide sequences with size multiple " + "of three are supported (in-frame)."); byte[] aaData = new byte[sequence.size() / 3]; GeneticCode.translate(aaData, 0, sequence, 0, sequence.size()); return new AminoAcidSequence(aaData, true); }
[ "public", "static", "AminoAcidSequence", "translate", "(", "NucleotideSequence", "sequence", ")", "{", "if", "(", "sequence", ".", "size", "(", ")", "%", "3", "!=", "0", ")", "throw", "new", "IllegalArgumentException", "(", "\"Only nucleotide sequences with size mul...
Translates sequence having length divisible by 3, starting from first nucleotide. @param sequence nucleotide sequence @return translated amino acid sequence
[ "Translates", "sequence", "having", "length", "divisible", "by", "3", "starting", "from", "first", "nucleotide", "." ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/sequence/AminoAcidSequence.java#L145-L152
train
milaboratory/milib
src/main/java/com/milaboratory/cli/ACommand.java
ACommand.validate
public void validate() { for (String in : getInputFiles()) { if (!new File(in).exists()) throwValidationException("ERROR: input file \"" + in + "\" does not exist.", false); validateInfo(in); } }
java
public void validate() { for (String in : getInputFiles()) { if (!new File(in).exists()) throwValidationException("ERROR: input file \"" + in + "\" does not exist.", false); validateInfo(in); } }
[ "public", "void", "validate", "(", ")", "{", "for", "(", "String", "in", ":", "getInputFiles", "(", ")", ")", "{", "if", "(", "!", "new", "File", "(", "in", ")", ".", "exists", "(", ")", ")", "throwValidationException", "(", "\"ERROR: input file \\\"\"",...
Validate injected parameters and options
[ "Validate", "injected", "parameters", "and", "options" ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/cli/ACommand.java#L70-L76
train