id
int32
0
165k
repo
stringlengths
7
58
path
stringlengths
12
218
func_name
stringlengths
3
140
original_string
stringlengths
73
34.1k
language
stringclasses
1 value
code
stringlengths
73
34.1k
code_tokens
list
docstring
stringlengths
3
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
105
339
6,900
wcm-io/wcm-io-tooling
maven/plugins/i18n-maven-plugin/src/main/java/io/wcm/maven/plugins/i18n/TransformMojo.java
TransformMojo.isI18nSourceFileChanged
private boolean isI18nSourceFileChanged(File sourceDirectory) { Scanner scanner = buildContext.newScanner(sourceDirectory); Scanner deleteScanner = buildContext.newDeleteScanner(sourceDirectory); return isI18nSourceFileChanged(scanner) || isI18nSourceFileChanged(deleteScanner); }
java
private boolean isI18nSourceFileChanged(File sourceDirectory) { Scanner scanner = buildContext.newScanner(sourceDirectory); Scanner deleteScanner = buildContext.newDeleteScanner(sourceDirectory); return isI18nSourceFileChanged(scanner) || isI18nSourceFileChanged(deleteScanner); }
[ "private", "boolean", "isI18nSourceFileChanged", "(", "File", "sourceDirectory", ")", "{", "Scanner", "scanner", "=", "buildContext", ".", "newScanner", "(", "sourceDirectory", ")", ";", "Scanner", "deleteScanner", "=", "buildContext", ".", "newDeleteScanner", "(", "sourceDirectory", ")", ";", "return", "isI18nSourceFileChanged", "(", "scanner", ")", "||", "isI18nSourceFileChanged", "(", "deleteScanner", ")", ";", "}" ]
Checks if and i18n source file was changes in incremental build. @param sourceDirectory Source directory @return true if changes detected
[ "Checks", "if", "and", "i18n", "source", "file", "was", "changes", "in", "incremental", "build", "." ]
1abcd01dd3ad4cc248f03b431f929573d84fa9b4
https://github.com/wcm-io/wcm-io-tooling/blob/1abcd01dd3ad4cc248f03b431f929573d84fa9b4/maven/plugins/i18n-maven-plugin/src/main/java/io/wcm/maven/plugins/i18n/TransformMojo.java#L137-L141
6,901
wcm-io/wcm-io-tooling
maven/plugins/i18n-maven-plugin/src/main/java/io/wcm/maven/plugins/i18n/TransformMojo.java
TransformMojo.intialize
private void intialize(File sourceDirectory) throws IOException { getLog().debug("Initializing i18n plugin..."); // resource if (!getI18nSourceFiles(sourceDirectory).isEmpty()) { File myGeneratedResourcesFolder = getGeneratedResourcesFolder(); addResource(myGeneratedResourcesFolder.getPath(), target); } }
java
private void intialize(File sourceDirectory) throws IOException { getLog().debug("Initializing i18n plugin..."); // resource if (!getI18nSourceFiles(sourceDirectory).isEmpty()) { File myGeneratedResourcesFolder = getGeneratedResourcesFolder(); addResource(myGeneratedResourcesFolder.getPath(), target); } }
[ "private", "void", "intialize", "(", "File", "sourceDirectory", ")", "throws", "IOException", "{", "getLog", "(", ")", ".", "debug", "(", "\"Initializing i18n plugin...\"", ")", ";", "// resource", "if", "(", "!", "getI18nSourceFiles", "(", "sourceDirectory", ")", ".", "isEmpty", "(", ")", ")", "{", "File", "myGeneratedResourcesFolder", "=", "getGeneratedResourcesFolder", "(", ")", ";", "addResource", "(", "myGeneratedResourcesFolder", ".", "getPath", "(", ")", ",", "target", ")", ";", "}", "}" ]
Initialize parameters, which cannot get defaults from annotations. Currently only the root nodes. @throws IOException
[ "Initialize", "parameters", "which", "cannot", "get", "defaults", "from", "annotations", ".", "Currently", "only", "the", "root", "nodes", "." ]
1abcd01dd3ad4cc248f03b431f929573d84fa9b4
https://github.com/wcm-io/wcm-io-tooling/blob/1abcd01dd3ad4cc248f03b431f929573d84fa9b4/maven/plugins/i18n-maven-plugin/src/main/java/io/wcm/maven/plugins/i18n/TransformMojo.java#L154-L163
6,902
wcm-io/wcm-io-tooling
maven/plugins/i18n-maven-plugin/src/main/java/io/wcm/maven/plugins/i18n/TransformMojo.java
TransformMojo.getI18nSourceFiles
@SuppressWarnings("unchecked") private List<File> getI18nSourceFiles(File sourceDirectory) throws IOException { if (i18nSourceFiles == null) { if (!sourceDirectory.isDirectory()) { i18nSourceFiles = Collections.emptyList(); } else { // get list of source files String includes = StringUtils.join(SOURCE_FILES_INCLUDES, ","); String excludes = FileUtils.getDefaultExcludesAsString(); i18nSourceFiles = FileUtils.getFiles(sourceDirectory, includes, excludes); } } return i18nSourceFiles; }
java
@SuppressWarnings("unchecked") private List<File> getI18nSourceFiles(File sourceDirectory) throws IOException { if (i18nSourceFiles == null) { if (!sourceDirectory.isDirectory()) { i18nSourceFiles = Collections.emptyList(); } else { // get list of source files String includes = StringUtils.join(SOURCE_FILES_INCLUDES, ","); String excludes = FileUtils.getDefaultExcludesAsString(); i18nSourceFiles = FileUtils.getFiles(sourceDirectory, includes, excludes); } } return i18nSourceFiles; }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "private", "List", "<", "File", ">", "getI18nSourceFiles", "(", "File", "sourceDirectory", ")", "throws", "IOException", "{", "if", "(", "i18nSourceFiles", "==", "null", ")", "{", "if", "(", "!", "sourceDirectory", ".", "isDirectory", "(", ")", ")", "{", "i18nSourceFiles", "=", "Collections", ".", "emptyList", "(", ")", ";", "}", "else", "{", "// get list of source files", "String", "includes", "=", "StringUtils", ".", "join", "(", "SOURCE_FILES_INCLUDES", ",", "\",\"", ")", ";", "String", "excludes", "=", "FileUtils", ".", "getDefaultExcludesAsString", "(", ")", ";", "i18nSourceFiles", "=", "FileUtils", ".", "getFiles", "(", "sourceDirectory", ",", "includes", ",", "excludes", ")", ";", "}", "}", "return", "i18nSourceFiles", ";", "}" ]
Fetches i18n source files from source directory. @param sourceDirectory Source directory @return a list of XML files @throws IOException
[ "Fetches", "i18n", "source", "files", "from", "source", "directory", "." ]
1abcd01dd3ad4cc248f03b431f929573d84fa9b4
https://github.com/wcm-io/wcm-io-tooling/blob/1abcd01dd3ad4cc248f03b431f929573d84fa9b4/maven/plugins/i18n-maven-plugin/src/main/java/io/wcm/maven/plugins/i18n/TransformMojo.java#L184-L201
6,903
wcm-io/wcm-io-tooling
maven/plugins/i18n-maven-plugin/src/main/java/io/wcm/maven/plugins/i18n/TransformMojo.java
TransformMojo.getSourceDirectory
private File getSourceDirectory() throws IOException { File file = new File(source); if (!file.isDirectory()) { getLog().debug("Could not find directory at '" + source + "'"); } return file.getCanonicalFile(); }
java
private File getSourceDirectory() throws IOException { File file = new File(source); if (!file.isDirectory()) { getLog().debug("Could not find directory at '" + source + "'"); } return file.getCanonicalFile(); }
[ "private", "File", "getSourceDirectory", "(", ")", "throws", "IOException", "{", "File", "file", "=", "new", "File", "(", "source", ")", ";", "if", "(", "!", "file", ".", "isDirectory", "(", ")", ")", "{", "getLog", "(", ")", ".", "debug", "(", "\"Could not find directory at '\"", "+", "source", "+", "\"'\"", ")", ";", "}", "return", "file", ".", "getCanonicalFile", "(", ")", ";", "}" ]
Get directory containing source i18n files. @return directory containing source i18n files. @throws IOException
[ "Get", "directory", "containing", "source", "i18n", "files", "." ]
1abcd01dd3ad4cc248f03b431f929573d84fa9b4
https://github.com/wcm-io/wcm-io-tooling/blob/1abcd01dd3ad4cc248f03b431f929573d84fa9b4/maven/plugins/i18n-maven-plugin/src/main/java/io/wcm/maven/plugins/i18n/TransformMojo.java#L208-L214
6,904
wcm-io/wcm-io-tooling
maven/plugins/i18n-maven-plugin/src/main/java/io/wcm/maven/plugins/i18n/TransformMojo.java
TransformMojo.writeTargetI18nFile
private void writeTargetI18nFile(SlingI18nMap i18nMap, File targetfile, OutputFormat selectedOutputFormat) throws IOException, JSONException { if (selectedOutputFormat == OutputFormat.XML) { FileUtils.fileWrite(targetfile, CharEncoding.UTF_8, i18nMap.getI18nXmlString()); } else if (selectedOutputFormat == OutputFormat.PROPERTIES) { FileUtils.fileWrite(targetfile, CharEncoding.ISO_8859_1, i18nMap.getI18nPropertiesString()); } else { FileUtils.fileWrite(targetfile, CharEncoding.UTF_8, i18nMap.getI18nJsonString()); } buildContext.refresh(targetfile); }
java
private void writeTargetI18nFile(SlingI18nMap i18nMap, File targetfile, OutputFormat selectedOutputFormat) throws IOException, JSONException { if (selectedOutputFormat == OutputFormat.XML) { FileUtils.fileWrite(targetfile, CharEncoding.UTF_8, i18nMap.getI18nXmlString()); } else if (selectedOutputFormat == OutputFormat.PROPERTIES) { FileUtils.fileWrite(targetfile, CharEncoding.ISO_8859_1, i18nMap.getI18nPropertiesString()); } else { FileUtils.fileWrite(targetfile, CharEncoding.UTF_8, i18nMap.getI18nJsonString()); } buildContext.refresh(targetfile); }
[ "private", "void", "writeTargetI18nFile", "(", "SlingI18nMap", "i18nMap", ",", "File", "targetfile", ",", "OutputFormat", "selectedOutputFormat", ")", "throws", "IOException", ",", "JSONException", "{", "if", "(", "selectedOutputFormat", "==", "OutputFormat", ".", "XML", ")", "{", "FileUtils", ".", "fileWrite", "(", "targetfile", ",", "CharEncoding", ".", "UTF_8", ",", "i18nMap", ".", "getI18nXmlString", "(", ")", ")", ";", "}", "else", "if", "(", "selectedOutputFormat", "==", "OutputFormat", ".", "PROPERTIES", ")", "{", "FileUtils", ".", "fileWrite", "(", "targetfile", ",", "CharEncoding", ".", "ISO_8859_1", ",", "i18nMap", ".", "getI18nPropertiesString", "(", ")", ")", ";", "}", "else", "{", "FileUtils", ".", "fileWrite", "(", "targetfile", ",", "CharEncoding", ".", "UTF_8", ",", "i18nMap", ".", "getI18nJsonString", "(", ")", ")", ";", "}", "buildContext", ".", "refresh", "(", "targetfile", ")", ";", "}" ]
Writes mappings to file in Sling compatible JSON format. @param i18nMap mappings @param targetfile target file @param selectedOutputFormat Output format @throws IOException @throws JSONException
[ "Writes", "mappings", "to", "file", "in", "Sling", "compatible", "JSON", "format", "." ]
1abcd01dd3ad4cc248f03b431f929573d84fa9b4
https://github.com/wcm-io/wcm-io-tooling/blob/1abcd01dd3ad4cc248f03b431f929573d84fa9b4/maven/plugins/i18n-maven-plugin/src/main/java/io/wcm/maven/plugins/i18n/TransformMojo.java#L224-L235
6,905
wcm-io/wcm-io-tooling
maven/plugins/i18n-maven-plugin/src/main/java/io/wcm/maven/plugins/i18n/TransformMojo.java
TransformMojo.getTargetFile
private File getTargetFile(File sourceFile, OutputFormat selectedOutputFormat) throws IOException { File sourceDirectory = getSourceDirectory(); String relativePath = StringUtils.substringAfter(sourceFile.getAbsolutePath(), sourceDirectory.getAbsolutePath()); String relativeTargetPath = FileUtils.removeExtension(relativePath) + "." + selectedOutputFormat.getFileExtension(); File jsonFile = new File(getGeneratedResourcesFolder().getPath() + relativeTargetPath); jsonFile = jsonFile.getCanonicalFile(); File parentDirectory = jsonFile.getParentFile(); if (!parentDirectory.exists()) { parentDirectory.mkdirs(); buildContext.refresh(parentDirectory); } return jsonFile; }
java
private File getTargetFile(File sourceFile, OutputFormat selectedOutputFormat) throws IOException { File sourceDirectory = getSourceDirectory(); String relativePath = StringUtils.substringAfter(sourceFile.getAbsolutePath(), sourceDirectory.getAbsolutePath()); String relativeTargetPath = FileUtils.removeExtension(relativePath) + "." + selectedOutputFormat.getFileExtension(); File jsonFile = new File(getGeneratedResourcesFolder().getPath() + relativeTargetPath); jsonFile = jsonFile.getCanonicalFile(); File parentDirectory = jsonFile.getParentFile(); if (!parentDirectory.exists()) { parentDirectory.mkdirs(); buildContext.refresh(parentDirectory); } return jsonFile; }
[ "private", "File", "getTargetFile", "(", "File", "sourceFile", ",", "OutputFormat", "selectedOutputFormat", ")", "throws", "IOException", "{", "File", "sourceDirectory", "=", "getSourceDirectory", "(", ")", ";", "String", "relativePath", "=", "StringUtils", ".", "substringAfter", "(", "sourceFile", ".", "getAbsolutePath", "(", ")", ",", "sourceDirectory", ".", "getAbsolutePath", "(", ")", ")", ";", "String", "relativeTargetPath", "=", "FileUtils", ".", "removeExtension", "(", "relativePath", ")", "+", "\".\"", "+", "selectedOutputFormat", ".", "getFileExtension", "(", ")", ";", "File", "jsonFile", "=", "new", "File", "(", "getGeneratedResourcesFolder", "(", ")", ".", "getPath", "(", ")", "+", "relativeTargetPath", ")", ";", "jsonFile", "=", "jsonFile", ".", "getCanonicalFile", "(", ")", ";", "File", "parentDirectory", "=", "jsonFile", ".", "getParentFile", "(", ")", ";", "if", "(", "!", "parentDirectory", ".", "exists", "(", ")", ")", "{", "parentDirectory", ".", "mkdirs", "(", ")", ";", "buildContext", ".", "refresh", "(", "parentDirectory", ")", ";", "}", "return", "jsonFile", ";", "}" ]
Get the JSON file for source file. @param sourceFile the source file @param selectedOutputFormat Output format @return File with name and path based on file parameter @throws IOException
[ "Get", "the", "JSON", "file", "for", "source", "file", "." ]
1abcd01dd3ad4cc248f03b431f929573d84fa9b4
https://github.com/wcm-io/wcm-io-tooling/blob/1abcd01dd3ad4cc248f03b431f929573d84fa9b4/maven/plugins/i18n-maven-plugin/src/main/java/io/wcm/maven/plugins/i18n/TransformMojo.java#L244-L261
6,906
wcm-io/wcm-io-tooling
maven/plugins/i18n-maven-plugin/src/main/java/io/wcm/maven/plugins/i18n/TransformMojo.java
TransformMojo.getI18nReader
private I18nReader getI18nReader(File sourceFile) throws MojoFailureException { String extension = FileUtils.getExtension(sourceFile.getName()); if (StringUtils.equalsIgnoreCase(extension, FILE_EXTENSION_PROPERTIES)) { return new PropertiesI18nReader(); } if (StringUtils.equalsIgnoreCase(extension, FILE_EXTENSION_XML)) { return new XmlI18nReader(); } if (StringUtils.equalsIgnoreCase(extension, FILE_EXTENSION_JSON)) { return new JsonI18nReader(); } throw new MojoFailureException("Unsupported file extension '" + extension + "': " + sourceFile.getAbsolutePath()); }
java
private I18nReader getI18nReader(File sourceFile) throws MojoFailureException { String extension = FileUtils.getExtension(sourceFile.getName()); if (StringUtils.equalsIgnoreCase(extension, FILE_EXTENSION_PROPERTIES)) { return new PropertiesI18nReader(); } if (StringUtils.equalsIgnoreCase(extension, FILE_EXTENSION_XML)) { return new XmlI18nReader(); } if (StringUtils.equalsIgnoreCase(extension, FILE_EXTENSION_JSON)) { return new JsonI18nReader(); } throw new MojoFailureException("Unsupported file extension '" + extension + "': " + sourceFile.getAbsolutePath()); }
[ "private", "I18nReader", "getI18nReader", "(", "File", "sourceFile", ")", "throws", "MojoFailureException", "{", "String", "extension", "=", "FileUtils", ".", "getExtension", "(", "sourceFile", ".", "getName", "(", ")", ")", ";", "if", "(", "StringUtils", ".", "equalsIgnoreCase", "(", "extension", ",", "FILE_EXTENSION_PROPERTIES", ")", ")", "{", "return", "new", "PropertiesI18nReader", "(", ")", ";", "}", "if", "(", "StringUtils", ".", "equalsIgnoreCase", "(", "extension", ",", "FILE_EXTENSION_XML", ")", ")", "{", "return", "new", "XmlI18nReader", "(", ")", ";", "}", "if", "(", "StringUtils", ".", "equalsIgnoreCase", "(", "extension", ",", "FILE_EXTENSION_JSON", ")", ")", "{", "return", "new", "JsonI18nReader", "(", ")", ";", "}", "throw", "new", "MojoFailureException", "(", "\"Unsupported file extension '\"", "+", "extension", "+", "\"': \"", "+", "sourceFile", ".", "getAbsolutePath", "(", ")", ")", ";", "}" ]
Get i18n reader for source file. @param sourceFile Source file @return I18n reader @throws MojoFailureException
[ "Get", "i18n", "reader", "for", "source", "file", "." ]
1abcd01dd3ad4cc248f03b431f929573d84fa9b4
https://github.com/wcm-io/wcm-io-tooling/blob/1abcd01dd3ad4cc248f03b431f929573d84fa9b4/maven/plugins/i18n-maven-plugin/src/main/java/io/wcm/maven/plugins/i18n/TransformMojo.java#L281-L293
6,907
wcm-io/wcm-io-tooling
netbeans/sightly/src/main/java/io/wcm/tooling/netbeans/sightly/completion/classLookup/ClassLookupResolver.java
ClassLookupResolver.resolve
public List<CompletionItem> resolve(String filter, int startOffset, int caretOffset) { final Set<ElementHandle<TypeElement>> result = classpath.getClassIndex().getDeclaredTypes("", ClassIndex.NameKind.PREFIX, EnumSet.of(ClassIndex.SearchScope.SOURCE)); List<CompletionItem> ret = new ArrayList<>(); for (ElementHandle<TypeElement> te : result) { if (te.getKind().isClass()) { String binaryName = te.getBinaryName(); if (!StringUtils.equals(binaryName, "") && StringUtils.startsWith(binaryName, filter)) { ret.add(new BasicCompletionItem(te.getBinaryName(), false, startOffset, caretOffset)); } } } return ret; }
java
public List<CompletionItem> resolve(String filter, int startOffset, int caretOffset) { final Set<ElementHandle<TypeElement>> result = classpath.getClassIndex().getDeclaredTypes("", ClassIndex.NameKind.PREFIX, EnumSet.of(ClassIndex.SearchScope.SOURCE)); List<CompletionItem> ret = new ArrayList<>(); for (ElementHandle<TypeElement> te : result) { if (te.getKind().isClass()) { String binaryName = te.getBinaryName(); if (!StringUtils.equals(binaryName, "") && StringUtils.startsWith(binaryName, filter)) { ret.add(new BasicCompletionItem(te.getBinaryName(), false, startOffset, caretOffset)); } } } return ret; }
[ "public", "List", "<", "CompletionItem", ">", "resolve", "(", "String", "filter", ",", "int", "startOffset", ",", "int", "caretOffset", ")", "{", "final", "Set", "<", "ElementHandle", "<", "TypeElement", ">", ">", "result", "=", "classpath", ".", "getClassIndex", "(", ")", ".", "getDeclaredTypes", "(", "\"\"", ",", "ClassIndex", ".", "NameKind", ".", "PREFIX", ",", "EnumSet", ".", "of", "(", "ClassIndex", ".", "SearchScope", ".", "SOURCE", ")", ")", ";", "List", "<", "CompletionItem", ">", "ret", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "ElementHandle", "<", "TypeElement", ">", "te", ":", "result", ")", "{", "if", "(", "te", ".", "getKind", "(", ")", ".", "isClass", "(", ")", ")", "{", "String", "binaryName", "=", "te", ".", "getBinaryName", "(", ")", ";", "if", "(", "!", "StringUtils", ".", "equals", "(", "binaryName", ",", "\"\"", ")", "&&", "StringUtils", ".", "startsWith", "(", "binaryName", ",", "filter", ")", ")", "{", "ret", ".", "add", "(", "new", "BasicCompletionItem", "(", "te", ".", "getBinaryName", "(", ")", ",", "false", ",", "startOffset", ",", "caretOffset", ")", ")", ";", "}", "}", "}", "return", "ret", ";", "}" ]
returns a list with all classes matchting the given filter
[ "returns", "a", "list", "with", "all", "classes", "matchting", "the", "given", "filter" ]
1abcd01dd3ad4cc248f03b431f929573d84fa9b4
https://github.com/wcm-io/wcm-io-tooling/blob/1abcd01dd3ad4cc248f03b431f929573d84fa9b4/netbeans/sightly/src/main/java/io/wcm/tooling/netbeans/sightly/completion/classLookup/ClassLookupResolver.java#L48-L62
6,908
wcm-io/wcm-io-tooling
commons/content-package-builder/src/main/java/io/wcm/tooling/commons/contentpackagebuilder/ContentPackageBuilder.java
ContentPackageBuilder.property
public ContentPackageBuilder property(String property, Object value) { metadata.addProperty(property, value); return this; }
java
public ContentPackageBuilder property(String property, Object value) { metadata.addProperty(property, value); return this; }
[ "public", "ContentPackageBuilder", "property", "(", "String", "property", ",", "Object", "value", ")", "{", "metadata", ".", "addProperty", "(", "property", ",", "value", ")", ";", "return", "this", ";", "}" ]
Add custom package metadata property. @param property Property name @param value Property value @return this
[ "Add", "custom", "package", "metadata", "property", "." ]
1abcd01dd3ad4cc248f03b431f929573d84fa9b4
https://github.com/wcm-io/wcm-io-tooling/blob/1abcd01dd3ad4cc248f03b431f929573d84fa9b4/commons/content-package-builder/src/main/java/io/wcm/tooling/commons/contentpackagebuilder/ContentPackageBuilder.java#L138-L141
6,909
wcm-io/wcm-io-tooling
commons/content-package-builder/src/main/java/io/wcm/tooling/commons/contentpackagebuilder/ContentPackageBuilder.java
ContentPackageBuilder.xmlNamespace
public ContentPackageBuilder xmlNamespace(String prefix, String uri) { metadata.addXmlNamespace(prefix, uri); return this; }
java
public ContentPackageBuilder xmlNamespace(String prefix, String uri) { metadata.addXmlNamespace(prefix, uri); return this; }
[ "public", "ContentPackageBuilder", "xmlNamespace", "(", "String", "prefix", ",", "String", "uri", ")", "{", "metadata", ".", "addXmlNamespace", "(", "prefix", ",", "uri", ")", ";", "return", "this", ";", "}" ]
Register a XML namespace that is used by your content added to the JCR XML. This method can be called multiple times to register multiple namespaces. The JCR namespaces "jcr", "nt", "cq" and "sling" are registered by default. @param prefix Namespace prefix @param uri Namespace URI @return this
[ "Register", "a", "XML", "namespace", "that", "is", "used", "by", "your", "content", "added", "to", "the", "JCR", "XML", ".", "This", "method", "can", "be", "called", "multiple", "times", "to", "register", "multiple", "namespaces", ".", "The", "JCR", "namespaces", "jcr", "nt", "cq", "and", "sling", "are", "registered", "by", "default", "." ]
1abcd01dd3ad4cc248f03b431f929573d84fa9b4
https://github.com/wcm-io/wcm-io-tooling/blob/1abcd01dd3ad4cc248f03b431f929573d84fa9b4/commons/content-package-builder/src/main/java/io/wcm/tooling/commons/contentpackagebuilder/ContentPackageBuilder.java#L151-L154
6,910
wcm-io/wcm-io-tooling
commons/content-package-builder/src/main/java/io/wcm/tooling/commons/contentpackagebuilder/ContentPackageBuilder.java
ContentPackageBuilder.thumbnailImage
public ContentPackageBuilder thumbnailImage(InputStream is) throws IOException { metadata.setThumbnailImage(IOUtils.toByteArray(is)); return this; }
java
public ContentPackageBuilder thumbnailImage(InputStream is) throws IOException { metadata.setThumbnailImage(IOUtils.toByteArray(is)); return this; }
[ "public", "ContentPackageBuilder", "thumbnailImage", "(", "InputStream", "is", ")", "throws", "IOException", "{", "metadata", ".", "setThumbnailImage", "(", "IOUtils", ".", "toByteArray", "(", "is", ")", ")", ";", "return", "this", ";", "}" ]
Set thumbnail PNG image. @param is Input stream with Thumbnail PNG image binary data @return this @throws IOException I/O exception
[ "Set", "thumbnail", "PNG", "image", "." ]
1abcd01dd3ad4cc248f03b431f929573d84fa9b4
https://github.com/wcm-io/wcm-io-tooling/blob/1abcd01dd3ad4cc248f03b431f929573d84fa9b4/commons/content-package-builder/src/main/java/io/wcm/tooling/commons/contentpackagebuilder/ContentPackageBuilder.java#L162-L165
6,911
craftercms/commons
utilities/src/main/java/org/craftercms/commons/jackson/JacksonUtils.java
JacksonUtils.createModule
@SuppressWarnings("unchecked") public static final Module createModule(List<JsonSerializer<?>> serializers, Map<Class<?>, JsonDeserializer<?>> deserializers) { SimpleModule module = new SimpleModule(); if (CollectionUtils.isNotEmpty(serializers)) { for (JsonSerializer<?> serializer : serializers) { module.addSerializer(serializer); } } if (MapUtils.isNotEmpty(deserializers)) { for (Map.Entry<Class<?>, JsonDeserializer<?>> entry : deserializers.entrySet()) { Class<Object> type = (Class<Object>) entry.getKey(); JsonDeserializer<Object> des = (JsonDeserializer<Object>) entry.getValue(); module.addDeserializer(type, des); } } return module; }
java
@SuppressWarnings("unchecked") public static final Module createModule(List<JsonSerializer<?>> serializers, Map<Class<?>, JsonDeserializer<?>> deserializers) { SimpleModule module = new SimpleModule(); if (CollectionUtils.isNotEmpty(serializers)) { for (JsonSerializer<?> serializer : serializers) { module.addSerializer(serializer); } } if (MapUtils.isNotEmpty(deserializers)) { for (Map.Entry<Class<?>, JsonDeserializer<?>> entry : deserializers.entrySet()) { Class<Object> type = (Class<Object>) entry.getKey(); JsonDeserializer<Object> des = (JsonDeserializer<Object>) entry.getValue(); module.addDeserializer(type, des); } } return module; }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "static", "final", "Module", "createModule", "(", "List", "<", "JsonSerializer", "<", "?", ">", ">", "serializers", ",", "Map", "<", "Class", "<", "?", ">", ",", "JsonDeserializer", "<", "?", ">", ">", "deserializers", ")", "{", "SimpleModule", "module", "=", "new", "SimpleModule", "(", ")", ";", "if", "(", "CollectionUtils", ".", "isNotEmpty", "(", "serializers", ")", ")", "{", "for", "(", "JsonSerializer", "<", "?", ">", "serializer", ":", "serializers", ")", "{", "module", ".", "addSerializer", "(", "serializer", ")", ";", "}", "}", "if", "(", "MapUtils", ".", "isNotEmpty", "(", "deserializers", ")", ")", "{", "for", "(", "Map", ".", "Entry", "<", "Class", "<", "?", ">", ",", "JsonDeserializer", "<", "?", ">", ">", "entry", ":", "deserializers", ".", "entrySet", "(", ")", ")", "{", "Class", "<", "Object", ">", "type", "=", "(", "Class", "<", "Object", ">", ")", "entry", ".", "getKey", "(", ")", ";", "JsonDeserializer", "<", "Object", ">", "des", "=", "(", "JsonDeserializer", "<", "Object", ">", ")", "entry", ".", "getValue", "(", ")", ";", "module", ".", "addDeserializer", "(", "type", ",", "des", ")", ";", "}", "}", "return", "module", ";", "}" ]
Creates a module from a set of serializers and deserializes. @param serializers the serializers, can be null or empty @param deserializers the deserializers, can be null or empty @return a non-reusable Jackson module composed of the specified serializers and deserializers
[ "Creates", "a", "module", "from", "a", "set", "of", "serializers", "and", "deserializes", "." ]
3074fe49e56c2a4aae0832f40b17ae563335dc83
https://github.com/craftercms/commons/blob/3074fe49e56c2a4aae0832f40b17ae563335dc83/utilities/src/main/java/org/craftercms/commons/jackson/JacksonUtils.java#L47-L68
6,912
craftercms/commons
utilities/src/main/java/org/craftercms/commons/crypto/CryptoUtils.java
CryptoUtils.generateKey
public static SecretKey generateKey(String cipherAlgorithm) throws NoSuchAlgorithmException { KeyGenerator keyGenerator = KeyGenerator.getInstance(cipherAlgorithm); keyGenerator.init(secureRandom); return keyGenerator.generateKey(); }
java
public static SecretKey generateKey(String cipherAlgorithm) throws NoSuchAlgorithmException { KeyGenerator keyGenerator = KeyGenerator.getInstance(cipherAlgorithm); keyGenerator.init(secureRandom); return keyGenerator.generateKey(); }
[ "public", "static", "SecretKey", "generateKey", "(", "String", "cipherAlgorithm", ")", "throws", "NoSuchAlgorithmException", "{", "KeyGenerator", "keyGenerator", "=", "KeyGenerator", ".", "getInstance", "(", "cipherAlgorithm", ")", ";", "keyGenerator", ".", "init", "(", "secureRandom", ")", ";", "return", "keyGenerator", ".", "generateKey", "(", ")", ";", "}" ]
Generates a random encryption key. @param cipherAlgorithm the cipher algorithm the key will be used with. Will determine the key size @return the generated key
[ "Generates", "a", "random", "encryption", "key", "." ]
3074fe49e56c2a4aae0832f40b17ae563335dc83
https://github.com/craftercms/commons/blob/3074fe49e56c2a4aae0832f40b17ae563335dc83/utilities/src/main/java/org/craftercms/commons/crypto/CryptoUtils.java#L78-L83
6,913
craftercms/commons
utilities/src/main/java/org/craftercms/commons/crypto/CryptoUtils.java
CryptoUtils.matchPassword
public static boolean matchPassword(String hashedPswdAndSalt, String clearPswd) { if (StringUtils.isNotEmpty(hashedPswdAndSalt) && StringUtils.isNotEmpty(clearPswd)) { int idxOfSep = hashedPswdAndSalt.indexOf(PASSWORD_SEP); String storedHash = hashedPswdAndSalt.substring(0, idxOfSep); String salt = hashedPswdAndSalt.substring(idxOfSep + 1); SimpleDigest digest = new SimpleDigest(); digest.setBase64Salt(salt); return storedHash.equals(digest.digestBase64(clearPswd)); } else if (hashedPswdAndSalt == null && clearPswd == null) { return true; } else if (hashedPswdAndSalt.isEmpty() && clearPswd.isEmpty()) { return true; } else { return false; } }
java
public static boolean matchPassword(String hashedPswdAndSalt, String clearPswd) { if (StringUtils.isNotEmpty(hashedPswdAndSalt) && StringUtils.isNotEmpty(clearPswd)) { int idxOfSep = hashedPswdAndSalt.indexOf(PASSWORD_SEP); String storedHash = hashedPswdAndSalt.substring(0, idxOfSep); String salt = hashedPswdAndSalt.substring(idxOfSep + 1); SimpleDigest digest = new SimpleDigest(); digest.setBase64Salt(salt); return storedHash.equals(digest.digestBase64(clearPswd)); } else if (hashedPswdAndSalt == null && clearPswd == null) { return true; } else if (hashedPswdAndSalt.isEmpty() && clearPswd.isEmpty()) { return true; } else { return false; } }
[ "public", "static", "boolean", "matchPassword", "(", "String", "hashedPswdAndSalt", ",", "String", "clearPswd", ")", "{", "if", "(", "StringUtils", ".", "isNotEmpty", "(", "hashedPswdAndSalt", ")", "&&", "StringUtils", ".", "isNotEmpty", "(", "clearPswd", ")", ")", "{", "int", "idxOfSep", "=", "hashedPswdAndSalt", ".", "indexOf", "(", "PASSWORD_SEP", ")", ";", "String", "storedHash", "=", "hashedPswdAndSalt", ".", "substring", "(", "0", ",", "idxOfSep", ")", ";", "String", "salt", "=", "hashedPswdAndSalt", ".", "substring", "(", "idxOfSep", "+", "1", ")", ";", "SimpleDigest", "digest", "=", "new", "SimpleDigest", "(", ")", ";", "digest", ".", "setBase64Salt", "(", "salt", ")", ";", "return", "storedHash", ".", "equals", "(", "digest", ".", "digestBase64", "(", "clearPswd", ")", ")", ";", "}", "else", "if", "(", "hashedPswdAndSalt", "==", "null", "&&", "clearPswd", "==", "null", ")", "{", "return", "true", ";", "}", "else", "if", "(", "hashedPswdAndSalt", ".", "isEmpty", "(", ")", "&&", "clearPswd", ".", "isEmpty", "(", ")", ")", "{", "return", "true", ";", "}", "else", "{", "return", "false", ";", "}", "}" ]
Returns true if it's a password match, that is, if the hashed clear password equals the given hash. @param hashedPswdAndSalt the hashed password + {@link #PASSWORD_SEP} + salt, as returned by {@link #hashPassword(String)} @param clearPswd the password that we're trying to match, in clear @return if the password matches
[ "Returns", "true", "if", "it", "s", "a", "password", "match", "that", "is", "if", "the", "hashed", "clear", "password", "equals", "the", "given", "hash", "." ]
3074fe49e56c2a4aae0832f40b17ae563335dc83
https://github.com/craftercms/commons/blob/3074fe49e56c2a4aae0832f40b17ae563335dc83/utilities/src/main/java/org/craftercms/commons/crypto/CryptoUtils.java#L120-L137
6,914
craftercms/commons
utilities/src/main/java/org/craftercms/commons/collections/IterableUtils.java
IterableUtils.toList
public static <T> List<T> toList(Iterable<T> iterable) { List<T> list = null; if (iterable != null) { list = new ArrayList<>(); for (T elem : iterable) { list.add(elem); } } return list; }
java
public static <T> List<T> toList(Iterable<T> iterable) { List<T> list = null; if (iterable != null) { list = new ArrayList<>(); for (T elem : iterable) { list.add(elem); } } return list; }
[ "public", "static", "<", "T", ">", "List", "<", "T", ">", "toList", "(", "Iterable", "<", "T", ">", "iterable", ")", "{", "List", "<", "T", ">", "list", "=", "null", ";", "if", "(", "iterable", "!=", "null", ")", "{", "list", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "T", "elem", ":", "iterable", ")", "{", "list", ".", "add", "(", "elem", ")", ";", "}", "}", "return", "list", ";", "}" ]
Creates a new list from the iterable elements. @param iterable the iterable @return a list with the iterable elements
[ "Creates", "a", "new", "list", "from", "the", "iterable", "elements", "." ]
3074fe49e56c2a4aae0832f40b17ae563335dc83
https://github.com/craftercms/commons/blob/3074fe49e56c2a4aae0832f40b17ae563335dc83/utilities/src/main/java/org/craftercms/commons/collections/IterableUtils.java#L39-L50
6,915
craftercms/commons
utilities/src/main/java/org/craftercms/commons/collections/IterableUtils.java
IterableUtils.count
public static <T> int count(Iterable<T> iterable) { int count = 0; if (iterable != null) { Iterator<T> iter = iterable.iterator(); while (iter.hasNext()) { iter.next(); count++; } } return count; }
java
public static <T> int count(Iterable<T> iterable) { int count = 0; if (iterable != null) { Iterator<T> iter = iterable.iterator(); while (iter.hasNext()) { iter.next(); count++; } } return count; }
[ "public", "static", "<", "T", ">", "int", "count", "(", "Iterable", "<", "T", ">", "iterable", ")", "{", "int", "count", "=", "0", ";", "if", "(", "iterable", "!=", "null", ")", "{", "Iterator", "<", "T", ">", "iter", "=", "iterable", ".", "iterator", "(", ")", ";", "while", "(", "iter", ".", "hasNext", "(", ")", ")", "{", "iter", ".", "next", "(", ")", ";", "count", "++", ";", "}", "}", "return", "count", ";", "}" ]
Returns the number of elements the iterable contains. @param iterable the iterable @return the element count of the iterable
[ "Returns", "the", "number", "of", "elements", "the", "iterable", "contains", "." ]
3074fe49e56c2a4aae0832f40b17ae563335dc83
https://github.com/craftercms/commons/blob/3074fe49e56c2a4aae0832f40b17ae563335dc83/utilities/src/main/java/org/craftercms/commons/collections/IterableUtils.java#L58-L70
6,916
craftercms/commons
utilities/src/main/java/org/craftercms/commons/http/HttpUtils.java
HttpUtils.getBaseRequestUrl
public static StringBuilder getBaseRequestUrl(HttpServletRequest request, boolean forceHttps) { String scheme = forceHttps ? HTTPS_SCHEME : request.getScheme(); String serverName = request.getServerName(); int serverPort = request.getServerPort(); StringBuilder url = new StringBuilder(); url.append(scheme).append("://").append(serverName); if (!(scheme.equals(HTTP_SCHEME) && serverPort == DEFAULT_HTTP_PORT) && !(scheme.equals(HTTPS_SCHEME) && serverPort == DEFAULT_HTTPS_PORT)) { url.append(":").append(serverPort); } return url; }
java
public static StringBuilder getBaseRequestUrl(HttpServletRequest request, boolean forceHttps) { String scheme = forceHttps ? HTTPS_SCHEME : request.getScheme(); String serverName = request.getServerName(); int serverPort = request.getServerPort(); StringBuilder url = new StringBuilder(); url.append(scheme).append("://").append(serverName); if (!(scheme.equals(HTTP_SCHEME) && serverPort == DEFAULT_HTTP_PORT) && !(scheme.equals(HTTPS_SCHEME) && serverPort == DEFAULT_HTTPS_PORT)) { url.append(":").append(serverPort); } return url; }
[ "public", "static", "StringBuilder", "getBaseRequestUrl", "(", "HttpServletRequest", "request", ",", "boolean", "forceHttps", ")", "{", "String", "scheme", "=", "forceHttps", "?", "HTTPS_SCHEME", ":", "request", ".", "getScheme", "(", ")", ";", "String", "serverName", "=", "request", ".", "getServerName", "(", ")", ";", "int", "serverPort", "=", "request", ".", "getServerPort", "(", ")", ";", "StringBuilder", "url", "=", "new", "StringBuilder", "(", ")", ";", "url", ".", "append", "(", "scheme", ")", ".", "append", "(", "\"://\"", ")", ".", "append", "(", "serverName", ")", ";", "if", "(", "!", "(", "scheme", ".", "equals", "(", "HTTP_SCHEME", ")", "&&", "serverPort", "==", "DEFAULT_HTTP_PORT", ")", "&&", "!", "(", "scheme", ".", "equals", "(", "HTTPS_SCHEME", ")", "&&", "serverPort", "==", "DEFAULT_HTTPS_PORT", ")", ")", "{", "url", ".", "append", "(", "\":\"", ")", ".", "append", "(", "serverPort", ")", ";", "}", "return", "url", ";", "}" ]
Returns the portion from the URL that includes the scheme, server name and port number, without the server path. @param request the request object used to build the base URL @param forceHttps if HTTPS should be enforced @return the base request URL
[ "Returns", "the", "portion", "from", "the", "URL", "that", "includes", "the", "scheme", "server", "name", "and", "port", "number", "without", "the", "server", "path", "." ]
3074fe49e56c2a4aae0832f40b17ae563335dc83
https://github.com/craftercms/commons/blob/3074fe49e56c2a4aae0832f40b17ae563335dc83/utilities/src/main/java/org/craftercms/commons/http/HttpUtils.java#L64-L78
6,917
craftercms/commons
utilities/src/main/java/org/craftercms/commons/http/HttpUtils.java
HttpUtils.getFullUrl
public static String getFullUrl(HttpServletRequest request, String relativeUrl) { StringBuilder baseUrl = getBaseRequestUrl(request, false); String contextPath = request.getContextPath(); String servletPath = request.getServletPath(); if (contextPath.equals("/")) { contextPath = ""; } if (servletPath.equals("/")) { servletPath = ""; } return baseUrl.append(contextPath).append(servletPath).append(relativeUrl).toString(); }
java
public static String getFullUrl(HttpServletRequest request, String relativeUrl) { StringBuilder baseUrl = getBaseRequestUrl(request, false); String contextPath = request.getContextPath(); String servletPath = request.getServletPath(); if (contextPath.equals("/")) { contextPath = ""; } if (servletPath.equals("/")) { servletPath = ""; } return baseUrl.append(contextPath).append(servletPath).append(relativeUrl).toString(); }
[ "public", "static", "String", "getFullUrl", "(", "HttpServletRequest", "request", ",", "String", "relativeUrl", ")", "{", "StringBuilder", "baseUrl", "=", "getBaseRequestUrl", "(", "request", ",", "false", ")", ";", "String", "contextPath", "=", "request", ".", "getContextPath", "(", ")", ";", "String", "servletPath", "=", "request", ".", "getServletPath", "(", ")", ";", "if", "(", "contextPath", ".", "equals", "(", "\"/\"", ")", ")", "{", "contextPath", "=", "\"\"", ";", "}", "if", "(", "servletPath", ".", "equals", "(", "\"/\"", ")", ")", "{", "servletPath", "=", "\"\"", ";", "}", "return", "baseUrl", ".", "append", "(", "contextPath", ")", ".", "append", "(", "servletPath", ")", ".", "append", "(", "relativeUrl", ")", ".", "toString", "(", ")", ";", "}" ]
Returns the full URL for the relative URL based in the specified request. The full URL includes the scheme, server name, port number, context path and server path. @param request the request object used to build the base URL @param relativeUrl the relative URL @return the full URL
[ "Returns", "the", "full", "URL", "for", "the", "relative", "URL", "based", "in", "the", "specified", "request", ".", "The", "full", "URL", "includes", "the", "scheme", "server", "name", "port", "number", "context", "path", "and", "server", "path", "." ]
3074fe49e56c2a4aae0832f40b17ae563335dc83
https://github.com/craftercms/commons/blob/3074fe49e56c2a4aae0832f40b17ae563335dc83/utilities/src/main/java/org/craftercms/commons/http/HttpUtils.java#L89-L102
6,918
craftercms/commons
utilities/src/main/java/org/craftercms/commons/http/HttpUtils.java
HttpUtils.getRequestUriWithoutContextPath
public static final String getRequestUriWithoutContextPath(HttpServletRequest request) { String uri = request.getRequestURI().substring(request.getContextPath().length()); if (!uri.isEmpty()) { return uri; } else { return "/"; } }
java
public static final String getRequestUriWithoutContextPath(HttpServletRequest request) { String uri = request.getRequestURI().substring(request.getContextPath().length()); if (!uri.isEmpty()) { return uri; } else { return "/"; } }
[ "public", "static", "final", "String", "getRequestUriWithoutContextPath", "(", "HttpServletRequest", "request", ")", "{", "String", "uri", "=", "request", ".", "getRequestURI", "(", ")", ".", "substring", "(", "request", ".", "getContextPath", "(", ")", ".", "length", "(", ")", ")", ";", "if", "(", "!", "uri", ".", "isEmpty", "(", ")", ")", "{", "return", "uri", ";", "}", "else", "{", "return", "\"/\"", ";", "}", "}" ]
Returns the request URI without the context path. @param request the request where to get the URI from
[ "Returns", "the", "request", "URI", "without", "the", "context", "path", "." ]
3074fe49e56c2a4aae0832f40b17ae563335dc83
https://github.com/craftercms/commons/blob/3074fe49e56c2a4aae0832f40b17ae563335dc83/utilities/src/main/java/org/craftercms/commons/http/HttpUtils.java#L109-L116
6,919
craftercms/commons
utilities/src/main/java/org/craftercms/commons/http/HttpUtils.java
HttpUtils.getFullRequestUri
public static final String getFullRequestUri(HttpServletRequest request, boolean includeQueryString) { StringBuilder uri = getBaseRequestUrl(request, false).append(request.getRequestURI()); if (includeQueryString) { String queryStr = request.getQueryString(); if (StringUtils.isNotEmpty(queryStr)) { uri.append('?').append(queryStr); } } return uri.toString(); }
java
public static final String getFullRequestUri(HttpServletRequest request, boolean includeQueryString) { StringBuilder uri = getBaseRequestUrl(request, false).append(request.getRequestURI()); if (includeQueryString) { String queryStr = request.getQueryString(); if (StringUtils.isNotEmpty(queryStr)) { uri.append('?').append(queryStr); } } return uri.toString(); }
[ "public", "static", "final", "String", "getFullRequestUri", "(", "HttpServletRequest", "request", ",", "boolean", "includeQueryString", ")", "{", "StringBuilder", "uri", "=", "getBaseRequestUrl", "(", "request", ",", "false", ")", ".", "append", "(", "request", ".", "getRequestURI", "(", ")", ")", ";", "if", "(", "includeQueryString", ")", "{", "String", "queryStr", "=", "request", ".", "getQueryString", "(", ")", ";", "if", "(", "StringUtils", ".", "isNotEmpty", "(", "queryStr", ")", ")", "{", "uri", ".", "append", "(", "'", "'", ")", ".", "append", "(", "queryStr", ")", ";", "}", "}", "return", "uri", ".", "toString", "(", ")", ";", "}" ]
Returns the full request URI, including scheme, server name, port number and server path. The query string is optional. @param request the request object used to build the URI @param includeQueryString if the query string should be appended to the URI @return the full request URI
[ "Returns", "the", "full", "request", "URI", "including", "scheme", "server", "name", "port", "number", "and", "server", "path", ".", "The", "query", "string", "is", "optional", "." ]
3074fe49e56c2a4aae0832f40b17ae563335dc83
https://github.com/craftercms/commons/blob/3074fe49e56c2a4aae0832f40b17ae563335dc83/utilities/src/main/java/org/craftercms/commons/http/HttpUtils.java#L127-L138
6,920
craftercms/commons
utilities/src/main/java/org/craftercms/commons/http/HttpUtils.java
HttpUtils.getCookie
public static Cookie getCookie(String name, HttpServletRequest request) { Cookie[] cookies = request.getCookies(); if (ArrayUtils.isNotEmpty(cookies)) { for (Cookie cookie : cookies) { if (cookie.getName().equals(name)) { return cookie; } } } return null; }
java
public static Cookie getCookie(String name, HttpServletRequest request) { Cookie[] cookies = request.getCookies(); if (ArrayUtils.isNotEmpty(cookies)) { for (Cookie cookie : cookies) { if (cookie.getName().equals(name)) { return cookie; } } } return null; }
[ "public", "static", "Cookie", "getCookie", "(", "String", "name", ",", "HttpServletRequest", "request", ")", "{", "Cookie", "[", "]", "cookies", "=", "request", ".", "getCookies", "(", ")", ";", "if", "(", "ArrayUtils", ".", "isNotEmpty", "(", "cookies", ")", ")", "{", "for", "(", "Cookie", "cookie", ":", "cookies", ")", "{", "if", "(", "cookie", ".", "getName", "(", ")", ".", "equals", "(", "name", ")", ")", "{", "return", "cookie", ";", "}", "}", "}", "return", "null", ";", "}" ]
Returns the cookie with the given name for the given request @param name the name of the cookie @param request the request where to extract the request from @return the cookie object, or null if not found
[ "Returns", "the", "cookie", "with", "the", "given", "name", "for", "the", "given", "request" ]
3074fe49e56c2a4aae0832f40b17ae563335dc83
https://github.com/craftercms/commons/blob/3074fe49e56c2a4aae0832f40b17ae563335dc83/utilities/src/main/java/org/craftercms/commons/http/HttpUtils.java#L148-L159
6,921
craftercms/commons
utilities/src/main/java/org/craftercms/commons/http/HttpUtils.java
HttpUtils.getCookieValue
public static String getCookieValue(String name, HttpServletRequest request) { Cookie cookie = getCookie(name, request); if (cookie != null) { return cookie.getValue(); } else { return null; } }
java
public static String getCookieValue(String name, HttpServletRequest request) { Cookie cookie = getCookie(name, request); if (cookie != null) { return cookie.getValue(); } else { return null; } }
[ "public", "static", "String", "getCookieValue", "(", "String", "name", ",", "HttpServletRequest", "request", ")", "{", "Cookie", "cookie", "=", "getCookie", "(", "name", ",", "request", ")", ";", "if", "(", "cookie", "!=", "null", ")", "{", "return", "cookie", ".", "getValue", "(", ")", ";", "}", "else", "{", "return", "null", ";", "}", "}" ]
Returns the cookie value with the given name for the given request @param name the name of the cookie @param request the request where to extract the request from @return the cookie value, or null if no cookie found
[ "Returns", "the", "cookie", "value", "with", "the", "given", "name", "for", "the", "given", "request" ]
3074fe49e56c2a4aae0832f40b17ae563335dc83
https://github.com/craftercms/commons/blob/3074fe49e56c2a4aae0832f40b17ae563335dc83/utilities/src/main/java/org/craftercms/commons/http/HttpUtils.java#L169-L176
6,922
craftercms/commons
utilities/src/main/java/org/craftercms/commons/http/HttpUtils.java
HttpUtils.addValue
public static void addValue(String key, Object value, MultiValueMap<String, String> params) { if (value != null) { params.add(key, value.toString()); } }
java
public static void addValue(String key, Object value, MultiValueMap<String, String> params) { if (value != null) { params.add(key, value.toString()); } }
[ "public", "static", "void", "addValue", "(", "String", "key", ",", "Object", "value", ",", "MultiValueMap", "<", "String", ",", "String", ">", "params", ")", "{", "if", "(", "value", "!=", "null", ")", "{", "params", ".", "add", "(", "key", ",", "value", ".", "toString", "(", ")", ")", ";", "}", "}" ]
Adds a param value to a params map. If value is null, nothing is done. @param key the param key @param value the param value @param params the params map
[ "Adds", "a", "param", "value", "to", "a", "params", "map", ".", "If", "value", "is", "null", "nothing", "is", "done", "." ]
3074fe49e56c2a4aae0832f40b17ae563335dc83
https://github.com/craftercms/commons/blob/3074fe49e56c2a4aae0832f40b17ae563335dc83/utilities/src/main/java/org/craftercms/commons/http/HttpUtils.java#L185-L189
6,923
craftercms/commons
utilities/src/main/java/org/craftercms/commons/http/HttpUtils.java
HttpUtils.addValues
public static void addValues(String key, Collection<String> values, MultiValueMap<String, String> params) { if (values != null) { for (String value : values) { params.add(key, value); } } }
java
public static void addValues(String key, Collection<String> values, MultiValueMap<String, String> params) { if (values != null) { for (String value : values) { params.add(key, value); } } }
[ "public", "static", "void", "addValues", "(", "String", "key", ",", "Collection", "<", "String", ">", "values", ",", "MultiValueMap", "<", "String", ",", "String", ">", "params", ")", "{", "if", "(", "values", "!=", "null", ")", "{", "for", "(", "String", "value", ":", "values", ")", "{", "params", ".", "add", "(", "key", ",", "value", ")", ";", "}", "}", "}" ]
Adds a collection of param values to a params map. If the collection is null, nothing is done. @param key the param key @param values the collection of param values @param params the params map
[ "Adds", "a", "collection", "of", "param", "values", "to", "a", "params", "map", ".", "If", "the", "collection", "is", "null", "nothing", "is", "done", "." ]
3074fe49e56c2a4aae0832f40b17ae563335dc83
https://github.com/craftercms/commons/blob/3074fe49e56c2a4aae0832f40b17ae563335dc83/utilities/src/main/java/org/craftercms/commons/http/HttpUtils.java#L198-L204
6,924
craftercms/commons
utilities/src/main/java/org/craftercms/commons/http/HttpUtils.java
HttpUtils.getParamsFromQueryString
@SuppressWarnings("unchecked") public static MultiValueMap<String, String> getParamsFromQueryString(String queryString) { MultiValueMap queryParams = new LinkedMultiValueMap<>(); if (StringUtils.isNotEmpty(queryString)) { String[] params = queryString.split("&"); for (String param : params) { String[] splitParam = param.split("="); String paramName = splitParam[0]; String paramValue = splitParam[1]; queryParams.add(paramName, paramValue); } } return queryParams; }
java
@SuppressWarnings("unchecked") public static MultiValueMap<String, String> getParamsFromQueryString(String queryString) { MultiValueMap queryParams = new LinkedMultiValueMap<>(); if (StringUtils.isNotEmpty(queryString)) { String[] params = queryString.split("&"); for (String param : params) { String[] splitParam = param.split("="); String paramName = splitParam[0]; String paramValue = splitParam[1]; queryParams.add(paramName, paramValue); } } return queryParams; }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "static", "MultiValueMap", "<", "String", ",", "String", ">", "getParamsFromQueryString", "(", "String", "queryString", ")", "{", "MultiValueMap", "queryParams", "=", "new", "LinkedMultiValueMap", "<>", "(", ")", ";", "if", "(", "StringUtils", ".", "isNotEmpty", "(", "queryString", ")", ")", "{", "String", "[", "]", "params", "=", "queryString", ".", "split", "(", "\"&\"", ")", ";", "for", "(", "String", "param", ":", "params", ")", "{", "String", "[", "]", "splitParam", "=", "param", ".", "split", "(", "\"=\"", ")", ";", "String", "paramName", "=", "splitParam", "[", "0", "]", ";", "String", "paramValue", "=", "splitParam", "[", "1", "]", ";", "queryParams", ".", "add", "(", "paramName", ",", "paramValue", ")", ";", "}", "}", "return", "queryParams", ";", "}" ]
Returns a map with the extracted parameters from the specified query string. A multi value map is used since there can be several values for the same param. @param queryString the query string to extract the params from @return the param map
[ "Returns", "a", "map", "with", "the", "extracted", "parameters", "from", "the", "specified", "query", "string", ".", "A", "multi", "value", "map", "is", "used", "since", "there", "can", "be", "several", "values", "for", "the", "same", "param", "." ]
3074fe49e56c2a4aae0832f40b17ae563335dc83
https://github.com/craftercms/commons/blob/3074fe49e56c2a4aae0832f40b17ae563335dc83/utilities/src/main/java/org/craftercms/commons/http/HttpUtils.java#L228-L244
6,925
craftercms/commons
utilities/src/main/java/org/craftercms/commons/http/HttpUtils.java
HttpUtils.createRequestParamsMap
public static Map<String, Object> createRequestParamsMap(HttpServletRequest request) { Map<String, Object> paramsMap = new HashMap<>(); for (Enumeration paramNameEnum = request.getParameterNames(); paramNameEnum.hasMoreElements(); ) { String paramName = (String)paramNameEnum.nextElement(); String[] paramValues = request.getParameterValues(paramName); if (paramValues.length == 1) { paramsMap.put(paramName, paramValues[0]); } else { paramsMap.put(paramName, paramValues); } } return paramsMap; }
java
public static Map<String, Object> createRequestParamsMap(HttpServletRequest request) { Map<String, Object> paramsMap = new HashMap<>(); for (Enumeration paramNameEnum = request.getParameterNames(); paramNameEnum.hasMoreElements(); ) { String paramName = (String)paramNameEnum.nextElement(); String[] paramValues = request.getParameterValues(paramName); if (paramValues.length == 1) { paramsMap.put(paramName, paramValues[0]); } else { paramsMap.put(paramName, paramValues); } } return paramsMap; }
[ "public", "static", "Map", "<", "String", ",", "Object", ">", "createRequestParamsMap", "(", "HttpServletRequest", "request", ")", "{", "Map", "<", "String", ",", "Object", ">", "paramsMap", "=", "new", "HashMap", "<>", "(", ")", ";", "for", "(", "Enumeration", "paramNameEnum", "=", "request", ".", "getParameterNames", "(", ")", ";", "paramNameEnum", ".", "hasMoreElements", "(", ")", ";", ")", "{", "String", "paramName", "=", "(", "String", ")", "paramNameEnum", ".", "nextElement", "(", ")", ";", "String", "[", "]", "paramValues", "=", "request", ".", "getParameterValues", "(", "paramName", ")", ";", "if", "(", "paramValues", ".", "length", "==", "1", ")", "{", "paramsMap", ".", "put", "(", "paramName", ",", "paramValues", "[", "0", "]", ")", ";", "}", "else", "{", "paramsMap", ".", "put", "(", "paramName", ",", "paramValues", ")", ";", "}", "}", "return", "paramsMap", ";", "}" ]
Creates a map from the parameters in the specified request. Multi value parameters will be in an array. @param request the request
[ "Creates", "a", "map", "from", "the", "parameters", "in", "the", "specified", "request", ".", "Multi", "value", "parameters", "will", "be", "in", "an", "array", "." ]
3074fe49e56c2a4aae0832f40b17ae563335dc83
https://github.com/craftercms/commons/blob/3074fe49e56c2a4aae0832f40b17ae563335dc83/utilities/src/main/java/org/craftercms/commons/http/HttpUtils.java#L318-L332
6,926
craftercms/commons
utilities/src/main/java/org/craftercms/commons/http/HttpUtils.java
HttpUtils.createRequestAttributesMap
public static Map<String, Object> createRequestAttributesMap(HttpServletRequest request) { Map<String, Object> attributesMap = new HashMap<>(); for (Enumeration attributeNameEnum = request.getAttributeNames(); attributeNameEnum.hasMoreElements(); ) { String attributeName = (String)attributeNameEnum.nextElement(); attributesMap.put(attributeName, request.getAttribute(attributeName)); } return attributesMap; }
java
public static Map<String, Object> createRequestAttributesMap(HttpServletRequest request) { Map<String, Object> attributesMap = new HashMap<>(); for (Enumeration attributeNameEnum = request.getAttributeNames(); attributeNameEnum.hasMoreElements(); ) { String attributeName = (String)attributeNameEnum.nextElement(); attributesMap.put(attributeName, request.getAttribute(attributeName)); } return attributesMap; }
[ "public", "static", "Map", "<", "String", ",", "Object", ">", "createRequestAttributesMap", "(", "HttpServletRequest", "request", ")", "{", "Map", "<", "String", ",", "Object", ">", "attributesMap", "=", "new", "HashMap", "<>", "(", ")", ";", "for", "(", "Enumeration", "attributeNameEnum", "=", "request", ".", "getAttributeNames", "(", ")", ";", "attributeNameEnum", ".", "hasMoreElements", "(", ")", ";", ")", "{", "String", "attributeName", "=", "(", "String", ")", "attributeNameEnum", ".", "nextElement", "(", ")", ";", "attributesMap", ".", "put", "(", "attributeName", ",", "request", ".", "getAttribute", "(", "attributeName", ")", ")", ";", "}", "return", "attributesMap", ";", "}" ]
Creates a map from the request attributes in the specified request. @param request the request
[ "Creates", "a", "map", "from", "the", "request", "attributes", "in", "the", "specified", "request", "." ]
3074fe49e56c2a4aae0832f40b17ae563335dc83
https://github.com/craftercms/commons/blob/3074fe49e56c2a4aae0832f40b17ae563335dc83/utilities/src/main/java/org/craftercms/commons/http/HttpUtils.java#L339-L348
6,927
craftercms/commons
utilities/src/main/java/org/craftercms/commons/http/HttpUtils.java
HttpUtils.createHeadersMap
public static Map<String, Object> createHeadersMap(HttpServletRequest request) { Map<String, Object> headersMap = new HashMap<>(); for (Enumeration headerNameEnum = request.getHeaderNames(); headerNameEnum.hasMoreElements(); ) { String headerName = (String)headerNameEnum.nextElement(); List<String> headerValues = new ArrayList<String>(); CollectionUtils.addAll(headerValues, request.getHeaders(headerName)); if (headerValues.size() == 1) { headersMap.put(headerName, headerValues.get(0)); } else { headersMap.put(headerName, headerValues.toArray(new String[headerValues.size()])); } } return headersMap; }
java
public static Map<String, Object> createHeadersMap(HttpServletRequest request) { Map<String, Object> headersMap = new HashMap<>(); for (Enumeration headerNameEnum = request.getHeaderNames(); headerNameEnum.hasMoreElements(); ) { String headerName = (String)headerNameEnum.nextElement(); List<String> headerValues = new ArrayList<String>(); CollectionUtils.addAll(headerValues, request.getHeaders(headerName)); if (headerValues.size() == 1) { headersMap.put(headerName, headerValues.get(0)); } else { headersMap.put(headerName, headerValues.toArray(new String[headerValues.size()])); } } return headersMap; }
[ "public", "static", "Map", "<", "String", ",", "Object", ">", "createHeadersMap", "(", "HttpServletRequest", "request", ")", "{", "Map", "<", "String", ",", "Object", ">", "headersMap", "=", "new", "HashMap", "<>", "(", ")", ";", "for", "(", "Enumeration", "headerNameEnum", "=", "request", ".", "getHeaderNames", "(", ")", ";", "headerNameEnum", ".", "hasMoreElements", "(", ")", ";", ")", "{", "String", "headerName", "=", "(", "String", ")", "headerNameEnum", ".", "nextElement", "(", ")", ";", "List", "<", "String", ">", "headerValues", "=", "new", "ArrayList", "<", "String", ">", "(", ")", ";", "CollectionUtils", ".", "addAll", "(", "headerValues", ",", "request", ".", "getHeaders", "(", "headerName", ")", ")", ";", "if", "(", "headerValues", ".", "size", "(", ")", "==", "1", ")", "{", "headersMap", ".", "put", "(", "headerName", ",", "headerValues", ".", "get", "(", "0", ")", ")", ";", "}", "else", "{", "headersMap", ".", "put", "(", "headerName", ",", "headerValues", ".", "toArray", "(", "new", "String", "[", "headerValues", ".", "size", "(", ")", "]", ")", ")", ";", "}", "}", "return", "headersMap", ";", "}" ]
Creates a map from the headers in the specified request. Multi value headers will be in an array. @param request the request
[ "Creates", "a", "map", "from", "the", "headers", "in", "the", "specified", "request", ".", "Multi", "value", "headers", "will", "be", "in", "an", "array", "." ]
3074fe49e56c2a4aae0832f40b17ae563335dc83
https://github.com/craftercms/commons/blob/3074fe49e56c2a4aae0832f40b17ae563335dc83/utilities/src/main/java/org/craftercms/commons/http/HttpUtils.java#L355-L371
6,928
craftercms/commons
utilities/src/main/java/org/craftercms/commons/http/HttpUtils.java
HttpUtils.createCookiesMap
public static Map<String, String> createCookiesMap(HttpServletRequest request) { Map<String, String> cookiesMap = new HashMap<String, String>(); Cookie[] cookies = request.getCookies(); if (ArrayUtils.isNotEmpty(cookies)) { for (Cookie cookie : request.getCookies()) { cookiesMap.put(cookie.getName(), cookie.getValue()); } } return cookiesMap; }
java
public static Map<String, String> createCookiesMap(HttpServletRequest request) { Map<String, String> cookiesMap = new HashMap<String, String>(); Cookie[] cookies = request.getCookies(); if (ArrayUtils.isNotEmpty(cookies)) { for (Cookie cookie : request.getCookies()) { cookiesMap.put(cookie.getName(), cookie.getValue()); } } return cookiesMap; }
[ "public", "static", "Map", "<", "String", ",", "String", ">", "createCookiesMap", "(", "HttpServletRequest", "request", ")", "{", "Map", "<", "String", ",", "String", ">", "cookiesMap", "=", "new", "HashMap", "<", "String", ",", "String", ">", "(", ")", ";", "Cookie", "[", "]", "cookies", "=", "request", ".", "getCookies", "(", ")", ";", "if", "(", "ArrayUtils", ".", "isNotEmpty", "(", "cookies", ")", ")", "{", "for", "(", "Cookie", "cookie", ":", "request", ".", "getCookies", "(", ")", ")", "{", "cookiesMap", ".", "put", "(", "cookie", ".", "getName", "(", ")", ",", "cookie", ".", "getValue", "(", ")", ")", ";", "}", "}", "return", "cookiesMap", ";", "}" ]
Creates a map from the cookies in the specified request. @param request the request
[ "Creates", "a", "map", "from", "the", "cookies", "in", "the", "specified", "request", "." ]
3074fe49e56c2a4aae0832f40b17ae563335dc83
https://github.com/craftercms/commons/blob/3074fe49e56c2a4aae0832f40b17ae563335dc83/utilities/src/main/java/org/craftercms/commons/http/HttpUtils.java#L378-L389
6,929
craftercms/commons
utilities/src/main/java/org/craftercms/commons/http/HttpUtils.java
HttpUtils.createSessionMap
public static Map<String, Object> createSessionMap(HttpServletRequest request) { Map<String, Object> sessionMap = new HashMap<>(); HttpSession session = request.getSession(false); if (session != null) { for (Enumeration attributeNameEnum = session.getAttributeNames(); attributeNameEnum.hasMoreElements(); ) { String attributeName = (String)attributeNameEnum.nextElement(); sessionMap.put(attributeName, session.getAttribute(attributeName)); } } return sessionMap; }
java
public static Map<String, Object> createSessionMap(HttpServletRequest request) { Map<String, Object> sessionMap = new HashMap<>(); HttpSession session = request.getSession(false); if (session != null) { for (Enumeration attributeNameEnum = session.getAttributeNames(); attributeNameEnum.hasMoreElements(); ) { String attributeName = (String)attributeNameEnum.nextElement(); sessionMap.put(attributeName, session.getAttribute(attributeName)); } } return sessionMap; }
[ "public", "static", "Map", "<", "String", ",", "Object", ">", "createSessionMap", "(", "HttpServletRequest", "request", ")", "{", "Map", "<", "String", ",", "Object", ">", "sessionMap", "=", "new", "HashMap", "<>", "(", ")", ";", "HttpSession", "session", "=", "request", ".", "getSession", "(", "false", ")", ";", "if", "(", "session", "!=", "null", ")", "{", "for", "(", "Enumeration", "attributeNameEnum", "=", "session", ".", "getAttributeNames", "(", ")", ";", "attributeNameEnum", ".", "hasMoreElements", "(", ")", ";", ")", "{", "String", "attributeName", "=", "(", "String", ")", "attributeNameEnum", ".", "nextElement", "(", ")", ";", "sessionMap", ".", "put", "(", "attributeName", ",", "session", ".", "getAttribute", "(", "attributeName", ")", ")", ";", "}", "}", "return", "sessionMap", ";", "}" ]
Creates a map from the session attributes in the specified request. @param request the request
[ "Creates", "a", "map", "from", "the", "session", "attributes", "in", "the", "specified", "request", "." ]
3074fe49e56c2a4aae0832f40b17ae563335dc83
https://github.com/craftercms/commons/blob/3074fe49e56c2a4aae0832f40b17ae563335dc83/utilities/src/main/java/org/craftercms/commons/http/HttpUtils.java#L396-L408
6,930
craftercms/commons
utilities/src/main/java/org/craftercms/commons/http/HttpUtils.java
HttpUtils.disableCaching
public static void disableCaching(HttpServletResponse response) { response.addHeader(PRAGMA_HEADER_NAME, "no-cache"); response.addHeader(CACHE_CONTROL_HEADER_NAME, "no-cache, no-store, max-age=0"); response.addDateHeader(EXPIRES_HEADER_NAME, 1L); }
java
public static void disableCaching(HttpServletResponse response) { response.addHeader(PRAGMA_HEADER_NAME, "no-cache"); response.addHeader(CACHE_CONTROL_HEADER_NAME, "no-cache, no-store, max-age=0"); response.addDateHeader(EXPIRES_HEADER_NAME, 1L); }
[ "public", "static", "void", "disableCaching", "(", "HttpServletResponse", "response", ")", "{", "response", ".", "addHeader", "(", "PRAGMA_HEADER_NAME", ",", "\"no-cache\"", ")", ";", "response", ".", "addHeader", "(", "CACHE_CONTROL_HEADER_NAME", ",", "\"no-cache, no-store, max-age=0\"", ")", ";", "response", ".", "addDateHeader", "(", "EXPIRES_HEADER_NAME", ",", "1L", ")", ";", "}" ]
Disable caching in the client. @param response the response to add the headers for disabling caching.
[ "Disable", "caching", "in", "the", "client", "." ]
3074fe49e56c2a4aae0832f40b17ae563335dc83
https://github.com/craftercms/commons/blob/3074fe49e56c2a4aae0832f40b17ae563335dc83/utilities/src/main/java/org/craftercms/commons/http/HttpUtils.java#L415-L419
6,931
craftercms/commons
utilities/src/main/java/org/craftercms/commons/http/CookieManager.java
CookieManager.addCookie
public void addCookie(String name, String value, HttpServletResponse response) { Cookie cookie = new Cookie(name, value); cookie.setHttpOnly(httpOnly); cookie.setSecure(secure); if (StringUtils.isNotEmpty(domain)) { cookie.setDomain(domain); } if (StringUtils.isNotEmpty(path)) { cookie.setPath(path); } if (maxAge != null) { cookie.setMaxAge(maxAge); } response.addCookie(cookie); logger.debug(LOG_KEY_ADDED_COOKIE, name); }
java
public void addCookie(String name, String value, HttpServletResponse response) { Cookie cookie = new Cookie(name, value); cookie.setHttpOnly(httpOnly); cookie.setSecure(secure); if (StringUtils.isNotEmpty(domain)) { cookie.setDomain(domain); } if (StringUtils.isNotEmpty(path)) { cookie.setPath(path); } if (maxAge != null) { cookie.setMaxAge(maxAge); } response.addCookie(cookie); logger.debug(LOG_KEY_ADDED_COOKIE, name); }
[ "public", "void", "addCookie", "(", "String", "name", ",", "String", "value", ",", "HttpServletResponse", "response", ")", "{", "Cookie", "cookie", "=", "new", "Cookie", "(", "name", ",", "value", ")", ";", "cookie", ".", "setHttpOnly", "(", "httpOnly", ")", ";", "cookie", ".", "setSecure", "(", "secure", ")", ";", "if", "(", "StringUtils", ".", "isNotEmpty", "(", "domain", ")", ")", "{", "cookie", ".", "setDomain", "(", "domain", ")", ";", "}", "if", "(", "StringUtils", ".", "isNotEmpty", "(", "path", ")", ")", "{", "cookie", ".", "setPath", "(", "path", ")", ";", "}", "if", "(", "maxAge", "!=", "null", ")", "{", "cookie", ".", "setMaxAge", "(", "maxAge", ")", ";", "}", "response", ".", "addCookie", "(", "cookie", ")", ";", "logger", ".", "debug", "(", "LOG_KEY_ADDED_COOKIE", ",", "name", ")", ";", "}" ]
Add a new cookie, using the configured domain, path and max age, to the response. @param name the name of the cookie @param value the value of the cookie
[ "Add", "a", "new", "cookie", "using", "the", "configured", "domain", "path", "and", "max", "age", "to", "the", "response", "." ]
3074fe49e56c2a4aae0832f40b17ae563335dc83
https://github.com/craftercms/commons/blob/3074fe49e56c2a4aae0832f40b17ae563335dc83/utilities/src/main/java/org/craftercms/commons/http/CookieManager.java#L71-L88
6,932
craftercms/commons
utilities/src/main/java/org/craftercms/commons/rest/HttpMessageConvertingResponseWriter.java
HttpMessageConvertingResponseWriter.getAcceptableMediaTypes
protected List<MediaType> getAcceptableMediaTypes(HttpServletRequest request) throws HttpMediaTypeNotAcceptableException { List<MediaType> mediaTypes = contentNegotiationManager.resolveMediaTypes(new ServletWebRequest(request)); return mediaTypes.isEmpty() ? Collections.singletonList(MediaType.ALL) : mediaTypes; }
java
protected List<MediaType> getAcceptableMediaTypes(HttpServletRequest request) throws HttpMediaTypeNotAcceptableException { List<MediaType> mediaTypes = contentNegotiationManager.resolveMediaTypes(new ServletWebRequest(request)); return mediaTypes.isEmpty() ? Collections.singletonList(MediaType.ALL) : mediaTypes; }
[ "protected", "List", "<", "MediaType", ">", "getAcceptableMediaTypes", "(", "HttpServletRequest", "request", ")", "throws", "HttpMediaTypeNotAcceptableException", "{", "List", "<", "MediaType", ">", "mediaTypes", "=", "contentNegotiationManager", ".", "resolveMediaTypes", "(", "new", "ServletWebRequest", "(", "request", ")", ")", ";", "return", "mediaTypes", ".", "isEmpty", "(", ")", "?", "Collections", ".", "singletonList", "(", "MediaType", ".", "ALL", ")", ":", "mediaTypes", ";", "}" ]
Return the acceptable media types from the request.
[ "Return", "the", "acceptable", "media", "types", "from", "the", "request", "." ]
3074fe49e56c2a4aae0832f40b17ae563335dc83
https://github.com/craftercms/commons/blob/3074fe49e56c2a4aae0832f40b17ae563335dc83/utilities/src/main/java/org/craftercms/commons/rest/HttpMessageConvertingResponseWriter.java#L141-L145
6,933
craftercms/commons
utilities/src/main/java/org/craftercms/commons/rest/HttpMessageConvertingResponseWriter.java
HttpMessageConvertingResponseWriter.getMostSpecificMediaType
protected MediaType getMostSpecificMediaType(MediaType acceptType, MediaType produceType) { produceType = produceType.copyQualityValue(acceptType); return MediaType.SPECIFICITY_COMPARATOR.compare(acceptType, produceType) <= 0 ? acceptType : produceType; }
java
protected MediaType getMostSpecificMediaType(MediaType acceptType, MediaType produceType) { produceType = produceType.copyQualityValue(acceptType); return MediaType.SPECIFICITY_COMPARATOR.compare(acceptType, produceType) <= 0 ? acceptType : produceType; }
[ "protected", "MediaType", "getMostSpecificMediaType", "(", "MediaType", "acceptType", ",", "MediaType", "produceType", ")", "{", "produceType", "=", "produceType", ".", "copyQualityValue", "(", "acceptType", ")", ";", "return", "MediaType", ".", "SPECIFICITY_COMPARATOR", ".", "compare", "(", "acceptType", ",", "produceType", ")", "<=", "0", "?", "acceptType", ":", "produceType", ";", "}" ]
Return the more specific of the acceptable and the producible media types with the q-value of the former.
[ "Return", "the", "more", "specific", "of", "the", "acceptable", "and", "the", "producible", "media", "types", "with", "the", "q", "-", "value", "of", "the", "former", "." ]
3074fe49e56c2a4aae0832f40b17ae563335dc83
https://github.com/craftercms/commons/blob/3074fe49e56c2a4aae0832f40b17ae563335dc83/utilities/src/main/java/org/craftercms/commons/rest/HttpMessageConvertingResponseWriter.java#L150-L154
6,934
spotify/logging-java
src/main/java/com/spotify/logging/LoggingConfigurator.java
LoggingConfigurator.configureNoLogging
public static void configureNoLogging() { final Logger rootLogger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); final LoggerContext context = rootLogger.getLoggerContext(); // Clear context, removing all appenders context.reset(); // Set logging level to OFF for (final Logger logger : context.getLoggerList()) { if (logger != rootLogger) { logger.setLevel(null); } } rootLogger.setLevel(OFF); }
java
public static void configureNoLogging() { final Logger rootLogger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); final LoggerContext context = rootLogger.getLoggerContext(); // Clear context, removing all appenders context.reset(); // Set logging level to OFF for (final Logger logger : context.getLoggerList()) { if (logger != rootLogger) { logger.setLevel(null); } } rootLogger.setLevel(OFF); }
[ "public", "static", "void", "configureNoLogging", "(", ")", "{", "final", "Logger", "rootLogger", "=", "(", "Logger", ")", "LoggerFactory", ".", "getLogger", "(", "Logger", ".", "ROOT_LOGGER_NAME", ")", ";", "final", "LoggerContext", "context", "=", "rootLogger", ".", "getLoggerContext", "(", ")", ";", "// Clear context, removing all appenders", "context", ".", "reset", "(", ")", ";", "// Set logging level to OFF", "for", "(", "final", "Logger", "logger", ":", "context", ".", "getLoggerList", "(", ")", ")", "{", "if", "(", "logger", "!=", "rootLogger", ")", "{", "logger", ".", "setLevel", "(", "null", ")", ";", "}", "}", "rootLogger", ".", "setLevel", "(", "OFF", ")", ";", "}" ]
Mute all logging.
[ "Mute", "all", "logging", "." ]
73a7ebf6578c5f4228953375214a0afb44318d4d
https://github.com/spotify/logging-java/blob/73a7ebf6578c5f4228953375214a0afb44318d4d/src/main/java/com/spotify/logging/LoggingConfigurator.java#L96-L110
6,935
spotify/logging-java
src/main/java/com/spotify/logging/LoggingConfigurator.java
LoggingConfigurator.addSentryAppender
public static SentryAppender addSentryAppender(final String dsn, Level logLevelThreshold) { final Logger rootLogger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); final LoggerContext context = rootLogger.getLoggerContext(); SentryAppender appender = new SentryAppender(); appender.setDsn(dsn); appender.setContext(context); ThresholdFilter levelFilter = new ThresholdFilter(); levelFilter.setLevel(logLevelThreshold.logbackLevel.toString()); levelFilter.start(); appender.addFilter(levelFilter); appender.start(); rootLogger.addAppender(appender); return appender; }
java
public static SentryAppender addSentryAppender(final String dsn, Level logLevelThreshold) { final Logger rootLogger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); final LoggerContext context = rootLogger.getLoggerContext(); SentryAppender appender = new SentryAppender(); appender.setDsn(dsn); appender.setContext(context); ThresholdFilter levelFilter = new ThresholdFilter(); levelFilter.setLevel(logLevelThreshold.logbackLevel.toString()); levelFilter.start(); appender.addFilter(levelFilter); appender.start(); rootLogger.addAppender(appender); return appender; }
[ "public", "static", "SentryAppender", "addSentryAppender", "(", "final", "String", "dsn", ",", "Level", "logLevelThreshold", ")", "{", "final", "Logger", "rootLogger", "=", "(", "Logger", ")", "LoggerFactory", ".", "getLogger", "(", "Logger", ".", "ROOT_LOGGER_NAME", ")", ";", "final", "LoggerContext", "context", "=", "rootLogger", ".", "getLoggerContext", "(", ")", ";", "SentryAppender", "appender", "=", "new", "SentryAppender", "(", ")", ";", "appender", ".", "setDsn", "(", "dsn", ")", ";", "appender", ".", "setContext", "(", "context", ")", ";", "ThresholdFilter", "levelFilter", "=", "new", "ThresholdFilter", "(", ")", ";", "levelFilter", ".", "setLevel", "(", "logLevelThreshold", ".", "logbackLevel", ".", "toString", "(", ")", ")", ";", "levelFilter", ".", "start", "(", ")", ";", "appender", ".", "addFilter", "(", "levelFilter", ")", ";", "appender", ".", "start", "(", ")", ";", "rootLogger", ".", "addAppender", "(", "appender", ")", ";", "return", "appender", ";", "}" ]
Add a sentry appender. @param dsn the sentry dsn to use (as produced by the sentry webinterface). @param logLevelThreshold the threshold for log events to be sent to sentry. @return the configured sentry appender.
[ "Add", "a", "sentry", "appender", "." ]
73a7ebf6578c5f4228953375214a0afb44318d4d
https://github.com/spotify/logging-java/blob/73a7ebf6578c5f4228953375214a0afb44318d4d/src/main/java/com/spotify/logging/LoggingConfigurator.java#L300-L319
6,936
spotify/logging-java
src/main/java/com/spotify/logging/LoggingConfigurator.java
LoggingConfigurator.getStdErrAppender
private static Appender<ILoggingEvent> getStdErrAppender(final LoggerContext context, final ReplaceNewLines replaceNewLines) { // Setup format final PatternLayoutEncoder encoder = new PatternLayoutEncoder(); encoder.setContext(context); encoder.setPattern( "%date{HH:mm:ss.SSS} %property{ident}[%property{pid}]: %-5level [%thread] %logger{0}: " + ReplaceNewLines.getMsgPattern(replaceNewLines) + "%n"); encoder.setCharset(Charsets.UTF_8); encoder.start(); // Setup stderr appender final ConsoleAppender<ILoggingEvent> appender = new ConsoleAppender<ILoggingEvent>(); appender.setTarget("System.err"); appender.setName("stderr"); appender.setEncoder(encoder); appender.setContext(context); appender.start(); return appender; }
java
private static Appender<ILoggingEvent> getStdErrAppender(final LoggerContext context, final ReplaceNewLines replaceNewLines) { // Setup format final PatternLayoutEncoder encoder = new PatternLayoutEncoder(); encoder.setContext(context); encoder.setPattern( "%date{HH:mm:ss.SSS} %property{ident}[%property{pid}]: %-5level [%thread] %logger{0}: " + ReplaceNewLines.getMsgPattern(replaceNewLines) + "%n"); encoder.setCharset(Charsets.UTF_8); encoder.start(); // Setup stderr appender final ConsoleAppender<ILoggingEvent> appender = new ConsoleAppender<ILoggingEvent>(); appender.setTarget("System.err"); appender.setName("stderr"); appender.setEncoder(encoder); appender.setContext(context); appender.start(); return appender; }
[ "private", "static", "Appender", "<", "ILoggingEvent", ">", "getStdErrAppender", "(", "final", "LoggerContext", "context", ",", "final", "ReplaceNewLines", "replaceNewLines", ")", "{", "// Setup format", "final", "PatternLayoutEncoder", "encoder", "=", "new", "PatternLayoutEncoder", "(", ")", ";", "encoder", ".", "setContext", "(", "context", ")", ";", "encoder", ".", "setPattern", "(", "\"%date{HH:mm:ss.SSS} %property{ident}[%property{pid}]: %-5level [%thread] %logger{0}: \"", "+", "ReplaceNewLines", ".", "getMsgPattern", "(", "replaceNewLines", ")", "+", "\"%n\"", ")", ";", "encoder", ".", "setCharset", "(", "Charsets", ".", "UTF_8", ")", ";", "encoder", ".", "start", "(", ")", ";", "// Setup stderr appender", "final", "ConsoleAppender", "<", "ILoggingEvent", ">", "appender", "=", "new", "ConsoleAppender", "<", "ILoggingEvent", ">", "(", ")", ";", "appender", ".", "setTarget", "(", "\"System.err\"", ")", ";", "appender", ".", "setName", "(", "\"stderr\"", ")", ";", "appender", ".", "setEncoder", "(", "encoder", ")", ";", "appender", ".", "setContext", "(", "context", ")", ";", "appender", ".", "start", "(", ")", ";", "return", "appender", ";", "}" ]
Create a stderr appender. @param context The logger context to use. @return An appender writing to stderr.
[ "Create", "a", "stderr", "appender", "." ]
73a7ebf6578c5f4228953375214a0afb44318d4d
https://github.com/spotify/logging-java/blob/73a7ebf6578c5f4228953375214a0afb44318d4d/src/main/java/com/spotify/logging/LoggingConfigurator.java#L327-L348
6,937
spotify/logging-java
src/main/java/com/spotify/logging/LoggingConfigurator.java
LoggingConfigurator.getSyslogAppender
static Appender<ILoggingEvent> getSyslogAppender(final LoggerContext context, final String host, final int port, final ReplaceNewLines replaceNewLines) { final String h = isNullOrEmpty(host) ? "localhost" : host; final int p = port < 0 ? 514 : port; final MillisecondPrecisionSyslogAppender appender = new MillisecondPrecisionSyslogAppender(); appender.setFacility("LOCAL0"); appender.setSyslogHost(h); appender.setPort(p); appender.setName("syslog"); appender.setCharset(Charsets.UTF_8); appender.setContext(context); appender.setSuffixPattern( "%property{ident}[%property{pid}]: " + ReplaceNewLines.getMsgPattern(replaceNewLines)); appender.setStackTracePattern( "%property{ident}[%property{pid}]: " + CoreConstants.TAB); appender.start(); return appender; }
java
static Appender<ILoggingEvent> getSyslogAppender(final LoggerContext context, final String host, final int port, final ReplaceNewLines replaceNewLines) { final String h = isNullOrEmpty(host) ? "localhost" : host; final int p = port < 0 ? 514 : port; final MillisecondPrecisionSyslogAppender appender = new MillisecondPrecisionSyslogAppender(); appender.setFacility("LOCAL0"); appender.setSyslogHost(h); appender.setPort(p); appender.setName("syslog"); appender.setCharset(Charsets.UTF_8); appender.setContext(context); appender.setSuffixPattern( "%property{ident}[%property{pid}]: " + ReplaceNewLines.getMsgPattern(replaceNewLines)); appender.setStackTracePattern( "%property{ident}[%property{pid}]: " + CoreConstants.TAB); appender.start(); return appender; }
[ "static", "Appender", "<", "ILoggingEvent", ">", "getSyslogAppender", "(", "final", "LoggerContext", "context", ",", "final", "String", "host", ",", "final", "int", "port", ",", "final", "ReplaceNewLines", "replaceNewLines", ")", "{", "final", "String", "h", "=", "isNullOrEmpty", "(", "host", ")", "?", "\"localhost\"", ":", "host", ";", "final", "int", "p", "=", "port", "<", "0", "?", "514", ":", "port", ";", "final", "MillisecondPrecisionSyslogAppender", "appender", "=", "new", "MillisecondPrecisionSyslogAppender", "(", ")", ";", "appender", ".", "setFacility", "(", "\"LOCAL0\"", ")", ";", "appender", ".", "setSyslogHost", "(", "h", ")", ";", "appender", ".", "setPort", "(", "p", ")", ";", "appender", ".", "setName", "(", "\"syslog\"", ")", ";", "appender", ".", "setCharset", "(", "Charsets", ".", "UTF_8", ")", ";", "appender", ".", "setContext", "(", "context", ")", ";", "appender", ".", "setSuffixPattern", "(", "\"%property{ident}[%property{pid}]: \"", "+", "ReplaceNewLines", ".", "getMsgPattern", "(", "replaceNewLines", ")", ")", ";", "appender", ".", "setStackTracePattern", "(", "\"%property{ident}[%property{pid}]: \"", "+", "CoreConstants", ".", "TAB", ")", ";", "appender", ".", "start", "(", ")", ";", "return", "appender", ";", "}" ]
Create a syslog appender. The appender will use the facility local0. If host is null or an empty string, default to "localhost". If port is less than 0, default to 514. @param context The logger context to use. @param host The host running the syslog daemon. @param port The port to connect to. @return An appender that writes to syslog.
[ "Create", "a", "syslog", "appender", ".", "The", "appender", "will", "use", "the", "facility", "local0", ".", "If", "host", "is", "null", "or", "an", "empty", "string", "default", "to", "localhost", ".", "If", "port", "is", "less", "than", "0", "default", "to", "514", "." ]
73a7ebf6578c5f4228953375214a0afb44318d4d
https://github.com/spotify/logging-java/blob/73a7ebf6578c5f4228953375214a0afb44318d4d/src/main/java/com/spotify/logging/LoggingConfigurator.java#L359-L381
6,938
spotify/logging-java
src/main/java/com/spotify/logging/LoggingConfigurator.java
LoggingConfigurator.configure
public static void configure(final File file, final String defaultIdent) { final Logger rootLogger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); // Setup context final LoggerContext context = rootLogger.getLoggerContext(); context.reset(); // Log uncaught exceptions UncaughtExceptionLogger.setDefaultUncaughtExceptionHandler(); // Load logging configuration from file try { final JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(context); configurator.doConfigure(file); } catch (JoranException je) { // StatusPrinter will handle this } context.putProperty("pid", getMyPid()); final String hostname = getSpotifyHostname(); if (hostname != null) { context.putProperty("hostname", hostname); } final String ident = context.getProperty("ident"); if (ident == null) { context.putProperty("ident", defaultIdent); } StatusPrinter.printInCaseOfErrorsOrWarnings(context); }
java
public static void configure(final File file, final String defaultIdent) { final Logger rootLogger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); // Setup context final LoggerContext context = rootLogger.getLoggerContext(); context.reset(); // Log uncaught exceptions UncaughtExceptionLogger.setDefaultUncaughtExceptionHandler(); // Load logging configuration from file try { final JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(context); configurator.doConfigure(file); } catch (JoranException je) { // StatusPrinter will handle this } context.putProperty("pid", getMyPid()); final String hostname = getSpotifyHostname(); if (hostname != null) { context.putProperty("hostname", hostname); } final String ident = context.getProperty("ident"); if (ident == null) { context.putProperty("ident", defaultIdent); } StatusPrinter.printInCaseOfErrorsOrWarnings(context); }
[ "public", "static", "void", "configure", "(", "final", "File", "file", ",", "final", "String", "defaultIdent", ")", "{", "final", "Logger", "rootLogger", "=", "(", "Logger", ")", "LoggerFactory", ".", "getLogger", "(", "Logger", ".", "ROOT_LOGGER_NAME", ")", ";", "// Setup context", "final", "LoggerContext", "context", "=", "rootLogger", ".", "getLoggerContext", "(", ")", ";", "context", ".", "reset", "(", ")", ";", "// Log uncaught exceptions", "UncaughtExceptionLogger", ".", "setDefaultUncaughtExceptionHandler", "(", ")", ";", "// Load logging configuration from file", "try", "{", "final", "JoranConfigurator", "configurator", "=", "new", "JoranConfigurator", "(", ")", ";", "configurator", ".", "setContext", "(", "context", ")", ";", "configurator", ".", "doConfigure", "(", "file", ")", ";", "}", "catch", "(", "JoranException", "je", ")", "{", "// StatusPrinter will handle this", "}", "context", ".", "putProperty", "(", "\"pid\"", ",", "getMyPid", "(", ")", ")", ";", "final", "String", "hostname", "=", "getSpotifyHostname", "(", ")", ";", "if", "(", "hostname", "!=", "null", ")", "{", "context", ".", "putProperty", "(", "\"hostname\"", ",", "hostname", ")", ";", "}", "final", "String", "ident", "=", "context", ".", "getProperty", "(", "\"ident\"", ")", ";", "if", "(", "ident", "==", "null", ")", "{", "context", ".", "putProperty", "(", "\"ident\"", ",", "defaultIdent", ")", ";", "}", "StatusPrinter", ".", "printInCaseOfErrorsOrWarnings", "(", "context", ")", ";", "}" ]
Configure logging using a logback configuration file. @param file A logback configuration file. @param defaultIdent Fallback logging identity, used if not specified in config file.
[ "Configure", "logging", "using", "a", "logback", "configuration", "file", "." ]
73a7ebf6578c5f4228953375214a0afb44318d4d
https://github.com/spotify/logging-java/blob/73a7ebf6578c5f4228953375214a0afb44318d4d/src/main/java/com/spotify/logging/LoggingConfigurator.java#L468-L499
6,939
spotify/logging-java
src/main/java/com/spotify/logging/LoggingConfigurator.java
LoggingConfigurator.getMyPid
private static String getMyPid() { String pid = "0"; try { final String nameStr = ManagementFactory.getRuntimeMXBean().getName(); // XXX (bjorn): Really stupid parsing assuming that nameStr will be of the form // "pid@hostname", which is probably not guaranteed. pid = nameStr.split("@")[0]; } catch (RuntimeException e) { // Fall through. } return pid; }
java
private static String getMyPid() { String pid = "0"; try { final String nameStr = ManagementFactory.getRuntimeMXBean().getName(); // XXX (bjorn): Really stupid parsing assuming that nameStr will be of the form // "pid@hostname", which is probably not guaranteed. pid = nameStr.split("@")[0]; } catch (RuntimeException e) { // Fall through. } return pid; }
[ "private", "static", "String", "getMyPid", "(", ")", "{", "String", "pid", "=", "\"0\"", ";", "try", "{", "final", "String", "nameStr", "=", "ManagementFactory", ".", "getRuntimeMXBean", "(", ")", ".", "getName", "(", ")", ";", "// XXX (bjorn): Really stupid parsing assuming that nameStr will be of the form", "// \"pid@hostname\", which is probably not guaranteed.", "pid", "=", "nameStr", ".", "split", "(", "\"@\"", ")", "[", "0", "]", ";", "}", "catch", "(", "RuntimeException", "e", ")", "{", "// Fall through.", "}", "return", "pid", ";", "}" ]
Also, the portability of this function is not guaranteed.
[ "Also", "the", "portability", "of", "this", "function", "is", "not", "guaranteed", "." ]
73a7ebf6578c5f4228953375214a0afb44318d4d
https://github.com/spotify/logging-java/blob/73a7ebf6578c5f4228953375214a0afb44318d4d/src/main/java/com/spotify/logging/LoggingConfigurator.java#L512-L524
6,940
spotify/logging-java
src/main/java/com/spotify/logging/LoggingSupport.java
LoggingSupport.debug
public static void debug(final Logger logger, final String type, final int version, final Ident ident, final Object... args) { logger.debug(buildLogLine(type, version, ident, args)); }
java
public static void debug(final Logger logger, final String type, final int version, final Ident ident, final Object... args) { logger.debug(buildLogLine(type, version, ident, args)); }
[ "public", "static", "void", "debug", "(", "final", "Logger", "logger", ",", "final", "String", "type", ",", "final", "int", "version", ",", "final", "Ident", "ident", ",", "final", "Object", "...", "args", ")", "{", "logger", ".", "debug", "(", "buildLogLine", "(", "type", ",", "version", ",", "ident", ",", "args", ")", ")", ";", "}" ]
Generate a new debug log message according to the Spotify log format. @param logger Which Logger to use for writing the log messages. It is assumed that this Logger is already set up via com.spotify.logging.LoggingConfigurator and a [service]-log4j.xml configuration so that the time stamp, hostname, service, and process ID portions of the log message are automatically prepended. @param type Log message type. Log messages are defined in the messages.py module in the log-parser git project. When a new message type is added or changed in a service, it should also be changed/added in messages.py. @param version Version of the log message. This is incremented by callers and in messages.py if the format of a given log message type is changed. @param ident Ident object to give information generally about a client who made the request that resulted in this message. @param args Additional arguments that will be converted to strings, escaped, and appended (tab-separated) after the log message type and version number.
[ "Generate", "a", "new", "debug", "log", "message", "according", "to", "the", "Spotify", "log", "format", "." ]
73a7ebf6578c5f4228953375214a0afb44318d4d
https://github.com/spotify/logging-java/blob/73a7ebf6578c5f4228953375214a0afb44318d4d/src/main/java/com/spotify/logging/LoggingSupport.java#L91-L95
6,941
craftercms/commons
utilities/src/main/java/org/craftercms/commons/collections/SetUtils.java
SetUtils.asSet
@SafeVarargs public static <T> Set<T> asSet(T... array) { Set<T> set = null; if (array != null) { set = new HashSet<>(Arrays.asList(array)); } return set; }
java
@SafeVarargs public static <T> Set<T> asSet(T... array) { Set<T> set = null; if (array != null) { set = new HashSet<>(Arrays.asList(array)); } return set; }
[ "@", "SafeVarargs", "public", "static", "<", "T", ">", "Set", "<", "T", ">", "asSet", "(", "T", "...", "array", ")", "{", "Set", "<", "T", ">", "set", "=", "null", ";", "if", "(", "array", "!=", "null", ")", "{", "set", "=", "new", "HashSet", "<>", "(", "Arrays", ".", "asList", "(", "array", ")", ")", ";", "}", "return", "set", ";", "}" ]
Creates a set from the array elements. @param array the array with the elements @return the set with the elements
[ "Creates", "a", "set", "from", "the", "array", "elements", "." ]
3074fe49e56c2a4aae0832f40b17ae563335dc83
https://github.com/craftercms/commons/blob/3074fe49e56c2a4aae0832f40b17ae563335dc83/utilities/src/main/java/org/craftercms/commons/collections/SetUtils.java#L40-L47
6,942
craftercms/commons
utilities/src/main/java/org/craftercms/commons/monitoring/VersionMonitor.java
VersionMonitor.getVersion
public static VersionMonitor getVersion(Class clazz) throws IOException { Manifest manifest = new Manifest(); manifest.read(clazz.getResourceAsStream(MANIFEST_PATH)); return getVersion(manifest); }
java
public static VersionMonitor getVersion(Class clazz) throws IOException { Manifest manifest = new Manifest(); manifest.read(clazz.getResourceAsStream(MANIFEST_PATH)); return getVersion(manifest); }
[ "public", "static", "VersionMonitor", "getVersion", "(", "Class", "clazz", ")", "throws", "IOException", "{", "Manifest", "manifest", "=", "new", "Manifest", "(", ")", ";", "manifest", ".", "read", "(", "clazz", ".", "getResourceAsStream", "(", "MANIFEST_PATH", ")", ")", ";", "return", "getVersion", "(", "manifest", ")", ";", "}" ]
Gets the current VersionMonitor base on a Class that will load it's manifest file. @param clazz Class that will load the manifest MF file @return A {@link VersionMonitor} pojo with the information. @throws IOException If Unable to read the Manifest file.
[ "Gets", "the", "current", "VersionMonitor", "base", "on", "a", "Class", "that", "will", "load", "it", "s", "manifest", "file", "." ]
3074fe49e56c2a4aae0832f40b17ae563335dc83
https://github.com/craftercms/commons/blob/3074fe49e56c2a4aae0832f40b17ae563335dc83/utilities/src/main/java/org/craftercms/commons/monitoring/VersionMonitor.java#L130-L134
6,943
craftercms/commons
utilities/src/main/java/org/craftercms/commons/crypto/PGPUtils.java
PGPUtils.getPublicKey
public static PGPPublicKey getPublicKey(InputStream content) throws Exception { InputStream in = PGPUtil.getDecoderStream(content); PGPPublicKeyRingCollection keyRingCollection = new PGPPublicKeyRingCollection(in, new BcKeyFingerprintCalculator()); PGPPublicKey key = null; Iterator<PGPPublicKeyRing> keyRings = keyRingCollection.getKeyRings(); while(key == null && keyRings.hasNext()) { PGPPublicKeyRing keyRing = keyRings.next(); Iterator<PGPPublicKey> keys = keyRing.getPublicKeys(); while(key == null && keys.hasNext()) { PGPPublicKey current = keys.next(); if(current.isEncryptionKey()) { key = current; } } } return key; }
java
public static PGPPublicKey getPublicKey(InputStream content) throws Exception { InputStream in = PGPUtil.getDecoderStream(content); PGPPublicKeyRingCollection keyRingCollection = new PGPPublicKeyRingCollection(in, new BcKeyFingerprintCalculator()); PGPPublicKey key = null; Iterator<PGPPublicKeyRing> keyRings = keyRingCollection.getKeyRings(); while(key == null && keyRings.hasNext()) { PGPPublicKeyRing keyRing = keyRings.next(); Iterator<PGPPublicKey> keys = keyRing.getPublicKeys(); while(key == null && keys.hasNext()) { PGPPublicKey current = keys.next(); if(current.isEncryptionKey()) { key = current; } } } return key; }
[ "public", "static", "PGPPublicKey", "getPublicKey", "(", "InputStream", "content", ")", "throws", "Exception", "{", "InputStream", "in", "=", "PGPUtil", ".", "getDecoderStream", "(", "content", ")", ";", "PGPPublicKeyRingCollection", "keyRingCollection", "=", "new", "PGPPublicKeyRingCollection", "(", "in", ",", "new", "BcKeyFingerprintCalculator", "(", ")", ")", ";", "PGPPublicKey", "key", "=", "null", ";", "Iterator", "<", "PGPPublicKeyRing", ">", "keyRings", "=", "keyRingCollection", ".", "getKeyRings", "(", ")", ";", "while", "(", "key", "==", "null", "&&", "keyRings", ".", "hasNext", "(", ")", ")", "{", "PGPPublicKeyRing", "keyRing", "=", "keyRings", ".", "next", "(", ")", ";", "Iterator", "<", "PGPPublicKey", ">", "keys", "=", "keyRing", ".", "getPublicKeys", "(", ")", ";", "while", "(", "key", "==", "null", "&&", "keys", ".", "hasNext", "(", ")", ")", "{", "PGPPublicKey", "current", "=", "keys", ".", "next", "(", ")", ";", "if", "(", "current", ".", "isEncryptionKey", "(", ")", ")", "{", "key", "=", "current", ";", "}", "}", "}", "return", "key", ";", "}" ]
Extracts the PGP public key from an encoded stream. @param content stream to extract the key @return key object @throws IOException if there is an error reading the stream @throws PGPException if the public key cannot be extracted
[ "Extracts", "the", "PGP", "public", "key", "from", "an", "encoded", "stream", "." ]
3074fe49e56c2a4aae0832f40b17ae563335dc83
https://github.com/craftercms/commons/blob/3074fe49e56c2a4aae0832f40b17ae563335dc83/utilities/src/main/java/org/craftercms/commons/crypto/PGPUtils.java#L134-L150
6,944
craftercms/commons
utilities/src/main/java/org/craftercms/commons/crypto/PGPUtils.java
PGPUtils.encrypt
public static void encrypt(Path path, InputStream publicKeyStream, OutputStream targetStream) throws Exception { PGPPublicKey publicKey = getPublicKey(publicKeyStream); try(ByteArrayOutputStream compressed = new ByteArrayOutputStream(); ArmoredOutputStream armOut = new ArmoredOutputStream(targetStream)) { PGPCompressedDataGenerator compressedGenerator = new PGPCompressedDataGenerator(PGPCompressedData.ZIP); PGPUtil.writeFileToLiteralData(compressedGenerator.open(compressed), PGPLiteralData.BINARY, path.toFile()); compressedGenerator.close(); JcePGPDataEncryptorBuilder encryptorBuilder = new JcePGPDataEncryptorBuilder(PGPEncryptedData.CAST5) .setWithIntegrityPacket(true).setSecureRandom(new SecureRandom()).setProvider(PROVIDER); PGPEncryptedDataGenerator dataGenerator = new PGPEncryptedDataGenerator(encryptorBuilder); JcePublicKeyKeyEncryptionMethodGenerator methodGenerator = new JcePublicKeyKeyEncryptionMethodGenerator (publicKey).setProvider(PROVIDER).setSecureRandom(new SecureRandom()); dataGenerator.addMethod(methodGenerator); byte[] compressedData = compressed.toByteArray(); OutputStream encryptedOut = dataGenerator.open(armOut, compressedData.length); encryptedOut.write(compressedData); encryptedOut.close(); } }
java
public static void encrypt(Path path, InputStream publicKeyStream, OutputStream targetStream) throws Exception { PGPPublicKey publicKey = getPublicKey(publicKeyStream); try(ByteArrayOutputStream compressed = new ByteArrayOutputStream(); ArmoredOutputStream armOut = new ArmoredOutputStream(targetStream)) { PGPCompressedDataGenerator compressedGenerator = new PGPCompressedDataGenerator(PGPCompressedData.ZIP); PGPUtil.writeFileToLiteralData(compressedGenerator.open(compressed), PGPLiteralData.BINARY, path.toFile()); compressedGenerator.close(); JcePGPDataEncryptorBuilder encryptorBuilder = new JcePGPDataEncryptorBuilder(PGPEncryptedData.CAST5) .setWithIntegrityPacket(true).setSecureRandom(new SecureRandom()).setProvider(PROVIDER); PGPEncryptedDataGenerator dataGenerator = new PGPEncryptedDataGenerator(encryptorBuilder); JcePublicKeyKeyEncryptionMethodGenerator methodGenerator = new JcePublicKeyKeyEncryptionMethodGenerator (publicKey).setProvider(PROVIDER).setSecureRandom(new SecureRandom()); dataGenerator.addMethod(methodGenerator); byte[] compressedData = compressed.toByteArray(); OutputStream encryptedOut = dataGenerator.open(armOut, compressedData.length); encryptedOut.write(compressedData); encryptedOut.close(); } }
[ "public", "static", "void", "encrypt", "(", "Path", "path", ",", "InputStream", "publicKeyStream", ",", "OutputStream", "targetStream", ")", "throws", "Exception", "{", "PGPPublicKey", "publicKey", "=", "getPublicKey", "(", "publicKeyStream", ")", ";", "try", "(", "ByteArrayOutputStream", "compressed", "=", "new", "ByteArrayOutputStream", "(", ")", ";", "ArmoredOutputStream", "armOut", "=", "new", "ArmoredOutputStream", "(", "targetStream", ")", ")", "{", "PGPCompressedDataGenerator", "compressedGenerator", "=", "new", "PGPCompressedDataGenerator", "(", "PGPCompressedData", ".", "ZIP", ")", ";", "PGPUtil", ".", "writeFileToLiteralData", "(", "compressedGenerator", ".", "open", "(", "compressed", ")", ",", "PGPLiteralData", ".", "BINARY", ",", "path", ".", "toFile", "(", ")", ")", ";", "compressedGenerator", ".", "close", "(", ")", ";", "JcePGPDataEncryptorBuilder", "encryptorBuilder", "=", "new", "JcePGPDataEncryptorBuilder", "(", "PGPEncryptedData", ".", "CAST5", ")", ".", "setWithIntegrityPacket", "(", "true", ")", ".", "setSecureRandom", "(", "new", "SecureRandom", "(", ")", ")", ".", "setProvider", "(", "PROVIDER", ")", ";", "PGPEncryptedDataGenerator", "dataGenerator", "=", "new", "PGPEncryptedDataGenerator", "(", "encryptorBuilder", ")", ";", "JcePublicKeyKeyEncryptionMethodGenerator", "methodGenerator", "=", "new", "JcePublicKeyKeyEncryptionMethodGenerator", "(", "publicKey", ")", ".", "setProvider", "(", "PROVIDER", ")", ".", "setSecureRandom", "(", "new", "SecureRandom", "(", ")", ")", ";", "dataGenerator", ".", "addMethod", "(", "methodGenerator", ")", ";", "byte", "[", "]", "compressedData", "=", "compressed", ".", "toByteArray", "(", ")", ";", "OutputStream", "encryptedOut", "=", "dataGenerator", ".", "open", "(", "armOut", ",", "compressedData", ".", "length", ")", ";", "encryptedOut", ".", "write", "(", "compressedData", ")", ";", "encryptedOut", ".", "close", "(", ")", ";", "}", "}" ]
Performs encryption on a single file using a PGP public key. @param path file to be encrypted @param publicKeyStream stream providing the encoded public key @param targetStream stream to receive the encrypted data @throws IOException if there is an error reading or writing from the streams @throws PGPException if the encryption process fails
[ "Performs", "encryption", "on", "a", "single", "file", "using", "a", "PGP", "public", "key", "." ]
3074fe49e56c2a4aae0832f40b17ae563335dc83
https://github.com/craftercms/commons/blob/3074fe49e56c2a4aae0832f40b17ae563335dc83/utilities/src/main/java/org/craftercms/commons/crypto/PGPUtils.java#L160-L181
6,945
craftercms/commons
utilities/src/main/java/org/craftercms/commons/crypto/PGPUtils.java
PGPUtils.decrypt
@SuppressWarnings("rawtypes") public static void decrypt(InputStream encryptedStream, OutputStream targetStream, InputStream privateKeyStream, char[] password) throws Exception { BcKeyFingerprintCalculator calculator = new BcKeyFingerprintCalculator(); PGPObjectFactory factory = new PGPObjectFactory(PGPUtil.getDecoderStream(encryptedStream), calculator); PGPEncryptedDataList dataList; Object object = factory.nextObject(); if(object instanceof PGPEncryptedDataList) { dataList = (PGPEncryptedDataList) object; } else { dataList = (PGPEncryptedDataList) factory.nextObject(); } Iterator objects = dataList.getEncryptedDataObjects(); PGPPrivateKey privateKey = null; PGPPublicKeyEncryptedData data = null; while(privateKey == null && objects.hasNext()) { data = (PGPPublicKeyEncryptedData) objects.next(); privateKey = findSecretKey(privateKeyStream, data.getKeyID(), password); } if(privateKey == null) { throw new IllegalArgumentException("Secret key for message not found."); } decryptData(privateKey, data, calculator, targetStream); }
java
@SuppressWarnings("rawtypes") public static void decrypt(InputStream encryptedStream, OutputStream targetStream, InputStream privateKeyStream, char[] password) throws Exception { BcKeyFingerprintCalculator calculator = new BcKeyFingerprintCalculator(); PGPObjectFactory factory = new PGPObjectFactory(PGPUtil.getDecoderStream(encryptedStream), calculator); PGPEncryptedDataList dataList; Object object = factory.nextObject(); if(object instanceof PGPEncryptedDataList) { dataList = (PGPEncryptedDataList) object; } else { dataList = (PGPEncryptedDataList) factory.nextObject(); } Iterator objects = dataList.getEncryptedDataObjects(); PGPPrivateKey privateKey = null; PGPPublicKeyEncryptedData data = null; while(privateKey == null && objects.hasNext()) { data = (PGPPublicKeyEncryptedData) objects.next(); privateKey = findSecretKey(privateKeyStream, data.getKeyID(), password); } if(privateKey == null) { throw new IllegalArgumentException("Secret key for message not found."); } decryptData(privateKey, data, calculator, targetStream); }
[ "@", "SuppressWarnings", "(", "\"rawtypes\"", ")", "public", "static", "void", "decrypt", "(", "InputStream", "encryptedStream", ",", "OutputStream", "targetStream", ",", "InputStream", "privateKeyStream", ",", "char", "[", "]", "password", ")", "throws", "Exception", "{", "BcKeyFingerprintCalculator", "calculator", "=", "new", "BcKeyFingerprintCalculator", "(", ")", ";", "PGPObjectFactory", "factory", "=", "new", "PGPObjectFactory", "(", "PGPUtil", ".", "getDecoderStream", "(", "encryptedStream", ")", ",", "calculator", ")", ";", "PGPEncryptedDataList", "dataList", ";", "Object", "object", "=", "factory", ".", "nextObject", "(", ")", ";", "if", "(", "object", "instanceof", "PGPEncryptedDataList", ")", "{", "dataList", "=", "(", "PGPEncryptedDataList", ")", "object", ";", "}", "else", "{", "dataList", "=", "(", "PGPEncryptedDataList", ")", "factory", ".", "nextObject", "(", ")", ";", "}", "Iterator", "objects", "=", "dataList", ".", "getEncryptedDataObjects", "(", ")", ";", "PGPPrivateKey", "privateKey", "=", "null", ";", "PGPPublicKeyEncryptedData", "data", "=", "null", ";", "while", "(", "privateKey", "==", "null", "&&", "objects", ".", "hasNext", "(", ")", ")", "{", "data", "=", "(", "PGPPublicKeyEncryptedData", ")", "objects", ".", "next", "(", ")", ";", "privateKey", "=", "findSecretKey", "(", "privateKeyStream", ",", "data", ".", "getKeyID", "(", ")", ",", "password", ")", ";", "}", "if", "(", "privateKey", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Secret key for message not found.\"", ")", ";", "}", "decryptData", "(", "privateKey", ",", "data", ",", "calculator", ",", "targetStream", ")", ";", "}" ]
Performs decryption of a given stream using a PGP private key. @param encryptedStream stream providing the encrypted data @param targetStream stream to receive the decrypted data @param privateKeyStream stream providing the encoded PGP private key @param password passphrase for the private key @throws IOException if there is an error reading or writing from the streams @throws PGPException if the decryption process fails
[ "Performs", "decryption", "of", "a", "given", "stream", "using", "a", "PGP", "private", "key", "." ]
3074fe49e56c2a4aae0832f40b17ae563335dc83
https://github.com/craftercms/commons/blob/3074fe49e56c2a4aae0832f40b17ae563335dc83/utilities/src/main/java/org/craftercms/commons/crypto/PGPUtils.java#L192-L217
6,946
craftercms/commons
utilities/src/main/java/org/craftercms/commons/crypto/PGPUtils.java
PGPUtils.findSecretKey
protected static PGPPrivateKey findSecretKey(InputStream keyStream, long keyId, char[] password) throws Exception { PGPSecretKeyRingCollection keyRings = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(keyStream), new BcKeyFingerprintCalculator()); PGPSecretKey secretKey = keyRings.getSecretKey(keyId); if(secretKey == null) { return null; } PBESecretKeyDecryptor decryptor = new JcePBESecretKeyDecryptorBuilder( new JcaPGPDigestCalculatorProviderBuilder().setProvider(PROVIDER).build()) .setProvider(PROVIDER).build(password); return secretKey.extractPrivateKey(decryptor); }
java
protected static PGPPrivateKey findSecretKey(InputStream keyStream, long keyId, char[] password) throws Exception { PGPSecretKeyRingCollection keyRings = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(keyStream), new BcKeyFingerprintCalculator()); PGPSecretKey secretKey = keyRings.getSecretKey(keyId); if(secretKey == null) { return null; } PBESecretKeyDecryptor decryptor = new JcePBESecretKeyDecryptorBuilder( new JcaPGPDigestCalculatorProviderBuilder().setProvider(PROVIDER).build()) .setProvider(PROVIDER).build(password); return secretKey.extractPrivateKey(decryptor); }
[ "protected", "static", "PGPPrivateKey", "findSecretKey", "(", "InputStream", "keyStream", ",", "long", "keyId", ",", "char", "[", "]", "password", ")", "throws", "Exception", "{", "PGPSecretKeyRingCollection", "keyRings", "=", "new", "PGPSecretKeyRingCollection", "(", "PGPUtil", ".", "getDecoderStream", "(", "keyStream", ")", ",", "new", "BcKeyFingerprintCalculator", "(", ")", ")", ";", "PGPSecretKey", "secretKey", "=", "keyRings", ".", "getSecretKey", "(", "keyId", ")", ";", "if", "(", "secretKey", "==", "null", ")", "{", "return", "null", ";", "}", "PBESecretKeyDecryptor", "decryptor", "=", "new", "JcePBESecretKeyDecryptorBuilder", "(", "new", "JcaPGPDigestCalculatorProviderBuilder", "(", ")", ".", "setProvider", "(", "PROVIDER", ")", ".", "build", "(", ")", ")", ".", "setProvider", "(", "PROVIDER", ")", ".", "build", "(", "password", ")", ";", "return", "secretKey", ".", "extractPrivateKey", "(", "decryptor", ")", ";", "}" ]
Extracts the PGP private key from an encoded stream. @param keyStream stream providing the encoded private key @param keyId id of the secret key to extract @param password passphrase for the secret key @return the private key object @throws IOException if there is an error reading from the stream @throws PGPException if the secret key cannot be extracted
[ "Extracts", "the", "PGP", "private", "key", "from", "an", "encoded", "stream", "." ]
3074fe49e56c2a4aae0832f40b17ae563335dc83
https://github.com/craftercms/commons/blob/3074fe49e56c2a4aae0832f40b17ae563335dc83/utilities/src/main/java/org/craftercms/commons/crypto/PGPUtils.java#L228-L239
6,947
craftercms/commons
utilities/src/main/java/org/craftercms/commons/crypto/PGPUtils.java
PGPUtils.decryptData
protected static void decryptData(final PGPPrivateKey privateKey, final PGPPublicKeyEncryptedData data, final BcKeyFingerprintCalculator calculator, final OutputStream targetStream) throws PGPException, IOException { PublicKeyDataDecryptorFactory decryptorFactory = new JcePublicKeyDataDecryptorFactoryBuilder().setProvider (PROVIDER).setContentProvider(PROVIDER).build(privateKey); InputStream content = data.getDataStream(decryptorFactory); PGPObjectFactory plainFactory = new PGPObjectFactory(content, calculator); Object message = plainFactory.nextObject(); if(message instanceof PGPCompressedData) { PGPCompressedData compressedData = (PGPCompressedData) message; PGPObjectFactory compressedFactory = new PGPObjectFactory(compressedData.getDataStream(), calculator); message = compressedFactory.nextObject(); } if(message instanceof PGPLiteralData) { PGPLiteralData literalData = (PGPLiteralData) message; try(InputStream literalStream = literalData.getInputStream()) { IOUtils.copy(literalStream, targetStream); } } else if(message instanceof PGPOnePassSignatureList) { throw new PGPException("Encrypted message contains a signed message - not literal data."); } else { throw new PGPException("Message is not a simple encrypted file - type unknown."); } if(data.isIntegrityProtected() && !data.verify()) { throw new PGPException("Message failed integrity check"); } }
java
protected static void decryptData(final PGPPrivateKey privateKey, final PGPPublicKeyEncryptedData data, final BcKeyFingerprintCalculator calculator, final OutputStream targetStream) throws PGPException, IOException { PublicKeyDataDecryptorFactory decryptorFactory = new JcePublicKeyDataDecryptorFactoryBuilder().setProvider (PROVIDER).setContentProvider(PROVIDER).build(privateKey); InputStream content = data.getDataStream(decryptorFactory); PGPObjectFactory plainFactory = new PGPObjectFactory(content, calculator); Object message = plainFactory.nextObject(); if(message instanceof PGPCompressedData) { PGPCompressedData compressedData = (PGPCompressedData) message; PGPObjectFactory compressedFactory = new PGPObjectFactory(compressedData.getDataStream(), calculator); message = compressedFactory.nextObject(); } if(message instanceof PGPLiteralData) { PGPLiteralData literalData = (PGPLiteralData) message; try(InputStream literalStream = literalData.getInputStream()) { IOUtils.copy(literalStream, targetStream); } } else if(message instanceof PGPOnePassSignatureList) { throw new PGPException("Encrypted message contains a signed message - not literal data."); } else { throw new PGPException("Message is not a simple encrypted file - type unknown."); } if(data.isIntegrityProtected() && !data.verify()) { throw new PGPException("Message failed integrity check"); } }
[ "protected", "static", "void", "decryptData", "(", "final", "PGPPrivateKey", "privateKey", ",", "final", "PGPPublicKeyEncryptedData", "data", ",", "final", "BcKeyFingerprintCalculator", "calculator", ",", "final", "OutputStream", "targetStream", ")", "throws", "PGPException", ",", "IOException", "{", "PublicKeyDataDecryptorFactory", "decryptorFactory", "=", "new", "JcePublicKeyDataDecryptorFactoryBuilder", "(", ")", ".", "setProvider", "(", "PROVIDER", ")", ".", "setContentProvider", "(", "PROVIDER", ")", ".", "build", "(", "privateKey", ")", ";", "InputStream", "content", "=", "data", ".", "getDataStream", "(", "decryptorFactory", ")", ";", "PGPObjectFactory", "plainFactory", "=", "new", "PGPObjectFactory", "(", "content", ",", "calculator", ")", ";", "Object", "message", "=", "plainFactory", ".", "nextObject", "(", ")", ";", "if", "(", "message", "instanceof", "PGPCompressedData", ")", "{", "PGPCompressedData", "compressedData", "=", "(", "PGPCompressedData", ")", "message", ";", "PGPObjectFactory", "compressedFactory", "=", "new", "PGPObjectFactory", "(", "compressedData", ".", "getDataStream", "(", ")", ",", "calculator", ")", ";", "message", "=", "compressedFactory", ".", "nextObject", "(", ")", ";", "}", "if", "(", "message", "instanceof", "PGPLiteralData", ")", "{", "PGPLiteralData", "literalData", "=", "(", "PGPLiteralData", ")", "message", ";", "try", "(", "InputStream", "literalStream", "=", "literalData", ".", "getInputStream", "(", ")", ")", "{", "IOUtils", ".", "copy", "(", "literalStream", ",", "targetStream", ")", ";", "}", "}", "else", "if", "(", "message", "instanceof", "PGPOnePassSignatureList", ")", "{", "throw", "new", "PGPException", "(", "\"Encrypted message contains a signed message - not literal data.\"", ")", ";", "}", "else", "{", "throw", "new", "PGPException", "(", "\"Message is not a simple encrypted file - type unknown.\"", ")", ";", "}", "if", "(", "data", ".", "isIntegrityProtected", "(", ")", "&&", "!", "data", ".", "verify", "(", ")", ")", "{", "throw", "new", "PGPException", "(", "\"Message failed integrity check\"", ")", ";", "}", "}" ]
Performs the decryption of the given data. @param privateKey PGP Private Key to decrypt @param data encrypted data @param calculator instance of {@link BcKeyFingerprintCalculator} @param targetStream stream to receive the decrypted data @throws PGPException if the decryption process fails @throws IOException if the stream write operation fails
[ "Performs", "the", "decryption", "of", "the", "given", "data", "." ]
3074fe49e56c2a4aae0832f40b17ae563335dc83
https://github.com/craftercms/commons/blob/3074fe49e56c2a4aae0832f40b17ae563335dc83/utilities/src/main/java/org/craftercms/commons/crypto/PGPUtils.java#L250-L282
6,948
spotify/logging-java
src/main/java/com/spotify/logging/logback/MillisecondPrecisionSyslogAppender.java
MillisecondPrecisionSyslogAppender.getSyslogOutputStream
private OutputStream getSyslogOutputStream() { Field f; try { f = SyslogAppenderBase.class.getDeclaredField("sos"); f.setAccessible(true); return (OutputStream) f.get(this); } catch (ReflectiveOperationException e) { throw Throwables.propagate(e); } }
java
private OutputStream getSyslogOutputStream() { Field f; try { f = SyslogAppenderBase.class.getDeclaredField("sos"); f.setAccessible(true); return (OutputStream) f.get(this); } catch (ReflectiveOperationException e) { throw Throwables.propagate(e); } }
[ "private", "OutputStream", "getSyslogOutputStream", "(", ")", "{", "Field", "f", ";", "try", "{", "f", "=", "SyslogAppenderBase", ".", "class", ".", "getDeclaredField", "(", "\"sos\"", ")", ";", "f", ".", "setAccessible", "(", "true", ")", ";", "return", "(", "OutputStream", ")", "f", ".", "get", "(", "this", ")", ";", "}", "catch", "(", "ReflectiveOperationException", "e", ")", "{", "throw", "Throwables", ".", "propagate", "(", "e", ")", ";", "}", "}" ]
Horrible hack to access the syslog stream through reflection
[ "Horrible", "hack", "to", "access", "the", "syslog", "stream", "through", "reflection" ]
73a7ebf6578c5f4228953375214a0afb44318d4d
https://github.com/spotify/logging-java/blob/73a7ebf6578c5f4228953375214a0afb44318d4d/src/main/java/com/spotify/logging/logback/MillisecondPrecisionSyslogAppender.java#L149-L158
6,949
craftercms/commons
utilities/src/main/java/org/craftercms/commons/lang/UrlUtils.java
UrlUtils.addParam
public static String addParam(String url, String name, String value, String charset) throws UnsupportedEncodingException { StringBuilder newUrl = new StringBuilder(url); if (!url.endsWith("?") && !url.endsWith("&")) { if (url.contains("?")) { newUrl.append('&'); } else { newUrl.append('?'); } } newUrl.append(URLEncoder.encode(name, charset)); newUrl.append('='); newUrl.append(URLEncoder.encode(value, charset)); return newUrl.toString(); }
java
public static String addParam(String url, String name, String value, String charset) throws UnsupportedEncodingException { StringBuilder newUrl = new StringBuilder(url); if (!url.endsWith("?") && !url.endsWith("&")) { if (url.contains("?")) { newUrl.append('&'); } else { newUrl.append('?'); } } newUrl.append(URLEncoder.encode(name, charset)); newUrl.append('='); newUrl.append(URLEncoder.encode(value, charset)); return newUrl.toString(); }
[ "public", "static", "String", "addParam", "(", "String", "url", ",", "String", "name", ",", "String", "value", ",", "String", "charset", ")", "throws", "UnsupportedEncodingException", "{", "StringBuilder", "newUrl", "=", "new", "StringBuilder", "(", "url", ")", ";", "if", "(", "!", "url", ".", "endsWith", "(", "\"?\"", ")", "&&", "!", "url", ".", "endsWith", "(", "\"&\"", ")", ")", "{", "if", "(", "url", ".", "contains", "(", "\"?\"", ")", ")", "{", "newUrl", ".", "append", "(", "'", "'", ")", ";", "}", "else", "{", "newUrl", ".", "append", "(", "'", "'", ")", ";", "}", "}", "newUrl", ".", "append", "(", "URLEncoder", ".", "encode", "(", "name", ",", "charset", ")", ")", ";", "newUrl", ".", "append", "(", "'", "'", ")", ";", "newUrl", ".", "append", "(", "URLEncoder", ".", "encode", "(", "value", ",", "charset", ")", ")", ";", "return", "newUrl", ".", "toString", "(", ")", ";", "}" ]
Adds a query string param to the URL, adding a '?' if there's no query string yet. @param url the URL @param name the name of the param @param value the value of the param @param charset the charset to encode the param key/value with @return the URL with the query string param appended
[ "Adds", "a", "query", "string", "param", "to", "the", "URL", "adding", "a", "?", "if", "there", "s", "no", "query", "string", "yet", "." ]
3074fe49e56c2a4aae0832f40b17ae563335dc83
https://github.com/craftercms/commons/blob/3074fe49e56c2a4aae0832f40b17ae563335dc83/utilities/src/main/java/org/craftercms/commons/lang/UrlUtils.java#L94-L111
6,950
craftercms/commons
utilities/src/main/java/org/craftercms/commons/lang/UrlUtils.java
UrlUtils.addQueryStringFragment
public static String addQueryStringFragment(String url, String fragment) { StringBuilder newUrl = new StringBuilder(url); if (fragment.startsWith("?") || fragment.startsWith("&")) { fragment = fragment.substring(1); } if (!url.endsWith("?") && !url.endsWith("&")) { if (url.contains("?")) { newUrl.append('&'); } else { newUrl.append('?'); } } return newUrl.append(fragment).toString(); }
java
public static String addQueryStringFragment(String url, String fragment) { StringBuilder newUrl = new StringBuilder(url); if (fragment.startsWith("?") || fragment.startsWith("&")) { fragment = fragment.substring(1); } if (!url.endsWith("?") && !url.endsWith("&")) { if (url.contains("?")) { newUrl.append('&'); } else { newUrl.append('?'); } } return newUrl.append(fragment).toString(); }
[ "public", "static", "String", "addQueryStringFragment", "(", "String", "url", ",", "String", "fragment", ")", "{", "StringBuilder", "newUrl", "=", "new", "StringBuilder", "(", "url", ")", ";", "if", "(", "fragment", ".", "startsWith", "(", "\"?\"", ")", "||", "fragment", ".", "startsWith", "(", "\"&\"", ")", ")", "{", "fragment", "=", "fragment", ".", "substring", "(", "1", ")", ";", "}", "if", "(", "!", "url", ".", "endsWith", "(", "\"?\"", ")", "&&", "!", "url", ".", "endsWith", "(", "\"&\"", ")", ")", "{", "if", "(", "url", ".", "contains", "(", "\"?\"", ")", ")", "{", "newUrl", ".", "append", "(", "'", "'", ")", ";", "}", "else", "{", "newUrl", ".", "append", "(", "'", "'", ")", ";", "}", "}", "return", "newUrl", ".", "append", "(", "fragment", ")", ".", "toString", "(", ")", ";", "}" ]
Adds a query string fragment to the URL, adding a '?' if there's no query string yet. @param url the URL @param fragment the query string fragment @return the URL with the query string fragment appended
[ "Adds", "a", "query", "string", "fragment", "to", "the", "URL", "adding", "a", "?", "if", "there", "s", "no", "query", "string", "yet", "." ]
3074fe49e56c2a4aae0832f40b17ae563335dc83
https://github.com/craftercms/commons/blob/3074fe49e56c2a4aae0832f40b17ae563335dc83/utilities/src/main/java/org/craftercms/commons/lang/UrlUtils.java#L121-L137
6,951
craftercms/commons
utilities/src/main/java/org/craftercms/commons/zip/ZipUtils.java
ZipUtils.zipFiles
public static void zipFiles(List<File> files, OutputStream outputStream) throws IOException { ZipOutputStream zos = new ZipOutputStream(outputStream); for (File file : files) { if (file.isDirectory()) { //if it's a folder addFolderToZip("", file, zos); } else { addFileToZip("", file, zos); } } zos.finish(); }
java
public static void zipFiles(List<File> files, OutputStream outputStream) throws IOException { ZipOutputStream zos = new ZipOutputStream(outputStream); for (File file : files) { if (file.isDirectory()) { //if it's a folder addFolderToZip("", file, zos); } else { addFileToZip("", file, zos); } } zos.finish(); }
[ "public", "static", "void", "zipFiles", "(", "List", "<", "File", ">", "files", ",", "OutputStream", "outputStream", ")", "throws", "IOException", "{", "ZipOutputStream", "zos", "=", "new", "ZipOutputStream", "(", "outputStream", ")", ";", "for", "(", "File", "file", ":", "files", ")", "{", "if", "(", "file", ".", "isDirectory", "(", ")", ")", "{", "//if it's a folder", "addFolderToZip", "(", "\"\"", ",", "file", ",", "zos", ")", ";", "}", "else", "{", "addFileToZip", "(", "\"\"", ",", "file", ",", "zos", ")", ";", "}", "}", "zos", ".", "finish", "(", ")", ";", "}" ]
Zips a collection of files to a destination zip output stream. @param files A collection of files and directories @param outputStream The output stream of the destination zip file @throws FileNotFoundException @throws IOException
[ "Zips", "a", "collection", "of", "files", "to", "a", "destination", "zip", "output", "stream", "." ]
3074fe49e56c2a4aae0832f40b17ae563335dc83
https://github.com/craftercms/commons/blob/3074fe49e56c2a4aae0832f40b17ae563335dc83/utilities/src/main/java/org/craftercms/commons/zip/ZipUtils.java#L53-L65
6,952
craftercms/commons
utilities/src/main/java/org/craftercms/commons/zip/ZipUtils.java
ZipUtils.zipFiles
public static void zipFiles(List<File> files, File zipFile) throws IOException { OutputStream os = new BufferedOutputStream(new FileOutputStream(zipFile)); try { zipFiles(files, os); } finally { IOUtils.closeQuietly(os); } }
java
public static void zipFiles(List<File> files, File zipFile) throws IOException { OutputStream os = new BufferedOutputStream(new FileOutputStream(zipFile)); try { zipFiles(files, os); } finally { IOUtils.closeQuietly(os); } }
[ "public", "static", "void", "zipFiles", "(", "List", "<", "File", ">", "files", ",", "File", "zipFile", ")", "throws", "IOException", "{", "OutputStream", "os", "=", "new", "BufferedOutputStream", "(", "new", "FileOutputStream", "(", "zipFile", ")", ")", ";", "try", "{", "zipFiles", "(", "files", ",", "os", ")", ";", "}", "finally", "{", "IOUtils", ".", "closeQuietly", "(", "os", ")", ";", "}", "}" ]
Zips a collection of files to a destination zip file. @param files A collection of files and directories @param zipFile The path of the destination zip file @throws FileNotFoundException @throws IOException
[ "Zips", "a", "collection", "of", "files", "to", "a", "destination", "zip", "file", "." ]
3074fe49e56c2a4aae0832f40b17ae563335dc83
https://github.com/craftercms/commons/blob/3074fe49e56c2a4aae0832f40b17ae563335dc83/utilities/src/main/java/org/craftercms/commons/zip/ZipUtils.java#L75-L82
6,953
craftercms/commons
utilities/src/main/java/org/craftercms/commons/zip/ZipUtils.java
ZipUtils.unZipFiles
public static void unZipFiles(InputStream inputStream, File outputFolder) throws IOException { ZipInputStream zis = new ZipInputStream(inputStream); ZipEntry ze = zis.getNextEntry(); while (ze != null) { File file = new File(outputFolder, ze.getName()); OutputStream os = new BufferedOutputStream(FileUtils.openOutputStream(file)); try { IOUtils.copy(zis, os); } finally { IOUtils.closeQuietly(os); } zis.closeEntry(); ze = zis.getNextEntry(); } }
java
public static void unZipFiles(InputStream inputStream, File outputFolder) throws IOException { ZipInputStream zis = new ZipInputStream(inputStream); ZipEntry ze = zis.getNextEntry(); while (ze != null) { File file = new File(outputFolder, ze.getName()); OutputStream os = new BufferedOutputStream(FileUtils.openOutputStream(file)); try { IOUtils.copy(zis, os); } finally { IOUtils.closeQuietly(os); } zis.closeEntry(); ze = zis.getNextEntry(); } }
[ "public", "static", "void", "unZipFiles", "(", "InputStream", "inputStream", ",", "File", "outputFolder", ")", "throws", "IOException", "{", "ZipInputStream", "zis", "=", "new", "ZipInputStream", "(", "inputStream", ")", ";", "ZipEntry", "ze", "=", "zis", ".", "getNextEntry", "(", ")", ";", "while", "(", "ze", "!=", "null", ")", "{", "File", "file", "=", "new", "File", "(", "outputFolder", ",", "ze", ".", "getName", "(", ")", ")", ";", "OutputStream", "os", "=", "new", "BufferedOutputStream", "(", "FileUtils", ".", "openOutputStream", "(", "file", ")", ")", ";", "try", "{", "IOUtils", ".", "copy", "(", "zis", ",", "os", ")", ";", "}", "finally", "{", "IOUtils", ".", "closeQuietly", "(", "os", ")", ";", "}", "zis", ".", "closeEntry", "(", ")", ";", "ze", "=", "zis", ".", "getNextEntry", "(", ")", ";", "}", "}" ]
Unzips a zip from an input stream into an output folder. @param inputStream the zip input stream @param outputFolder the output folder where the files @throws IOException
[ "Unzips", "a", "zip", "from", "an", "input", "stream", "into", "an", "output", "folder", "." ]
3074fe49e56c2a4aae0832f40b17ae563335dc83
https://github.com/craftercms/commons/blob/3074fe49e56c2a4aae0832f40b17ae563335dc83/utilities/src/main/java/org/craftercms/commons/zip/ZipUtils.java#L91-L108
6,954
craftercms/commons
utilities/src/main/java/org/craftercms/commons/zip/ZipUtils.java
ZipUtils.unZipFiles
public static void unZipFiles(File zipFile, File outputFolder) throws IOException { InputStream is = new BufferedInputStream(new FileInputStream(zipFile)); try { unZipFiles(is, outputFolder); } finally { IOUtils.closeQuietly(is); } }
java
public static void unZipFiles(File zipFile, File outputFolder) throws IOException { InputStream is = new BufferedInputStream(new FileInputStream(zipFile)); try { unZipFiles(is, outputFolder); } finally { IOUtils.closeQuietly(is); } }
[ "public", "static", "void", "unZipFiles", "(", "File", "zipFile", ",", "File", "outputFolder", ")", "throws", "IOException", "{", "InputStream", "is", "=", "new", "BufferedInputStream", "(", "new", "FileInputStream", "(", "zipFile", ")", ")", ";", "try", "{", "unZipFiles", "(", "is", ",", "outputFolder", ")", ";", "}", "finally", "{", "IOUtils", ".", "closeQuietly", "(", "is", ")", ";", "}", "}" ]
Unzips a zip file into an output folder. @param zipFile the zip file @param outputFolder the output folder where the files @throws IOException
[ "Unzips", "a", "zip", "file", "into", "an", "output", "folder", "." ]
3074fe49e56c2a4aae0832f40b17ae563335dc83
https://github.com/craftercms/commons/blob/3074fe49e56c2a4aae0832f40b17ae563335dc83/utilities/src/main/java/org/craftercms/commons/zip/ZipUtils.java#L117-L124
6,955
craftercms/commons
utilities/src/main/java/org/craftercms/commons/zip/ZipUtils.java
ZipUtils.addFolderToZip
private static void addFolderToZip(String path, File folder, ZipOutputStream zos) throws IOException { String currentPath = StringUtils.isNotEmpty(path)? path + "/" + folder.getName(): folder.getName(); for (File file : folder.listFiles()) { if (file.isDirectory()) { addFolderToZip(currentPath, file, zos); } else { addFileToZip(currentPath, file, zos); } } }
java
private static void addFolderToZip(String path, File folder, ZipOutputStream zos) throws IOException { String currentPath = StringUtils.isNotEmpty(path)? path + "/" + folder.getName(): folder.getName(); for (File file : folder.listFiles()) { if (file.isDirectory()) { addFolderToZip(currentPath, file, zos); } else { addFileToZip(currentPath, file, zos); } } }
[ "private", "static", "void", "addFolderToZip", "(", "String", "path", ",", "File", "folder", ",", "ZipOutputStream", "zos", ")", "throws", "IOException", "{", "String", "currentPath", "=", "StringUtils", ".", "isNotEmpty", "(", "path", ")", "?", "path", "+", "\"/\"", "+", "folder", ".", "getName", "(", ")", ":", "folder", ".", "getName", "(", ")", ";", "for", "(", "File", "file", ":", "folder", ".", "listFiles", "(", ")", ")", "{", "if", "(", "file", ".", "isDirectory", "(", ")", ")", "{", "addFolderToZip", "(", "currentPath", ",", "file", ",", "zos", ")", ";", "}", "else", "{", "addFileToZip", "(", "currentPath", ",", "file", ",", "zos", ")", ";", "}", "}", "}" ]
Adds a directory to the current zip @param path the path of the parent folder in the zip @param folder the directory to be added @param zos the current zip output stream @throws FileNotFoundException @throws IOException
[ "Adds", "a", "directory", "to", "the", "current", "zip" ]
3074fe49e56c2a4aae0832f40b17ae563335dc83
https://github.com/craftercms/commons/blob/3074fe49e56c2a4aae0832f40b17ae563335dc83/utilities/src/main/java/org/craftercms/commons/zip/ZipUtils.java#L135-L145
6,956
craftercms/commons
utilities/src/main/java/org/craftercms/commons/zip/ZipUtils.java
ZipUtils.addFileToZip
private static void addFileToZip(String path, File file, ZipOutputStream zos) throws IOException { String currentPath = StringUtils.isNotEmpty(path)? path + "/" + file.getName(): file.getName(); zos.putNextEntry(new ZipEntry(currentPath)); InputStream is = new BufferedInputStream(new FileInputStream(file)); try { IOUtils.copy(is, zos); } finally { IOUtils.closeQuietly(is); } zos.closeEntry(); }
java
private static void addFileToZip(String path, File file, ZipOutputStream zos) throws IOException { String currentPath = StringUtils.isNotEmpty(path)? path + "/" + file.getName(): file.getName(); zos.putNextEntry(new ZipEntry(currentPath)); InputStream is = new BufferedInputStream(new FileInputStream(file)); try { IOUtils.copy(is, zos); } finally { IOUtils.closeQuietly(is); } zos.closeEntry(); }
[ "private", "static", "void", "addFileToZip", "(", "String", "path", ",", "File", "file", ",", "ZipOutputStream", "zos", ")", "throws", "IOException", "{", "String", "currentPath", "=", "StringUtils", ".", "isNotEmpty", "(", "path", ")", "?", "path", "+", "\"/\"", "+", "file", ".", "getName", "(", ")", ":", "file", ".", "getName", "(", ")", ";", "zos", ".", "putNextEntry", "(", "new", "ZipEntry", "(", "currentPath", ")", ")", ";", "InputStream", "is", "=", "new", "BufferedInputStream", "(", "new", "FileInputStream", "(", "file", ")", ")", ";", "try", "{", "IOUtils", ".", "copy", "(", "is", ",", "zos", ")", ";", "}", "finally", "{", "IOUtils", ".", "closeQuietly", "(", "is", ")", ";", "}", "zos", ".", "closeEntry", "(", ")", ";", "}" ]
Adds a file to the current zip output stream @param path the path of the parent folder in the zip @param file the file to be added @param zos the current zip output stream @throws FileNotFoundException @throws IOException
[ "Adds", "a", "file", "to", "the", "current", "zip", "output", "stream" ]
3074fe49e56c2a4aae0832f40b17ae563335dc83
https://github.com/craftercms/commons/blob/3074fe49e56c2a4aae0832f40b17ae563335dc83/utilities/src/main/java/org/craftercms/commons/zip/ZipUtils.java#L156-L169
6,957
craftercms/commons
utilities/src/main/java/org/craftercms/commons/collections/MapUtils.java
MapUtils.deepMerge
@SuppressWarnings("unchecked") public static Map deepMerge(Map dst, Map src) { if (dst != null && src != null) { for (Object key : src.keySet()) { if (src.get(key) instanceof Map && dst.get(key) instanceof Map) { Map originalChild = (Map)dst.get(key); Map newChild = (Map)src.get(key); dst.put(key, deepMerge(originalChild, newChild)); } else { dst.put(key, src.get(key)); } } } return dst; }
java
@SuppressWarnings("unchecked") public static Map deepMerge(Map dst, Map src) { if (dst != null && src != null) { for (Object key : src.keySet()) { if (src.get(key) instanceof Map && dst.get(key) instanceof Map) { Map originalChild = (Map)dst.get(key); Map newChild = (Map)src.get(key); dst.put(key, deepMerge(originalChild, newChild)); } else { dst.put(key, src.get(key)); } } } return dst; }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "static", "Map", "deepMerge", "(", "Map", "dst", ",", "Map", "src", ")", "{", "if", "(", "dst", "!=", "null", "&&", "src", "!=", "null", ")", "{", "for", "(", "Object", "key", ":", "src", ".", "keySet", "(", ")", ")", "{", "if", "(", "src", ".", "get", "(", "key", ")", "instanceof", "Map", "&&", "dst", ".", "get", "(", "key", ")", "instanceof", "Map", ")", "{", "Map", "originalChild", "=", "(", "Map", ")", "dst", ".", "get", "(", "key", ")", ";", "Map", "newChild", "=", "(", "Map", ")", "src", ".", "get", "(", "key", ")", ";", "dst", ".", "put", "(", "key", ",", "deepMerge", "(", "originalChild", ",", "newChild", ")", ")", ";", "}", "else", "{", "dst", ".", "put", "(", "key", ",", "src", ".", "get", "(", "key", ")", ")", ";", "}", "}", "}", "return", "dst", ";", "}" ]
Deep merges two maps @param dst the map where elements will be merged into @param src the map with the elements to merge @return a deep merge of the two given maps.
[ "Deep", "merges", "two", "maps" ]
3074fe49e56c2a4aae0832f40b17ae563335dc83
https://github.com/craftercms/commons/blob/3074fe49e56c2a4aae0832f40b17ae563335dc83/utilities/src/main/java/org/craftercms/commons/collections/MapUtils.java#L39-L54
6,958
craftercms/commons
utilities/src/main/java/org/craftercms/commons/properties/OverrideProperties.java
OverrideProperties.init
public void init() { for (Resource resource : resources) { if (resource.exists()) { try (InputStream in = resource.getInputStream()) { readPropertyFile(in); } catch (IOException ex) { log.debug("Unable to load queries from " + resource.getDescription(), ex); } } else { log.info("Query file at {} not found. Ignoring it...", resource.getDescription()); } } }
java
public void init() { for (Resource resource : resources) { if (resource.exists()) { try (InputStream in = resource.getInputStream()) { readPropertyFile(in); } catch (IOException ex) { log.debug("Unable to load queries from " + resource.getDescription(), ex); } } else { log.info("Query file at {} not found. Ignoring it...", resource.getDescription()); } } }
[ "public", "void", "init", "(", ")", "{", "for", "(", "Resource", "resource", ":", "resources", ")", "{", "if", "(", "resource", ".", "exists", "(", ")", ")", "{", "try", "(", "InputStream", "in", "=", "resource", ".", "getInputStream", "(", ")", ")", "{", "readPropertyFile", "(", "in", ")", ";", "}", "catch", "(", "IOException", "ex", ")", "{", "log", ".", "debug", "(", "\"Unable to load queries from \"", "+", "resource", ".", "getDescription", "(", ")", ",", "ex", ")", ";", "}", "}", "else", "{", "log", ".", "info", "(", "\"Query file at {} not found. Ignoring it...\"", ",", "resource", ".", "getDescription", "(", ")", ")", ";", "}", "}", "}" ]
Checks and starts the reading of the given Resources.
[ "Checks", "and", "starts", "the", "reading", "of", "the", "given", "Resources", "." ]
3074fe49e56c2a4aae0832f40b17ae563335dc83
https://github.com/craftercms/commons/blob/3074fe49e56c2a4aae0832f40b17ae563335dc83/utilities/src/main/java/org/craftercms/commons/properties/OverrideProperties.java#L56-L68
6,959
craftercms/commons
audit/src/main/java/org/craftercms/commons/audit/AuditReaper.java
AuditReaper.getIdList
private List<String> getIdList(final List<? extends AuditModel> toDelete) { List<String> ids = new ArrayList<>(toDelete.size()); for (AuditModel auditModel : toDelete) { ids.add(auditModel.getId()); } return ids; }
java
private List<String> getIdList(final List<? extends AuditModel> toDelete) { List<String> ids = new ArrayList<>(toDelete.size()); for (AuditModel auditModel : toDelete) { ids.add(auditModel.getId()); } return ids; }
[ "private", "List", "<", "String", ">", "getIdList", "(", "final", "List", "<", "?", "extends", "AuditModel", ">", "toDelete", ")", "{", "List", "<", "String", ">", "ids", "=", "new", "ArrayList", "<>", "(", "toDelete", ".", "size", "(", ")", ")", ";", "for", "(", "AuditModel", "auditModel", ":", "toDelete", ")", "{", "ids", ".", "add", "(", "auditModel", ".", "getId", "(", ")", ")", ";", "}", "return", "ids", ";", "}" ]
Gets the list of Id's of the given List of Models. @param toDelete List of AuditModels to get there Ids. @return A List of Ids.
[ "Gets", "the", "list", "of", "Id", "s", "of", "the", "given", "List", "of", "Models", "." ]
3074fe49e56c2a4aae0832f40b17ae563335dc83
https://github.com/craftercms/commons/blob/3074fe49e56c2a4aae0832f40b17ae563335dc83/audit/src/main/java/org/craftercms/commons/audit/AuditReaper.java#L82-L88
6,960
craftercms/commons
mongo/src/main/java/org/craftercms/commons/mongo/AbstractJongoRepository.java
AbstractJongoRepository.returnList
@SuppressWarnings("uncheck")// cortiz, might change in jongo 1.4 protected Iterable<T> returnList(final Find find) { return (Iterable<T>)find.as(clazz); }
java
@SuppressWarnings("uncheck")// cortiz, might change in jongo 1.4 protected Iterable<T> returnList(final Find find) { return (Iterable<T>)find.as(clazz); }
[ "@", "SuppressWarnings", "(", "\"uncheck\"", ")", "// cortiz, might change in jongo 1.4", "protected", "Iterable", "<", "T", ">", "returnList", "(", "final", "Find", "find", ")", "{", "return", "(", "Iterable", "<", "T", ">", ")", "find", ".", "as", "(", "clazz", ")", ";", "}" ]
Actually makes the transformation form Jongo to List of Objects. @param find Find object to transform. @return a Iterable with the results <b>null</b> if nothing is found.
[ "Actually", "makes", "the", "transformation", "form", "Jongo", "to", "List", "of", "Objects", "." ]
3074fe49e56c2a4aae0832f40b17ae563335dc83
https://github.com/craftercms/commons/blob/3074fe49e56c2a4aae0832f40b17ae563335dc83/mongo/src/main/java/org/craftercms/commons/mongo/AbstractJongoRepository.java#L539-L542
6,961
craftercms/commons
mongo/src/main/java/org/craftercms/commons/mongo/AbstractJongoRepository.java
AbstractJongoRepository.getQueryFor
protected String getQueryFor(final String key) { log.trace("Trying to get query for {} ", key); String query = queries.get(key); log.trace("Query found {} for key {}", query, key); if (query == null) { log.error("Query for {} key does not exist", key); throw new IllegalArgumentException("Query for key " + key + " does not exist"); } else if (StringUtils.isBlank(query)) { log.error("Query for key {} can't be blank or be only whitespace", key); throw new IllegalArgumentException("Query for key " + key + " can't be blank or be only whitespace"); } return query.trim().replaceAll("\\s+", " "); }
java
protected String getQueryFor(final String key) { log.trace("Trying to get query for {} ", key); String query = queries.get(key); log.trace("Query found {} for key {}", query, key); if (query == null) { log.error("Query for {} key does not exist", key); throw new IllegalArgumentException("Query for key " + key + " does not exist"); } else if (StringUtils.isBlank(query)) { log.error("Query for key {} can't be blank or be only whitespace", key); throw new IllegalArgumentException("Query for key " + key + " can't be blank or be only whitespace"); } return query.trim().replaceAll("\\s+", " "); }
[ "protected", "String", "getQueryFor", "(", "final", "String", "key", ")", "{", "log", ".", "trace", "(", "\"Trying to get query for {} \"", ",", "key", ")", ";", "String", "query", "=", "queries", ".", "get", "(", "key", ")", ";", "log", ".", "trace", "(", "\"Query found {} for key {}\"", ",", "query", ",", "key", ")", ";", "if", "(", "query", "==", "null", ")", "{", "log", ".", "error", "(", "\"Query for {} key does not exist\"", ",", "key", ")", ";", "throw", "new", "IllegalArgumentException", "(", "\"Query for key \"", "+", "key", "+", "\" does not exist\"", ")", ";", "}", "else", "if", "(", "StringUtils", ".", "isBlank", "(", "query", ")", ")", "{", "log", ".", "error", "(", "\"Query for key {} can't be blank or be only whitespace\"", ",", "key", ")", ";", "throw", "new", "IllegalArgumentException", "(", "\"Query for key \"", "+", "key", "+", "\" can't be blank or be only whitespace\"", ")", ";", "}", "return", "query", ".", "trim", "(", ")", ".", "replaceAll", "(", "\"\\\\s+\"", ",", "\" \"", ")", ";", "}" ]
Get the query string for a given key @param key Key of the query, @return Query with the given key. IllegalArgumentException if query does not exist @throws java.lang.IllegalArgumentException if q
[ "Get", "the", "query", "string", "for", "a", "given", "key" ]
3074fe49e56c2a4aae0832f40b17ae563335dc83
https://github.com/craftercms/commons/blob/3074fe49e56c2a4aae0832f40b17ae563335dc83/mongo/src/main/java/org/craftercms/commons/mongo/AbstractJongoRepository.java#L561-L573
6,962
baasbox/Android-SDK
library/src/main/java/com/baasbox/android/BaasDocument.java
BaasDocument.refreshSync
public BaasResult<BaasDocument> refreshSync(boolean withAcl) { BaasBox box = BaasBox.getDefaultChecked(); if (id == null) throw new IllegalStateException("this document is not bound to any remote entity"); Refresh refresh = new Refresh(box, this,withAcl, RequestOptions.DEFAULT, null); return box.submitSync(refresh); }
java
public BaasResult<BaasDocument> refreshSync(boolean withAcl) { BaasBox box = BaasBox.getDefaultChecked(); if (id == null) throw new IllegalStateException("this document is not bound to any remote entity"); Refresh refresh = new Refresh(box, this,withAcl, RequestOptions.DEFAULT, null); return box.submitSync(refresh); }
[ "public", "BaasResult", "<", "BaasDocument", ">", "refreshSync", "(", "boolean", "withAcl", ")", "{", "BaasBox", "box", "=", "BaasBox", ".", "getDefaultChecked", "(", ")", ";", "if", "(", "id", "==", "null", ")", "throw", "new", "IllegalStateException", "(", "\"this document is not bound to any remote entity\"", ")", ";", "Refresh", "refresh", "=", "new", "Refresh", "(", "box", ",", "this", ",", "withAcl", ",", "RequestOptions", ".", "DEFAULT", ",", "null", ")", ";", "return", "box", ".", "submitSync", "(", "refresh", ")", ";", "}" ]
Synchronously refresh the content of this document @param withAcl if true will fetch acl @return the result of the request @throws java.lang.IllegalStateException if this document has no id
[ "Synchronously", "refresh", "the", "content", "of", "this", "document" ]
6bb2203246b885b2ad63a7bfaf37c83caf15e0d8
https://github.com/baasbox/Android-SDK/blob/6bb2203246b885b2ad63a7bfaf37c83caf15e0d8/library/src/main/java/com/baasbox/android/BaasDocument.java#L481-L487
6,963
baasbox/Android-SDK
library/src/main/java/com/baasbox/android/BaasDocument.java
BaasDocument.deleteSync
public BaasResult<Void> deleteSync() { if (id == null) throw new IllegalStateException("this document is not bound to any remote entity"); BaasBox box = BaasBox.getDefaultChecked(); Delete delete = new Delete(box, this, RequestOptions.DEFAULT, null); return box.submitSync(delete); }
java
public BaasResult<Void> deleteSync() { if (id == null) throw new IllegalStateException("this document is not bound to any remote entity"); BaasBox box = BaasBox.getDefaultChecked(); Delete delete = new Delete(box, this, RequestOptions.DEFAULT, null); return box.submitSync(delete); }
[ "public", "BaasResult", "<", "Void", ">", "deleteSync", "(", ")", "{", "if", "(", "id", "==", "null", ")", "throw", "new", "IllegalStateException", "(", "\"this document is not bound to any remote entity\"", ")", ";", "BaasBox", "box", "=", "BaasBox", ".", "getDefaultChecked", "(", ")", ";", "Delete", "delete", "=", "new", "Delete", "(", "box", ",", "this", ",", "RequestOptions", ".", "DEFAULT", ",", "null", ")", ";", "return", "box", ".", "submitSync", "(", "delete", ")", ";", "}" ]
Syncrhonously deletes this document on the server. @return the result of the request
[ "Syncrhonously", "deletes", "this", "document", "on", "the", "server", "." ]
6bb2203246b885b2ad63a7bfaf37c83caf15e0d8
https://github.com/baasbox/Android-SDK/blob/6bb2203246b885b2ad63a7bfaf37c83caf15e0d8/library/src/main/java/com/baasbox/android/BaasDocument.java#L559-L565
6,964
baasbox/Android-SDK
library/src/main/java/com/baasbox/android/BaasDocument.java
BaasDocument.saveSync
public BaasResult<BaasDocument> saveSync(SaveMode mode,BaasACL acl) { BaasBox box = BaasBox.getDefaultChecked(); if (mode == null) throw new IllegalArgumentException("mode cannot be null"); Save save = new Save(box, mode,acl, this, RequestOptions.DEFAULT, null); return box.submitSync(save); }
java
public BaasResult<BaasDocument> saveSync(SaveMode mode,BaasACL acl) { BaasBox box = BaasBox.getDefaultChecked(); if (mode == null) throw new IllegalArgumentException("mode cannot be null"); Save save = new Save(box, mode,acl, this, RequestOptions.DEFAULT, null); return box.submitSync(save); }
[ "public", "BaasResult", "<", "BaasDocument", ">", "saveSync", "(", "SaveMode", "mode", ",", "BaasACL", "acl", ")", "{", "BaasBox", "box", "=", "BaasBox", ".", "getDefaultChecked", "(", ")", ";", "if", "(", "mode", "==", "null", ")", "throw", "new", "IllegalArgumentException", "(", "\"mode cannot be null\"", ")", ";", "Save", "save", "=", "new", "Save", "(", "box", ",", "mode", ",", "acl", ",", "this", ",", "RequestOptions", ".", "DEFAULT", ",", "null", ")", ";", "return", "box", ".", "submitSync", "(", "save", ")", ";", "}" ]
Synchronously saves the document on the server with initial acl @param mode {@link com.baasbox.android.SaveMode} @param acl {@link com.baasbox.android.BaasACL} the initial acl settings @return the result of the request
[ "Synchronously", "saves", "the", "document", "on", "the", "server", "with", "initial", "acl" ]
6bb2203246b885b2ad63a7bfaf37c83caf15e0d8
https://github.com/baasbox/Android-SDK/blob/6bb2203246b885b2ad63a7bfaf37c83caf15e0d8/library/src/main/java/com/baasbox/android/BaasDocument.java#L656-L661
6,965
danieldk/dictomaton
src/main/java/eu/danieldk/dictomaton/PerfectHashDictionaryStateCard.java
PerfectHashDictionaryStateCard.number
public int number(CharSequence seq) { StateInfo info = getStateInfo(seq); return info.isInFinalState() ? info.getHash() : -1; }
java
public int number(CharSequence seq) { StateInfo info = getStateInfo(seq); return info.isInFinalState() ? info.getHash() : -1; }
[ "public", "int", "number", "(", "CharSequence", "seq", ")", "{", "StateInfo", "info", "=", "getStateInfo", "(", "seq", ")", ";", "return", "info", ".", "isInFinalState", "(", ")", "?", "info", ".", "getHash", "(", ")", ":", "-", "1", ";", "}" ]
Compute the perfect hash code of the given character sequence. @param seq @return
[ "Compute", "the", "perfect", "hash", "code", "of", "the", "given", "character", "sequence", "." ]
c0a3ae2d407ebd88023ea2d0f02a4882b0492df0
https://github.com/danieldk/dictomaton/blob/c0a3ae2d407ebd88023ea2d0f02a4882b0492df0/src/main/java/eu/danieldk/dictomaton/PerfectHashDictionaryStateCard.java#L43-L46
6,966
danieldk/dictomaton
src/main/java/eu/danieldk/dictomaton/PerfectHashDictionaryStateCard.java
PerfectHashDictionaryStateCard.toDot
@Override public String toDot() { StringBuilder dotBuilder = new StringBuilder(); dotBuilder.append("digraph G {\n"); for (int state = 0; state < d_stateOffsets.size(); ++state) { for (int trans = d_stateOffsets.get(state); trans < transitionsUpperBound(state); ++trans) dotBuilder.append(String.format("%d -> %d [label=\"%c\"]\n", state, d_transitionTo.get(trans), d_transitionChars[trans])); if (d_finalStates.get(state)) dotBuilder.append(String.format("%d [peripheries=2,label=\"%d (%d)\"];\n", state, state, d_stateNSuffixes.get(state))); else dotBuilder.append(String.format("%d [label=\"%d (%d)\"];\n", state, state, d_stateNSuffixes.get(state))); } dotBuilder.append("}"); return dotBuilder.toString(); }
java
@Override public String toDot() { StringBuilder dotBuilder = new StringBuilder(); dotBuilder.append("digraph G {\n"); for (int state = 0; state < d_stateOffsets.size(); ++state) { for (int trans = d_stateOffsets.get(state); trans < transitionsUpperBound(state); ++trans) dotBuilder.append(String.format("%d -> %d [label=\"%c\"]\n", state, d_transitionTo.get(trans), d_transitionChars[trans])); if (d_finalStates.get(state)) dotBuilder.append(String.format("%d [peripheries=2,label=\"%d (%d)\"];\n", state, state, d_stateNSuffixes.get(state))); else dotBuilder.append(String.format("%d [label=\"%d (%d)\"];\n", state, state, d_stateNSuffixes.get(state))); } dotBuilder.append("}"); return dotBuilder.toString(); }
[ "@", "Override", "public", "String", "toDot", "(", ")", "{", "StringBuilder", "dotBuilder", "=", "new", "StringBuilder", "(", ")", ";", "dotBuilder", ".", "append", "(", "\"digraph G {\\n\"", ")", ";", "for", "(", "int", "state", "=", "0", ";", "state", "<", "d_stateOffsets", ".", "size", "(", ")", ";", "++", "state", ")", "{", "for", "(", "int", "trans", "=", "d_stateOffsets", ".", "get", "(", "state", ")", ";", "trans", "<", "transitionsUpperBound", "(", "state", ")", ";", "++", "trans", ")", "dotBuilder", ".", "append", "(", "String", ".", "format", "(", "\"%d -> %d [label=\\\"%c\\\"]\\n\"", "", ",", "state", ",", "d_transitionTo", ".", "get", "(", "trans", ")", ",", "d_transitionChars", "[", "trans", "]", ")", ")", ";", "if", "(", "d_finalStates", ".", "get", "(", "state", ")", ")", "dotBuilder", ".", "append", "(", "String", ".", "format", "(", "\"%d [peripheries=2,label=\\\"%d (%d)\\\"];\\n\"", ",", "state", ",", "state", ",", "d_stateNSuffixes", ".", "get", "(", "state", ")", ")", ")", ";", "else", "dotBuilder", ".", "append", "(", "String", ".", "format", "(", "\"%d [label=\\\"%d (%d)\\\"];\\n\"", ",", "state", ",", "state", ",", "d_stateNSuffixes", ".", "get", "(", "state", ")", ")", ")", ";", "}", "dotBuilder", ".", "append", "(", "\"}\"", ")", ";", "return", "dotBuilder", ".", "toString", "(", ")", ";", "}" ]
Give the Graphviz dot representation of this automaton. States will also list the number of suffixes 'under' that state. @return
[ "Give", "the", "Graphviz", "dot", "representation", "of", "this", "automaton", ".", "States", "will", "also", "list", "the", "number", "of", "suffixes", "under", "that", "state", "." ]
c0a3ae2d407ebd88023ea2d0f02a4882b0492df0
https://github.com/danieldk/dictomaton/blob/c0a3ae2d407ebd88023ea2d0f02a4882b0492df0/src/main/java/eu/danieldk/dictomaton/PerfectHashDictionaryStateCard.java#L152-L172
6,967
danieldk/dictomaton
src/main/java/eu/danieldk/dictomaton/PerfectHashDictionaryStateCard.java
PerfectHashDictionaryStateCard.computeStateSuffixesTopological
private void computeStateSuffixesTopological(final int initialState, final int magicMarker) { for (Iterator<Integer> iterator = sortStatesTopological(initialState).iterator(); iterator.hasNext(); ) { Integer currentState = iterator.next(); int currentSuffixes = d_stateNSuffixes.get(currentState); if (currentSuffixes == magicMarker) { // is not yet computed int trans = d_stateOffsets.get(currentState); int transUpperBound = transitionsUpperBound(currentState); if (trans < transUpperBound) { // has children int suffixes = d_finalStates.get(currentState) ? 1 : 0; // add one if current state is final for (; trans < transUpperBound; ++trans) { // add known number of suffixes of children int childState = d_transitionTo.get(trans); assert d_stateNSuffixes.get(childState) != magicMarker : "suffxies should have been calculated for state " + childState; suffixes += d_stateNSuffixes.get(childState); } d_stateNSuffixes.set(currentState, suffixes); } else { d_stateNSuffixes.set(currentState, d_finalStates.get(currentState) ? 1 : 0); } } // else already computed from a different path in the DAG } }
java
private void computeStateSuffixesTopological(final int initialState, final int magicMarker) { for (Iterator<Integer> iterator = sortStatesTopological(initialState).iterator(); iterator.hasNext(); ) { Integer currentState = iterator.next(); int currentSuffixes = d_stateNSuffixes.get(currentState); if (currentSuffixes == magicMarker) { // is not yet computed int trans = d_stateOffsets.get(currentState); int transUpperBound = transitionsUpperBound(currentState); if (trans < transUpperBound) { // has children int suffixes = d_finalStates.get(currentState) ? 1 : 0; // add one if current state is final for (; trans < transUpperBound; ++trans) { // add known number of suffixes of children int childState = d_transitionTo.get(trans); assert d_stateNSuffixes.get(childState) != magicMarker : "suffxies should have been calculated for state " + childState; suffixes += d_stateNSuffixes.get(childState); } d_stateNSuffixes.set(currentState, suffixes); } else { d_stateNSuffixes.set(currentState, d_finalStates.get(currentState) ? 1 : 0); } } // else already computed from a different path in the DAG } }
[ "private", "void", "computeStateSuffixesTopological", "(", "final", "int", "initialState", ",", "final", "int", "magicMarker", ")", "{", "for", "(", "Iterator", "<", "Integer", ">", "iterator", "=", "sortStatesTopological", "(", "initialState", ")", ".", "iterator", "(", ")", ";", "iterator", ".", "hasNext", "(", ")", ";", ")", "{", "Integer", "currentState", "=", "iterator", ".", "next", "(", ")", ";", "int", "currentSuffixes", "=", "d_stateNSuffixes", ".", "get", "(", "currentState", ")", ";", "if", "(", "currentSuffixes", "==", "magicMarker", ")", "{", "// is not yet computed", "int", "trans", "=", "d_stateOffsets", ".", "get", "(", "currentState", ")", ";", "int", "transUpperBound", "=", "transitionsUpperBound", "(", "currentState", ")", ";", "if", "(", "trans", "<", "transUpperBound", ")", "{", "// has children", "int", "suffixes", "=", "d_finalStates", ".", "get", "(", "currentState", ")", "?", "1", ":", "0", ";", "// add one if current state is final", "for", "(", ";", "trans", "<", "transUpperBound", ";", "++", "trans", ")", "{", "// add known number of suffixes of children", "int", "childState", "=", "d_transitionTo", ".", "get", "(", "trans", ")", ";", "assert", "d_stateNSuffixes", ".", "get", "(", "childState", ")", "!=", "magicMarker", ":", "\"suffxies should have been calculated for state \"", "+", "childState", ";", "suffixes", "+=", "d_stateNSuffixes", ".", "get", "(", "childState", ")", ";", "}", "d_stateNSuffixes", ".", "set", "(", "currentState", ",", "suffixes", ")", ";", "}", "else", "{", "d_stateNSuffixes", ".", "set", "(", "currentState", ",", "d_finalStates", ".", "get", "(", "currentState", ")", "?", "1", ":", "0", ")", ";", "}", "}", "// else already computed from a different path in the DAG", "}", "}" ]
Iteratively computes the number of suffixes by topological order @param initialState the root of the graph @param magicMarker the value in d_stateNSuffixes indicating that the value has not yet been computed
[ "Iteratively", "computes", "the", "number", "of", "suffixes", "by", "topological", "order" ]
c0a3ae2d407ebd88023ea2d0f02a4882b0492df0
https://github.com/danieldk/dictomaton/blob/c0a3ae2d407ebd88023ea2d0f02a4882b0492df0/src/main/java/eu/danieldk/dictomaton/PerfectHashDictionaryStateCard.java#L199-L220
6,968
danieldk/dictomaton
src/main/java/eu/danieldk/dictomaton/DictionaryImpl.java
DictionaryImpl.transitionsUpperBound
protected int transitionsUpperBound(int state) { return state + 1 < d_stateOffsets.size() ? d_stateOffsets.get(state + 1) : d_transitionChars.length; }
java
protected int transitionsUpperBound(int state) { return state + 1 < d_stateOffsets.size() ? d_stateOffsets.get(state + 1) : d_transitionChars.length; }
[ "protected", "int", "transitionsUpperBound", "(", "int", "state", ")", "{", "return", "state", "+", "1", "<", "d_stateOffsets", ".", "size", "(", ")", "?", "d_stateOffsets", ".", "get", "(", "state", "+", "1", ")", ":", "d_transitionChars", ".", "length", ";", "}" ]
Calculate the upper bound for this state in the transition table. @param state @return
[ "Calculate", "the", "upper", "bound", "for", "this", "state", "in", "the", "transition", "table", "." ]
c0a3ae2d407ebd88023ea2d0f02a4882b0492df0
https://github.com/danieldk/dictomaton/blob/c0a3ae2d407ebd88023ea2d0f02a4882b0492df0/src/main/java/eu/danieldk/dictomaton/DictionaryImpl.java#L280-L283
6,969
danieldk/dictomaton
src/main/java/eu/danieldk/dictomaton/DictionaryImpl.java
DictionaryImpl.findTransition
protected int findTransition(int state, char c) { int start = d_stateOffsets.get(state); int end = transitionsUpperBound(state) - 1; // Binary search while (end >= start) { int mid = start + ((end - start) / 2); if (d_transitionChars[mid] > c) end = mid - 1; else if (d_transitionChars[mid] < c) start = mid + 1; else return mid; } return -1; }
java
protected int findTransition(int state, char c) { int start = d_stateOffsets.get(state); int end = transitionsUpperBound(state) - 1; // Binary search while (end >= start) { int mid = start + ((end - start) / 2); if (d_transitionChars[mid] > c) end = mid - 1; else if (d_transitionChars[mid] < c) start = mid + 1; else return mid; } return -1; }
[ "protected", "int", "findTransition", "(", "int", "state", ",", "char", "c", ")", "{", "int", "start", "=", "d_stateOffsets", ".", "get", "(", "state", ")", ";", "int", "end", "=", "transitionsUpperBound", "(", "state", ")", "-", "1", ";", "// Binary search", "while", "(", "end", ">=", "start", ")", "{", "int", "mid", "=", "start", "+", "(", "(", "end", "-", "start", ")", "/", "2", ")", ";", "if", "(", "d_transitionChars", "[", "mid", "]", ">", "c", ")", "end", "=", "mid", "-", "1", ";", "else", "if", "(", "d_transitionChars", "[", "mid", "]", "<", "c", ")", "start", "=", "mid", "+", "1", ";", "else", "return", "mid", ";", "}", "return", "-", "1", ";", "}" ]
Find the transition for the given character in the given state. Since the transitions are ordered by character, we can use a binary search. @param state @param c @return
[ "Find", "the", "transition", "for", "the", "given", "character", "in", "the", "given", "state", ".", "Since", "the", "transitions", "are", "ordered", "by", "character", "we", "can", "use", "a", "binary", "search", "." ]
c0a3ae2d407ebd88023ea2d0f02a4882b0492df0
https://github.com/danieldk/dictomaton/blob/c0a3ae2d407ebd88023ea2d0f02a4882b0492df0/src/main/java/eu/danieldk/dictomaton/DictionaryImpl.java#L293-L310
6,970
danieldk/dictomaton
src/main/java/eu/danieldk/dictomaton/DictionaryImpl.java
DictionaryImpl.containsSeq
private boolean containsSeq(String seq) { int state = 0; for (int i = 0; i < seq.length(); i++) { state = next(state, seq.charAt(i)); if (state == -1) return false; } return d_finalStates.get(state); }
java
private boolean containsSeq(String seq) { int state = 0; for (int i = 0; i < seq.length(); i++) { state = next(state, seq.charAt(i)); if (state == -1) return false; } return d_finalStates.get(state); }
[ "private", "boolean", "containsSeq", "(", "String", "seq", ")", "{", "int", "state", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "seq", ".", "length", "(", ")", ";", "i", "++", ")", "{", "state", "=", "next", "(", "state", ",", "seq", ".", "charAt", "(", "i", ")", ")", ";", "if", "(", "state", "==", "-", "1", ")", "return", "false", ";", "}", "return", "d_finalStates", ".", "get", "(", "state", ")", ";", "}" ]
Check whether the dictionary contains the given sequence. @param seq @return
[ "Check", "whether", "the", "dictionary", "contains", "the", "given", "sequence", "." ]
c0a3ae2d407ebd88023ea2d0f02a4882b0492df0
https://github.com/danieldk/dictomaton/blob/c0a3ae2d407ebd88023ea2d0f02a4882b0492df0/src/main/java/eu/danieldk/dictomaton/DictionaryImpl.java#L318-L328
6,971
danieldk/dictomaton
src/main/java/eu/danieldk/dictomaton/collections/ImmutableStringShortMap.java
ImmutableStringShortMap.getOrElse
public short getOrElse(String key, short defaultValue) { int hash = d_keys.number(key); if (hash == -1) return defaultValue; return d_values[hash - 1]; }
java
public short getOrElse(String key, short defaultValue) { int hash = d_keys.number(key); if (hash == -1) return defaultValue; return d_values[hash - 1]; }
[ "public", "short", "getOrElse", "(", "String", "key", ",", "short", "defaultValue", ")", "{", "int", "hash", "=", "d_keys", ".", "number", "(", "key", ")", ";", "if", "(", "hash", "==", "-", "1", ")", "return", "defaultValue", ";", "return", "d_values", "[", "hash", "-", "1", "]", ";", "}" ]
Get the value associated with a key, returning a default value is it is not in the mapping.
[ "Get", "the", "value", "associated", "with", "a", "key", "returning", "a", "default", "value", "is", "it", "is", "not", "in", "the", "mapping", "." ]
c0a3ae2d407ebd88023ea2d0f02a4882b0492df0
https://github.com/danieldk/dictomaton/blob/c0a3ae2d407ebd88023ea2d0f02a4882b0492df0/src/main/java/eu/danieldk/dictomaton/collections/ImmutableStringShortMap.java#L261-L267
6,972
baasbox/Android-SDK
library/src/main/java/com/baasbox/android/json/JsonWriter.java
JsonWriter.name
public JsonWriter name(String name) throws IOException { if (name == null) { throw new NullPointerException("name == null"); } beforeName(); string(name); return this; }
java
public JsonWriter name(String name) throws IOException { if (name == null) { throw new NullPointerException("name == null"); } beforeName(); string(name); return this; }
[ "public", "JsonWriter", "name", "(", "String", "name", ")", "throws", "IOException", "{", "if", "(", "name", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", "\"name == null\"", ")", ";", "}", "beforeName", "(", ")", ";", "string", "(", "name", ")", ";", "return", "this", ";", "}" ]
Encodes the property name. @param name the name of the forthcoming value. May not be null. @return this writer.
[ "Encodes", "the", "property", "name", "." ]
6bb2203246b885b2ad63a7bfaf37c83caf15e0d8
https://github.com/baasbox/Android-SDK/blob/6bb2203246b885b2ad63a7bfaf37c83caf15e0d8/library/src/main/java/com/baasbox/android/json/JsonWriter.java#L354-L361
6,973
baasbox/Android-SDK
library/src/main/java/com/baasbox/android/json/JsonReader.java
JsonReader.nextLiteral
private String nextLiteral(boolean assignOffsetsOnly) throws IOException { StringBuilder builder = null; valuePos = -1; valueLength = 0; int i = 0; findNonLiteralCharacter: while (true) { for (; pos + i < limit; i++) { switch (buffer[pos + i]) { case '/': case '\\': case ';': case '#': case '=': checkLenient(); // fall-through case '{': case '}': case '[': case ']': case ':': case ',': case ' ': case '\t': case '\f': case '\r': case '\n': break findNonLiteralCharacter; } } /* * Attempt to load the entire literal into the buffer at once. If * we run out of input, add a non-literal character at the end so * that decoding doesn't need to do bounds checks. */ if (i < buffer.length) { if (fillBuffer(i + 1)) { continue; } else { buffer[limit] = '\0'; break; } } // use a StringBuilder when the value is too long. It must be an unquoted string. if (builder == null) { builder = new StringBuilder(); } builder.append(buffer, pos, i); valueLength += i; pos += i; i = 0; if (!fillBuffer(1)) { break; } } String result; if (assignOffsetsOnly && builder == null) { valuePos = pos; result = null; } else if (skipping) { result = "skipped!"; } else if (builder == null) { result = stringPool.get(buffer, pos, i); } else { builder.append(buffer, pos, i); result = builder.toString(); } valueLength += i; pos += i; return result; }
java
private String nextLiteral(boolean assignOffsetsOnly) throws IOException { StringBuilder builder = null; valuePos = -1; valueLength = 0; int i = 0; findNonLiteralCharacter: while (true) { for (; pos + i < limit; i++) { switch (buffer[pos + i]) { case '/': case '\\': case ';': case '#': case '=': checkLenient(); // fall-through case '{': case '}': case '[': case ']': case ':': case ',': case ' ': case '\t': case '\f': case '\r': case '\n': break findNonLiteralCharacter; } } /* * Attempt to load the entire literal into the buffer at once. If * we run out of input, add a non-literal character at the end so * that decoding doesn't need to do bounds checks. */ if (i < buffer.length) { if (fillBuffer(i + 1)) { continue; } else { buffer[limit] = '\0'; break; } } // use a StringBuilder when the value is too long. It must be an unquoted string. if (builder == null) { builder = new StringBuilder(); } builder.append(buffer, pos, i); valueLength += i; pos += i; i = 0; if (!fillBuffer(1)) { break; } } String result; if (assignOffsetsOnly && builder == null) { valuePos = pos; result = null; } else if (skipping) { result = "skipped!"; } else if (builder == null) { result = stringPool.get(buffer, pos, i); } else { builder.append(buffer, pos, i); result = builder.toString(); } valueLength += i; pos += i; return result; }
[ "private", "String", "nextLiteral", "(", "boolean", "assignOffsetsOnly", ")", "throws", "IOException", "{", "StringBuilder", "builder", "=", "null", ";", "valuePos", "=", "-", "1", ";", "valueLength", "=", "0", ";", "int", "i", "=", "0", ";", "findNonLiteralCharacter", ":", "while", "(", "true", ")", "{", "for", "(", ";", "pos", "+", "i", "<", "limit", ";", "i", "++", ")", "{", "switch", "(", "buffer", "[", "pos", "+", "i", "]", ")", "{", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "checkLenient", "(", ")", ";", "// fall-through", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "break", "findNonLiteralCharacter", ";", "}", "}", "/*\n * Attempt to load the entire literal into the buffer at once. If\n * we run out of input, add a non-literal character at the end so\n * that decoding doesn't need to do bounds checks.\n */", "if", "(", "i", "<", "buffer", ".", "length", ")", "{", "if", "(", "fillBuffer", "(", "i", "+", "1", ")", ")", "{", "continue", ";", "}", "else", "{", "buffer", "[", "limit", "]", "=", "'", "'", ";", "break", ";", "}", "}", "// use a StringBuilder when the value is too long. It must be an unquoted string.", "if", "(", "builder", "==", "null", ")", "{", "builder", "=", "new", "StringBuilder", "(", ")", ";", "}", "builder", ".", "append", "(", "buffer", ",", "pos", ",", "i", ")", ";", "valueLength", "+=", "i", ";", "pos", "+=", "i", ";", "i", "=", "0", ";", "if", "(", "!", "fillBuffer", "(", "1", ")", ")", "{", "break", ";", "}", "}", "String", "result", ";", "if", "(", "assignOffsetsOnly", "&&", "builder", "==", "null", ")", "{", "valuePos", "=", "pos", ";", "result", "=", "null", ";", "}", "else", "if", "(", "skipping", ")", "{", "result", "=", "\"skipped!\"", ";", "}", "else", "if", "(", "builder", "==", "null", ")", "{", "result", "=", "stringPool", ".", "get", "(", "buffer", ",", "pos", ",", "i", ")", ";", "}", "else", "{", "builder", ".", "append", "(", "buffer", ",", "pos", ",", "i", ")", ";", "result", "=", "builder", ".", "toString", "(", ")", ";", "}", "valueLength", "+=", "i", ";", "pos", "+=", "i", ";", "return", "result", ";", "}" ]
Reads the value up to but not including any delimiter characters. This does not consume the delimiter character. @param assignOffsetsOnly true for this method to only set the valuePos and valueLength fields and return a null result. This only works if the literal is short; a string is returned otherwise.
[ "Reads", "the", "value", "up", "to", "but", "not", "including", "any", "delimiter", "characters", ".", "This", "does", "not", "consume", "the", "delimiter", "character", "." ]
6bb2203246b885b2ad63a7bfaf37c83caf15e0d8
https://github.com/baasbox/Android-SDK/blob/6bb2203246b885b2ad63a7bfaf37c83caf15e0d8/library/src/main/java/com/baasbox/android/json/JsonReader.java#L737-L810
6,974
baasbox/Android-SDK
library/src/main/java/com/baasbox/android/json/JsonReader.java
JsonReader.readLiteral
private JsonToken readLiteral() throws IOException { value = nextLiteral(true); if (valueLength == 0) { throw syntaxError("Expected literal value"); } token = decodeLiteral(); if (token == JsonToken.STRING) { checkLenient(); } return token; }
java
private JsonToken readLiteral() throws IOException { value = nextLiteral(true); if (valueLength == 0) { throw syntaxError("Expected literal value"); } token = decodeLiteral(); if (token == JsonToken.STRING) { checkLenient(); } return token; }
[ "private", "JsonToken", "readLiteral", "(", ")", "throws", "IOException", "{", "value", "=", "nextLiteral", "(", "true", ")", ";", "if", "(", "valueLength", "==", "0", ")", "{", "throw", "syntaxError", "(", "\"Expected literal value\"", ")", ";", "}", "token", "=", "decodeLiteral", "(", ")", ";", "if", "(", "token", "==", "JsonToken", ".", "STRING", ")", "{", "checkLenient", "(", ")", ";", "}", "return", "token", ";", "}" ]
Reads a null, boolean, numeric or unquoted string literal value.
[ "Reads", "a", "null", "boolean", "numeric", "or", "unquoted", "string", "literal", "value", "." ]
6bb2203246b885b2ad63a7bfaf37c83caf15e0d8
https://github.com/baasbox/Android-SDK/blob/6bb2203246b885b2ad63a7bfaf37c83caf15e0d8/library/src/main/java/com/baasbox/android/json/JsonReader.java#L842-L852
6,975
baasbox/Android-SDK
library/src/main/java/com/baasbox/android/json/JsonReader.java
JsonReader.decodeNumber
private JsonToken decodeNumber(char[] chars, int offset, int length) { int i = offset; int c = chars[i]; if (c == '-') { c = chars[++i]; } if (c == '0') { c = chars[++i]; } else if (c >= '1' && c <= '9') { c = chars[++i]; while (c >= '0' && c <= '9') { c = chars[++i]; } } else { return JsonToken.STRING; } if (c == '.') { c = chars[++i]; while (c >= '0' && c <= '9') { c = chars[++i]; } } if (c == 'e' || c == 'E') { c = chars[++i]; if (c == '+' || c == '-') { c = chars[++i]; } if (c >= '0' && c <= '9') { c = chars[++i]; while (c >= '0' && c <= '9') { c = chars[++i]; } } else { return JsonToken.STRING; } } if (i == offset + length) { return JsonToken.NUMBER; } else { return JsonToken.STRING; } }
java
private JsonToken decodeNumber(char[] chars, int offset, int length) { int i = offset; int c = chars[i]; if (c == '-') { c = chars[++i]; } if (c == '0') { c = chars[++i]; } else if (c >= '1' && c <= '9') { c = chars[++i]; while (c >= '0' && c <= '9') { c = chars[++i]; } } else { return JsonToken.STRING; } if (c == '.') { c = chars[++i]; while (c >= '0' && c <= '9') { c = chars[++i]; } } if (c == 'e' || c == 'E') { c = chars[++i]; if (c == '+' || c == '-') { c = chars[++i]; } if (c >= '0' && c <= '9') { c = chars[++i]; while (c >= '0' && c <= '9') { c = chars[++i]; } } else { return JsonToken.STRING; } } if (i == offset + length) { return JsonToken.NUMBER; } else { return JsonToken.STRING; } }
[ "private", "JsonToken", "decodeNumber", "(", "char", "[", "]", "chars", ",", "int", "offset", ",", "int", "length", ")", "{", "int", "i", "=", "offset", ";", "int", "c", "=", "chars", "[", "i", "]", ";", "if", "(", "c", "==", "'", "'", ")", "{", "c", "=", "chars", "[", "++", "i", "]", ";", "}", "if", "(", "c", "==", "'", "'", ")", "{", "c", "=", "chars", "[", "++", "i", "]", ";", "}", "else", "if", "(", "c", ">=", "'", "'", "&&", "c", "<=", "'", "'", ")", "{", "c", "=", "chars", "[", "++", "i", "]", ";", "while", "(", "c", ">=", "'", "'", "&&", "c", "<=", "'", "'", ")", "{", "c", "=", "chars", "[", "++", "i", "]", ";", "}", "}", "else", "{", "return", "JsonToken", ".", "STRING", ";", "}", "if", "(", "c", "==", "'", "'", ")", "{", "c", "=", "chars", "[", "++", "i", "]", ";", "while", "(", "c", ">=", "'", "'", "&&", "c", "<=", "'", "'", ")", "{", "c", "=", "chars", "[", "++", "i", "]", ";", "}", "}", "if", "(", "c", "==", "'", "'", "||", "c", "==", "'", "'", ")", "{", "c", "=", "chars", "[", "++", "i", "]", ";", "if", "(", "c", "==", "'", "'", "||", "c", "==", "'", "'", ")", "{", "c", "=", "chars", "[", "++", "i", "]", ";", "}", "if", "(", "c", ">=", "'", "'", "&&", "c", "<=", "'", "'", ")", "{", "c", "=", "chars", "[", "++", "i", "]", ";", "while", "(", "c", ">=", "'", "'", "&&", "c", "<=", "'", "'", ")", "{", "c", "=", "chars", "[", "++", "i", "]", ";", "}", "}", "else", "{", "return", "JsonToken", ".", "STRING", ";", "}", "}", "if", "(", "i", "==", "offset", "+", "length", ")", "{", "return", "JsonToken", ".", "NUMBER", ";", "}", "else", "{", "return", "JsonToken", ".", "STRING", ";", "}", "}" ]
Determine whether the characters is a JSON number. Numbers are of the form -12.34e+56. Fractional and exponential parts are optional. Leading zeroes are not allowed in the value or exponential part, but are allowed in the fraction.
[ "Determine", "whether", "the", "characters", "is", "a", "JSON", "number", ".", "Numbers", "are", "of", "the", "form", "-", "12", ".", "34e", "+", "56", ".", "Fractional", "and", "exponential", "parts", "are", "optional", ".", "Leading", "zeroes", "are", "not", "allowed", "in", "the", "value", "or", "exponential", "part", "but", "are", "allowed", "in", "the", "fraction", "." ]
6bb2203246b885b2ad63a7bfaf37c83caf15e0d8
https://github.com/baasbox/Android-SDK/blob/6bb2203246b885b2ad63a7bfaf37c83caf15e0d8/library/src/main/java/com/baasbox/android/json/JsonReader.java#L895-L941
6,976
baasbox/Android-SDK
library/src/main/java/com/baasbox/android/json/JsonReader.java
JsonReader.advance
private JsonToken advance() throws IOException { peek(); JsonToken result = token; token = null; value = null; name = null; return result; }
java
private JsonToken advance() throws IOException { peek(); JsonToken result = token; token = null; value = null; name = null; return result; }
[ "private", "JsonToken", "advance", "(", ")", "throws", "IOException", "{", "peek", "(", ")", ";", "JsonToken", "result", "=", "token", ";", "token", "=", "null", ";", "value", "=", "null", ";", "name", "=", "null", ";", "return", "result", ";", "}" ]
Advances the cursor in the JSON stream to the next token.
[ "Advances", "the", "cursor", "in", "the", "JSON", "stream", "to", "the", "next", "token", "." ]
6bb2203246b885b2ad63a7bfaf37c83caf15e0d8
https://github.com/baasbox/Android-SDK/blob/6bb2203246b885b2ad63a7bfaf37c83caf15e0d8/library/src/main/java/com/baasbox/android/json/JsonReader.java#L977-L985
6,977
baasbox/Android-SDK
library/src/main/java/com/baasbox/android/json/JsonReader.java
JsonReader.skipValue
public void skipValue() throws IOException { skipping = true; try { int count = 0; do { JsonToken token = advance(); if (token == JsonToken.BEGIN_ARRAY || token == JsonToken.BEGIN_OBJECT) { count++; } else if (token == JsonToken.END_ARRAY || token == JsonToken.END_OBJECT) { count--; } } while (count != 0); } finally { skipping = false; } }
java
public void skipValue() throws IOException { skipping = true; try { int count = 0; do { JsonToken token = advance(); if (token == JsonToken.BEGIN_ARRAY || token == JsonToken.BEGIN_OBJECT) { count++; } else if (token == JsonToken.END_ARRAY || token == JsonToken.END_OBJECT) { count--; } } while (count != 0); } finally { skipping = false; } }
[ "public", "void", "skipValue", "(", ")", "throws", "IOException", "{", "skipping", "=", "true", ";", "try", "{", "int", "count", "=", "0", ";", "do", "{", "JsonToken", "token", "=", "advance", "(", ")", ";", "if", "(", "token", "==", "JsonToken", ".", "BEGIN_ARRAY", "||", "token", "==", "JsonToken", ".", "BEGIN_OBJECT", ")", "{", "count", "++", ";", "}", "else", "if", "(", "token", "==", "JsonToken", ".", "END_ARRAY", "||", "token", "==", "JsonToken", ".", "END_OBJECT", ")", "{", "count", "--", ";", "}", "}", "while", "(", "count", "!=", "0", ")", ";", "}", "finally", "{", "skipping", "=", "false", ";", "}", "}" ]
Skips the next value recursively. If it is an object or array, all nested elements are skipped. This method is intended for use when the JSON token stream contains unrecognized or unhandled values.
[ "Skips", "the", "next", "value", "recursively", ".", "If", "it", "is", "an", "object", "or", "array", "all", "nested", "elements", "are", "skipped", ".", "This", "method", "is", "intended", "for", "use", "when", "the", "JSON", "token", "stream", "contains", "unrecognized", "or", "unhandled", "values", "." ]
6bb2203246b885b2ad63a7bfaf37c83caf15e0d8
https://github.com/baasbox/Android-SDK/blob/6bb2203246b885b2ad63a7bfaf37c83caf15e0d8/library/src/main/java/com/baasbox/android/json/JsonReader.java#L1174-L1189
6,978
danieldk/dictomaton
src/main/java/eu/danieldk/dictomaton/DictionaryBuilder.java
DictionaryBuilder.add
public DictionaryBuilder add(CharSequence seq) throws DictionaryBuilderException { if (d_finalized) throw new DictionaryBuilderException("Cannot add a sequence to a finalized DictionaryBuilder."); if (d_prevSeq != null && compareCharacterSequences(d_prevSeq, seq) >= 0) throw new DictionaryBuilderException(String.format("Sequences are not added in lexicographic order: %s %s", d_prevSeq, seq)); d_prevSeq = seq; // Traverse across the shared prefix. int i = 0; State curState = d_startState; for (int len = seq.length(); i < len; i++) { State nextState = curState.move(seq.charAt(i)); if (nextState != null) curState = nextState; else break; } if (curState.hasOutgoing()) replaceOrRegisterIterative(curState); addSuffix(curState, seq.subSequence(i, seq.length())); ++d_nSeqs; return this; }
java
public DictionaryBuilder add(CharSequence seq) throws DictionaryBuilderException { if (d_finalized) throw new DictionaryBuilderException("Cannot add a sequence to a finalized DictionaryBuilder."); if (d_prevSeq != null && compareCharacterSequences(d_prevSeq, seq) >= 0) throw new DictionaryBuilderException(String.format("Sequences are not added in lexicographic order: %s %s", d_prevSeq, seq)); d_prevSeq = seq; // Traverse across the shared prefix. int i = 0; State curState = d_startState; for (int len = seq.length(); i < len; i++) { State nextState = curState.move(seq.charAt(i)); if (nextState != null) curState = nextState; else break; } if (curState.hasOutgoing()) replaceOrRegisterIterative(curState); addSuffix(curState, seq.subSequence(i, seq.length())); ++d_nSeqs; return this; }
[ "public", "DictionaryBuilder", "add", "(", "CharSequence", "seq", ")", "throws", "DictionaryBuilderException", "{", "if", "(", "d_finalized", ")", "throw", "new", "DictionaryBuilderException", "(", "\"Cannot add a sequence to a finalized DictionaryBuilder.\"", ")", ";", "if", "(", "d_prevSeq", "!=", "null", "&&", "compareCharacterSequences", "(", "d_prevSeq", ",", "seq", ")", ">=", "0", ")", "throw", "new", "DictionaryBuilderException", "(", "String", ".", "format", "(", "\"Sequences are not added in lexicographic order: %s %s\"", ",", "d_prevSeq", ",", "seq", ")", ")", ";", "d_prevSeq", "=", "seq", ";", "// Traverse across the shared prefix.", "int", "i", "=", "0", ";", "State", "curState", "=", "d_startState", ";", "for", "(", "int", "len", "=", "seq", ".", "length", "(", ")", ";", "i", "<", "len", ";", "i", "++", ")", "{", "State", "nextState", "=", "curState", ".", "move", "(", "seq", ".", "charAt", "(", "i", ")", ")", ";", "if", "(", "nextState", "!=", "null", ")", "curState", "=", "nextState", ";", "else", "break", ";", "}", "if", "(", "curState", ".", "hasOutgoing", "(", ")", ")", "replaceOrRegisterIterative", "(", "curState", ")", ";", "addSuffix", "(", "curState", ",", "seq", ".", "subSequence", "(", "i", ",", "seq", ".", "length", "(", ")", ")", ")", ";", "++", "d_nSeqs", ";", "return", "this", ";", "}" ]
Add a character sequence. @param seq The sequence.
[ "Add", "a", "character", "sequence", "." ]
c0a3ae2d407ebd88023ea2d0f02a4882b0492df0
https://github.com/danieldk/dictomaton/blob/c0a3ae2d407ebd88023ea2d0f02a4882b0492df0/src/main/java/eu/danieldk/dictomaton/DictionaryBuilder.java#L72-L100
6,979
danieldk/dictomaton
src/main/java/eu/danieldk/dictomaton/DictionaryBuilder.java
DictionaryBuilder.addAll
public DictionaryBuilder addAll(Collection<? extends CharSequence> seqs) throws DictionaryBuilderException { for (CharSequence seq : seqs) add(seq); return this; }
java
public DictionaryBuilder addAll(Collection<? extends CharSequence> seqs) throws DictionaryBuilderException { for (CharSequence seq : seqs) add(seq); return this; }
[ "public", "DictionaryBuilder", "addAll", "(", "Collection", "<", "?", "extends", "CharSequence", ">", "seqs", ")", "throws", "DictionaryBuilderException", "{", "for", "(", "CharSequence", "seq", ":", "seqs", ")", "add", "(", "seq", ")", ";", "return", "this", ";", "}" ]
Add all sequences from a lexicographically sorted collection. @param seqs A collection of sequences. @throws DictionaryBuilderException
[ "Add", "all", "sequences", "from", "a", "lexicographically", "sorted", "collection", "." ]
c0a3ae2d407ebd88023ea2d0f02a4882b0492df0
https://github.com/danieldk/dictomaton/blob/c0a3ae2d407ebd88023ea2d0f02a4882b0492df0/src/main/java/eu/danieldk/dictomaton/DictionaryBuilder.java#L128-L133
6,980
danieldk/dictomaton
src/main/java/eu/danieldk/dictomaton/levenshtein/LevenshteinAutomatonState.java
LevenshteinAutomatonState.reduce
public void reduce(Character otherChar) { Set<Integer> seen = new HashSet<>(); Queue<LevenshteinAutomatonState> q = new LinkedList<>(); q.add(this); while (!q.isEmpty()) { LevenshteinAutomatonState s = q.poll(); if (seen.contains(System.identityHashCode(s))) continue; LevenshteinAutomatonState otherTo = s.transitions.get(otherChar); if (otherTo == null) { // There is no reduction possible in this state: queue the to-states, mark this state // as seen and continue with the next state. for (LevenshteinAutomatonState toState : s.transitions.values()) q.add(toState); seen.add(System.identityHashCode(s)); continue; } // Find transitions that can be removed, because they are handled by an 'other' transition. This // is the case when a transition is not the 'other' transition, but has the same to-state as the // 'other' transition. Set<Character> remove = new HashSet<>(); for (Entry<Character, LevenshteinAutomatonState> trans : s.transitions.entrySet()) if (!trans.getKey().equals(otherChar) && trans.getValue() == otherTo) remove.add(trans.getKey()); // Remove the transitions that were found. for (Character c : remove) s.transitions.remove(c); // Recompute the hash if the state table has changed. if (remove.size() != 0) s.d_recomputeHash = true; // We have now seen this state. seen.add(System.identityHashCode(s)); // Queue states that can be reached via this state. for (LevenshteinAutomatonState toState : s.transitions.values()) q.add(toState); } }
java
public void reduce(Character otherChar) { Set<Integer> seen = new HashSet<>(); Queue<LevenshteinAutomatonState> q = new LinkedList<>(); q.add(this); while (!q.isEmpty()) { LevenshteinAutomatonState s = q.poll(); if (seen.contains(System.identityHashCode(s))) continue; LevenshteinAutomatonState otherTo = s.transitions.get(otherChar); if (otherTo == null) { // There is no reduction possible in this state: queue the to-states, mark this state // as seen and continue with the next state. for (LevenshteinAutomatonState toState : s.transitions.values()) q.add(toState); seen.add(System.identityHashCode(s)); continue; } // Find transitions that can be removed, because they are handled by an 'other' transition. This // is the case when a transition is not the 'other' transition, but has the same to-state as the // 'other' transition. Set<Character> remove = new HashSet<>(); for (Entry<Character, LevenshteinAutomatonState> trans : s.transitions.entrySet()) if (!trans.getKey().equals(otherChar) && trans.getValue() == otherTo) remove.add(trans.getKey()); // Remove the transitions that were found. for (Character c : remove) s.transitions.remove(c); // Recompute the hash if the state table has changed. if (remove.size() != 0) s.d_recomputeHash = true; // We have now seen this state. seen.add(System.identityHashCode(s)); // Queue states that can be reached via this state. for (LevenshteinAutomatonState toState : s.transitions.values()) q.add(toState); } }
[ "public", "void", "reduce", "(", "Character", "otherChar", ")", "{", "Set", "<", "Integer", ">", "seen", "=", "new", "HashSet", "<>", "(", ")", ";", "Queue", "<", "LevenshteinAutomatonState", ">", "q", "=", "new", "LinkedList", "<>", "(", ")", ";", "q", ".", "add", "(", "this", ")", ";", "while", "(", "!", "q", ".", "isEmpty", "(", ")", ")", "{", "LevenshteinAutomatonState", "s", "=", "q", ".", "poll", "(", ")", ";", "if", "(", "seen", ".", "contains", "(", "System", ".", "identityHashCode", "(", "s", ")", ")", ")", "continue", ";", "LevenshteinAutomatonState", "otherTo", "=", "s", ".", "transitions", ".", "get", "(", "otherChar", ")", ";", "if", "(", "otherTo", "==", "null", ")", "{", "// There is no reduction possible in this state: queue the to-states, mark this state", "// as seen and continue with the next state.", "for", "(", "LevenshteinAutomatonState", "toState", ":", "s", ".", "transitions", ".", "values", "(", ")", ")", "q", ".", "(", "toState", ")", ";", "seen", ".", "add", "(", "System", ".", "identityHashCode", "(", "s", ")", ")", ";", "continue", ";", "}", "// Find transitions that can be removed, because they are handled by an 'other' transition. This", "// is the case when a transition is not the 'other' transition, but has the same to-state as the", "// 'other' transition.", "Set", "<", "Character", ">", "remove", "=", "new", "HashSet", "<>", "(", ")", ";", "for", "(", "Entry", "<", "Character", ",", "LevenshteinAutomatonState", ">", "trans", ":", "s", ".", "transitions", ".", "entrySet", "(", ")", ")", "if", "(", "!", "trans", ".", "getKey", "(", ")", ".", "equals", "(", "otherChar", ")", "&&", "trans", ".", "getValue", "(", ")", "==", "otherTo", ")", "remove", ".", "add", "(", "trans", ".", "getKey", "(", ")", ")", ";", "// Remove the transitions that were found.", "for", "(", "Character", "c", ":", "remove", ")", "s", ".", "transitions", ".", "remove", "(", ")", ";", "// Recompute the hash if the state table has changed.", "if", "(", "remove", ".", "size", "(", ")", "!=", "0", ")", "s", ".", "d_recomputeHash", "=", "true", ";", "// We have now seen this state.", "seen", ".", "add", "(", "System", ".", "identityHashCode", "(", "s", ")", ")", ";", "// Queue states that can be reached via this state.", "for", "(", "LevenshteinAutomatonState", "toState", ":", "s", ".", "transitions", ".", "values", "(", ")", ")", "q", ".", "(", "toState", ")", ";", "}", "}" ]
Reduce the set of outgoing transitions by removing transitions that are also captured by the 'other'-transition. The 'other'-transition are transitions with the given character. @param otherChar The character representing any other character.
[ "Reduce", "the", "set", "of", "outgoing", "transitions", "by", "removing", "transitions", "that", "are", "also", "captured", "by", "the", "other", "-", "transition", ".", "The", "other", "-", "transition", "are", "transitions", "with", "the", "given", "character", "." ]
c0a3ae2d407ebd88023ea2d0f02a4882b0492df0
https://github.com/danieldk/dictomaton/blob/c0a3ae2d407ebd88023ea2d0f02a4882b0492df0/src/main/java/eu/danieldk/dictomaton/levenshtein/LevenshteinAutomatonState.java#L122-L167
6,981
baasbox/Android-SDK
library/src/main/java/com/baasbox/android/BaasAsset.java
BaasAsset.fetchData
public static RequestToken fetchData(String id, BaasHandler<JsonObject> handler){ return fetchData(id, RequestOptions.DEFAULT, handler); }
java
public static RequestToken fetchData(String id, BaasHandler<JsonObject> handler){ return fetchData(id, RequestOptions.DEFAULT, handler); }
[ "public", "static", "RequestToken", "fetchData", "(", "String", "id", ",", "BaasHandler", "<", "JsonObject", ">", "handler", ")", "{", "return", "fetchData", "(", "id", ",", "RequestOptions", ".", "DEFAULT", ",", "handler", ")", ";", "}" ]
Asynchronously retrieves named assets data, If the named asset is a document, the document is retrieved otherwise attached data to the file are returned. This version of the method uses default priority. @param id the name of the asset @param handler an handler that will be handed the response @return a request token
[ "Asynchronously", "retrieves", "named", "assets", "data", "If", "the", "named", "asset", "is", "a", "document", "the", "document", "is", "retrieved", "otherwise", "attached", "data", "to", "the", "file", "are", "returned", ".", "This", "version", "of", "the", "method", "uses", "default", "priority", "." ]
6bb2203246b885b2ad63a7bfaf37c83caf15e0d8
https://github.com/baasbox/Android-SDK/blob/6bb2203246b885b2ad63a7bfaf37c83caf15e0d8/library/src/main/java/com/baasbox/android/BaasAsset.java#L41-L43
6,982
baasbox/Android-SDK
library/src/main/java/com/baasbox/android/BaasAsset.java
BaasAsset.fetchData
public static RequestToken fetchData(String id, int flags, BaasHandler<JsonObject> handler){ if(id==null) throw new IllegalArgumentException("asset id cannot be null"); BaasBox box = BaasBox.getDefaultChecked(); AssetDataRequest req = new AssetDataRequest(box,id,flags,handler); return box.submitAsync(req); }
java
public static RequestToken fetchData(String id, int flags, BaasHandler<JsonObject> handler){ if(id==null) throw new IllegalArgumentException("asset id cannot be null"); BaasBox box = BaasBox.getDefaultChecked(); AssetDataRequest req = new AssetDataRequest(box,id,flags,handler); return box.submitAsync(req); }
[ "public", "static", "RequestToken", "fetchData", "(", "String", "id", ",", "int", "flags", ",", "BaasHandler", "<", "JsonObject", ">", "handler", ")", "{", "if", "(", "id", "==", "null", ")", "throw", "new", "IllegalArgumentException", "(", "\"asset id cannot be null\"", ")", ";", "BaasBox", "box", "=", "BaasBox", ".", "getDefaultChecked", "(", ")", ";", "AssetDataRequest", "req", "=", "new", "AssetDataRequest", "(", "box", ",", "id", ",", "flags", ",", "handler", ")", ";", "return", "box", ".", "submitAsync", "(", "req", ")", ";", "}" ]
Asynchronously retrieves named assets data, If the named asset is a document, the document is retrieved otherwise attached data to the file are returned. @param id the name of the asset @param flags used for the request a bit or of {@link RequestOptions} constants @param handler an handler that will be handed the response @return a request token
[ "Asynchronously", "retrieves", "named", "assets", "data", "If", "the", "named", "asset", "is", "a", "document", "the", "document", "is", "retrieved", "otherwise", "attached", "data", "to", "the", "file", "are", "returned", "." ]
6bb2203246b885b2ad63a7bfaf37c83caf15e0d8
https://github.com/baasbox/Android-SDK/blob/6bb2203246b885b2ad63a7bfaf37c83caf15e0d8/library/src/main/java/com/baasbox/android/BaasAsset.java#L55-L60
6,983
baasbox/Android-SDK
library/src/main/java/com/baasbox/android/BaasAsset.java
BaasAsset.fetchDataSync
public static BaasResult<JsonObject> fetchDataSync(String id){ if (id == null) throw new IllegalArgumentException("asset id cannot be null"); BaasBox box = BaasBox.getDefaultChecked(); AssetDataRequest req = new AssetDataRequest(box,id, RequestOptions.DEFAULT,null); return box.submitSync(req); }
java
public static BaasResult<JsonObject> fetchDataSync(String id){ if (id == null) throw new IllegalArgumentException("asset id cannot be null"); BaasBox box = BaasBox.getDefaultChecked(); AssetDataRequest req = new AssetDataRequest(box,id, RequestOptions.DEFAULT,null); return box.submitSync(req); }
[ "public", "static", "BaasResult", "<", "JsonObject", ">", "fetchDataSync", "(", "String", "id", ")", "{", "if", "(", "id", "==", "null", ")", "throw", "new", "IllegalArgumentException", "(", "\"asset id cannot be null\"", ")", ";", "BaasBox", "box", "=", "BaasBox", ".", "getDefaultChecked", "(", ")", ";", "AssetDataRequest", "req", "=", "new", "AssetDataRequest", "(", "box", ",", "id", ",", "RequestOptions", ".", "DEFAULT", ",", "null", ")", ";", "return", "box", ".", "submitSync", "(", "req", ")", ";", "}" ]
Synchronously retrieves named assets data, If the named asset is a document, the document is retrieved otherwise attached data to the file are returned. @param id the name of the asset @return a baas result wrapping the response.
[ "Synchronously", "retrieves", "named", "assets", "data", "If", "the", "named", "asset", "is", "a", "document", "the", "document", "is", "retrieved", "otherwise", "attached", "data", "to", "the", "file", "are", "returned", "." ]
6bb2203246b885b2ad63a7bfaf37c83caf15e0d8
https://github.com/baasbox/Android-SDK/blob/6bb2203246b885b2ad63a7bfaf37c83caf15e0d8/library/src/main/java/com/baasbox/android/BaasAsset.java#L71-L76
6,984
danieldk/dictomaton
src/main/java/eu/danieldk/dictomaton/State.java
State.addTransition
public void addTransition(Character c, State s) { transitions.put(c, s); d_recomputeHash = true; }
java
public void addTransition(Character c, State s) { transitions.put(c, s); d_recomputeHash = true; }
[ "public", "void", "addTransition", "(", "Character", "c", ",", "State", "s", ")", "{", "transitions", ".", "put", "(", "c", ",", "s", ")", ";", "d_recomputeHash", "=", "true", ";", "}" ]
Add a transition to the state. If a transition with the provided character already exists, it will be replaced. @param c The transition character. @param s The to-state.
[ "Add", "a", "transition", "to", "the", "state", ".", "If", "a", "transition", "with", "the", "provided", "character", "already", "exists", "it", "will", "be", "replaced", "." ]
c0a3ae2d407ebd88023ea2d0f02a4882b0492df0
https://github.com/danieldk/dictomaton/blob/c0a3ae2d407ebd88023ea2d0f02a4882b0492df0/src/main/java/eu/danieldk/dictomaton/State.java#L45-L48
6,985
baasbox/Android-SDK
library/src/main/java/com/baasbox/android/BaasBox.java
BaasBox.rest
@Deprecated public RequestToken rest(int method, String endpoint, JsonArray body, int flags,boolean authenticate, BaasHandler<JsonObject> jsonHandler) { return mRest.async(RestImpl.methodFrom(method), endpoint, body, authenticate, flags, jsonHandler); }
java
@Deprecated public RequestToken rest(int method, String endpoint, JsonArray body, int flags,boolean authenticate, BaasHandler<JsonObject> jsonHandler) { return mRest.async(RestImpl.methodFrom(method), endpoint, body, authenticate, flags, jsonHandler); }
[ "@", "Deprecated", "public", "RequestToken", "rest", "(", "int", "method", ",", "String", "endpoint", ",", "JsonArray", "body", ",", "int", "flags", ",", "boolean", "authenticate", ",", "BaasHandler", "<", "JsonObject", ">", "jsonHandler", ")", "{", "return", "mRest", ".", "async", "(", "RestImpl", ".", "methodFrom", "(", "method", ")", ",", "endpoint", ",", "body", ",", "authenticate", ",", "flags", ",", "jsonHandler", ")", ";", "}" ]
Asynchronously sends a raw rest request to the server that is specified by the parameters passed in @param flags bitmask of flags for the request {@see Flags} @param method the method to use @param endpoint the resource @param body an optional json array @return a raw {@link com.baasbox.android.json.JsonObject} response wrapped as {@link com.baasbox.android.BaasResult}
[ "Asynchronously", "sends", "a", "raw", "rest", "request", "to", "the", "server", "that", "is", "specified", "by", "the", "parameters", "passed", "in" ]
6bb2203246b885b2ad63a7bfaf37c83caf15e0d8
https://github.com/baasbox/Android-SDK/blob/6bb2203246b885b2ad63a7bfaf37c83caf15e0d8/library/src/main/java/com/baasbox/android/BaasBox.java#L227-L230
6,986
baasbox/Android-SDK
library/src/main/java/com/baasbox/android/BaasBox.java
BaasBox.rest
@Deprecated public RequestToken rest(int method, String endpoint, JsonArray body, boolean authenticate, BaasHandler<JsonObject> handler) { return rest(method, endpoint, body, 0, authenticate, handler); }
java
@Deprecated public RequestToken rest(int method, String endpoint, JsonArray body, boolean authenticate, BaasHandler<JsonObject> handler) { return rest(method, endpoint, body, 0, authenticate, handler); }
[ "@", "Deprecated", "public", "RequestToken", "rest", "(", "int", "method", ",", "String", "endpoint", ",", "JsonArray", "body", ",", "boolean", "authenticate", ",", "BaasHandler", "<", "JsonObject", ">", "handler", ")", "{", "return", "rest", "(", "method", ",", "endpoint", ",", "body", ",", "0", ",", "authenticate", ",", "handler", ")", ";", "}" ]
Asynchronously sends a raw rest request to the server that is specified by the parameters passed in. @param method the method to use @param endpoint the resource @param body an optional jsono bject @param authenticate true if the client should try to refresh authentication automatically @param handler a callback to handle the json response @return a raw {@link com.baasbox.android.json.JsonObject} response wrapped as {@link com.baasbox.android.BaasResult}
[ "Asynchronously", "sends", "a", "raw", "rest", "request", "to", "the", "server", "that", "is", "specified", "by", "the", "parameters", "passed", "in", "." ]
6bb2203246b885b2ad63a7bfaf37c83caf15e0d8
https://github.com/baasbox/Android-SDK/blob/6bb2203246b885b2ad63a7bfaf37c83caf15e0d8/library/src/main/java/com/baasbox/android/BaasBox.java#L258-L261
6,987
baasbox/Android-SDK
library/src/main/java/com/baasbox/android/BaasBox.java
BaasBox.restSync
@Deprecated public BaasResult<JsonObject> restSync(int method, String endpoint, JsonArray body, boolean authenticate) { return mRest.sync(RestImpl.methodFrom(method), endpoint, body, authenticate); }
java
@Deprecated public BaasResult<JsonObject> restSync(int method, String endpoint, JsonArray body, boolean authenticate) { return mRest.sync(RestImpl.methodFrom(method), endpoint, body, authenticate); }
[ "@", "Deprecated", "public", "BaasResult", "<", "JsonObject", ">", "restSync", "(", "int", "method", ",", "String", "endpoint", ",", "JsonArray", "body", ",", "boolean", "authenticate", ")", "{", "return", "mRest", ".", "sync", "(", "RestImpl", ".", "methodFrom", "(", "method", ")", ",", "endpoint", ",", "body", ",", "authenticate", ")", ";", "}" ]
Synchronously sends a raw rest request to the server that is specified by the parameters passed in. @param method the method to use @param endpoint the resource @param body an optional jsono bject @param authenticate true if the client should try to refresh authentication automatically @return a raw {@link com.baasbox.android.json.JsonObject} response wrapped as {@link com.baasbox.android.BaasResult}
[ "Synchronously", "sends", "a", "raw", "rest", "request", "to", "the", "server", "that", "is", "specified", "by", "the", "parameters", "passed", "in", "." ]
6bb2203246b885b2ad63a7bfaf37c83caf15e0d8
https://github.com/baasbox/Android-SDK/blob/6bb2203246b885b2ad63a7bfaf37c83caf15e0d8/library/src/main/java/com/baasbox/android/BaasBox.java#L288-L291
6,988
baasbox/Android-SDK
library/src/main/java/com/baasbox/android/RequestToken.java
RequestToken.loadAndResume
public static RequestToken loadAndResume(Bundle bundle, String name, BaasHandler<?> handler) { if (bundle == null) throw new IllegalArgumentException("bunlde cannot be null"); if (name == null) throw new IllegalArgumentException("name cannot be null"); RequestToken token = bundle.getParcelable(name); if (token != null && token.resume(handler)) { return token; } return null; }
java
public static RequestToken loadAndResume(Bundle bundle, String name, BaasHandler<?> handler) { if (bundle == null) throw new IllegalArgumentException("bunlde cannot be null"); if (name == null) throw new IllegalArgumentException("name cannot be null"); RequestToken token = bundle.getParcelable(name); if (token != null && token.resume(handler)) { return token; } return null; }
[ "public", "static", "RequestToken", "loadAndResume", "(", "Bundle", "bundle", ",", "String", "name", ",", "BaasHandler", "<", "?", ">", "handler", ")", "{", "if", "(", "bundle", "==", "null", ")", "throw", "new", "IllegalArgumentException", "(", "\"bunlde cannot be null\"", ")", ";", "if", "(", "name", "==", "null", ")", "throw", "new", "IllegalArgumentException", "(", "\"name cannot be null\"", ")", ";", "RequestToken", "token", "=", "bundle", ".", "getParcelable", "(", "name", ")", ";", "if", "(", "token", "!=", "null", "&&", "token", ".", "resume", "(", "handler", ")", ")", "{", "return", "token", ";", "}", "return", "null", ";", "}" ]
Loads a request token from the bundle and immediately tries to resume the request with handler @param bundle a non null bundle @param name the key of the saved token @param handler a handler to resume the request with. @return the token if resumed, null otherwise
[ "Loads", "a", "request", "token", "from", "the", "bundle", "and", "immediately", "tries", "to", "resume", "the", "request", "with", "handler" ]
6bb2203246b885b2ad63a7bfaf37c83caf15e0d8
https://github.com/baasbox/Android-SDK/blob/6bb2203246b885b2ad63a7bfaf37c83caf15e0d8/library/src/main/java/com/baasbox/android/RequestToken.java#L64-L74
6,989
baasbox/Android-SDK
library/src/main/java/com/baasbox/android/RequestToken.java
RequestToken.resume
public boolean resume(BaasHandler<?> handler) { return BaasBox.getDefaultChecked().resume(this, handler==null?BaasHandler.NOOP:handler); }
java
public boolean resume(BaasHandler<?> handler) { return BaasBox.getDefaultChecked().resume(this, handler==null?BaasHandler.NOOP:handler); }
[ "public", "boolean", "resume", "(", "BaasHandler", "<", "?", ">", "handler", ")", "{", "return", "BaasBox", ".", "getDefaultChecked", "(", ")", ".", "resume", "(", "this", ",", "handler", "==", "null", "?", "BaasHandler", ".", "NOOP", ":", "handler", ")", ";", "}" ]
Resumes a suspended asynchronous request, with the new provided handler @param handler a handler to resume the request with. @return
[ "Resumes", "a", "suspended", "asynchronous", "request", "with", "the", "new", "provided", "handler" ]
6bb2203246b885b2ad63a7bfaf37c83caf15e0d8
https://github.com/baasbox/Android-SDK/blob/6bb2203246b885b2ad63a7bfaf37c83caf15e0d8/library/src/main/java/com/baasbox/android/RequestToken.java#L83-L85
6,990
baasbox/Android-SDK
library/src/main/java/com/baasbox/android/RequestToken.java
RequestToken.suspendAndSave
public boolean suspendAndSave(Bundle bundle, String name) { if (bundle == null) throw new IllegalArgumentException("bunlde cannot be null"); if (name == null) throw new IllegalArgumentException("name cannot be null"); if (suspend()) { bundle.putParcelable(name, this); return true; } else { return false; } }
java
public boolean suspendAndSave(Bundle bundle, String name) { if (bundle == null) throw new IllegalArgumentException("bunlde cannot be null"); if (name == null) throw new IllegalArgumentException("name cannot be null"); if (suspend()) { bundle.putParcelable(name, this); return true; } else { return false; } }
[ "public", "boolean", "suspendAndSave", "(", "Bundle", "bundle", ",", "String", "name", ")", "{", "if", "(", "bundle", "==", "null", ")", "throw", "new", "IllegalArgumentException", "(", "\"bunlde cannot be null\"", ")", ";", "if", "(", "name", "==", "null", ")", "throw", "new", "IllegalArgumentException", "(", "\"name cannot be null\"", ")", ";", "if", "(", "suspend", "(", ")", ")", "{", "bundle", ".", "putParcelable", "(", "name", ",", "this", ")", ";", "return", "true", ";", "}", "else", "{", "return", "false", ";", "}", "}" ]
Suspends a request and immediately save it in a bundle @param bundle a non null bundle @param name the key to save the token with @return true if the token was suspended
[ "Suspends", "a", "request", "and", "immediately", "save", "it", "in", "a", "bundle" ]
6bb2203246b885b2ad63a7bfaf37c83caf15e0d8
https://github.com/baasbox/Android-SDK/blob/6bb2203246b885b2ad63a7bfaf37c83caf15e0d8/library/src/main/java/com/baasbox/android/RequestToken.java#L146-L157
6,991
baasbox/Android-SDK
library/src/main/java/com/baasbox/android/json/JsonArray.java
JsonArray.getString
public String getString(int index, String otherwise) { Object o = list.get(index); if (o == null) return otherwise; if (o instanceof String) return (String) o; if (o instanceof byte[]) return encodeBinary((byte[])o); throw new JsonException("not a string"); }
java
public String getString(int index, String otherwise) { Object o = list.get(index); if (o == null) return otherwise; if (o instanceof String) return (String) o; if (o instanceof byte[]) return encodeBinary((byte[])o); throw new JsonException("not a string"); }
[ "public", "String", "getString", "(", "int", "index", ",", "String", "otherwise", ")", "{", "Object", "o", "=", "list", ".", "get", "(", "index", ")", ";", "if", "(", "o", "==", "null", ")", "return", "otherwise", ";", "if", "(", "o", "instanceof", "String", ")", "return", "(", "String", ")", "o", ";", "if", "(", "o", "instanceof", "byte", "[", "]", ")", "return", "encodeBinary", "(", "(", "byte", "[", "]", ")", "o", ")", ";", "throw", "new", "JsonException", "(", "\"not a string\"", ")", ";", "}" ]
Returns the String at index or otherwise if not found @param index @param otherwise @return the value at index or otherwise @throws java.lang.IndexOutOfBoundsException if the index is out of the array bounds
[ "Returns", "the", "String", "at", "index", "or", "otherwise", "if", "not", "found" ]
6bb2203246b885b2ad63a7bfaf37c83caf15e0d8
https://github.com/baasbox/Android-SDK/blob/6bb2203246b885b2ad63a7bfaf37c83caf15e0d8/library/src/main/java/com/baasbox/android/json/JsonArray.java#L575-L581
6,992
baasbox/Android-SDK
library/src/main/java/com/baasbox/android/BaasUser.java
BaasUser.follow
public RequestToken follow(int flags, BaasHandler<BaasUser> handler) { BaasBox box = BaasBox.getDefaultChecked(); Follow follow = new Follow(box, true, this, RequestOptions.DEFAULT, handler); return box.submitAsync(follow); }
java
public RequestToken follow(int flags, BaasHandler<BaasUser> handler) { BaasBox box = BaasBox.getDefaultChecked(); Follow follow = new Follow(box, true, this, RequestOptions.DEFAULT, handler); return box.submitAsync(follow); }
[ "public", "RequestToken", "follow", "(", "int", "flags", ",", "BaasHandler", "<", "BaasUser", ">", "handler", ")", "{", "BaasBox", "box", "=", "BaasBox", ".", "getDefaultChecked", "(", ")", ";", "Follow", "follow", "=", "new", "Follow", "(", "box", ",", "true", ",", "this", ",", "RequestOptions", ".", "DEFAULT", ",", "handler", ")", ";", "return", "box", ".", "submitAsync", "(", "follow", ")", ";", "}" ]
Asynchronously requests to follow the user. @param flags {@link RequestOptions} @param handler an handler to be invoked when the request completes @return a {@link com.baasbox.android.RequestToken} to manage the request
[ "Asynchronously", "requests", "to", "follow", "the", "user", "." ]
6bb2203246b885b2ad63a7bfaf37c83caf15e0d8
https://github.com/baasbox/Android-SDK/blob/6bb2203246b885b2ad63a7bfaf37c83caf15e0d8/library/src/main/java/com/baasbox/android/BaasUser.java#L600-L604
6,993
baasbox/Android-SDK
library/src/main/java/com/baasbox/android/BaasUser.java
BaasUser.isCurrent
public boolean isCurrent() { BaasUser current = current(); if (current == null) return false; Logger.debug("Current username is %s and mine is %s", current.username, username); return current.username.equals(username); }
java
public boolean isCurrent() { BaasUser current = current(); if (current == null) return false; Logger.debug("Current username is %s and mine is %s", current.username, username); return current.username.equals(username); }
[ "public", "boolean", "isCurrent", "(", ")", "{", "BaasUser", "current", "=", "current", "(", ")", ";", "if", "(", "current", "==", "null", ")", "return", "false", ";", "Logger", ".", "debug", "(", "\"Current username is %s and mine is %s\"", ",", "current", ".", "username", ",", "username", ")", ";", "return", "current", ".", "username", ".", "equals", "(", "username", ")", ";", "}" ]
Checks if this user is the currently logged in user on this device. @return true if <code>this == BaasUser.current()</code>
[ "Checks", "if", "this", "user", "is", "the", "currently", "logged", "in", "user", "on", "this", "device", "." ]
6bb2203246b885b2ad63a7bfaf37c83caf15e0d8
https://github.com/baasbox/Android-SDK/blob/6bb2203246b885b2ad63a7bfaf37c83caf15e0d8/library/src/main/java/com/baasbox/android/BaasUser.java#L636-L641
6,994
baasbox/Android-SDK
library/src/main/java/com/baasbox/android/BaasUser.java
BaasUser.getRoles
public Set<String> getRoles() { HashSet<String> rolescopy; rolescopy = new HashSet<>(roles); return Collections.unmodifiableSet(rolescopy); }
java
public Set<String> getRoles() { HashSet<String> rolescopy; rolescopy = new HashSet<>(roles); return Collections.unmodifiableSet(rolescopy); }
[ "public", "Set", "<", "String", ">", "getRoles", "(", ")", "{", "HashSet", "<", "String", ">", "rolescopy", ";", "rolescopy", "=", "new", "HashSet", "<>", "(", "roles", ")", ";", "return", "Collections", ".", "unmodifiableSet", "(", "rolescopy", ")", ";", "}" ]
Returns an unmodifialble set of the roles to which the user belongs if it's available @return a {@link java.util.Set} of role names
[ "Returns", "an", "unmodifialble", "set", "of", "the", "roles", "to", "which", "the", "user", "belongs", "if", "it", "s", "available" ]
6bb2203246b885b2ad63a7bfaf37c83caf15e0d8
https://github.com/baasbox/Android-SDK/blob/6bb2203246b885b2ad63a7bfaf37c83caf15e0d8/library/src/main/java/com/baasbox/android/BaasUser.java#L707-L711
6,995
baasbox/Android-SDK
library/src/main/java/com/baasbox/android/BaasUser.java
BaasUser.login
public RequestToken login(BaasHandler<BaasUser> handler) { return login(null, RequestOptions.DEFAULT, handler); }
java
public RequestToken login(BaasHandler<BaasUser> handler) { return login(null, RequestOptions.DEFAULT, handler); }
[ "public", "RequestToken", "login", "(", "BaasHandler", "<", "BaasUser", ">", "handler", ")", "{", "return", "login", "(", "null", ",", "RequestOptions", ".", "DEFAULT", ",", "handler", ")", ";", "}" ]
Asynchronously logins this user. The handler will be invoked upon completion of the request. @param handler an handler to be invoked when the request completes @return a {@link com.baasbox.android.RequestToken} to handle the async request
[ "Asynchronously", "logins", "this", "user", ".", "The", "handler", "will", "be", "invoked", "upon", "completion", "of", "the", "request", "." ]
6bb2203246b885b2ad63a7bfaf37c83caf15e0d8
https://github.com/baasbox/Android-SDK/blob/6bb2203246b885b2ad63a7bfaf37c83caf15e0d8/library/src/main/java/com/baasbox/android/BaasUser.java#L771-L773
6,996
baasbox/Android-SDK
library/src/main/java/com/baasbox/android/BaasUser.java
BaasUser.login
public RequestToken login(String registrationId, BaasHandler<BaasUser> handler) { return login(registrationId, RequestOptions.DEFAULT, handler); }
java
public RequestToken login(String registrationId, BaasHandler<BaasUser> handler) { return login(registrationId, RequestOptions.DEFAULT, handler); }
[ "public", "RequestToken", "login", "(", "String", "registrationId", ",", "BaasHandler", "<", "BaasUser", ">", "handler", ")", "{", "return", "login", "(", "registrationId", ",", "RequestOptions", ".", "DEFAULT", ",", "handler", ")", ";", "}" ]
Asynchronously logins this user with password and registrationId obtained through gcm. The handler will be invoked upon completion of the request. @param registrationId a registration id for gcm @param handler an handler to be invoked when the request completes @return a {@link com.baasbox.android.RequestToken} to handle the async request
[ "Asynchronously", "logins", "this", "user", "with", "password", "and", "registrationId", "obtained", "through", "gcm", ".", "The", "handler", "will", "be", "invoked", "upon", "completion", "of", "the", "request", "." ]
6bb2203246b885b2ad63a7bfaf37c83caf15e0d8
https://github.com/baasbox/Android-SDK/blob/6bb2203246b885b2ad63a7bfaf37c83caf15e0d8/library/src/main/java/com/baasbox/android/BaasUser.java#L783-L785
6,997
baasbox/Android-SDK
library/src/main/java/com/baasbox/android/BaasUser.java
BaasUser.login
public RequestToken login(String regitrationId, int flags, BaasHandler<BaasUser> handler) { BaasBox box = BaasBox.getDefault(); if (password == null) throw new IllegalStateException("password cannot be null"); NetworkTask<BaasUser> task = new LoginRequest(box, this, regitrationId, flags, handler); return box.submitAsync(task); }
java
public RequestToken login(String regitrationId, int flags, BaasHandler<BaasUser> handler) { BaasBox box = BaasBox.getDefault(); if (password == null) throw new IllegalStateException("password cannot be null"); NetworkTask<BaasUser> task = new LoginRequest(box, this, regitrationId, flags, handler); return box.submitAsync(task); }
[ "public", "RequestToken", "login", "(", "String", "regitrationId", ",", "int", "flags", ",", "BaasHandler", "<", "BaasUser", ">", "handler", ")", "{", "BaasBox", "box", "=", "BaasBox", ".", "getDefault", "(", ")", ";", "if", "(", "password", "==", "null", ")", "throw", "new", "IllegalStateException", "(", "\"password cannot be null\"", ")", ";", "NetworkTask", "<", "BaasUser", ">", "task", "=", "new", "LoginRequest", "(", "box", ",", "this", ",", "regitrationId", ",", "flags", ",", "handler", ")", ";", "return", "box", ".", "submitAsync", "(", "task", ")", ";", "}" ]
Asynchronously logins the user with password and registrationId obtained through gcm. The handler will be invoked upon completion of the request. The request is executed at the gien priority. @param regitrationId the registrationId @param flags {@link RequestOptions} @param handler an handler to be invoked when the request completes @return a {@link com.baasbox.android.RequestToken} to handle the async request
[ "Asynchronously", "logins", "the", "user", "with", "password", "and", "registrationId", "obtained", "through", "gcm", ".", "The", "handler", "will", "be", "invoked", "upon", "completion", "of", "the", "request", ".", "The", "request", "is", "executed", "at", "the", "gien", "priority", "." ]
6bb2203246b885b2ad63a7bfaf37c83caf15e0d8
https://github.com/baasbox/Android-SDK/blob/6bb2203246b885b2ad63a7bfaf37c83caf15e0d8/library/src/main/java/com/baasbox/android/BaasUser.java#L797-L802
6,998
baasbox/Android-SDK
library/src/main/java/com/baasbox/android/BaasUser.java
BaasUser.loginSync
public BaasResult<BaasUser> loginSync(String registrationId) { BaasBox box = BaasBox.getDefault(); if (password == null) throw new IllegalStateException("password cannot be null"); NetworkTask<BaasUser> task = new LoginRequest(box, this, registrationId, RequestOptions.DEFAULT, null); return box.submitSync(task); }
java
public BaasResult<BaasUser> loginSync(String registrationId) { BaasBox box = BaasBox.getDefault(); if (password == null) throw new IllegalStateException("password cannot be null"); NetworkTask<BaasUser> task = new LoginRequest(box, this, registrationId, RequestOptions.DEFAULT, null); return box.submitSync(task); }
[ "public", "BaasResult", "<", "BaasUser", ">", "loginSync", "(", "String", "registrationId", ")", "{", "BaasBox", "box", "=", "BaasBox", ".", "getDefault", "(", ")", ";", "if", "(", "password", "==", "null", ")", "throw", "new", "IllegalStateException", "(", "\"password cannot be null\"", ")", ";", "NetworkTask", "<", "BaasUser", ">", "task", "=", "new", "LoginRequest", "(", "box", ",", "this", ",", "registrationId", ",", "RequestOptions", ".", "DEFAULT", ",", "null", ")", ";", "return", "box", ".", "submitSync", "(", "task", ")", ";", "}" ]
Synchronously logins the user with password and registrationId obtained through gcm. @param registrationId a registration id for gcm @return the result of the request
[ "Synchronously", "logins", "the", "user", "with", "password", "and", "registrationId", "obtained", "through", "gcm", "." ]
6bb2203246b885b2ad63a7bfaf37c83caf15e0d8
https://github.com/baasbox/Android-SDK/blob/6bb2203246b885b2ad63a7bfaf37c83caf15e0d8/library/src/main/java/com/baasbox/android/BaasUser.java#L819-L824
6,999
baasbox/Android-SDK
library/src/main/java/com/baasbox/android/BaasUser.java
BaasUser.logoutSync
public BaasResult<Void> logoutSync(String registration) { BaasBox box = BaasBox.getDefaultChecked(); LogoutRequest request = new LogoutRequest(box, this, registration, RequestOptions.DEFAULT, null); return box.submitSync(request); }
java
public BaasResult<Void> logoutSync(String registration) { BaasBox box = BaasBox.getDefaultChecked(); LogoutRequest request = new LogoutRequest(box, this, registration, RequestOptions.DEFAULT, null); return box.submitSync(request); }
[ "public", "BaasResult", "<", "Void", ">", "logoutSync", "(", "String", "registration", ")", "{", "BaasBox", "box", "=", "BaasBox", ".", "getDefaultChecked", "(", ")", ";", "LogoutRequest", "request", "=", "new", "LogoutRequest", "(", "box", ",", "this", ",", "registration", ",", "RequestOptions", ".", "DEFAULT", ",", "null", ")", ";", "return", "box", ".", "submitSync", "(", "request", ")", ";", "}" ]
Synchronously logouts current user from the server. @param registration a registration id to remove @return the result of the request
[ "Synchronously", "logouts", "current", "user", "from", "the", "server", "." ]
6bb2203246b885b2ad63a7bfaf37c83caf15e0d8
https://github.com/baasbox/Android-SDK/blob/6bb2203246b885b2ad63a7bfaf37c83caf15e0d8/library/src/main/java/com/baasbox/android/BaasUser.java#L881-L885