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
161,400
Wikidata/Wikidata-Toolkit
wdtk-datamodel/src/main/java/org/wikidata/wdtk/datamodel/helpers/ItemDocumentBuilder.java
ItemDocumentBuilder.withSiteLink
public ItemDocumentBuilder withSiteLink(String title, String siteKey, ItemIdValue... badges) { withSiteLink(factory.getSiteLink(title, siteKey, Arrays.asList(badges))); return this; }
java
public ItemDocumentBuilder withSiteLink(String title, String siteKey, ItemIdValue... badges) { withSiteLink(factory.getSiteLink(title, siteKey, Arrays.asList(badges))); return this; }
[ "public", "ItemDocumentBuilder", "withSiteLink", "(", "String", "title", ",", "String", "siteKey", ",", "ItemIdValue", "...", "badges", ")", "{", "withSiteLink", "(", "factory", ".", "getSiteLink", "(", "title", ",", "siteKey", ",", "Arrays", ".", "asList", "(", "badges", ")", ")", ")", ";", "return", "this", ";", "}" ]
Adds an additional site link to the constructed document. @param title the title of the linked page @param siteKey identifier of the site, e.g., "enwiki" @param badges one or more badges
[ "Adds", "an", "additional", "site", "link", "to", "the", "constructed", "document", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-datamodel/src/main/java/org/wikidata/wdtk/datamodel/helpers/ItemDocumentBuilder.java#L121-L125
161,401
Wikidata/Wikidata-Toolkit
wdtk-rdf/src/main/java/org/wikidata/wdtk/rdf/ReferenceRdfConverter.java
ReferenceRdfConverter.addReference
public Resource addReference(Reference reference) { Resource resource = this.rdfWriter.getUri(Vocabulary.getReferenceUri(reference)); this.referenceQueue.add(reference); this.referenceSubjectQueue.add(resource); return resource; }
java
public Resource addReference(Reference reference) { Resource resource = this.rdfWriter.getUri(Vocabulary.getReferenceUri(reference)); this.referenceQueue.add(reference); this.referenceSubjectQueue.add(resource); return resource; }
[ "public", "Resource", "addReference", "(", "Reference", "reference", ")", "{", "Resource", "resource", "=", "this", ".", "rdfWriter", ".", "getUri", "(", "Vocabulary", ".", "getReferenceUri", "(", "reference", ")", ")", ";", "this", ".", "referenceQueue", ".", "add", "(", "reference", ")", ";", "this", ".", "referenceSubjectQueue", ".", "add", "(", "resource", ")", ";", "return", "resource", ";", "}" ]
Adds the given reference to the list of references that should still be serialized, and returns the RDF resource that will be used as a subject. @param reference the reference to be serialized @return RDF resource that represents this reference
[ "Adds", "the", "given", "reference", "to", "the", "list", "of", "references", "that", "should", "still", "be", "serialized", "and", "returns", "the", "RDF", "resource", "that", "will", "be", "used", "as", "a", "subject", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-rdf/src/main/java/org/wikidata/wdtk/rdf/ReferenceRdfConverter.java#L75-L82
161,402
Wikidata/Wikidata-Toolkit
wdtk-rdf/src/main/java/org/wikidata/wdtk/rdf/ReferenceRdfConverter.java
ReferenceRdfConverter.writeReferences
public void writeReferences() throws RDFHandlerException { Iterator<Reference> referenceIterator = this.referenceQueue.iterator(); for (Resource resource : this.referenceSubjectQueue) { final Reference reference = referenceIterator.next(); if (this.declaredReferences.add(resource)) { writeReference(reference, resource); } } this.referenceSubjectQueue.clear(); this.referenceQueue.clear(); this.snakRdfConverter.writeAuxiliaryTriples(); }
java
public void writeReferences() throws RDFHandlerException { Iterator<Reference> referenceIterator = this.referenceQueue.iterator(); for (Resource resource : this.referenceSubjectQueue) { final Reference reference = referenceIterator.next(); if (this.declaredReferences.add(resource)) { writeReference(reference, resource); } } this.referenceSubjectQueue.clear(); this.referenceQueue.clear(); this.snakRdfConverter.writeAuxiliaryTriples(); }
[ "public", "void", "writeReferences", "(", ")", "throws", "RDFHandlerException", "{", "Iterator", "<", "Reference", ">", "referenceIterator", "=", "this", ".", "referenceQueue", ".", "iterator", "(", ")", ";", "for", "(", "Resource", "resource", ":", "this", ".", "referenceSubjectQueue", ")", "{", "final", "Reference", "reference", "=", "referenceIterator", ".", "next", "(", ")", ";", "if", "(", "this", ".", "declaredReferences", ".", "add", "(", "resource", ")", ")", "{", "writeReference", "(", "reference", ",", "resource", ")", ";", "}", "}", "this", ".", "referenceSubjectQueue", ".", "clear", "(", ")", ";", "this", ".", "referenceQueue", ".", "clear", "(", ")", ";", "this", ".", "snakRdfConverter", ".", "writeAuxiliaryTriples", "(", ")", ";", "}" ]
Writes references that have been added recently. Auxiliary triples that are generated for serializing snaks in references will be written right afterwards. This will also trigger any other auxiliary triples to be written that the snak converter object may have buffered. @throws RDFHandlerException if there was a problem writing the restrictions
[ "Writes", "references", "that", "have", "been", "added", "recently", ".", "Auxiliary", "triples", "that", "are", "generated", "for", "serializing", "snaks", "in", "references", "will", "be", "written", "right", "afterwards", ".", "This", "will", "also", "trigger", "any", "other", "auxiliary", "triples", "to", "be", "written", "that", "the", "snak", "converter", "object", "may", "have", "buffered", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-rdf/src/main/java/org/wikidata/wdtk/rdf/ReferenceRdfConverter.java#L93-L105
161,403
Wikidata/Wikidata-Toolkit
wdtk-dumpfiles/src/main/java/org/wikidata/wdtk/dumpfiles/DumpProcessingController.java
DumpProcessingController.getSitesInformation
public Sites getSitesInformation() throws IOException { MwDumpFile sitesTableDump = getMostRecentDump(DumpContentType.SITES); if (sitesTableDump == null) { return null; } // Create a suitable processor for such dumps and process the file: MwSitesDumpFileProcessor sitesDumpFileProcessor = new MwSitesDumpFileProcessor(); sitesDumpFileProcessor.processDumpFileContents( sitesTableDump.getDumpFileStream(), sitesTableDump); return sitesDumpFileProcessor.getSites(); }
java
public Sites getSitesInformation() throws IOException { MwDumpFile sitesTableDump = getMostRecentDump(DumpContentType.SITES); if (sitesTableDump == null) { return null; } // Create a suitable processor for such dumps and process the file: MwSitesDumpFileProcessor sitesDumpFileProcessor = new MwSitesDumpFileProcessor(); sitesDumpFileProcessor.processDumpFileContents( sitesTableDump.getDumpFileStream(), sitesTableDump); return sitesDumpFileProcessor.getSites(); }
[ "public", "Sites", "getSitesInformation", "(", ")", "throws", "IOException", "{", "MwDumpFile", "sitesTableDump", "=", "getMostRecentDump", "(", "DumpContentType", ".", "SITES", ")", ";", "if", "(", "sitesTableDump", "==", "null", ")", "{", "return", "null", ";", "}", "// Create a suitable processor for such dumps and process the file:", "MwSitesDumpFileProcessor", "sitesDumpFileProcessor", "=", "new", "MwSitesDumpFileProcessor", "(", ")", ";", "sitesDumpFileProcessor", ".", "processDumpFileContents", "(", "sitesTableDump", ".", "getDumpFileStream", "(", ")", ",", "sitesTableDump", ")", ";", "return", "sitesDumpFileProcessor", ".", "getSites", "(", ")", ";", "}" ]
Processes the most recent dump of the sites table to extract information about registered sites. @return a Sites objects that contains the extracted information, or null if no sites dump was available (typically in offline mode without having any previously downloaded sites dumps) @throws IOException if there was a problem accessing the sites table dump or the dump download directory
[ "Processes", "the", "most", "recent", "dump", "of", "the", "sites", "table", "to", "extract", "information", "about", "registered", "sites", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-dumpfiles/src/main/java/org/wikidata/wdtk/dumpfiles/DumpProcessingController.java#L347-L359
161,404
Wikidata/Wikidata-Toolkit
wdtk-dumpfiles/src/main/java/org/wikidata/wdtk/dumpfiles/DumpProcessingController.java
DumpProcessingController.processMostRecentDump
@Deprecated public void processMostRecentDump(DumpContentType dumpContentType, MwDumpFileProcessor dumpFileProcessor) { MwDumpFile dumpFile = getMostRecentDump(dumpContentType); if (dumpFile != null) { processDumpFile(dumpFile, dumpFileProcessor); } }
java
@Deprecated public void processMostRecentDump(DumpContentType dumpContentType, MwDumpFileProcessor dumpFileProcessor) { MwDumpFile dumpFile = getMostRecentDump(dumpContentType); if (dumpFile != null) { processDumpFile(dumpFile, dumpFileProcessor); } }
[ "@", "Deprecated", "public", "void", "processMostRecentDump", "(", "DumpContentType", "dumpContentType", ",", "MwDumpFileProcessor", "dumpFileProcessor", ")", "{", "MwDumpFile", "dumpFile", "=", "getMostRecentDump", "(", "dumpContentType", ")", ";", "if", "(", "dumpFile", "!=", "null", ")", "{", "processDumpFile", "(", "dumpFile", ",", "dumpFileProcessor", ")", ";", "}", "}" ]
Processes the most recent dump of the given type using the given dump processor. @see DumpProcessingController#processMostRecentMainDump() @see DumpProcessingController#processAllRecentRevisionDumps() @param dumpContentType the type of dump to process @param dumpFileProcessor the processor to use @deprecated Use {@link #getMostRecentDump(DumpContentType)} and {@link #processDump(MwDumpFile)} instead; method will vanish in WDTK 0.5
[ "Processes", "the", "most", "recent", "dump", "of", "the", "given", "type", "using", "the", "given", "dump", "processor", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-dumpfiles/src/main/java/org/wikidata/wdtk/dumpfiles/DumpProcessingController.java#L496-L503
161,405
Wikidata/Wikidata-Toolkit
wdtk-dumpfiles/src/main/java/org/wikidata/wdtk/dumpfiles/DumpProcessingController.java
DumpProcessingController.processDumpFile
void processDumpFile(MwDumpFile dumpFile, MwDumpFileProcessor dumpFileProcessor) { try (InputStream inputStream = dumpFile.getDumpFileStream()) { dumpFileProcessor.processDumpFileContents(inputStream, dumpFile); } catch (FileAlreadyExistsException e) { logger.error("Dump file " + dumpFile.toString() + " could not be processed since file " + e.getFile() + " already exists. Try deleting the file or dumpfile directory to attempt a new download."); } catch (IOException e) { logger.error("Dump file " + dumpFile.toString() + " could not be processed: " + e.toString()); } }
java
void processDumpFile(MwDumpFile dumpFile, MwDumpFileProcessor dumpFileProcessor) { try (InputStream inputStream = dumpFile.getDumpFileStream()) { dumpFileProcessor.processDumpFileContents(inputStream, dumpFile); } catch (FileAlreadyExistsException e) { logger.error("Dump file " + dumpFile.toString() + " could not be processed since file " + e.getFile() + " already exists. Try deleting the file or dumpfile directory to attempt a new download."); } catch (IOException e) { logger.error("Dump file " + dumpFile.toString() + " could not be processed: " + e.toString()); } }
[ "void", "processDumpFile", "(", "MwDumpFile", "dumpFile", ",", "MwDumpFileProcessor", "dumpFileProcessor", ")", "{", "try", "(", "InputStream", "inputStream", "=", "dumpFile", ".", "getDumpFileStream", "(", ")", ")", "{", "dumpFileProcessor", ".", "processDumpFileContents", "(", "inputStream", ",", "dumpFile", ")", ";", "}", "catch", "(", "FileAlreadyExistsException", "e", ")", "{", "logger", ".", "error", "(", "\"Dump file \"", "+", "dumpFile", ".", "toString", "(", ")", "+", "\" could not be processed since file \"", "+", "e", ".", "getFile", "(", ")", "+", "\" already exists. Try deleting the file or dumpfile directory to attempt a new download.\"", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "logger", ".", "error", "(", "\"Dump file \"", "+", "dumpFile", ".", "toString", "(", ")", "+", "\" could not be processed: \"", "+", "e", ".", "toString", "(", ")", ")", ";", "}", "}" ]
Processes one dump file with the given dump file processor, handling exceptions appropriately. @param dumpFile the dump file to process @param dumpFileProcessor the dump file processor to use
[ "Processes", "one", "dump", "file", "with", "the", "given", "dump", "file", "processor", "handling", "exceptions", "appropriately", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-dumpfiles/src/main/java/org/wikidata/wdtk/dumpfiles/DumpProcessingController.java#L538-L552
161,406
Wikidata/Wikidata-Toolkit
wdtk-dumpfiles/src/main/java/org/wikidata/wdtk/dumpfiles/wmf/WmfDumpFileManager.java
WmfDumpFileManager.findMostRecentDump
public MwDumpFile findMostRecentDump(DumpContentType dumpContentType) { List<MwDumpFile> dumps = findAllDumps(dumpContentType); for (MwDumpFile dump : dumps) { if (dump.isAvailable()) { return dump; } } return null; }
java
public MwDumpFile findMostRecentDump(DumpContentType dumpContentType) { List<MwDumpFile> dumps = findAllDumps(dumpContentType); for (MwDumpFile dump : dumps) { if (dump.isAvailable()) { return dump; } } return null; }
[ "public", "MwDumpFile", "findMostRecentDump", "(", "DumpContentType", "dumpContentType", ")", "{", "List", "<", "MwDumpFile", ">", "dumps", "=", "findAllDumps", "(", "dumpContentType", ")", ";", "for", "(", "MwDumpFile", "dump", ":", "dumps", ")", "{", "if", "(", "dump", ".", "isAvailable", "(", ")", ")", "{", "return", "dump", ";", "}", "}", "return", "null", ";", "}" ]
Finds the most recent dump of the given type that is actually available. @param dumpContentType the type of the dump to look for @return most recent main dump or null if no such dump exists
[ "Finds", "the", "most", "recent", "dump", "of", "the", "given", "type", "that", "is", "actually", "available", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-dumpfiles/src/main/java/org/wikidata/wdtk/dumpfiles/wmf/WmfDumpFileManager.java#L177-L186
161,407
Wikidata/Wikidata-Toolkit
wdtk-dumpfiles/src/main/java/org/wikidata/wdtk/dumpfiles/wmf/WmfDumpFileManager.java
WmfDumpFileManager.mergeDumpLists
List<MwDumpFile> mergeDumpLists(List<MwDumpFile> localDumps, List<MwDumpFile> onlineDumps) { List<MwDumpFile> result = new ArrayList<>(localDumps); HashSet<String> localDateStamps = new HashSet<>(); for (MwDumpFile dumpFile : localDumps) { localDateStamps.add(dumpFile.getDateStamp()); } for (MwDumpFile dumpFile : onlineDumps) { if (!localDateStamps.contains(dumpFile.getDateStamp())) { result.add(dumpFile); } } result.sort(Collections.reverseOrder(new MwDumpFile.DateComparator())); return result; }
java
List<MwDumpFile> mergeDumpLists(List<MwDumpFile> localDumps, List<MwDumpFile> onlineDumps) { List<MwDumpFile> result = new ArrayList<>(localDumps); HashSet<String> localDateStamps = new HashSet<>(); for (MwDumpFile dumpFile : localDumps) { localDateStamps.add(dumpFile.getDateStamp()); } for (MwDumpFile dumpFile : onlineDumps) { if (!localDateStamps.contains(dumpFile.getDateStamp())) { result.add(dumpFile); } } result.sort(Collections.reverseOrder(new MwDumpFile.DateComparator())); return result; }
[ "List", "<", "MwDumpFile", ">", "mergeDumpLists", "(", "List", "<", "MwDumpFile", ">", "localDumps", ",", "List", "<", "MwDumpFile", ">", "onlineDumps", ")", "{", "List", "<", "MwDumpFile", ">", "result", "=", "new", "ArrayList", "<>", "(", "localDumps", ")", ";", "HashSet", "<", "String", ">", "localDateStamps", "=", "new", "HashSet", "<>", "(", ")", ";", "for", "(", "MwDumpFile", "dumpFile", ":", "localDumps", ")", "{", "localDateStamps", ".", "add", "(", "dumpFile", ".", "getDateStamp", "(", ")", ")", ";", "}", "for", "(", "MwDumpFile", "dumpFile", ":", "onlineDumps", ")", "{", "if", "(", "!", "localDateStamps", ".", "contains", "(", "dumpFile", ".", "getDateStamp", "(", ")", ")", ")", "{", "result", ".", "add", "(", "dumpFile", ")", ";", "}", "}", "result", ".", "sort", "(", "Collections", ".", "reverseOrder", "(", "new", "MwDumpFile", ".", "DateComparator", "(", ")", ")", ")", ";", "return", "result", ";", "}" ]
Merges a list of local and online dumps. For dumps available both online and locally, only the local version is included. The list is order with most recent dump date first. @return a merged list of dump files
[ "Merges", "a", "list", "of", "local", "and", "online", "dumps", ".", "For", "dumps", "available", "both", "online", "and", "locally", "only", "the", "local", "version", "is", "included", ".", "The", "list", "is", "order", "with", "most", "recent", "dump", "date", "first", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-dumpfiles/src/main/java/org/wikidata/wdtk/dumpfiles/wmf/WmfDumpFileManager.java#L215-L230
161,408
Wikidata/Wikidata-Toolkit
wdtk-dumpfiles/src/main/java/org/wikidata/wdtk/dumpfiles/wmf/WmfDumpFileManager.java
WmfDumpFileManager.findDumpsLocally
List<MwDumpFile> findDumpsLocally(DumpContentType dumpContentType) { String directoryPattern = WmfDumpFile.getDumpFileDirectoryName( dumpContentType, "*"); List<String> dumpFileDirectories; try { dumpFileDirectories = this.dumpfileDirectoryManager .getSubdirectories(directoryPattern); } catch (IOException e) { logger.error("Unable to access dump directory: " + e.toString()); return Collections.emptyList(); } List<MwDumpFile> result = new ArrayList<>(); for (String directory : dumpFileDirectories) { String dateStamp = WmfDumpFile .getDateStampFromDumpFileDirectoryName(dumpContentType, directory); if (dateStamp.matches(WmfDumpFileManager.DATE_STAMP_PATTERN)) { WmfLocalDumpFile dumpFile = new WmfLocalDumpFile(dateStamp, this.projectName, dumpfileDirectoryManager, dumpContentType); if (dumpFile.isAvailable()) { result.add(dumpFile); } else { logger.error("Incomplete local dump file data. Maybe delete " + dumpFile.getDumpfileDirectory() + " to attempt fresh download."); } } // else: silently ignore directories that don't match } result.sort(Collections.reverseOrder(new MwDumpFile.DateComparator())); logger.info("Found " + result.size() + " local dumps of type " + dumpContentType + ": " + result); return result; }
java
List<MwDumpFile> findDumpsLocally(DumpContentType dumpContentType) { String directoryPattern = WmfDumpFile.getDumpFileDirectoryName( dumpContentType, "*"); List<String> dumpFileDirectories; try { dumpFileDirectories = this.dumpfileDirectoryManager .getSubdirectories(directoryPattern); } catch (IOException e) { logger.error("Unable to access dump directory: " + e.toString()); return Collections.emptyList(); } List<MwDumpFile> result = new ArrayList<>(); for (String directory : dumpFileDirectories) { String dateStamp = WmfDumpFile .getDateStampFromDumpFileDirectoryName(dumpContentType, directory); if (dateStamp.matches(WmfDumpFileManager.DATE_STAMP_PATTERN)) { WmfLocalDumpFile dumpFile = new WmfLocalDumpFile(dateStamp, this.projectName, dumpfileDirectoryManager, dumpContentType); if (dumpFile.isAvailable()) { result.add(dumpFile); } else { logger.error("Incomplete local dump file data. Maybe delete " + dumpFile.getDumpfileDirectory() + " to attempt fresh download."); } } // else: silently ignore directories that don't match } result.sort(Collections.reverseOrder(new MwDumpFile.DateComparator())); logger.info("Found " + result.size() + " local dumps of type " + dumpContentType + ": " + result); return result; }
[ "List", "<", "MwDumpFile", ">", "findDumpsLocally", "(", "DumpContentType", "dumpContentType", ")", "{", "String", "directoryPattern", "=", "WmfDumpFile", ".", "getDumpFileDirectoryName", "(", "dumpContentType", ",", "\"*\"", ")", ";", "List", "<", "String", ">", "dumpFileDirectories", ";", "try", "{", "dumpFileDirectories", "=", "this", ".", "dumpfileDirectoryManager", ".", "getSubdirectories", "(", "directoryPattern", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "logger", ".", "error", "(", "\"Unable to access dump directory: \"", "+", "e", ".", "toString", "(", ")", ")", ";", "return", "Collections", ".", "emptyList", "(", ")", ";", "}", "List", "<", "MwDumpFile", ">", "result", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "String", "directory", ":", "dumpFileDirectories", ")", "{", "String", "dateStamp", "=", "WmfDumpFile", ".", "getDateStampFromDumpFileDirectoryName", "(", "dumpContentType", ",", "directory", ")", ";", "if", "(", "dateStamp", ".", "matches", "(", "WmfDumpFileManager", ".", "DATE_STAMP_PATTERN", ")", ")", "{", "WmfLocalDumpFile", "dumpFile", "=", "new", "WmfLocalDumpFile", "(", "dateStamp", ",", "this", ".", "projectName", ",", "dumpfileDirectoryManager", ",", "dumpContentType", ")", ";", "if", "(", "dumpFile", ".", "isAvailable", "(", ")", ")", "{", "result", ".", "add", "(", "dumpFile", ")", ";", "}", "else", "{", "logger", ".", "error", "(", "\"Incomplete local dump file data. Maybe delete \"", "+", "dumpFile", ".", "getDumpfileDirectory", "(", ")", "+", "\" to attempt fresh download.\"", ")", ";", "}", "}", "// else: silently ignore directories that don't match", "}", "result", ".", "sort", "(", "Collections", ".", "reverseOrder", "(", "new", "MwDumpFile", ".", "DateComparator", "(", ")", ")", ")", ";", "logger", ".", "info", "(", "\"Found \"", "+", "result", ".", "size", "(", ")", "+", "\" local dumps of type \"", "+", "dumpContentType", "+", "\": \"", "+", "result", ")", ";", "return", "result", ";", "}" ]
Finds out which dump files of the given type have been downloaded already. The result is a list of objects that describe the available dump files, in descending order by their date. Not all of the dumps included might be actually available. @param dumpContentType the type of dump to consider @return list of objects that provide information on available dumps
[ "Finds", "out", "which", "dump", "files", "of", "the", "given", "type", "have", "been", "downloaded", "already", ".", "The", "result", "is", "a", "list", "of", "objects", "that", "describe", "the", "available", "dump", "files", "in", "descending", "order", "by", "their", "date", ".", "Not", "all", "of", "the", "dumps", "included", "might", "be", "actually", "available", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-dumpfiles/src/main/java/org/wikidata/wdtk/dumpfiles/wmf/WmfDumpFileManager.java#L242-L282
161,409
Wikidata/Wikidata-Toolkit
wdtk-dumpfiles/src/main/java/org/wikidata/wdtk/dumpfiles/wmf/WmfDumpFileManager.java
WmfDumpFileManager.findDumpsOnline
List<MwDumpFile> findDumpsOnline(DumpContentType dumpContentType) { List<String> dumpFileDates = findDumpDatesOnline(dumpContentType); List<MwDumpFile> result = new ArrayList<>(); for (String dateStamp : dumpFileDates) { if (dumpContentType == DumpContentType.DAILY) { result.add(new WmfOnlineDailyDumpFile(dateStamp, this.projectName, this.webResourceFetcher, this.dumpfileDirectoryManager)); } else if (dumpContentType == DumpContentType.JSON) { result.add(new JsonOnlineDumpFile(dateStamp, this.projectName, this.webResourceFetcher, this.dumpfileDirectoryManager)); } else { result.add(new WmfOnlineStandardDumpFile(dateStamp, this.projectName, this.webResourceFetcher, this.dumpfileDirectoryManager, dumpContentType)); } } logger.info("Found " + result.size() + " online dumps of type " + dumpContentType + ": " + result); return result; }
java
List<MwDumpFile> findDumpsOnline(DumpContentType dumpContentType) { List<String> dumpFileDates = findDumpDatesOnline(dumpContentType); List<MwDumpFile> result = new ArrayList<>(); for (String dateStamp : dumpFileDates) { if (dumpContentType == DumpContentType.DAILY) { result.add(new WmfOnlineDailyDumpFile(dateStamp, this.projectName, this.webResourceFetcher, this.dumpfileDirectoryManager)); } else if (dumpContentType == DumpContentType.JSON) { result.add(new JsonOnlineDumpFile(dateStamp, this.projectName, this.webResourceFetcher, this.dumpfileDirectoryManager)); } else { result.add(new WmfOnlineStandardDumpFile(dateStamp, this.projectName, this.webResourceFetcher, this.dumpfileDirectoryManager, dumpContentType)); } } logger.info("Found " + result.size() + " online dumps of type " + dumpContentType + ": " + result); return result; }
[ "List", "<", "MwDumpFile", ">", "findDumpsOnline", "(", "DumpContentType", "dumpContentType", ")", "{", "List", "<", "String", ">", "dumpFileDates", "=", "findDumpDatesOnline", "(", "dumpContentType", ")", ";", "List", "<", "MwDumpFile", ">", "result", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "String", "dateStamp", ":", "dumpFileDates", ")", "{", "if", "(", "dumpContentType", "==", "DumpContentType", ".", "DAILY", ")", "{", "result", ".", "add", "(", "new", "WmfOnlineDailyDumpFile", "(", "dateStamp", ",", "this", ".", "projectName", ",", "this", ".", "webResourceFetcher", ",", "this", ".", "dumpfileDirectoryManager", ")", ")", ";", "}", "else", "if", "(", "dumpContentType", "==", "DumpContentType", ".", "JSON", ")", "{", "result", ".", "add", "(", "new", "JsonOnlineDumpFile", "(", "dateStamp", ",", "this", ".", "projectName", ",", "this", ".", "webResourceFetcher", ",", "this", ".", "dumpfileDirectoryManager", ")", ")", ";", "}", "else", "{", "result", ".", "add", "(", "new", "WmfOnlineStandardDumpFile", "(", "dateStamp", ",", "this", ".", "projectName", ",", "this", ".", "webResourceFetcher", ",", "this", ".", "dumpfileDirectoryManager", ",", "dumpContentType", ")", ")", ";", "}", "}", "logger", ".", "info", "(", "\"Found \"", "+", "result", ".", "size", "(", ")", "+", "\" online dumps of type \"", "+", "dumpContentType", "+", "\": \"", "+", "result", ")", ";", "return", "result", ";", "}" ]
Finds out which dump files of the given type are available for download. The result is a list of objects that describe the available dump files, in descending order by their date. Not all of the dumps included might be actually available. @return list of objects that provide information on available full dumps
[ "Finds", "out", "which", "dump", "files", "of", "the", "given", "type", "are", "available", "for", "download", ".", "The", "result", "is", "a", "list", "of", "objects", "that", "describe", "the", "available", "dump", "files", "in", "descending", "order", "by", "their", "date", ".", "Not", "all", "of", "the", "dumps", "included", "might", "be", "actually", "available", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-dumpfiles/src/main/java/org/wikidata/wdtk/dumpfiles/wmf/WmfDumpFileManager.java#L292-L316
161,410
Wikidata/Wikidata-Toolkit
wdtk-examples/src/main/java/org/wikidata/wdtk/examples/TutorialDocumentProcessor.java
TutorialDocumentProcessor.processItemDocument
@Override public void processItemDocument(ItemDocument itemDocument) { this.countItems++; // Do some printing for demonstration/debugging. // Only print at most 50 items (or it would get too slow). if (this.countItems < 10) { System.out.println(itemDocument); } else if (this.countItems == 10) { System.out.println("*** I won't print any further items.\n" + "*** We will never finish if we print all the items.\n" + "*** Maybe remove this debug output altogether."); } }
java
@Override public void processItemDocument(ItemDocument itemDocument) { this.countItems++; // Do some printing for demonstration/debugging. // Only print at most 50 items (or it would get too slow). if (this.countItems < 10) { System.out.println(itemDocument); } else if (this.countItems == 10) { System.out.println("*** I won't print any further items.\n" + "*** We will never finish if we print all the items.\n" + "*** Maybe remove this debug output altogether."); } }
[ "@", "Override", "public", "void", "processItemDocument", "(", "ItemDocument", "itemDocument", ")", "{", "this", ".", "countItems", "++", ";", "// Do some printing for demonstration/debugging.", "// Only print at most 50 items (or it would get too slow).", "if", "(", "this", ".", "countItems", "<", "10", ")", "{", "System", ".", "out", ".", "println", "(", "itemDocument", ")", ";", "}", "else", "if", "(", "this", ".", "countItems", "==", "10", ")", "{", "System", ".", "out", ".", "println", "(", "\"*** I won't print any further items.\\n\"", "+", "\"*** We will never finish if we print all the items.\\n\"", "+", "\"*** Maybe remove this debug output altogether.\"", ")", ";", "}", "}" ]
Processes one item document. This is often the main workhorse that gathers the data you are interested in. You can modify this code as you wish.
[ "Processes", "one", "item", "document", ".", "This", "is", "often", "the", "main", "workhorse", "that", "gathers", "the", "data", "you", "are", "interested", "in", ".", "You", "can", "modify", "this", "code", "as", "you", "wish", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-examples/src/main/java/org/wikidata/wdtk/examples/TutorialDocumentProcessor.java#L106-L119
161,411
Wikidata/Wikidata-Toolkit
wdtk-datamodel/src/main/java/org/wikidata/wdtk/datamodel/implementation/EntityIdValueImpl.java
EntityIdValueImpl.fromId
static EntityIdValue fromId(String id, String siteIri) { switch (guessEntityTypeFromId(id)) { case EntityIdValueImpl.JSON_ENTITY_TYPE_ITEM: return new ItemIdValueImpl(id, siteIri); case EntityIdValueImpl.JSON_ENTITY_TYPE_PROPERTY: return new PropertyIdValueImpl(id, siteIri); case EntityIdValueImpl.JSON_ENTITY_TYPE_LEXEME: return new LexemeIdValueImpl(id, siteIri); case EntityIdValueImpl.JSON_ENTITY_TYPE_FORM: return new FormIdValueImpl(id, siteIri); case EntityIdValueImpl.JSON_ENTITY_TYPE_SENSE: return new SenseIdValueImpl(id, siteIri); default: throw new IllegalArgumentException("Entity id \"" + id + "\" is not supported."); } }
java
static EntityIdValue fromId(String id, String siteIri) { switch (guessEntityTypeFromId(id)) { case EntityIdValueImpl.JSON_ENTITY_TYPE_ITEM: return new ItemIdValueImpl(id, siteIri); case EntityIdValueImpl.JSON_ENTITY_TYPE_PROPERTY: return new PropertyIdValueImpl(id, siteIri); case EntityIdValueImpl.JSON_ENTITY_TYPE_LEXEME: return new LexemeIdValueImpl(id, siteIri); case EntityIdValueImpl.JSON_ENTITY_TYPE_FORM: return new FormIdValueImpl(id, siteIri); case EntityIdValueImpl.JSON_ENTITY_TYPE_SENSE: return new SenseIdValueImpl(id, siteIri); default: throw new IllegalArgumentException("Entity id \"" + id + "\" is not supported."); } }
[ "static", "EntityIdValue", "fromId", "(", "String", "id", ",", "String", "siteIri", ")", "{", "switch", "(", "guessEntityTypeFromId", "(", "id", ")", ")", "{", "case", "EntityIdValueImpl", ".", "JSON_ENTITY_TYPE_ITEM", ":", "return", "new", "ItemIdValueImpl", "(", "id", ",", "siteIri", ")", ";", "case", "EntityIdValueImpl", ".", "JSON_ENTITY_TYPE_PROPERTY", ":", "return", "new", "PropertyIdValueImpl", "(", "id", ",", "siteIri", ")", ";", "case", "EntityIdValueImpl", ".", "JSON_ENTITY_TYPE_LEXEME", ":", "return", "new", "LexemeIdValueImpl", "(", "id", ",", "siteIri", ")", ";", "case", "EntityIdValueImpl", ".", "JSON_ENTITY_TYPE_FORM", ":", "return", "new", "FormIdValueImpl", "(", "id", ",", "siteIri", ")", ";", "case", "EntityIdValueImpl", ".", "JSON_ENTITY_TYPE_SENSE", ":", "return", "new", "SenseIdValueImpl", "(", "id", ",", "siteIri", ")", ";", "default", ":", "throw", "new", "IllegalArgumentException", "(", "\"Entity id \\\"\"", "+", "id", "+", "\"\\\" is not supported.\"", ")", ";", "}", "}" ]
Parses an item id @param id the identifier of the entity, such as "Q42" @param siteIri the siteIRI that this value refers to @throws IllegalArgumentException if the id is invalid
[ "Parses", "an", "item", "id" ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-datamodel/src/main/java/org/wikidata/wdtk/datamodel/implementation/EntityIdValueImpl.java#L117-L132
161,412
Wikidata/Wikidata-Toolkit
wdtk-datamodel/src/main/java/org/wikidata/wdtk/datamodel/implementation/EntityIdValueImpl.java
EntityIdValueImpl.guessEntityTypeFromId
static String guessEntityTypeFromId(String id) { if(id.isEmpty()) { throw new IllegalArgumentException("Entity ids should not be empty."); } switch (id.charAt(0)) { case 'L': if(id.contains("-F")) { return JSON_ENTITY_TYPE_FORM; } else if(id.contains("-S")) { return JSON_ENTITY_TYPE_SENSE; } else { return JSON_ENTITY_TYPE_LEXEME; } case 'P': return JSON_ENTITY_TYPE_PROPERTY; case 'Q': return JSON_ENTITY_TYPE_ITEM; default: throw new IllegalArgumentException("Entity id \"" + id + "\" is not supported."); } }
java
static String guessEntityTypeFromId(String id) { if(id.isEmpty()) { throw new IllegalArgumentException("Entity ids should not be empty."); } switch (id.charAt(0)) { case 'L': if(id.contains("-F")) { return JSON_ENTITY_TYPE_FORM; } else if(id.contains("-S")) { return JSON_ENTITY_TYPE_SENSE; } else { return JSON_ENTITY_TYPE_LEXEME; } case 'P': return JSON_ENTITY_TYPE_PROPERTY; case 'Q': return JSON_ENTITY_TYPE_ITEM; default: throw new IllegalArgumentException("Entity id \"" + id + "\" is not supported."); } }
[ "static", "String", "guessEntityTypeFromId", "(", "String", "id", ")", "{", "if", "(", "id", ".", "isEmpty", "(", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Entity ids should not be empty.\"", ")", ";", "}", "switch", "(", "id", ".", "charAt", "(", "0", ")", ")", "{", "case", "'", "'", ":", "if", "(", "id", ".", "contains", "(", "\"-F\"", ")", ")", "{", "return", "JSON_ENTITY_TYPE_FORM", ";", "}", "else", "if", "(", "id", ".", "contains", "(", "\"-S\"", ")", ")", "{", "return", "JSON_ENTITY_TYPE_SENSE", ";", "}", "else", "{", "return", "JSON_ENTITY_TYPE_LEXEME", ";", "}", "case", "'", "'", ":", "return", "JSON_ENTITY_TYPE_PROPERTY", ";", "case", "'", "'", ":", "return", "JSON_ENTITY_TYPE_ITEM", ";", "default", ":", "throw", "new", "IllegalArgumentException", "(", "\"Entity id \\\"\"", "+", "id", "+", "\"\\\" is not supported.\"", ")", ";", "}", "}" ]
RReturns the entity type of the id like "item" or "property" @param id the identifier of the entity, such as "Q42" @throws IllegalArgumentException if the id is invalid
[ "RReturns", "the", "entity", "type", "of", "the", "id", "like", "item", "or", "property" ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-datamodel/src/main/java/org/wikidata/wdtk/datamodel/implementation/EntityIdValueImpl.java#L142-L162
161,413
Wikidata/Wikidata-Toolkit
wdtk-dumpfiles/src/main/java/org/wikidata/wdtk/dumpfiles/EntityTimerProcessor.java
EntityTimerProcessor.close
@Override public void close() { logger.info("Finished processing."); this.timer.stop(); this.lastSeconds = (int) (timer.getTotalWallTime() / 1000000000); printStatus(); }
java
@Override public void close() { logger.info("Finished processing."); this.timer.stop(); this.lastSeconds = (int) (timer.getTotalWallTime() / 1000000000); printStatus(); }
[ "@", "Override", "public", "void", "close", "(", ")", "{", "logger", ".", "info", "(", "\"Finished processing.\"", ")", ";", "this", ".", "timer", ".", "stop", "(", ")", ";", "this", ".", "lastSeconds", "=", "(", "int", ")", "(", "timer", ".", "getTotalWallTime", "(", ")", "/", "1000000000", ")", ";", "printStatus", "(", ")", ";", "}" ]
Stops the processing and prints the final time.
[ "Stops", "the", "processing", "and", "prints", "the", "final", "time", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-dumpfiles/src/main/java/org/wikidata/wdtk/dumpfiles/EntityTimerProcessor.java#L108-L114
161,414
Wikidata/Wikidata-Toolkit
wdtk-dumpfiles/src/main/java/org/wikidata/wdtk/dumpfiles/EntityTimerProcessor.java
EntityTimerProcessor.countEntity
private void countEntity() { if (!this.timer.isRunning()) { startTimer(); } this.entityCount++; if (this.entityCount % 100 == 0) { timer.stop(); int seconds = (int) (timer.getTotalWallTime() / 1000000000); if (seconds >= this.lastSeconds + this.reportInterval) { this.lastSeconds = seconds; printStatus(); if (this.timeout > 0 && seconds > this.timeout) { logger.info("Timeout. Aborting processing."); throw new TimeoutException(); } } timer.start(); } }
java
private void countEntity() { if (!this.timer.isRunning()) { startTimer(); } this.entityCount++; if (this.entityCount % 100 == 0) { timer.stop(); int seconds = (int) (timer.getTotalWallTime() / 1000000000); if (seconds >= this.lastSeconds + this.reportInterval) { this.lastSeconds = seconds; printStatus(); if (this.timeout > 0 && seconds > this.timeout) { logger.info("Timeout. Aborting processing."); throw new TimeoutException(); } } timer.start(); } }
[ "private", "void", "countEntity", "(", ")", "{", "if", "(", "!", "this", ".", "timer", ".", "isRunning", "(", ")", ")", "{", "startTimer", "(", ")", ";", "}", "this", ".", "entityCount", "++", ";", "if", "(", "this", ".", "entityCount", "%", "100", "==", "0", ")", "{", "timer", ".", "stop", "(", ")", ";", "int", "seconds", "=", "(", "int", ")", "(", "timer", ".", "getTotalWallTime", "(", ")", "/", "1000000000", ")", ";", "if", "(", "seconds", ">=", "this", ".", "lastSeconds", "+", "this", ".", "reportInterval", ")", "{", "this", ".", "lastSeconds", "=", "seconds", ";", "printStatus", "(", ")", ";", "if", "(", "this", ".", "timeout", ">", "0", "&&", "seconds", ">", "this", ".", "timeout", ")", "{", "logger", ".", "info", "(", "\"Timeout. Aborting processing.\"", ")", ";", "throw", "new", "TimeoutException", "(", ")", ";", "}", "}", "timer", ".", "start", "(", ")", ";", "}", "}" ]
Counts one entity. Every once in a while, the current time is checked so as to print an intermediate report roughly every ten seconds.
[ "Counts", "one", "entity", ".", "Every", "once", "in", "a", "while", "the", "current", "time", "is", "checked", "so", "as", "to", "print", "an", "intermediate", "report", "roughly", "every", "ten", "seconds", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-dumpfiles/src/main/java/org/wikidata/wdtk/dumpfiles/EntityTimerProcessor.java#L120-L139
161,415
Wikidata/Wikidata-Toolkit
wdtk-wikibaseapi/src/main/java/org/wikidata/wdtk/wikibaseapi/ApiConnection.java
ApiConnection.implodeObjects
public static String implodeObjects(Iterable<?> objects) { StringBuilder builder = new StringBuilder(); boolean first = true; for (Object o : objects) { if (first) { first = false; } else { builder.append("|"); } builder.append(o.toString()); } return builder.toString(); }
java
public static String implodeObjects(Iterable<?> objects) { StringBuilder builder = new StringBuilder(); boolean first = true; for (Object o : objects) { if (first) { first = false; } else { builder.append("|"); } builder.append(o.toString()); } return builder.toString(); }
[ "public", "static", "String", "implodeObjects", "(", "Iterable", "<", "?", ">", "objects", ")", "{", "StringBuilder", "builder", "=", "new", "StringBuilder", "(", ")", ";", "boolean", "first", "=", "true", ";", "for", "(", "Object", "o", ":", "objects", ")", "{", "if", "(", "first", ")", "{", "first", "=", "false", ";", "}", "else", "{", "builder", ".", "append", "(", "\"|\"", ")", ";", "}", "builder", ".", "append", "(", "o", ".", "toString", "(", ")", ")", ";", "}", "return", "builder", ".", "toString", "(", ")", ";", "}" ]
Builds a string that serializes a list of objects separated by the pipe character. The toString methods are used to turn objects into strings. This operation is commonly used to build parameter lists for API requests. @param objects the objects to implode @return string of imploded objects
[ "Builds", "a", "string", "that", "serializes", "a", "list", "of", "objects", "separated", "by", "the", "pipe", "character", ".", "The", "toString", "methods", "are", "used", "to", "turn", "objects", "into", "strings", ".", "This", "operation", "is", "commonly", "used", "to", "build", "parameter", "lists", "for", "API", "requests", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-wikibaseapi/src/main/java/org/wikidata/wdtk/wikibaseapi/ApiConnection.java#L266-L278
161,416
Wikidata/Wikidata-Toolkit
wdtk-wikibaseapi/src/main/java/org/wikidata/wdtk/wikibaseapi/ApiConnection.java
ApiConnection.logout
public void logout() throws IOException { if (this.loggedIn) { Map<String, String> params = new HashMap<>(); params.put("action", "logout"); params.put("format", "json"); // reduce the output try { sendJsonRequest("POST", params); } catch (MediaWikiApiErrorException e) { throw new IOException(e.getMessage(), e); //TODO: we should throw a better exception } this.loggedIn = false; this.username = ""; this.password = ""; } }
java
public void logout() throws IOException { if (this.loggedIn) { Map<String, String> params = new HashMap<>(); params.put("action", "logout"); params.put("format", "json"); // reduce the output try { sendJsonRequest("POST", params); } catch (MediaWikiApiErrorException e) { throw new IOException(e.getMessage(), e); //TODO: we should throw a better exception } this.loggedIn = false; this.username = ""; this.password = ""; } }
[ "public", "void", "logout", "(", ")", "throws", "IOException", "{", "if", "(", "this", ".", "loggedIn", ")", "{", "Map", "<", "String", ",", "String", ">", "params", "=", "new", "HashMap", "<>", "(", ")", ";", "params", ".", "put", "(", "\"action\"", ",", "\"logout\"", ")", ";", "params", ".", "put", "(", "\"format\"", ",", "\"json\"", ")", ";", "// reduce the output", "try", "{", "sendJsonRequest", "(", "\"POST\"", ",", "params", ")", ";", "}", "catch", "(", "MediaWikiApiErrorException", "e", ")", "{", "throw", "new", "IOException", "(", "e", ".", "getMessage", "(", ")", ",", "e", ")", ";", "//TODO: we should throw a better exception", "}", "this", ".", "loggedIn", "=", "false", ";", "this", ".", "username", "=", "\"\"", ";", "this", ".", "password", "=", "\"\"", ";", "}", "}" ]
Logs the current user out. @throws IOException
[ "Logs", "the", "current", "user", "out", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-wikibaseapi/src/main/java/org/wikidata/wdtk/wikibaseapi/ApiConnection.java#L333-L348
161,417
Wikidata/Wikidata-Toolkit
wdtk-wikibaseapi/src/main/java/org/wikidata/wdtk/wikibaseapi/ApiConnection.java
ApiConnection.fetchToken
String fetchToken(String tokenType) throws IOException, MediaWikiApiErrorException { Map<String, String> params = new HashMap<>(); params.put(ApiConnection.PARAM_ACTION, "query"); params.put("meta", "tokens"); params.put("type", tokenType); try { JsonNode root = this.sendJsonRequest("POST", params); return root.path("query").path("tokens").path(tokenType + "token").textValue(); } catch (IOException | MediaWikiApiErrorException e) { logger.error("Error when trying to fetch token: " + e.toString()); } return null; }
java
String fetchToken(String tokenType) throws IOException, MediaWikiApiErrorException { Map<String, String> params = new HashMap<>(); params.put(ApiConnection.PARAM_ACTION, "query"); params.put("meta", "tokens"); params.put("type", tokenType); try { JsonNode root = this.sendJsonRequest("POST", params); return root.path("query").path("tokens").path(tokenType + "token").textValue(); } catch (IOException | MediaWikiApiErrorException e) { logger.error("Error when trying to fetch token: " + e.toString()); } return null; }
[ "String", "fetchToken", "(", "String", "tokenType", ")", "throws", "IOException", ",", "MediaWikiApiErrorException", "{", "Map", "<", "String", ",", "String", ">", "params", "=", "new", "HashMap", "<>", "(", ")", ";", "params", ".", "put", "(", "ApiConnection", ".", "PARAM_ACTION", ",", "\"query\"", ")", ";", "params", ".", "put", "(", "\"meta\"", ",", "\"tokens\"", ")", ";", "params", ".", "put", "(", "\"type\"", ",", "tokenType", ")", ";", "try", "{", "JsonNode", "root", "=", "this", ".", "sendJsonRequest", "(", "\"POST\"", ",", "params", ")", ";", "return", "root", ".", "path", "(", "\"query\"", ")", ".", "path", "(", "\"tokens\"", ")", ".", "path", "(", "tokenType", "+", "\"token\"", ")", ".", "textValue", "(", ")", ";", "}", "catch", "(", "IOException", "|", "MediaWikiApiErrorException", "e", ")", "{", "logger", ".", "error", "(", "\"Error when trying to fetch token: \"", "+", "e", ".", "toString", "(", ")", ")", ";", "}", "return", "null", ";", "}" ]
Executes a API query action to get a new token. The method only executes the action, without doing any checks first. If errors occur, they are logged and null is returned. @param tokenType The kind of token to retrieve like "csrf" or "login" @return newly retrieved token or null if no token was retrieved
[ "Executes", "a", "API", "query", "action", "to", "get", "a", "new", "token", ".", "The", "method", "only", "executes", "the", "action", "without", "doing", "any", "checks", "first", ".", "If", "errors", "occur", "they", "are", "logged", "and", "null", "is", "returned", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-wikibaseapi/src/main/java/org/wikidata/wdtk/wikibaseapi/ApiConnection.java#L368-L381
161,418
Wikidata/Wikidata-Toolkit
wdtk-wikibaseapi/src/main/java/org/wikidata/wdtk/wikibaseapi/ApiConnection.java
ApiConnection.sendRequest
public InputStream sendRequest(String requestMethod, Map<String, String> parameters) throws IOException { String queryString = getQueryString(parameters); URL url = new URL(this.apiBaseUrl); HttpURLConnection connection = (HttpURLConnection) WebResourceFetcherImpl .getUrlConnection(url); setupConnection(requestMethod, queryString, connection); OutputStreamWriter writer = new OutputStreamWriter( connection.getOutputStream()); writer.write(queryString); writer.flush(); writer.close(); int rc = connection.getResponseCode(); if (rc != 200) { logger.warn("Error: API request returned response code " + rc); } InputStream iStream = connection.getInputStream(); fillCookies(connection.getHeaderFields()); return iStream; }
java
public InputStream sendRequest(String requestMethod, Map<String, String> parameters) throws IOException { String queryString = getQueryString(parameters); URL url = new URL(this.apiBaseUrl); HttpURLConnection connection = (HttpURLConnection) WebResourceFetcherImpl .getUrlConnection(url); setupConnection(requestMethod, queryString, connection); OutputStreamWriter writer = new OutputStreamWriter( connection.getOutputStream()); writer.write(queryString); writer.flush(); writer.close(); int rc = connection.getResponseCode(); if (rc != 200) { logger.warn("Error: API request returned response code " + rc); } InputStream iStream = connection.getInputStream(); fillCookies(connection.getHeaderFields()); return iStream; }
[ "public", "InputStream", "sendRequest", "(", "String", "requestMethod", ",", "Map", "<", "String", ",", "String", ">", "parameters", ")", "throws", "IOException", "{", "String", "queryString", "=", "getQueryString", "(", "parameters", ")", ";", "URL", "url", "=", "new", "URL", "(", "this", ".", "apiBaseUrl", ")", ";", "HttpURLConnection", "connection", "=", "(", "HttpURLConnection", ")", "WebResourceFetcherImpl", ".", "getUrlConnection", "(", "url", ")", ";", "setupConnection", "(", "requestMethod", ",", "queryString", ",", "connection", ")", ";", "OutputStreamWriter", "writer", "=", "new", "OutputStreamWriter", "(", "connection", ".", "getOutputStream", "(", ")", ")", ";", "writer", ".", "write", "(", "queryString", ")", ";", "writer", ".", "flush", "(", ")", ";", "writer", ".", "close", "(", ")", ";", "int", "rc", "=", "connection", ".", "getResponseCode", "(", ")", ";", "if", "(", "rc", "!=", "200", ")", "{", "logger", ".", "warn", "(", "\"Error: API request returned response code \"", "+", "rc", ")", ";", "}", "InputStream", "iStream", "=", "connection", ".", "getInputStream", "(", ")", ";", "fillCookies", "(", "connection", ".", "getHeaderFields", "(", ")", ")", ";", "return", "iStream", ";", "}" ]
Sends a request to the API with the given parameters and the given request method and returns the result string. It automatically fills the cookie map with cookies in the result header after the request. Warning: You probably want to use ApiConnection.sendJsonRequest that execute the request using JSON content format, throws the errors and logs the warnings. @param requestMethod either POST or GET @param parameters Maps parameter keys to values. Out of this map the function will create a query string for the request. @return API result @throws IOException
[ "Sends", "a", "request", "to", "the", "API", "with", "the", "given", "parameters", "and", "the", "given", "request", "method", "and", "returns", "the", "result", "string", ".", "It", "automatically", "fills", "the", "cookie", "map", "with", "cookies", "in", "the", "result", "header", "after", "the", "request", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-wikibaseapi/src/main/java/org/wikidata/wdtk/wikibaseapi/ApiConnection.java#L429-L451
161,419
Wikidata/Wikidata-Toolkit
wdtk-wikibaseapi/src/main/java/org/wikidata/wdtk/wikibaseapi/ApiConnection.java
ApiConnection.getWarnings
List<String> getWarnings(JsonNode root) { ArrayList<String> warnings = new ArrayList<>(); if (root.has("warnings")) { JsonNode warningNode = root.path("warnings"); Iterator<Map.Entry<String, JsonNode>> moduleIterator = warningNode .fields(); while (moduleIterator.hasNext()) { Map.Entry<String, JsonNode> moduleNode = moduleIterator.next(); Iterator<JsonNode> moduleOutputIterator = moduleNode.getValue() .elements(); while (moduleOutputIterator.hasNext()) { JsonNode moduleOutputNode = moduleOutputIterator.next(); if (moduleOutputNode.isTextual()) { warnings.add("[" + moduleNode.getKey() + "]: " + moduleOutputNode.textValue()); } else if (moduleOutputNode.isArray()) { Iterator<JsonNode> messageIterator = moduleOutputNode .elements(); while (messageIterator.hasNext()) { JsonNode messageNode = messageIterator.next(); warnings.add("[" + moduleNode.getKey() + "]: " + messageNode.path("html").path("*") .asText(messageNode.toString())); } } else { warnings.add("[" + moduleNode.getKey() + "]: " + "Warning was not understood. Please report this to Wikidata Toolkit. JSON source: " + moduleOutputNode.toString()); } } } } return warnings; }
java
List<String> getWarnings(JsonNode root) { ArrayList<String> warnings = new ArrayList<>(); if (root.has("warnings")) { JsonNode warningNode = root.path("warnings"); Iterator<Map.Entry<String, JsonNode>> moduleIterator = warningNode .fields(); while (moduleIterator.hasNext()) { Map.Entry<String, JsonNode> moduleNode = moduleIterator.next(); Iterator<JsonNode> moduleOutputIterator = moduleNode.getValue() .elements(); while (moduleOutputIterator.hasNext()) { JsonNode moduleOutputNode = moduleOutputIterator.next(); if (moduleOutputNode.isTextual()) { warnings.add("[" + moduleNode.getKey() + "]: " + moduleOutputNode.textValue()); } else if (moduleOutputNode.isArray()) { Iterator<JsonNode> messageIterator = moduleOutputNode .elements(); while (messageIterator.hasNext()) { JsonNode messageNode = messageIterator.next(); warnings.add("[" + moduleNode.getKey() + "]: " + messageNode.path("html").path("*") .asText(messageNode.toString())); } } else { warnings.add("[" + moduleNode.getKey() + "]: " + "Warning was not understood. Please report this to Wikidata Toolkit. JSON source: " + moduleOutputNode.toString()); } } } } return warnings; }
[ "List", "<", "String", ">", "getWarnings", "(", "JsonNode", "root", ")", "{", "ArrayList", "<", "String", ">", "warnings", "=", "new", "ArrayList", "<>", "(", ")", ";", "if", "(", "root", ".", "has", "(", "\"warnings\"", ")", ")", "{", "JsonNode", "warningNode", "=", "root", ".", "path", "(", "\"warnings\"", ")", ";", "Iterator", "<", "Map", ".", "Entry", "<", "String", ",", "JsonNode", ">", ">", "moduleIterator", "=", "warningNode", ".", "fields", "(", ")", ";", "while", "(", "moduleIterator", ".", "hasNext", "(", ")", ")", "{", "Map", ".", "Entry", "<", "String", ",", "JsonNode", ">", "moduleNode", "=", "moduleIterator", ".", "next", "(", ")", ";", "Iterator", "<", "JsonNode", ">", "moduleOutputIterator", "=", "moduleNode", ".", "getValue", "(", ")", ".", "elements", "(", ")", ";", "while", "(", "moduleOutputIterator", ".", "hasNext", "(", ")", ")", "{", "JsonNode", "moduleOutputNode", "=", "moduleOutputIterator", ".", "next", "(", ")", ";", "if", "(", "moduleOutputNode", ".", "isTextual", "(", ")", ")", "{", "warnings", ".", "add", "(", "\"[\"", "+", "moduleNode", ".", "getKey", "(", ")", "+", "\"]: \"", "+", "moduleOutputNode", ".", "textValue", "(", ")", ")", ";", "}", "else", "if", "(", "moduleOutputNode", ".", "isArray", "(", ")", ")", "{", "Iterator", "<", "JsonNode", ">", "messageIterator", "=", "moduleOutputNode", ".", "elements", "(", ")", ";", "while", "(", "messageIterator", ".", "hasNext", "(", ")", ")", "{", "JsonNode", "messageNode", "=", "messageIterator", ".", "next", "(", ")", ";", "warnings", ".", "add", "(", "\"[\"", "+", "moduleNode", ".", "getKey", "(", ")", "+", "\"]: \"", "+", "messageNode", ".", "path", "(", "\"html\"", ")", ".", "path", "(", "\"*\"", ")", ".", "asText", "(", "messageNode", ".", "toString", "(", ")", ")", ")", ";", "}", "}", "else", "{", "warnings", ".", "add", "(", "\"[\"", "+", "moduleNode", ".", "getKey", "(", ")", "+", "\"]: \"", "+", "\"Warning was not understood. Please report this to Wikidata Toolkit. JSON source: \"", "+", "moduleOutputNode", ".", "toString", "(", ")", ")", ";", "}", "}", "}", "}", "return", "warnings", ";", "}" ]
Extracts warnings that are returned in an API response. @param root root node of the JSON result
[ "Extracts", "warnings", "that", "are", "returned", "in", "an", "API", "response", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-wikibaseapi/src/main/java/org/wikidata/wdtk/wikibaseapi/ApiConnection.java#L510-L550
161,420
Wikidata/Wikidata-Toolkit
wdtk-wikibaseapi/src/main/java/org/wikidata/wdtk/wikibaseapi/ApiConnection.java
ApiConnection.getQueryString
String getQueryString(Map<String, String> params) { StringBuilder builder = new StringBuilder(); try { boolean first = true; for (Map.Entry<String,String> entry : params.entrySet()) { if (first) { first = false; } else { builder.append("&"); } builder.append(URLEncoder.encode(entry.getKey(), "UTF-8")); builder.append("="); builder.append(URLEncoder.encode(entry.getValue(), "UTF-8")); } } catch (UnsupportedEncodingException e) { throw new RuntimeException( "Your Java version does not support UTF-8 encoding."); } return builder.toString(); }
java
String getQueryString(Map<String, String> params) { StringBuilder builder = new StringBuilder(); try { boolean first = true; for (Map.Entry<String,String> entry : params.entrySet()) { if (first) { first = false; } else { builder.append("&"); } builder.append(URLEncoder.encode(entry.getKey(), "UTF-8")); builder.append("="); builder.append(URLEncoder.encode(entry.getValue(), "UTF-8")); } } catch (UnsupportedEncodingException e) { throw new RuntimeException( "Your Java version does not support UTF-8 encoding."); } return builder.toString(); }
[ "String", "getQueryString", "(", "Map", "<", "String", ",", "String", ">", "params", ")", "{", "StringBuilder", "builder", "=", "new", "StringBuilder", "(", ")", ";", "try", "{", "boolean", "first", "=", "true", ";", "for", "(", "Map", ".", "Entry", "<", "String", ",", "String", ">", "entry", ":", "params", ".", "entrySet", "(", ")", ")", "{", "if", "(", "first", ")", "{", "first", "=", "false", ";", "}", "else", "{", "builder", ".", "append", "(", "\"&\"", ")", ";", "}", "builder", ".", "append", "(", "URLEncoder", ".", "encode", "(", "entry", ".", "getKey", "(", ")", ",", "\"UTF-8\"", ")", ")", ";", "builder", ".", "append", "(", "\"=\"", ")", ";", "builder", ".", "append", "(", "URLEncoder", ".", "encode", "(", "entry", ".", "getValue", "(", ")", ",", "\"UTF-8\"", ")", ")", ";", "}", "}", "catch", "(", "UnsupportedEncodingException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "\"Your Java version does not support UTF-8 encoding.\"", ")", ";", "}", "return", "builder", ".", "toString", "(", ")", ";", "}" ]
Returns the query string of a URL from a parameter list. @param params Map with parameters @return query string
[ "Returns", "the", "query", "string", "of", "a", "URL", "from", "a", "parameter", "list", "." ]
7732851dda47e1febff406fba27bfec023f4786e
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-wikibaseapi/src/main/java/org/wikidata/wdtk/wikibaseapi/ApiConnection.java#L696-L716
161,421
actframework/actframework
src/main/java/act/inject/util/ResourceLoader.java
ResourceLoader.load
public static <T> T load(String resourcePath, BeanSpec spec) { return load(resourcePath, spec, false); }
java
public static <T> T load(String resourcePath, BeanSpec spec) { return load(resourcePath, spec, false); }
[ "public", "static", "<", "T", ">", "T", "load", "(", "String", "resourcePath", ",", "BeanSpec", "spec", ")", "{", "return", "load", "(", "resourcePath", ",", "spec", ",", "false", ")", ";", "}" ]
Load resource content from given path into variable with type specified by `spec`. @param resourcePath the resource path @param spec {@link BeanSpec} specifies the return value type @return the resource content in a specified type or `null` if resource not found @throws UnexpectedException if return value type not supported
[ "Load", "resource", "content", "from", "given", "path", "into", "variable", "with", "type", "specified", "by", "spec", "." ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/inject/util/ResourceLoader.java#L137-L139
161,422
actframework/actframework
src/main/java/act/util/LogSupport.java
LogSupport.printCenter
protected void printCenter(String format, Object... args) { String text = S.fmt(format, args); info(S.center(text, 80)); }
java
protected void printCenter(String format, Object... args) { String text = S.fmt(format, args); info(S.center(text, 80)); }
[ "protected", "void", "printCenter", "(", "String", "format", ",", "Object", "...", "args", ")", "{", "String", "text", "=", "S", ".", "fmt", "(", "format", ",", "args", ")", ";", "info", "(", "S", ".", "center", "(", "text", ",", "80", ")", ")", ";", "}" ]
Print formatted string in the center of 80 chars line, left and right padded. @param format The string format pattern @param args The string format arguments
[ "Print", "formatted", "string", "in", "the", "center", "of", "80", "chars", "line", "left", "and", "right", "padded", "." ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/util/LogSupport.java#L95-L98
161,423
actframework/actframework
src/main/java/act/util/LogSupport.java
LogSupport.printCenterWithLead
protected void printCenterWithLead(String lead, String format, Object ... args) { String text = S.fmt(format, args); int len = 80 - lead.length(); info(S.concat(lead, S.center(text, len))); }
java
protected void printCenterWithLead(String lead, String format, Object ... args) { String text = S.fmt(format, args); int len = 80 - lead.length(); info(S.concat(lead, S.center(text, len))); }
[ "protected", "void", "printCenterWithLead", "(", "String", "lead", ",", "String", "format", ",", "Object", "...", "args", ")", "{", "String", "text", "=", "S", ".", "fmt", "(", "format", ",", "args", ")", ";", "int", "len", "=", "80", "-", "lead", ".", "length", "(", ")", ";", "info", "(", "S", ".", "concat", "(", "lead", ",", "S", ".", "center", "(", "text", ",", "len", ")", ")", ")", ";", "}" ]
Print the lead string followed by centered formatted string. The whole length of the line is 80 chars. Example: ```java printCenterWithLead(" *", "Hello %s", "World"); ``` will print something like ``` * Hello World ``` Note the above is just a demo, the exact number of whitespace might not be correct. @param lead the lead string @param format The string format pattern @param args The string format arguments
[ "Print", "the", "lead", "string", "followed", "by", "centered", "formatted", "string", ".", "The", "whole", "length", "of", "the", "line", "is", "80", "chars", "." ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/util/LogSupport.java#L126-L130
161,424
actframework/actframework
src/main/java/ascii/Image2ascii.java
Image2ascii.convert
public String convert(BufferedImage image, boolean favicon) { // Reset statistics before anything statsArray = new int[12]; // Begin the timer dStart = System.nanoTime(); // Scale the image image = scale(image, favicon); // The +1 is for the newline characters StringBuilder sb = new StringBuilder((image.getWidth() + 1) * image.getHeight()); for (int y = 0; y < image.getHeight(); y++) { // At the end of each line, add a newline character if (sb.length() != 0) sb.append("\n"); for (int x = 0; x < image.getWidth(); x++) { // Color pixelColor = new Color(image.getRGB(x, y), true); int alpha = pixelColor.getAlpha(); boolean isTransient = alpha < 0.1; double gValue = isTransient ? 250 : ((double) pixelColor.getRed() * 0.2989 + (double) pixelColor.getBlue() * 0.5870 + (double) pixelColor.getGreen() * 0.1140) / ((double)alpha / (double)250); final char s = gValue < 130 ? darkGrayScaleMap(gValue) : lightGrayScaleMap(gValue); sb.append(s); } } imgArray = sb.toString().toCharArray(); dEnd = System.nanoTime(); return sb.toString(); }
java
public String convert(BufferedImage image, boolean favicon) { // Reset statistics before anything statsArray = new int[12]; // Begin the timer dStart = System.nanoTime(); // Scale the image image = scale(image, favicon); // The +1 is for the newline characters StringBuilder sb = new StringBuilder((image.getWidth() + 1) * image.getHeight()); for (int y = 0; y < image.getHeight(); y++) { // At the end of each line, add a newline character if (sb.length() != 0) sb.append("\n"); for (int x = 0; x < image.getWidth(); x++) { // Color pixelColor = new Color(image.getRGB(x, y), true); int alpha = pixelColor.getAlpha(); boolean isTransient = alpha < 0.1; double gValue = isTransient ? 250 : ((double) pixelColor.getRed() * 0.2989 + (double) pixelColor.getBlue() * 0.5870 + (double) pixelColor.getGreen() * 0.1140) / ((double)alpha / (double)250); final char s = gValue < 130 ? darkGrayScaleMap(gValue) : lightGrayScaleMap(gValue); sb.append(s); } } imgArray = sb.toString().toCharArray(); dEnd = System.nanoTime(); return sb.toString(); }
[ "public", "String", "convert", "(", "BufferedImage", "image", ",", "boolean", "favicon", ")", "{", "// Reset statistics before anything", "statsArray", "=", "new", "int", "[", "12", "]", ";", "// Begin the timer", "dStart", "=", "System", ".", "nanoTime", "(", ")", ";", "// Scale the image", "image", "=", "scale", "(", "image", ",", "favicon", ")", ";", "// The +1 is for the newline characters", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", "(", "image", ".", "getWidth", "(", ")", "+", "1", ")", "*", "image", ".", "getHeight", "(", ")", ")", ";", "for", "(", "int", "y", "=", "0", ";", "y", "<", "image", ".", "getHeight", "(", ")", ";", "y", "++", ")", "{", "// At the end of each line, add a newline character", "if", "(", "sb", ".", "length", "(", ")", "!=", "0", ")", "sb", ".", "append", "(", "\"\\n\"", ")", ";", "for", "(", "int", "x", "=", "0", ";", "x", "<", "image", ".", "getWidth", "(", ")", ";", "x", "++", ")", "{", "//", "Color", "pixelColor", "=", "new", "Color", "(", "image", ".", "getRGB", "(", "x", ",", "y", ")", ",", "true", ")", ";", "int", "alpha", "=", "pixelColor", ".", "getAlpha", "(", ")", ";", "boolean", "isTransient", "=", "alpha", "<", "0.1", ";", "double", "gValue", "=", "isTransient", "?", "250", ":", "(", "(", "double", ")", "pixelColor", ".", "getRed", "(", ")", "*", "0.2989", "+", "(", "double", ")", "pixelColor", ".", "getBlue", "(", ")", "*", "0.5870", "+", "(", "double", ")", "pixelColor", ".", "getGreen", "(", ")", "*", "0.1140", ")", "/", "(", "(", "double", ")", "alpha", "/", "(", "double", ")", "250", ")", ";", "final", "char", "s", "=", "gValue", "<", "130", "?", "darkGrayScaleMap", "(", "gValue", ")", ":", "lightGrayScaleMap", "(", "gValue", ")", ";", "sb", ".", "append", "(", "s", ")", ";", "}", "}", "imgArray", "=", "sb", ".", "toString", "(", ")", ".", "toCharArray", "(", ")", ";", "dEnd", "=", "System", ".", "nanoTime", "(", ")", ";", "return", "sb", ".", "toString", "(", ")", ";", "}" ]
The main conversion method. @param image A BufferedImage containing the image that needs to be converted @param favicon When ico is true it will convert ico file into 16 x 16 size @return A string containing the ASCII version of the original image.
[ "The", "main", "conversion", "method", "." ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/ascii/Image2ascii.java#L53-L79
161,425
actframework/actframework
src/main/java/ascii/Image2ascii.java
Image2ascii.scale
private static BufferedImage scale(BufferedImage imageToScale, int dWidth, int dHeight, double fWidth, double fHeight) { BufferedImage dbi = null; // Needed to create a new BufferedImage object int imageType = imageToScale.getType(); if (imageToScale != null) { dbi = new BufferedImage(dWidth, dHeight, imageType); Graphics2D g = dbi.createGraphics(); AffineTransform at = AffineTransform.getScaleInstance(fWidth, fHeight); g.drawRenderedImage(imageToScale, at); } return dbi; }
java
private static BufferedImage scale(BufferedImage imageToScale, int dWidth, int dHeight, double fWidth, double fHeight) { BufferedImage dbi = null; // Needed to create a new BufferedImage object int imageType = imageToScale.getType(); if (imageToScale != null) { dbi = new BufferedImage(dWidth, dHeight, imageType); Graphics2D g = dbi.createGraphics(); AffineTransform at = AffineTransform.getScaleInstance(fWidth, fHeight); g.drawRenderedImage(imageToScale, at); } return dbi; }
[ "private", "static", "BufferedImage", "scale", "(", "BufferedImage", "imageToScale", ",", "int", "dWidth", ",", "int", "dHeight", ",", "double", "fWidth", ",", "double", "fHeight", ")", "{", "BufferedImage", "dbi", "=", "null", ";", "// Needed to create a new BufferedImage object", "int", "imageType", "=", "imageToScale", ".", "getType", "(", ")", ";", "if", "(", "imageToScale", "!=", "null", ")", "{", "dbi", "=", "new", "BufferedImage", "(", "dWidth", ",", "dHeight", ",", "imageType", ")", ";", "Graphics2D", "g", "=", "dbi", ".", "createGraphics", "(", ")", ";", "AffineTransform", "at", "=", "AffineTransform", ".", "getScaleInstance", "(", "fWidth", ",", "fHeight", ")", ";", "g", ".", "drawRenderedImage", "(", "imageToScale", ",", "at", ")", ";", "}", "return", "dbi", ";", "}" ]
Image scale method @param imageToScale The image to be scaled @param dWidth Desired width, the new image object is created to this size @param dHeight Desired height, the new image object is created to this size @param fWidth What to multiply the width by. value < 1 scales down, and value > one scales up @param fHeight What to multiply the height by. value < 1 scales down, and value > one scales up @return A scaled image
[ "Image", "scale", "method" ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/ascii/Image2ascii.java#L91-L102
161,426
actframework/actframework
src/main/java/act/event/EventBus.java
EventBus.emit
public EventBus emit(Enum<?> event, Object... args) { return _emitWithOnceBus(eventContext(event, args)); }
java
public EventBus emit(Enum<?> event, Object... args) { return _emitWithOnceBus(eventContext(event, args)); }
[ "public", "EventBus", "emit", "(", "Enum", "<", "?", ">", "event", ",", "Object", "...", "args", ")", "{", "return", "_emitWithOnceBus", "(", "eventContext", "(", "event", ",", "args", ")", ")", ";", "}" ]
Emit an enum event with parameters supplied. This will invoke all {@link SimpleEventListener} bound to the specific enum value and all {@link SimpleEventListener} bound to the enum class given the listeners has the matching argument list. For example, given the following enum definition: ```java public enum UserActivity {LOGIN, LOGOUT} ``` We have the following simple event listener methods: ```java {@literal @}OnEvent public void handleUserActivity(UserActivity, User user) {...} {@literal @}OnUserActivity(UserActivity.LOGIN) public void logUserLogin(User user, long timestamp) {...} {@literal @}OnUserActivity(UserActivity.LOGOUT) public void logUserLogout(User user) {...} ``` The following code will invoke `logUserLogin` method: ```java User user = ...; eventBus.emit(UserActivity.LOGIN, user, System.currentTimeMills()); ``` The `handleUserActivity` is not invoked because * The method parameter `(UserActivity, User, long)` does not match the declared argument list `(UserActivity, User)` While the following code will invoke both `handleUserActivity` and `logUserLogout` methods: ```java User user = ...; eventBus.emit(UserActivity.LOGOUT, user); ``` The `logUserLogin` method will not be invoked because 1. the method is bound to `UserActivity.LOGIN` enum value specifically, while `LOGOUT` is triggered 2. the method has a `long timestamp` in the argument list and it is not passed to `eventBus.emit` @param event the target event @param args the arguments passed in @see SimpleEventListener
[ "Emit", "an", "enum", "event", "with", "parameters", "supplied", "." ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/event/EventBus.java#L865-L867
161,427
actframework/actframework
src/main/java/act/event/EventBus.java
EventBus.emit
public EventBus emit(String event, Object... args) { return _emitWithOnceBus(eventContext(event, args)); }
java
public EventBus emit(String event, Object... args) { return _emitWithOnceBus(eventContext(event, args)); }
[ "public", "EventBus", "emit", "(", "String", "event", ",", "Object", "...", "args", ")", "{", "return", "_emitWithOnceBus", "(", "eventContext", "(", "event", ",", "args", ")", ")", ";", "}" ]
Emit a string event with parameters. This will invoke all {@link SimpleEventListener} bound to the specified string value given the listeners has the matching argument list. For example, suppose we have the following simple event listener methods: ```java {@literal @}On("USER-LOGIN") public void logUserLogin(User user, long timestamp) {...} {@literal @}On("USER-LOGIN") public void checkDuplicateLoginAttempts(User user, Object... args) {...} {@literal @}On("USER-LOGIN") public void foo(User user) {...} ``` The following code will invoke `logUserLogin` and `checkDuplicateLoginAttempts` methods: ```java User user = ...; eventBus.emit("USER-LOGIN", user, System.currentTimeMills()); ``` The `foo(User)` will not invoked because: * The parameter list `(User, long)` does not match the declared argument list `(User)`. Here the `String` in the parameter list is taken out because it is used to indicate the event, instead of being passing through to the event handler method. * The method `checkDuplicateLoginAttempts(User, Object ...)` will be invoked because it declares a varargs typed arguments, meaning it matches any parameters passed in. @param event the target event @param args the arguments passed in @see SimpleEventListener
[ "Emit", "a", "string", "event", "with", "parameters", "." ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/event/EventBus.java#L909-L911
161,428
actframework/actframework
src/main/java/act/event/EventBus.java
EventBus.emit
public EventBus emit(EventObject event, Object... args) { return _emitWithOnceBus(eventContext(event, args)); }
java
public EventBus emit(EventObject event, Object... args) { return _emitWithOnceBus(eventContext(event, args)); }
[ "public", "EventBus", "emit", "(", "EventObject", "event", ",", "Object", "...", "args", ")", "{", "return", "_emitWithOnceBus", "(", "eventContext", "(", "event", ",", "args", ")", ")", ";", "}" ]
Emit an event object with parameters. This will invoke all {@link SimpleEventListener} bound to the event object class given the listeners has the matching argument list. If there is no parameter passed in, i.e. `args.length == 0`, then it will also invoke all the {@link ActEventListener} bound to the event class. For example, suppose we have the following Event defined: ```java public class UserActivityEvent extends ActEvent<User> { public UserActivityEvent(User user) {super(user);} } ``` And we have the following event handler defined: ```java {@literal @}OnEvent public void logUserLogin(UserActivityEvent event, long timestamp) {...} {@literal @}OnEvent public void checkDuplicateLoginAttempts(UserActivityEvent, Object... args) {...} {@literal @}OnEvent public void foo(UserActivityEvent event) {...} ``` The following code will invoke `logUserLogin` and `checkDuplicateLoginAttempts` methods: ```java User user = ...; eventBus.emit(new UserActivityEvent(user), System.currentTimeMills()); ``` The `foo(UserActivityEvent)` will not invoked because: * The parameter list `(UserActivityEvent, long)` does not match the declared argument list `(UserActivityEvent)`. Here the `String` in the parameter list is taken out because it is used to indicate the event, instead of being passing through to the event handler method. * The method `checkDuplicateLoginAttempts(UserActivityEvent, Object ...)` will be invoked because it declares a varargs typed arguments, meaning it matches any parameters passed in. @param event the target event @param args the arguments passed in @see SimpleEventListener
[ "Emit", "an", "event", "object", "with", "parameters", "." ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/event/EventBus.java#L966-L968
161,429
actframework/actframework
src/main/java/act/event/EventBus.java
EventBus.emitAsync
public EventBus emitAsync(Enum<?> event, Object... args) { return _emitWithOnceBus(eventContextAsync(event, args)); }
java
public EventBus emitAsync(Enum<?> event, Object... args) { return _emitWithOnceBus(eventContextAsync(event, args)); }
[ "public", "EventBus", "emitAsync", "(", "Enum", "<", "?", ">", "event", ",", "Object", "...", "args", ")", "{", "return", "_emitWithOnceBus", "(", "eventContextAsync", "(", "event", ",", "args", ")", ")", ";", "}" ]
Emit an enum event with parameters and force all listeners to be called asynchronously. @param event the target event @param args the arguments passed in @see #emit(Enum, Object...)
[ "Emit", "an", "enum", "event", "with", "parameters", "and", "force", "all", "listeners", "to", "be", "called", "asynchronously", "." ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/event/EventBus.java#L1009-L1011
161,430
actframework/actframework
src/main/java/act/event/EventBus.java
EventBus.emitAsync
public EventBus emitAsync(String event, Object... args) { return _emitWithOnceBus(eventContextAsync(event, args)); }
java
public EventBus emitAsync(String event, Object... args) { return _emitWithOnceBus(eventContextAsync(event, args)); }
[ "public", "EventBus", "emitAsync", "(", "String", "event", ",", "Object", "...", "args", ")", "{", "return", "_emitWithOnceBus", "(", "eventContextAsync", "(", "event", ",", "args", ")", ")", ";", "}" ]
Emit a string event with parameters and force all listeners to be called asynchronously. @param event the target event @param args the arguments passed in @see #emit(String, Object...)
[ "Emit", "a", "string", "event", "with", "parameters", "and", "force", "all", "listeners", "to", "be", "called", "asynchronously", "." ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/event/EventBus.java#L1022-L1024
161,431
actframework/actframework
src/main/java/act/event/EventBus.java
EventBus.emitAsync
public EventBus emitAsync(EventObject event, Object... args) { return _emitWithOnceBus(eventContextAsync(event, args)); }
java
public EventBus emitAsync(EventObject event, Object... args) { return _emitWithOnceBus(eventContextAsync(event, args)); }
[ "public", "EventBus", "emitAsync", "(", "EventObject", "event", ",", "Object", "...", "args", ")", "{", "return", "_emitWithOnceBus", "(", "eventContextAsync", "(", "event", ",", "args", ")", ")", ";", "}" ]
Emit a event object with parameters and force all listeners to be called asynchronously. @param event the target event @param args the arguments passed in @see #emit(EventObject, Object...)
[ "Emit", "a", "event", "object", "with", "parameters", "and", "force", "all", "listeners", "to", "be", "called", "asynchronously", "." ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/event/EventBus.java#L1035-L1037
161,432
actframework/actframework
src/main/java/act/event/EventBus.java
EventBus.emitSync
public EventBus emitSync(Enum<?> event, Object... args) { return _emitWithOnceBus(eventContextSync(event, args)); }
java
public EventBus emitSync(Enum<?> event, Object... args) { return _emitWithOnceBus(eventContextSync(event, args)); }
[ "public", "EventBus", "emitSync", "(", "Enum", "<", "?", ">", "event", ",", "Object", "...", "args", ")", "{", "return", "_emitWithOnceBus", "(", "eventContextSync", "(", "event", ",", "args", ")", ")", ";", "}" ]
Emit an enum event with parameters and force all listener to be called synchronously. @param event the target event @param args the arguments passed in @see #emit(Enum, Object...)
[ "Emit", "an", "enum", "event", "with", "parameters", "and", "force", "all", "listener", "to", "be", "called", "synchronously", "." ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/event/EventBus.java#L1079-L1081
161,433
actframework/actframework
src/main/java/act/event/EventBus.java
EventBus.emitSync
public EventBus emitSync(String event, Object... args) { return _emitWithOnceBus(eventContextSync(event, args)); }
java
public EventBus emitSync(String event, Object... args) { return _emitWithOnceBus(eventContextSync(event, args)); }
[ "public", "EventBus", "emitSync", "(", "String", "event", ",", "Object", "...", "args", ")", "{", "return", "_emitWithOnceBus", "(", "eventContextSync", "(", "event", ",", "args", ")", ")", ";", "}" ]
Emit a string event with parameters and force all listener to be called synchronously. @param event the target event @param args the arguments passed in @see #emit(String, Object...)
[ "Emit", "a", "string", "event", "with", "parameters", "and", "force", "all", "listener", "to", "be", "called", "synchronously", "." ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/event/EventBus.java#L1092-L1094
161,434
actframework/actframework
src/main/java/act/event/EventBus.java
EventBus.emitSync
public EventBus emitSync(EventObject event, Object... args) { return _emitWithOnceBus(eventContextSync(event, args)); }
java
public EventBus emitSync(EventObject event, Object... args) { return _emitWithOnceBus(eventContextSync(event, args)); }
[ "public", "EventBus", "emitSync", "(", "EventObject", "event", ",", "Object", "...", "args", ")", "{", "return", "_emitWithOnceBus", "(", "eventContextSync", "(", "event", ",", "args", ")", ")", ";", "}" ]
Emit a event object with parameters and force all listeners to be called synchronously. @param event the target event @param args the arguments passed in @see #emit(EventObject, Object...)
[ "Emit", "a", "event", "object", "with", "parameters", "and", "force", "all", "listeners", "to", "be", "called", "synchronously", "." ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/event/EventBus.java#L1105-L1107
161,435
actframework/actframework
src/main/java/act/conf/ConfLoader.java
ConfLoader.common
public static String common() { String common = SysProps.get(KEY_COMMON_CONF_TAG); if (S.blank(common)) { common = "common"; } return common; }
java
public static String common() { String common = SysProps.get(KEY_COMMON_CONF_TAG); if (S.blank(common)) { common = "common"; } return common; }
[ "public", "static", "String", "common", "(", ")", "{", "String", "common", "=", "SysProps", ".", "get", "(", "KEY_COMMON_CONF_TAG", ")", ";", "if", "(", "S", ".", "blank", "(", "common", ")", ")", "{", "common", "=", "\"common\"", ";", "}", "return", "common", ";", "}" ]
Return the "common" configuration set name. By default it is "common" @return the "common" conf set name
[ "Return", "the", "common", "configuration", "set", "name", ".", "By", "default", "it", "is", "common" ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/conf/ConfLoader.java#L87-L93
161,436
actframework/actframework
src/main/java/act/conf/ConfLoader.java
ConfLoader.confSetName
public static String confSetName() { String profile = SysProps.get(AppConfigKey.PROFILE.key()); if (S.blank(profile)) { profile = Act.mode().name().toLowerCase(); } return profile; }
java
public static String confSetName() { String profile = SysProps.get(AppConfigKey.PROFILE.key()); if (S.blank(profile)) { profile = Act.mode().name().toLowerCase(); } return profile; }
[ "public", "static", "String", "confSetName", "(", ")", "{", "String", "profile", "=", "SysProps", ".", "get", "(", "AppConfigKey", ".", "PROFILE", ".", "key", "(", ")", ")", ";", "if", "(", "S", ".", "blank", "(", "profile", ")", ")", "{", "profile", "=", "Act", ".", "mode", "(", ")", ".", "name", "(", ")", ".", "toLowerCase", "(", ")", ";", "}", "return", "profile", ";", "}" ]
Return the name of the current conf set @return the conf set name
[ "Return", "the", "name", "of", "the", "current", "conf", "set" ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/conf/ConfLoader.java#L99-L105
161,437
actframework/actframework
src/main/java/act/conf/ConfLoader.java
ConfLoader.processConf
private static Map<String, Object> processConf(Map<String, ?> conf) { Map<String, Object> m = new HashMap<String, Object>(conf.size()); for (String s : conf.keySet()) { Object o = conf.get(s); if (s.startsWith("act.")) s = s.substring(4); m.put(s, o); m.put(Config.canonical(s), o); } return m; }
java
private static Map<String, Object> processConf(Map<String, ?> conf) { Map<String, Object> m = new HashMap<String, Object>(conf.size()); for (String s : conf.keySet()) { Object o = conf.get(s); if (s.startsWith("act.")) s = s.substring(4); m.put(s, o); m.put(Config.canonical(s), o); } return m; }
[ "private", "static", "Map", "<", "String", ",", "Object", ">", "processConf", "(", "Map", "<", "String", ",", "?", ">", "conf", ")", "{", "Map", "<", "String", ",", "Object", ">", "m", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", "conf", ".", "size", "(", ")", ")", ";", "for", "(", "String", "s", ":", "conf", ".", "keySet", "(", ")", ")", "{", "Object", "o", "=", "conf", ".", "get", "(", "s", ")", ";", "if", "(", "s", ".", "startsWith", "(", "\"act.\"", ")", ")", "s", "=", "s", ".", "substring", "(", "4", ")", ";", "m", ".", "put", "(", "s", ",", "o", ")", ";", "m", ".", "put", "(", "Config", ".", "canonical", "(", "s", ")", ",", "o", ")", ";", "}", "return", "m", ";", "}" ]
trim "act." from conf keys
[ "trim", "act", ".", "from", "conf", "keys" ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/conf/ConfLoader.java#L226-L235
161,438
actframework/actframework
src/main/java/act/cli/CliContext.java
CliContext.curDir
public File curDir() { File file = session().attribute(ATTR_PWD); if (null == file) { file = new File(System.getProperty("user.dir")); session().attribute(ATTR_PWD, file); } return file; }
java
public File curDir() { File file = session().attribute(ATTR_PWD); if (null == file) { file = new File(System.getProperty("user.dir")); session().attribute(ATTR_PWD, file); } return file; }
[ "public", "File", "curDir", "(", ")", "{", "File", "file", "=", "session", "(", ")", ".", "attribute", "(", "ATTR_PWD", ")", ";", "if", "(", "null", "==", "file", ")", "{", "file", "=", "new", "File", "(", "System", ".", "getProperty", "(", "\"user.dir\"", ")", ")", ";", "session", "(", ")", ".", "attribute", "(", "ATTR_PWD", ",", "file", ")", ";", "}", "return", "file", ";", "}" ]
Return the current working directory @return the current working directory
[ "Return", "the", "current", "working", "directory" ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/cli/CliContext.java#L307-L314
161,439
actframework/actframework
src/main/java/act/cli/ascii_table/impl/SimpleASCIITableImpl.java
SimpleASCIITableImpl.getRowLineBuf
private String getRowLineBuf(int colCount, List<Integer> colMaxLenList, String[][] data) { S.Buffer rowBuilder = S.buffer(); int colWidth; for (int i = 0 ; i < colCount ; i ++) { colWidth = colMaxLenList.get(i) + 3; for (int j = 0; j < colWidth ; j ++) { if (j==0) { rowBuilder.append("+"); } else if ((i+1 == colCount && j+1 == colWidth)) {//for last column close the border rowBuilder.append("-+"); } else { rowBuilder.append("-"); } } } return rowBuilder.append("\n").toString(); }
java
private String getRowLineBuf(int colCount, List<Integer> colMaxLenList, String[][] data) { S.Buffer rowBuilder = S.buffer(); int colWidth; for (int i = 0 ; i < colCount ; i ++) { colWidth = colMaxLenList.get(i) + 3; for (int j = 0; j < colWidth ; j ++) { if (j==0) { rowBuilder.append("+"); } else if ((i+1 == colCount && j+1 == colWidth)) {//for last column close the border rowBuilder.append("-+"); } else { rowBuilder.append("-"); } } } return rowBuilder.append("\n").toString(); }
[ "private", "String", "getRowLineBuf", "(", "int", "colCount", ",", "List", "<", "Integer", ">", "colMaxLenList", ",", "String", "[", "]", "[", "]", "data", ")", "{", "S", ".", "Buffer", "rowBuilder", "=", "S", ".", "buffer", "(", ")", ";", "int", "colWidth", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "colCount", ";", "i", "++", ")", "{", "colWidth", "=", "colMaxLenList", ".", "get", "(", "i", ")", "+", "3", ";", "for", "(", "int", "j", "=", "0", ";", "j", "<", "colWidth", ";", "j", "++", ")", "{", "if", "(", "j", "==", "0", ")", "{", "rowBuilder", ".", "append", "(", "\"+\"", ")", ";", "}", "else", "if", "(", "(", "i", "+", "1", "==", "colCount", "&&", "j", "+", "1", "==", "colWidth", ")", ")", "{", "//for last column close the border", "rowBuilder", ".", "append", "(", "\"-+\"", ")", ";", "}", "else", "{", "rowBuilder", ".", "append", "(", "\"-\"", ")", ";", "}", "}", "}", "return", "rowBuilder", ".", "append", "(", "\"\\n\"", ")", ".", "toString", "(", ")", ";", "}" ]
Each string item rendering requires the border and a space on both sides. 12 3 12 3 12 34 +----- +-------- +------+ abc venkat last @param colCount @param colMaxLenList @param data @return
[ "Each", "string", "item", "rendering", "requires", "the", "border", "and", "a", "space", "on", "both", "sides", "." ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/cli/ascii_table/impl/SimpleASCIITableImpl.java#L338-L359
161,440
actframework/actframework
src/main/java/act/internal/util/AppDescriptor.java
AppDescriptor.toByteArray
public byte[] toByteArray() { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(this); return baos.toByteArray(); } catch (IOException e) { throw E.ioException(e); } }
java
public byte[] toByteArray() { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(this); return baos.toByteArray(); } catch (IOException e) { throw E.ioException(e); } }
[ "public", "byte", "[", "]", "toByteArray", "(", ")", "{", "try", "{", "ByteArrayOutputStream", "baos", "=", "new", "ByteArrayOutputStream", "(", ")", ";", "ObjectOutputStream", "oos", "=", "new", "ObjectOutputStream", "(", "baos", ")", ";", "oos", ".", "writeObject", "(", "this", ")", ";", "return", "baos", ".", "toByteArray", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "E", ".", "ioException", "(", "e", ")", ";", "}", "}" ]
Serialize this `AppDescriptor` and output byte array @return serialize this `AppDescriptor` into byte array
[ "Serialize", "this", "AppDescriptor", "and", "output", "byte", "array" ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/internal/util/AppDescriptor.java#L112-L121
161,441
actframework/actframework
src/main/java/act/internal/util/AppDescriptor.java
AppDescriptor.of
public static AppDescriptor of(String appName, Class<?> entryClass) { System.setProperty("osgl.version.suppress-var-found-warning", "true"); return of(appName, entryClass, Version.of(entryClass)); }
java
public static AppDescriptor of(String appName, Class<?> entryClass) { System.setProperty("osgl.version.suppress-var-found-warning", "true"); return of(appName, entryClass, Version.of(entryClass)); }
[ "public", "static", "AppDescriptor", "of", "(", "String", "appName", ",", "Class", "<", "?", ">", "entryClass", ")", "{", "System", ".", "setProperty", "(", "\"osgl.version.suppress-var-found-warning\"", ",", "\"true\"", ")", ";", "return", "of", "(", "appName", ",", "entryClass", ",", "Version", ".", "of", "(", "entryClass", ")", ")", ";", "}" ]
Create an `AppDescriptor` with appName and entry class specified. If `appName` is `null` or blank, it will try the following approach to get app name: 1. check the {@link Version#getArtifactId() artifact id} and use it unless 2. if artifact id is null or empty, then infer app name using {@link AppNameInferer} @param appName the app name @param entryClass the entry class @return an `AppDescriptor` instance
[ "Create", "an", "AppDescriptor", "with", "appName", "and", "entry", "class", "specified", "." ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/internal/util/AppDescriptor.java#L196-L199
161,442
actframework/actframework
src/main/java/act/internal/util/AppDescriptor.java
AppDescriptor.of
public static AppDescriptor of(String appName, String packageName) { String[] packages = packageName.split(S.COMMON_SEP); return of(appName, packageName, Version.ofPackage(packages[0])); }
java
public static AppDescriptor of(String appName, String packageName) { String[] packages = packageName.split(S.COMMON_SEP); return of(appName, packageName, Version.ofPackage(packages[0])); }
[ "public", "static", "AppDescriptor", "of", "(", "String", "appName", ",", "String", "packageName", ")", "{", "String", "[", "]", "packages", "=", "packageName", ".", "split", "(", "S", ".", "COMMON_SEP", ")", ";", "return", "of", "(", "appName", ",", "packageName", ",", "Version", ".", "ofPackage", "(", "packages", "[", "0", "]", ")", ")", ";", "}" ]
Create an `AppDescriptor` with appName and package name specified If `appName` is `null` or blank, it will try the following approach to get app name: 1. check the {@link Version#getArtifactId() artifact id} and use it unless 2. if artifact id is null or empty, then infer app name using {@link AppNameInferer} @param appName the app name @param packageName the package name of the app @return an `AppDescriptor` instance
[ "Create", "an", "AppDescriptor", "with", "appName", "and", "package", "name", "specified" ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/internal/util/AppDescriptor.java#L217-L220
161,443
actframework/actframework
src/main/java/act/internal/util/AppDescriptor.java
AppDescriptor.deserializeFrom
public static AppDescriptor deserializeFrom(byte[] bytes) { try { ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bais); return (AppDescriptor) ois.readObject(); } catch (IOException e) { throw E.ioException(e); } catch (ClassNotFoundException e) { throw E.unexpected(e); } }
java
public static AppDescriptor deserializeFrom(byte[] bytes) { try { ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bais); return (AppDescriptor) ois.readObject(); } catch (IOException e) { throw E.ioException(e); } catch (ClassNotFoundException e) { throw E.unexpected(e); } }
[ "public", "static", "AppDescriptor", "deserializeFrom", "(", "byte", "[", "]", "bytes", ")", "{", "try", "{", "ByteArrayInputStream", "bais", "=", "new", "ByteArrayInputStream", "(", "bytes", ")", ";", "ObjectInputStream", "ois", "=", "new", "ObjectInputStream", "(", "bais", ")", ";", "return", "(", "AppDescriptor", ")", "ois", ".", "readObject", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "E", ".", "ioException", "(", "e", ")", ";", "}", "catch", "(", "ClassNotFoundException", "e", ")", "{", "throw", "E", ".", "unexpected", "(", "e", ")", ";", "}", "}" ]
Deserialize an `AppDescriptor` from byte array @param bytes the byte array @return an `AppDescriptor` instance
[ "Deserialize", "an", "AppDescriptor", "from", "byte", "array" ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/internal/util/AppDescriptor.java#L260-L270
161,444
actframework/actframework
src/main/java/act/internal/util/AppNameInferer.java
AppNameInferer.from
static String from(Class<?> entryClass) { List<String> tokens = tokenOf(entryClass); return fromTokens(tokens); }
java
static String from(Class<?> entryClass) { List<String> tokens = tokenOf(entryClass); return fromTokens(tokens); }
[ "static", "String", "from", "(", "Class", "<", "?", ">", "entryClass", ")", "{", "List", "<", "String", ">", "tokens", "=", "tokenOf", "(", "entryClass", ")", ";", "return", "fromTokens", "(", "tokens", ")", ";", "}" ]
Infer app name from entry class @param entryClass the entry class @return app name inferred from the entry class
[ "Infer", "app", "name", "from", "entry", "class" ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/internal/util/AppNameInferer.java#L42-L45
161,445
actframework/actframework
src/main/java/act/internal/util/AppNameInferer.java
AppNameInferer.fromPackageName
static String fromPackageName(String packageName) { List<String> tokens = tokenOf(packageName); return fromTokens(tokens); }
java
static String fromPackageName(String packageName) { List<String> tokens = tokenOf(packageName); return fromTokens(tokens); }
[ "static", "String", "fromPackageName", "(", "String", "packageName", ")", "{", "List", "<", "String", ">", "tokens", "=", "tokenOf", "(", "packageName", ")", ";", "return", "fromTokens", "(", "tokens", ")", ";", "}" ]
Infer app name from scan package @param packageName the package name @return app name inferred from the package name
[ "Infer", "app", "name", "from", "scan", "package" ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/internal/util/AppNameInferer.java#L55-L58
161,446
actframework/actframework
src/main/java/act/apidoc/javadoc/Utils.java
Utils.nextWord
public static String nextWord(String string) { int index = 0; while (index < string.length() && !Character.isWhitespace(string.charAt(index))) { index++; } return string.substring(0, index); }
java
public static String nextWord(String string) { int index = 0; while (index < string.length() && !Character.isWhitespace(string.charAt(index))) { index++; } return string.substring(0, index); }
[ "public", "static", "String", "nextWord", "(", "String", "string", ")", "{", "int", "index", "=", "0", ";", "while", "(", "index", "<", "string", ".", "length", "(", ")", "&&", "!", "Character", ".", "isWhitespace", "(", "string", ".", "charAt", "(", "index", ")", ")", ")", "{", "index", "++", ";", "}", "return", "string", ".", "substring", "(", "0", ",", "index", ")", ";", "}" ]
Return the next word of the string, in other words it stops when a space is encountered.
[ "Return", "the", "next", "word", "of", "the", "string", "in", "other", "words", "it", "stops", "when", "a", "space", "is", "encountered", "." ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/apidoc/javadoc/Utils.java#L27-L33
161,447
actframework/actframework
src/main/java/act/data/ApacheMultipartParser.java
ApacheMultipartParser.getHeader
private final String getHeader(Map /* String, String */ headers, String name) { return (String) headers.get(name.toLowerCase()); }
java
private final String getHeader(Map /* String, String */ headers, String name) { return (String) headers.get(name.toLowerCase()); }
[ "private", "final", "String", "getHeader", "(", "Map", "/* String, String */", "headers", ",", "String", "name", ")", "{", "return", "(", "String", ")", "headers", ".", "get", "(", "name", ".", "toLowerCase", "(", ")", ")", ";", "}" ]
Returns the header with the specified name from the supplied map. The header lookup is case-insensitive. @param headers A <code>Map</code> containing the HTTP request headers. @param name The name of the header to return. @return The value of specified header, or a comma-separated list if there were multiple headers of that name.
[ "Returns", "the", "header", "with", "the", "specified", "name", "from", "the", "supplied", "map", ".", "The", "header", "lookup", "is", "case", "-", "insensitive", "." ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/data/ApacheMultipartParser.java#L322-L324
161,448
actframework/actframework
src/main/java/me/tongfei/progressbar/ProgressBar.java
ProgressBar.stop
public ProgressBar stop() { target.kill(); try { thread.join(); target.consoleStream.print("\n"); target.consoleStream.flush(); } catch (InterruptedException ex) { } return this; }
java
public ProgressBar stop() { target.kill(); try { thread.join(); target.consoleStream.print("\n"); target.consoleStream.flush(); } catch (InterruptedException ex) { } return this; }
[ "public", "ProgressBar", "stop", "(", ")", "{", "target", ".", "kill", "(", ")", ";", "try", "{", "thread", ".", "join", "(", ")", ";", "target", ".", "consoleStream", ".", "print", "(", "\"\\n\"", ")", ";", "target", ".", "consoleStream", ".", "flush", "(", ")", ";", "}", "catch", "(", "InterruptedException", "ex", ")", "{", "}", "return", "this", ";", "}" ]
Stops this progress bar.
[ "Stops", "this", "progress", "bar", "." ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/me/tongfei/progressbar/ProgressBar.java#L124-L133
161,449
actframework/actframework
src/main/java/act/data/DataPropertyRepository.java
DataPropertyRepository.propertyListOf
public synchronized List<String> propertyListOf(Class<?> c) { String cn = c.getName(); List<String> ls = repo.get(cn); if (ls != null) { return ls; } Set<Class<?>> circularReferenceDetector = new HashSet<>(); ls = propertyListOf(c, circularReferenceDetector, null); repo.put(c.getName(), ls); return ls; }
java
public synchronized List<String> propertyListOf(Class<?> c) { String cn = c.getName(); List<String> ls = repo.get(cn); if (ls != null) { return ls; } Set<Class<?>> circularReferenceDetector = new HashSet<>(); ls = propertyListOf(c, circularReferenceDetector, null); repo.put(c.getName(), ls); return ls; }
[ "public", "synchronized", "List", "<", "String", ">", "propertyListOf", "(", "Class", "<", "?", ">", "c", ")", "{", "String", "cn", "=", "c", ".", "getName", "(", ")", ";", "List", "<", "String", ">", "ls", "=", "repo", ".", "get", "(", "cn", ")", ";", "if", "(", "ls", "!=", "null", ")", "{", "return", "ls", ";", "}", "Set", "<", "Class", "<", "?", ">", ">", "circularReferenceDetector", "=", "new", "HashSet", "<>", "(", ")", ";", "ls", "=", "propertyListOf", "(", "c", ",", "circularReferenceDetector", ",", "null", ")", ";", "repo", ".", "put", "(", "c", ".", "getName", "(", ")", ",", "ls", ")", ";", "return", "ls", ";", "}" ]
Returns the complete property list of a class @param c the class @return the property list of the class
[ "Returns", "the", "complete", "property", "list", "of", "a", "class" ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/data/DataPropertyRepository.java#L82-L92
161,450
actframework/actframework
src/main/java/act/util/ClassNode.java
ClassNode.parent
public ClassNode parent(String name) { this.parent = infoBase.node(name); this.parent.addChild(this); for (ClassNode intf : parent.interfaces.values()) { addInterface(intf); } return this; }
java
public ClassNode parent(String name) { this.parent = infoBase.node(name); this.parent.addChild(this); for (ClassNode intf : parent.interfaces.values()) { addInterface(intf); } return this; }
[ "public", "ClassNode", "parent", "(", "String", "name", ")", "{", "this", ".", "parent", "=", "infoBase", ".", "node", "(", "name", ")", ";", "this", ".", "parent", ".", "addChild", "(", "this", ")", ";", "for", "(", "ClassNode", "intf", ":", "parent", ".", "interfaces", ".", "values", "(", ")", ")", "{", "addInterface", "(", "intf", ")", ";", "}", "return", "this", ";", "}" ]
Specify the class represented by this `ClassNode` extends a class with the name specified @param name the name of the parent class @return this `ClassNode` instance
[ "Specify", "the", "class", "represented", "by", "this", "ClassNode", "extends", "a", "class", "with", "the", "name", "specified" ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/util/ClassNode.java#L109-L116
161,451
actframework/actframework
src/main/java/act/util/ClassNode.java
ClassNode.addInterface
public ClassNode addInterface(String name) { ClassNode intf = infoBase.node(name); addInterface(intf); return this; }
java
public ClassNode addInterface(String name) { ClassNode intf = infoBase.node(name); addInterface(intf); return this; }
[ "public", "ClassNode", "addInterface", "(", "String", "name", ")", "{", "ClassNode", "intf", "=", "infoBase", ".", "node", "(", "name", ")", ";", "addInterface", "(", "intf", ")", ";", "return", "this", ";", "}" ]
Specify the class represented by this `ClassNode` implements an interface specified by the given name @param name the name of the interface class @return this `ClassNode` instance
[ "Specify", "the", "class", "represented", "by", "this", "ClassNode", "implements", "an", "interface", "specified", "by", "the", "given", "name" ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/util/ClassNode.java#L125-L129
161,452
actframework/actframework
src/main/java/act/util/ClassNode.java
ClassNode.annotatedWith
public ClassNode annotatedWith(String name) { ClassNode anno = infoBase.node(name); this.annotations.add(anno); anno.annotated.add(this); return this; }
java
public ClassNode annotatedWith(String name) { ClassNode anno = infoBase.node(name); this.annotations.add(anno); anno.annotated.add(this); return this; }
[ "public", "ClassNode", "annotatedWith", "(", "String", "name", ")", "{", "ClassNode", "anno", "=", "infoBase", ".", "node", "(", "name", ")", ";", "this", ".", "annotations", ".", "add", "(", "anno", ")", ";", "anno", ".", "annotated", ".", "add", "(", "this", ")", ";", "return", "this", ";", "}" ]
Specify the class represented by this `ClassNode` is annotated by an annotation class specified by the name @param name the name of the annotation class @return this `ClassNode` instance
[ "Specify", "the", "class", "represented", "by", "this", "ClassNode", "is", "annotated", "by", "an", "annotation", "class", "specified", "by", "the", "name" ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/util/ClassNode.java#L153-L158
161,453
actframework/actframework
src/main/java/act/i18n/TimeZoneResolver.java
TimeZoneResolver.timezoneOffset
public static int timezoneOffset(H.Session session) { String s = null != session ? session.get(SESSION_KEY) : null; return S.notBlank(s) ? Integer.parseInt(s) : serverTimezoneOffset(); }
java
public static int timezoneOffset(H.Session session) { String s = null != session ? session.get(SESSION_KEY) : null; return S.notBlank(s) ? Integer.parseInt(s) : serverTimezoneOffset(); }
[ "public", "static", "int", "timezoneOffset", "(", "H", ".", "Session", "session", ")", "{", "String", "s", "=", "null", "!=", "session", "?", "session", ".", "get", "(", "SESSION_KEY", ")", ":", "null", ";", "return", "S", ".", "notBlank", "(", "s", ")", "?", "Integer", ".", "parseInt", "(", "s", ")", ":", "serverTimezoneOffset", "(", ")", ";", "}" ]
Returns timezone offset from a session instance. The offset is in minutes to UTC time @param session the session instance @return the offset to UTC time in minutes
[ "Returns", "timezone", "offset", "from", "a", "session", "instance", ".", "The", "offset", "is", "in", "minutes", "to", "UTC", "time" ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/i18n/TimeZoneResolver.java#L62-L65
161,454
actframework/actframework
src/main/java/act/ws/WebSocketConnectionManager.java
WebSocketConnectionManager.sendJsonToUrl
public void sendJsonToUrl(Object data, String url) { sendToUrl(JSON.toJSONString(data), url); }
java
public void sendJsonToUrl(Object data, String url) { sendToUrl(JSON.toJSONString(data), url); }
[ "public", "void", "sendJsonToUrl", "(", "Object", "data", ",", "String", "url", ")", "{", "sendToUrl", "(", "JSON", ".", "toJSONString", "(", "data", ")", ",", "url", ")", ";", "}" ]
Send JSON representation of given data object to all connections connected to given URL @param data the data object @param url the url
[ "Send", "JSON", "representation", "of", "given", "data", "object", "to", "all", "connections", "connected", "to", "given", "URL" ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/ws/WebSocketConnectionManager.java#L129-L131
161,455
actframework/actframework
src/main/java/act/ws/WebSocketConnectionManager.java
WebSocketConnectionManager.sendToTagged
public void sendToTagged(String message, String ... labels) { for (String label : labels) { sendToTagged(message, label); } }
java
public void sendToTagged(String message, String ... labels) { for (String label : labels) { sendToTagged(message, label); } }
[ "public", "void", "sendToTagged", "(", "String", "message", ",", "String", "...", "labels", ")", "{", "for", "(", "String", "label", ":", "labels", ")", "{", "sendToTagged", "(", "message", ",", "label", ")", ";", "}", "}" ]
Send message to all connections tagged with all given tags @param message the message @param labels the tag labels
[ "Send", "message", "to", "all", "connections", "tagged", "with", "all", "given", "tags" ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/ws/WebSocketConnectionManager.java#L147-L151
161,456
actframework/actframework
src/main/java/act/ws/WebSocketConnectionManager.java
WebSocketConnectionManager.sendJsonToTagged
public void sendJsonToTagged(Object data, String label) { sendToTagged(JSON.toJSONString(data), label); }
java
public void sendJsonToTagged(Object data, String label) { sendToTagged(JSON.toJSONString(data), label); }
[ "public", "void", "sendJsonToTagged", "(", "Object", "data", ",", "String", "label", ")", "{", "sendToTagged", "(", "JSON", ".", "toJSONString", "(", "data", ")", ",", "label", ")", ";", "}" ]
Send JSON representation of given data object to all connections tagged with given label @param data the data object @param label the tag label
[ "Send", "JSON", "representation", "of", "given", "data", "object", "to", "all", "connections", "tagged", "with", "given", "label" ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/ws/WebSocketConnectionManager.java#L170-L172
161,457
actframework/actframework
src/main/java/act/ws/WebSocketConnectionManager.java
WebSocketConnectionManager.sendJsonToTagged
public void sendJsonToTagged(Object data, String ... labels) { for (String label : labels) { sendJsonToTagged(data, label); } }
java
public void sendJsonToTagged(Object data, String ... labels) { for (String label : labels) { sendJsonToTagged(data, label); } }
[ "public", "void", "sendJsonToTagged", "(", "Object", "data", ",", "String", "...", "labels", ")", "{", "for", "(", "String", "label", ":", "labels", ")", "{", "sendJsonToTagged", "(", "data", ",", "label", ")", ";", "}", "}" ]
Send JSON representation of given data object to all connections tagged with all give tag labels @param data the data object @param labels the tag labels
[ "Send", "JSON", "representation", "of", "given", "data", "object", "to", "all", "connections", "tagged", "with", "all", "give", "tag", "labels" ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/ws/WebSocketConnectionManager.java#L179-L183
161,458
actframework/actframework
src/main/java/act/ws/WebSocketConnectionManager.java
WebSocketConnectionManager.sendJsonToUser
public void sendJsonToUser(Object data, String username) { sendToUser(JSON.toJSONString(data), username); }
java
public void sendJsonToUser(Object data, String username) { sendToUser(JSON.toJSONString(data), username); }
[ "public", "void", "sendJsonToUser", "(", "Object", "data", ",", "String", "username", ")", "{", "sendToUser", "(", "JSON", ".", "toJSONString", "(", "data", ")", ",", "username", ")", ";", "}" ]
Send JSON representation of given data object to all connections of a user @param data the data object @param username the username
[ "Send", "JSON", "representation", "of", "given", "data", "object", "to", "all", "connections", "of", "a", "user" ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/ws/WebSocketConnectionManager.java#L210-L212
161,459
actframework/actframework
src/main/java/act/SysUtilAdmin.java
SysUtilAdmin.isBinary
private static boolean isBinary(InputStream in) { try { int size = in.available(); if (size > 1024) size = 1024; byte[] data = new byte[size]; in.read(data); in.close(); int ascii = 0; int other = 0; for (int i = 0; i < data.length; i++) { byte b = data[i]; if (b < 0x09) return true; if (b == 0x09 || b == 0x0A || b == 0x0C || b == 0x0D) ascii++; else if (b >= 0x20 && b <= 0x7E) ascii++; else other++; } return other != 0 && 100 * other / (ascii + other) > 95; } catch (IOException e) { throw E.ioException(e); } }
java
private static boolean isBinary(InputStream in) { try { int size = in.available(); if (size > 1024) size = 1024; byte[] data = new byte[size]; in.read(data); in.close(); int ascii = 0; int other = 0; for (int i = 0; i < data.length; i++) { byte b = data[i]; if (b < 0x09) return true; if (b == 0x09 || b == 0x0A || b == 0x0C || b == 0x0D) ascii++; else if (b >= 0x20 && b <= 0x7E) ascii++; else other++; } return other != 0 && 100 * other / (ascii + other) > 95; } catch (IOException e) { throw E.ioException(e); } }
[ "private", "static", "boolean", "isBinary", "(", "InputStream", "in", ")", "{", "try", "{", "int", "size", "=", "in", ".", "available", "(", ")", ";", "if", "(", "size", ">", "1024", ")", "size", "=", "1024", ";", "byte", "[", "]", "data", "=", "new", "byte", "[", "size", "]", ";", "in", ".", "read", "(", "data", ")", ";", "in", ".", "close", "(", ")", ";", "int", "ascii", "=", "0", ";", "int", "other", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "data", ".", "length", ";", "i", "++", ")", "{", "byte", "b", "=", "data", "[", "i", "]", ";", "if", "(", "b", "<", "0x09", ")", "return", "true", ";", "if", "(", "b", "==", "0x09", "||", "b", "==", "0x0A", "||", "b", "==", "0x0C", "||", "b", "==", "0x0D", ")", "ascii", "++", ";", "else", "if", "(", "b", ">=", "0x20", "&&", "b", "<=", "0x7E", ")", "ascii", "++", ";", "else", "other", "++", ";", "}", "return", "other", "!=", "0", "&&", "100", "*", "other", "/", "(", "ascii", "+", "other", ")", ">", "95", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "E", ".", "ioException", "(", "e", ")", ";", "}", "}" ]
Guess whether given file is binary. Just checks for anything under 0x09.
[ "Guess", "whether", "given", "file", "is", "binary", ".", "Just", "checks", "for", "anything", "under", "0x09", "." ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/SysUtilAdmin.java#L359-L384
161,460
actframework/actframework
src/main/java/act/apidoc/javadoc/Javadoc.java
Javadoc.toText
public String toText() { StringBuilder sb = new StringBuilder(); if (!description.isEmpty()) { sb.append(description.toText()); sb.append(EOL); } if (!blockTags.isEmpty()) { sb.append(EOL); } for (JavadocBlockTag tag : blockTags) { sb.append(tag.toText()).append(EOL); } return sb.toString(); }
java
public String toText() { StringBuilder sb = new StringBuilder(); if (!description.isEmpty()) { sb.append(description.toText()); sb.append(EOL); } if (!blockTags.isEmpty()) { sb.append(EOL); } for (JavadocBlockTag tag : blockTags) { sb.append(tag.toText()).append(EOL); } return sb.toString(); }
[ "public", "String", "toText", "(", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "if", "(", "!", "description", ".", "isEmpty", "(", ")", ")", "{", "sb", ".", "append", "(", "description", ".", "toText", "(", ")", ")", ";", "sb", ".", "append", "(", "EOL", ")", ";", "}", "if", "(", "!", "blockTags", ".", "isEmpty", "(", ")", ")", "{", "sb", ".", "append", "(", "EOL", ")", ";", "}", "for", "(", "JavadocBlockTag", "tag", ":", "blockTags", ")", "{", "sb", ".", "append", "(", "tag", ".", "toText", "(", ")", ")", ".", "append", "(", "EOL", ")", ";", "}", "return", "sb", ".", "toString", "(", ")", ";", "}" ]
Return the text content of the document. It does not containing trailing spaces and asterisks at the start of the line.
[ "Return", "the", "text", "content", "of", "the", "document", ".", "It", "does", "not", "containing", "trailing", "spaces", "and", "asterisks", "at", "the", "start", "of", "the", "line", "." ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/apidoc/javadoc/Javadoc.java#L82-L95
161,461
actframework/actframework
src/main/java/act/apidoc/javadoc/Javadoc.java
Javadoc.toComment
public JavadocComment toComment(String indentation) { for (char c : indentation.toCharArray()) { if (!Character.isWhitespace(c)) { throw new IllegalArgumentException("The indentation string should be composed only by whitespace characters"); } } StringBuilder sb = new StringBuilder(); sb.append(EOL); final String text = toText(); if (!text.isEmpty()) { for (String line : text.split(EOL)) { sb.append(indentation); sb.append(" * "); sb.append(line); sb.append(EOL); } } sb.append(indentation); sb.append(" "); return new JavadocComment(sb.toString()); }
java
public JavadocComment toComment(String indentation) { for (char c : indentation.toCharArray()) { if (!Character.isWhitespace(c)) { throw new IllegalArgumentException("The indentation string should be composed only by whitespace characters"); } } StringBuilder sb = new StringBuilder(); sb.append(EOL); final String text = toText(); if (!text.isEmpty()) { for (String line : text.split(EOL)) { sb.append(indentation); sb.append(" * "); sb.append(line); sb.append(EOL); } } sb.append(indentation); sb.append(" "); return new JavadocComment(sb.toString()); }
[ "public", "JavadocComment", "toComment", "(", "String", "indentation", ")", "{", "for", "(", "char", "c", ":", "indentation", ".", "toCharArray", "(", ")", ")", "{", "if", "(", "!", "Character", ".", "isWhitespace", "(", "c", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"The indentation string should be composed only by whitespace characters\"", ")", ";", "}", "}", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "sb", ".", "append", "(", "EOL", ")", ";", "final", "String", "text", "=", "toText", "(", ")", ";", "if", "(", "!", "text", ".", "isEmpty", "(", ")", ")", "{", "for", "(", "String", "line", ":", "text", ".", "split", "(", "EOL", ")", ")", "{", "sb", ".", "append", "(", "indentation", ")", ";", "sb", ".", "append", "(", "\" * \"", ")", ";", "sb", ".", "append", "(", "line", ")", ";", "sb", ".", "append", "(", "EOL", ")", ";", "}", "}", "sb", ".", "append", "(", "indentation", ")", ";", "sb", ".", "append", "(", "\" \"", ")", ";", "return", "new", "JavadocComment", "(", "sb", ".", "toString", "(", ")", ")", ";", "}" ]
Create a JavadocComment, by formatting the text of the Javadoc using the given indentation.
[ "Create", "a", "JavadocComment", "by", "formatting", "the", "text", "of", "the", "Javadoc", "using", "the", "given", "indentation", "." ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/apidoc/javadoc/Javadoc.java#L107-L127
161,462
actframework/actframework
src/main/java/act/view/ViewManager.java
ViewManager.isTemplatePath
public static boolean isTemplatePath(String string) { int sz = string.length(); if (sz == 0) { return true; } for (int i = 0; i < sz; ++i) { char c = string.charAt(i); switch (c) { case ' ': case '\t': case '\b': case '<': case '>': case '(': case ')': case '[': case ']': case '{': case '}': case '!': case '@': case '#': case '*': case '?': case '%': case '|': case ',': case ':': case ';': case '^': case '&': return false; } } return true; }
java
public static boolean isTemplatePath(String string) { int sz = string.length(); if (sz == 0) { return true; } for (int i = 0; i < sz; ++i) { char c = string.charAt(i); switch (c) { case ' ': case '\t': case '\b': case '<': case '>': case '(': case ')': case '[': case ']': case '{': case '}': case '!': case '@': case '#': case '*': case '?': case '%': case '|': case ',': case ':': case ';': case '^': case '&': return false; } } return true; }
[ "public", "static", "boolean", "isTemplatePath", "(", "String", "string", ")", "{", "int", "sz", "=", "string", ".", "length", "(", ")", ";", "if", "(", "sz", "==", "0", ")", "{", "return", "true", ";", "}", "for", "(", "int", "i", "=", "0", ";", "i", "<", "sz", ";", "++", "i", ")", "{", "char", "c", "=", "string", ".", "charAt", "(", "i", ")", ";", "switch", "(", "c", ")", "{", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Check if a given string is a template path or template content If the string contains anyone the following characters then we assume it is content, otherwise it is path: * space characters * non numeric-alphabetic characters except: ** dot "." ** dollar: "$" @param string the string to be tested @return `true` if the string literal is template content or `false` otherwise
[ "Check", "if", "a", "given", "string", "is", "a", "template", "path", "or", "template", "content" ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/view/ViewManager.java#L350-L385
161,463
actframework/actframework
src/main/java/act/validation/PasswordSpec.java
PasswordSpec.parse
public static PasswordSpec parse(String spec) { char[] ca = spec.toCharArray(); int len = ca.length; illegalIf(0 == len, spec); Builder builder = new Builder(); StringBuilder minBuf = new StringBuilder(); StringBuilder maxBuf = new StringBuilder(); boolean lenSpecStart = false; boolean minPart = false; for (int i = 0; i < len; ++i) { char c = ca[i]; switch (c) { case SPEC_LOWERCASE: illegalIf(lenSpecStart, spec); builder.requireLowercase(); break; case SPEC_UPPERCASE: illegalIf(lenSpecStart, spec); builder.requireUppercase(); break; case SPEC_SPECIAL_CHAR: illegalIf(lenSpecStart, spec); builder.requireSpecialChar(); break; case SPEC_LENSPEC_START: lenSpecStart = true; minPart = true; break; case SPEC_LENSPEC_CLOSE: illegalIf(minPart, spec); lenSpecStart = false; break; case SPEC_LENSPEC_SEP: minPart = false; break; case SPEC_DIGIT: if (!lenSpecStart) { builder.requireDigit(); } else { if (minPart) { minBuf.append(c); } else { maxBuf.append(c); } } break; default: illegalIf(!lenSpecStart || !isDigit(c), spec); if (minPart) { minBuf.append(c); } else { maxBuf.append(c); } } } illegalIf(lenSpecStart, spec); if (minBuf.length() != 0) { builder.minLength(Integer.parseInt(minBuf.toString())); } if (maxBuf.length() != 0) { builder.maxLength(Integer.parseInt(maxBuf.toString())); } return builder; }
java
public static PasswordSpec parse(String spec) { char[] ca = spec.toCharArray(); int len = ca.length; illegalIf(0 == len, spec); Builder builder = new Builder(); StringBuilder minBuf = new StringBuilder(); StringBuilder maxBuf = new StringBuilder(); boolean lenSpecStart = false; boolean minPart = false; for (int i = 0; i < len; ++i) { char c = ca[i]; switch (c) { case SPEC_LOWERCASE: illegalIf(lenSpecStart, spec); builder.requireLowercase(); break; case SPEC_UPPERCASE: illegalIf(lenSpecStart, spec); builder.requireUppercase(); break; case SPEC_SPECIAL_CHAR: illegalIf(lenSpecStart, spec); builder.requireSpecialChar(); break; case SPEC_LENSPEC_START: lenSpecStart = true; minPart = true; break; case SPEC_LENSPEC_CLOSE: illegalIf(minPart, spec); lenSpecStart = false; break; case SPEC_LENSPEC_SEP: minPart = false; break; case SPEC_DIGIT: if (!lenSpecStart) { builder.requireDigit(); } else { if (minPart) { minBuf.append(c); } else { maxBuf.append(c); } } break; default: illegalIf(!lenSpecStart || !isDigit(c), spec); if (minPart) { minBuf.append(c); } else { maxBuf.append(c); } } } illegalIf(lenSpecStart, spec); if (minBuf.length() != 0) { builder.minLength(Integer.parseInt(minBuf.toString())); } if (maxBuf.length() != 0) { builder.maxLength(Integer.parseInt(maxBuf.toString())); } return builder; }
[ "public", "static", "PasswordSpec", "parse", "(", "String", "spec", ")", "{", "char", "[", "]", "ca", "=", "spec", ".", "toCharArray", "(", ")", ";", "int", "len", "=", "ca", ".", "length", ";", "illegalIf", "(", "0", "==", "len", ",", "spec", ")", ";", "Builder", "builder", "=", "new", "Builder", "(", ")", ";", "StringBuilder", "minBuf", "=", "new", "StringBuilder", "(", ")", ";", "StringBuilder", "maxBuf", "=", "new", "StringBuilder", "(", ")", ";", "boolean", "lenSpecStart", "=", "false", ";", "boolean", "minPart", "=", "false", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "len", ";", "++", "i", ")", "{", "char", "c", "=", "ca", "[", "i", "]", ";", "switch", "(", "c", ")", "{", "case", "SPEC_LOWERCASE", ":", "illegalIf", "(", "lenSpecStart", ",", "spec", ")", ";", "builder", ".", "requireLowercase", "(", ")", ";", "break", ";", "case", "SPEC_UPPERCASE", ":", "illegalIf", "(", "lenSpecStart", ",", "spec", ")", ";", "builder", ".", "requireUppercase", "(", ")", ";", "break", ";", "case", "SPEC_SPECIAL_CHAR", ":", "illegalIf", "(", "lenSpecStart", ",", "spec", ")", ";", "builder", ".", "requireSpecialChar", "(", ")", ";", "break", ";", "case", "SPEC_LENSPEC_START", ":", "lenSpecStart", "=", "true", ";", "minPart", "=", "true", ";", "break", ";", "case", "SPEC_LENSPEC_CLOSE", ":", "illegalIf", "(", "minPart", ",", "spec", ")", ";", "lenSpecStart", "=", "false", ";", "break", ";", "case", "SPEC_LENSPEC_SEP", ":", "minPart", "=", "false", ";", "break", ";", "case", "SPEC_DIGIT", ":", "if", "(", "!", "lenSpecStart", ")", "{", "builder", ".", "requireDigit", "(", ")", ";", "}", "else", "{", "if", "(", "minPart", ")", "{", "minBuf", ".", "append", "(", "c", ")", ";", "}", "else", "{", "maxBuf", ".", "append", "(", "c", ")", ";", "}", "}", "break", ";", "default", ":", "illegalIf", "(", "!", "lenSpecStart", "||", "!", "isDigit", "(", "c", ")", ",", "spec", ")", ";", "if", "(", "minPart", ")", "{", "minBuf", ".", "append", "(", "c", ")", ";", "}", "else", "{", "maxBuf", ".", "append", "(", "c", ")", ";", "}", "}", "}", "illegalIf", "(", "lenSpecStart", ",", "spec", ")", ";", "if", "(", "minBuf", ".", "length", "(", ")", "!=", "0", ")", "{", "builder", ".", "minLength", "(", "Integer", ".", "parseInt", "(", "minBuf", ".", "toString", "(", ")", ")", ")", ";", "}", "if", "(", "maxBuf", ".", "length", "(", ")", "!=", "0", ")", "{", "builder", ".", "maxLength", "(", "Integer", ".", "parseInt", "(", "maxBuf", ".", "toString", "(", ")", ")", ")", ";", "}", "return", "builder", ";", "}" ]
Parse a string representation of password spec. A password spec string should be `<trait spec><length spec>`. Where "trait spec" should be a composition of * `a` - indicate lowercase letter required * `A` - indicate uppercase letter required * `0` - indicate digit letter required * `#` - indicate special character required "length spec" should be `[min,max]` where `max` can be omitted. Here are examples of valid "length spec": * `[6,20]` // min length: 6, max length: 20 * `[8,]` // min length: 8, max length: unlimited And examples of invalid "length spec": * `[8]` // "," required after min part * `[a,f]` // min and max part needs to be decimal digit(s) * `[3,9)` // length spec must be started with `[` and end with `]` @param spec a string representation of password spec @return a {@link PasswordSpec} instance
[ "Parse", "a", "string", "representation", "of", "password", "spec", "." ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/validation/PasswordSpec.java#L285-L348
161,464
actframework/actframework
src/main/java/act/xio/WebSocketConnectionHandler.java
WebSocketConnectionHandler._onConnect
protected final void _onConnect(WebSocketContext context) { if (null != connectionListener) { connectionListener.onConnect(context); } connectionListenerManager.notifyFreeListeners(context, false); Act.eventBus().emit(new WebSocketConnectEvent(context)); }
java
protected final void _onConnect(WebSocketContext context) { if (null != connectionListener) { connectionListener.onConnect(context); } connectionListenerManager.notifyFreeListeners(context, false); Act.eventBus().emit(new WebSocketConnectEvent(context)); }
[ "protected", "final", "void", "_onConnect", "(", "WebSocketContext", "context", ")", "{", "if", "(", "null", "!=", "connectionListener", ")", "{", "connectionListener", ".", "onConnect", "(", "context", ")", ";", "}", "connectionListenerManager", ".", "notifyFreeListeners", "(", "context", ",", "false", ")", ";", "Act", ".", "eventBus", "(", ")", ".", "emit", "(", "new", "WebSocketConnectEvent", "(", "context", ")", ")", ";", "}" ]
Called by implementation class once websocket connection established at networking layer. @param context the websocket context
[ "Called", "by", "implementation", "class", "once", "websocket", "connection", "established", "at", "networking", "layer", "." ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/xio/WebSocketConnectionHandler.java#L186-L192
161,465
actframework/actframework
src/main/java/act/util/IdGenerator.java
IdGenerator.genId
public String genId() { S.Buffer sb = S.newBuffer(); sb.a(longEncoder.longToStr(nodeIdProvider.nodeId())) .a(longEncoder.longToStr(startIdProvider.startId())) .a(longEncoder.longToStr(sequenceProvider.seqId())); return sb.toString(); }
java
public String genId() { S.Buffer sb = S.newBuffer(); sb.a(longEncoder.longToStr(nodeIdProvider.nodeId())) .a(longEncoder.longToStr(startIdProvider.startId())) .a(longEncoder.longToStr(sequenceProvider.seqId())); return sb.toString(); }
[ "public", "String", "genId", "(", ")", "{", "S", ".", "Buffer", "sb", "=", "S", ".", "newBuffer", "(", ")", ";", "sb", ".", "a", "(", "longEncoder", ".", "longToStr", "(", "nodeIdProvider", ".", "nodeId", "(", ")", ")", ")", ".", "a", "(", "longEncoder", ".", "longToStr", "(", "startIdProvider", ".", "startId", "(", ")", ")", ")", ".", "a", "(", "longEncoder", ".", "longToStr", "(", "sequenceProvider", ".", "seqId", "(", ")", ")", ")", ";", "return", "sb", ".", "toString", "(", ")", ";", "}" ]
Generate a unique ID across the cluster @return generated ID
[ "Generate", "a", "unique", "ID", "across", "the", "cluster" ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/util/IdGenerator.java#L388-L394
161,466
actframework/actframework
src/main/java/act/app/AppServiceRegistry.java
AppServiceRegistry.bulkRegisterSingleton
synchronized void bulkRegisterSingleton() { for (Map.Entry<Class<? extends AppService>, AppService> entry : registry.entrySet()) { if (isSingletonService(entry.getKey())) { app.registerSingleton(entry.getKey(), entry.getValue()); } } }
java
synchronized void bulkRegisterSingleton() { for (Map.Entry<Class<? extends AppService>, AppService> entry : registry.entrySet()) { if (isSingletonService(entry.getKey())) { app.registerSingleton(entry.getKey(), entry.getValue()); } } }
[ "synchronized", "void", "bulkRegisterSingleton", "(", ")", "{", "for", "(", "Map", ".", "Entry", "<", "Class", "<", "?", "extends", "AppService", ">", ",", "AppService", ">", "entry", ":", "registry", ".", "entrySet", "(", ")", ")", "{", "if", "(", "isSingletonService", "(", "entry", ".", "getKey", "(", ")", ")", ")", "{", "app", ".", "registerSingleton", "(", "entry", ".", "getKey", "(", ")", ",", "entry", ".", "getValue", "(", ")", ")", ";", "}", "}", "}" ]
Called when app's singleton registry has been initialized
[ "Called", "when", "app", "s", "singleton", "registry", "has", "been", "initialized" ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/app/AppServiceRegistry.java#L74-L80
161,467
actframework/actframework
src/main/java/act/app/ActionContext.java
ActionContext.paramKeys
@Override public Set<String> paramKeys() { Set<String> set = new HashSet<String>(); set.addAll(C.<String>list(request.paramNames())); set.addAll(extraParams.keySet()); set.addAll(bodyParams().keySet()); set.remove("_method"); set.remove("_body"); return set; }
java
@Override public Set<String> paramKeys() { Set<String> set = new HashSet<String>(); set.addAll(C.<String>list(request.paramNames())); set.addAll(extraParams.keySet()); set.addAll(bodyParams().keySet()); set.remove("_method"); set.remove("_body"); return set; }
[ "@", "Override", "public", "Set", "<", "String", ">", "paramKeys", "(", ")", "{", "Set", "<", "String", ">", "set", "=", "new", "HashSet", "<", "String", ">", "(", ")", ";", "set", ".", "addAll", "(", "C", ".", "<", "String", ">", "list", "(", "request", ".", "paramNames", "(", ")", ")", ")", ";", "set", ".", "addAll", "(", "extraParams", ".", "keySet", "(", ")", ")", ";", "set", ".", "addAll", "(", "bodyParams", "(", ")", ".", "keySet", "(", ")", ")", ";", "set", ".", "remove", "(", "\"_method\"", ")", ";", "set", ".", "remove", "(", "\"_body\"", ")", ";", "return", "set", ";", "}" ]
Get all parameter keys. @return a set of parameter keys
[ "Get", "all", "parameter", "keys", "." ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/app/ActionContext.java#L739-L748
161,468
actframework/actframework
src/main/java/act/app/ActionContext.java
ActionContext.applyContentType
public ActionContext applyContentType(Result result) { if (!result.status().isError()) { return applyContentType(); } return applyContentType(contentTypeForErrorResult(req())); }
java
public ActionContext applyContentType(Result result) { if (!result.status().isError()) { return applyContentType(); } return applyContentType(contentTypeForErrorResult(req())); }
[ "public", "ActionContext", "applyContentType", "(", "Result", "result", ")", "{", "if", "(", "!", "result", ".", "status", "(", ")", ".", "isError", "(", ")", ")", "{", "return", "applyContentType", "(", ")", ";", "}", "return", "applyContentType", "(", "contentTypeForErrorResult", "(", "req", "(", ")", ")", ")", ";", "}" ]
Apply content type to response with result provided. If `result` is an error then it might not apply content type as requested: * If request is not ajax request, then use `text/html` * If request is ajax request then apply requested content type only when `json` or `xml` is requested * otherwise use `text/html` @param result the result used to check if it is error result @return this `ActionContext`.
[ "Apply", "content", "type", "to", "response", "with", "result", "provided", "." ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/app/ActionContext.java#L935-L940
161,469
actframework/actframework
src/main/java/act/app/ActionContext.java
ActionContext.cached
public <T> T cached(String key) { H.Session sess = session(); if (null != sess) { return sess.cached(key); } else { return app().cache().get(key); } }
java
public <T> T cached(String key) { H.Session sess = session(); if (null != sess) { return sess.cached(key); } else { return app().cache().get(key); } }
[ "public", "<", "T", ">", "T", "cached", "(", "String", "key", ")", "{", "H", ".", "Session", "sess", "=", "session", "(", ")", ";", "if", "(", "null", "!=", "sess", ")", "{", "return", "sess", ".", "cached", "(", "key", ")", ";", "}", "else", "{", "return", "app", "(", ")", ".", "cache", "(", ")", ".", "get", "(", "key", ")", ";", "}", "}" ]
Return cached object by key. The key will be concatenated with current session id when fetching the cached object @param key @param <T> the object type @return the cached object
[ "Return", "cached", "object", "by", "key", ".", "The", "key", "will", "be", "concatenated", "with", "current", "session", "id", "when", "fetching", "the", "cached", "object" ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/app/ActionContext.java#L1089-L1096
161,470
actframework/actframework
src/main/java/act/app/ActionContext.java
ActionContext.cache
public void cache(String key, Object obj) { H.Session sess = session(); if (null != sess) { sess.cache(key, obj); } else { app().cache().put(key, obj); } }
java
public void cache(String key, Object obj) { H.Session sess = session(); if (null != sess) { sess.cache(key, obj); } else { app().cache().put(key, obj); } }
[ "public", "void", "cache", "(", "String", "key", ",", "Object", "obj", ")", "{", "H", ".", "Session", "sess", "=", "session", "(", ")", ";", "if", "(", "null", "!=", "sess", ")", "{", "sess", ".", "cache", "(", "key", ",", "obj", ")", ";", "}", "else", "{", "app", "(", ")", ".", "cache", "(", ")", ".", "put", "(", "key", ",", "obj", ")", ";", "}", "}" ]
Add an object into cache by key. The key will be used in conjunction with session id if there is a session instance @param key the key to index the object within the cache @param obj the object to be cached
[ "Add", "an", "object", "into", "cache", "by", "key", ".", "The", "key", "will", "be", "used", "in", "conjunction", "with", "session", "id", "if", "there", "is", "a", "session", "instance" ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/app/ActionContext.java#L1107-L1114
161,471
actframework/actframework
src/main/java/act/app/ActionContext.java
ActionContext.cache
public void cache(String key, Object obj, int expiration) { H.Session session = this.session; if (null != session) { session.cache(key, obj, expiration); } else { app().cache().put(key, obj, expiration); } }
java
public void cache(String key, Object obj, int expiration) { H.Session session = this.session; if (null != session) { session.cache(key, obj, expiration); } else { app().cache().put(key, obj, expiration); } }
[ "public", "void", "cache", "(", "String", "key", ",", "Object", "obj", ",", "int", "expiration", ")", "{", "H", ".", "Session", "session", "=", "this", ".", "session", ";", "if", "(", "null", "!=", "session", ")", "{", "session", ".", "cache", "(", "key", ",", "obj", ",", "expiration", ")", ";", "}", "else", "{", "app", "(", ")", ".", "cache", "(", ")", ".", "put", "(", "key", ",", "obj", ",", "expiration", ")", ";", "}", "}" ]
Add an object into cache by key with expiration time specified @param key the key to index the object within the cache @param obj the object to be cached @param expiration the seconds after which the object will be evicted from the cache
[ "Add", "an", "object", "into", "cache", "by", "key", "with", "expiration", "time", "specified" ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/app/ActionContext.java#L1126-L1133
161,472
actframework/actframework
src/main/java/act/app/ActionContext.java
ActionContext.evictCache
public void evictCache(String key) { H.Session sess = session(); if (null != sess) { sess.evict(key); } else { app().cache().evict(key); } }
java
public void evictCache(String key) { H.Session sess = session(); if (null != sess) { sess.evict(key); } else { app().cache().evict(key); } }
[ "public", "void", "evictCache", "(", "String", "key", ")", "{", "H", ".", "Session", "sess", "=", "session", "(", ")", ";", "if", "(", "null", "!=", "sess", ")", "{", "sess", ".", "evict", "(", "key", ")", ";", "}", "else", "{", "app", "(", ")", ".", "cache", "(", ")", ".", "evict", "(", "key", ")", ";", "}", "}" ]
Evict cached object @param key the key indexed the cached object to be evicted
[ "Evict", "cached", "object" ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/app/ActionContext.java#L1189-L1196
161,473
actframework/actframework
src/main/java/act/app/ActionContext.java
ActionContext.login
public void login(Object userIdentifier) { session().put(config().sessionKeyUsername(), userIdentifier); app().eventBus().trigger(new LoginEvent(userIdentifier.toString())); }
java
public void login(Object userIdentifier) { session().put(config().sessionKeyUsername(), userIdentifier); app().eventBus().trigger(new LoginEvent(userIdentifier.toString())); }
[ "public", "void", "login", "(", "Object", "userIdentifier", ")", "{", "session", "(", ")", ".", "put", "(", "config", "(", ")", ".", "sessionKeyUsername", "(", ")", ",", "userIdentifier", ")", ";", "app", "(", ")", ".", "eventBus", "(", ")", ".", "trigger", "(", "new", "LoginEvent", "(", "userIdentifier", ".", "toString", "(", ")", ")", ")", ";", "}" ]
Update the context session to mark a user logged in @param userIdentifier the user identifier, could be either userId or username
[ "Update", "the", "context", "session", "to", "mark", "a", "user", "logged", "in" ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/app/ActionContext.java#L1268-L1271
161,474
actframework/actframework
src/main/java/act/app/ActionContext.java
ActionContext.loginAndRedirectBack
public void loginAndRedirectBack(Object userIdentifier, String defaultLandingUrl) { login(userIdentifier); RedirectToLoginUrl.redirectToOriginalUrl(this, defaultLandingUrl); }
java
public void loginAndRedirectBack(Object userIdentifier, String defaultLandingUrl) { login(userIdentifier); RedirectToLoginUrl.redirectToOriginalUrl(this, defaultLandingUrl); }
[ "public", "void", "loginAndRedirectBack", "(", "Object", "userIdentifier", ",", "String", "defaultLandingUrl", ")", "{", "login", "(", "userIdentifier", ")", ";", "RedirectToLoginUrl", ".", "redirectToOriginalUrl", "(", "this", ",", "defaultLandingUrl", ")", ";", "}" ]
Login the user and redirect back to original URL. If no original URL found then redirect to `defaultLandingUrl`. @param userIdentifier the user identifier, could be either userId or username @param defaultLandingUrl the URL to be redirected if original URL not found
[ "Login", "the", "user", "and", "redirect", "back", "to", "original", "URL", ".", "If", "no", "original", "URL", "found", "then", "redirect", "to", "defaultLandingUrl", "." ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/app/ActionContext.java#L1293-L1296
161,475
actframework/actframework
src/main/java/act/app/ActionContext.java
ActionContext.logout
public void logout() { String userIdentifier = session.get(config().sessionKeyUsername()); SessionManager sessionManager = app().sessionManager(); sessionManager.logout(session); if (S.notBlank(userIdentifier)) { app().eventBus().trigger(new LogoutEvent(userIdentifier)); } }
java
public void logout() { String userIdentifier = session.get(config().sessionKeyUsername()); SessionManager sessionManager = app().sessionManager(); sessionManager.logout(session); if (S.notBlank(userIdentifier)) { app().eventBus().trigger(new LogoutEvent(userIdentifier)); } }
[ "public", "void", "logout", "(", ")", "{", "String", "userIdentifier", "=", "session", ".", "get", "(", "config", "(", ")", ".", "sessionKeyUsername", "(", ")", ")", ";", "SessionManager", "sessionManager", "=", "app", "(", ")", ".", "sessionManager", "(", ")", ";", "sessionManager", ".", "logout", "(", "session", ")", ";", "if", "(", "S", ".", "notBlank", "(", "userIdentifier", ")", ")", "{", "app", "(", ")", ".", "eventBus", "(", ")", ".", "trigger", "(", "new", "LogoutEvent", "(", "userIdentifier", ")", ")", ";", "}", "}" ]
Logout the current session. After calling this method, the session will be cleared
[ "Logout", "the", "current", "session", ".", "After", "calling", "this", "method", "the", "session", "will", "be", "cleared" ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/app/ActionContext.java#L1315-L1322
161,476
actframework/actframework
src/main/java/act/job/JobContext.java
JobContext.init
public static void init(String jobId) { JobContext parent = current_.get(); JobContext ctx = new JobContext(parent); current_.set(ctx); // don't call setJobId(String) // as it will trigger listeners -- TODO fix me ctx.jobId = jobId; if (null == parent) { Act.eventBus().trigger(new JobContextInitialized(ctx)); } }
java
public static void init(String jobId) { JobContext parent = current_.get(); JobContext ctx = new JobContext(parent); current_.set(ctx); // don't call setJobId(String) // as it will trigger listeners -- TODO fix me ctx.jobId = jobId; if (null == parent) { Act.eventBus().trigger(new JobContextInitialized(ctx)); } }
[ "public", "static", "void", "init", "(", "String", "jobId", ")", "{", "JobContext", "parent", "=", "current_", ".", "get", "(", ")", ";", "JobContext", "ctx", "=", "new", "JobContext", "(", "parent", ")", ";", "current_", ".", "set", "(", "ctx", ")", ";", "// don't call setJobId(String)", "// as it will trigger listeners -- TODO fix me", "ctx", ".", "jobId", "=", "jobId", ";", "if", "(", "null", "==", "parent", ")", "{", "Act", ".", "eventBus", "(", ")", ".", "trigger", "(", "new", "JobContextInitialized", "(", "ctx", ")", ")", ";", "}", "}" ]
make it public for CLI interaction to reuse JobContext
[ "make", "it", "public", "for", "CLI", "interaction", "to", "reuse", "JobContext" ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/job/JobContext.java#L120-L130
161,477
actframework/actframework
src/main/java/act/job/JobContext.java
JobContext.clear
public static void clear() { JobContext ctx = current_.get(); if (null != ctx) { ctx.bag_.clear(); JobContext parent = ctx.parent; if (null != parent) { current_.set(parent); ctx.parent = null; } else { current_.remove(); Act.eventBus().trigger(new JobContextDestroyed(ctx)); } } }
java
public static void clear() { JobContext ctx = current_.get(); if (null != ctx) { ctx.bag_.clear(); JobContext parent = ctx.parent; if (null != parent) { current_.set(parent); ctx.parent = null; } else { current_.remove(); Act.eventBus().trigger(new JobContextDestroyed(ctx)); } } }
[ "public", "static", "void", "clear", "(", ")", "{", "JobContext", "ctx", "=", "current_", ".", "get", "(", ")", ";", "if", "(", "null", "!=", "ctx", ")", "{", "ctx", ".", "bag_", ".", "clear", "(", ")", ";", "JobContext", "parent", "=", "ctx", ".", "parent", ";", "if", "(", "null", "!=", "parent", ")", "{", "current_", ".", "set", "(", "parent", ")", ";", "ctx", ".", "parent", "=", "null", ";", "}", "else", "{", "current_", ".", "remove", "(", ")", ";", "Act", ".", "eventBus", "(", ")", ".", "trigger", "(", "new", "JobContextDestroyed", "(", "ctx", ")", ")", ";", "}", "}", "}" ]
Clear JobContext of current thread
[ "Clear", "JobContext", "of", "current", "thread" ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/job/JobContext.java#L135-L148
161,478
actframework/actframework
src/main/java/act/job/JobContext.java
JobContext.get
public static <T> T get(String key, Class<T> clz) { return (T)m().get(key); }
java
public static <T> T get(String key, Class<T> clz) { return (T)m().get(key); }
[ "public", "static", "<", "T", ">", "T", "get", "(", "String", "key", ",", "Class", "<", "T", ">", "clz", ")", "{", "return", "(", "T", ")", "m", "(", ")", ".", "get", "(", "key", ")", ";", "}" ]
Generic version of getting value by key from the JobContext of current thread @param key the key @param clz the val class @param <T> the val type @return the value
[ "Generic", "version", "of", "getting", "value", "by", "key", "from", "the", "JobContext", "of", "current", "thread" ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/job/JobContext.java#L167-L169
161,479
actframework/actframework
src/main/java/act/job/JobContext.java
JobContext.copy
static JobContext copy() { JobContext current = current_.get(); //JobContext ctxt = new JobContext(keepParent ? current : null); JobContext ctxt = new JobContext(null); if (null != current) { ctxt.bag_.putAll(current.bag_); } return ctxt; }
java
static JobContext copy() { JobContext current = current_.get(); //JobContext ctxt = new JobContext(keepParent ? current : null); JobContext ctxt = new JobContext(null); if (null != current) { ctxt.bag_.putAll(current.bag_); } return ctxt; }
[ "static", "JobContext", "copy", "(", ")", "{", "JobContext", "current", "=", "current_", ".", "get", "(", ")", ";", "//JobContext ctxt = new JobContext(keepParent ? current : null);", "JobContext", "ctxt", "=", "new", "JobContext", "(", "null", ")", ";", "if", "(", "null", "!=", "current", ")", "{", "ctxt", ".", "bag_", ".", "putAll", "(", "current", ".", "bag_", ")", ";", "}", "return", "ctxt", ";", "}" ]
Make a copy of JobContext of current thread @return the copy of current job context or an empty job context
[ "Make", "a", "copy", "of", "JobContext", "of", "current", "thread" ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/job/JobContext.java#L192-L200
161,480
actframework/actframework
src/main/java/act/job/JobContext.java
JobContext.loadFromOrigin
static void loadFromOrigin(JobContext origin) { if (origin.bag_.isEmpty()) { return; } ActContext<?> actContext = ActContext.Base.currentContext(); if (null != actContext) { Locale locale = (Locale) origin.bag_.get("locale"); if (null != locale) { actContext.locale(locale); } H.Session session = (H.Session) origin.bag_.get("session"); if (null != session) { actContext.attribute("__session", session); } } }
java
static void loadFromOrigin(JobContext origin) { if (origin.bag_.isEmpty()) { return; } ActContext<?> actContext = ActContext.Base.currentContext(); if (null != actContext) { Locale locale = (Locale) origin.bag_.get("locale"); if (null != locale) { actContext.locale(locale); } H.Session session = (H.Session) origin.bag_.get("session"); if (null != session) { actContext.attribute("__session", session); } } }
[ "static", "void", "loadFromOrigin", "(", "JobContext", "origin", ")", "{", "if", "(", "origin", ".", "bag_", ".", "isEmpty", "(", ")", ")", "{", "return", ";", "}", "ActContext", "<", "?", ">", "actContext", "=", "ActContext", ".", "Base", ".", "currentContext", "(", ")", ";", "if", "(", "null", "!=", "actContext", ")", "{", "Locale", "locale", "=", "(", "Locale", ")", "origin", ".", "bag_", ".", "get", "(", "\"locale\"", ")", ";", "if", "(", "null", "!=", "locale", ")", "{", "actContext", ".", "locale", "(", "locale", ")", ";", "}", "H", ".", "Session", "session", "=", "(", "H", ".", "Session", ")", "origin", ".", "bag_", ".", "get", "(", "\"session\"", ")", ";", "if", "(", "null", "!=", "session", ")", "{", "actContext", ".", "attribute", "(", "\"__session\"", ",", "session", ")", ";", "}", "}", "}" ]
Initialize current thread's JobContext using specified copy @param origin the original job context
[ "Initialize", "current", "thread", "s", "JobContext", "using", "specified", "copy" ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/job/JobContext.java#L206-L221
161,481
actframework/actframework
src/main/java/act/controller/captcha/CaptchaSession.java
CaptchaSession.getToken
public String getToken() { String id = null == answer ? text : answer; return Act.app().crypto().generateToken(id); }
java
public String getToken() { String id = null == answer ? text : answer; return Act.app().crypto().generateToken(id); }
[ "public", "String", "getToken", "(", ")", "{", "String", "id", "=", "null", "==", "answer", "?", "text", ":", "answer", ";", "return", "Act", ".", "app", "(", ")", ".", "crypto", "(", ")", ".", "generateToken", "(", "id", ")", ";", "}" ]
Returns an encrypted token combined with answer.
[ "Returns", "an", "encrypted", "token", "combined", "with", "answer", "." ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/controller/captcha/CaptchaSession.java#L77-L80
161,482
actframework/actframework
src/main/java/act/app/RouterRegexMacroLookup.java
RouterRegexMacroLookup.expand
public String expand(String macro) { if (!isMacro(macro)) { return macro; } String definition = macros.get(Config.canonical(macro)); if (null == definition) { warn("possible missing definition of macro[%s]", macro); } return null == definition ? macro : definition; }
java
public String expand(String macro) { if (!isMacro(macro)) { return macro; } String definition = macros.get(Config.canonical(macro)); if (null == definition) { warn("possible missing definition of macro[%s]", macro); } return null == definition ? macro : definition; }
[ "public", "String", "expand", "(", "String", "macro", ")", "{", "if", "(", "!", "isMacro", "(", "macro", ")", ")", "{", "return", "macro", ";", "}", "String", "definition", "=", "macros", ".", "get", "(", "Config", ".", "canonical", "(", "macro", ")", ")", ";", "if", "(", "null", "==", "definition", ")", "{", "warn", "(", "\"possible missing definition of macro[%s]\"", ",", "macro", ")", ";", "}", "return", "null", "==", "definition", "?", "macro", ":", "definition", ";", "}" ]
Expand a macro. This will look up the macro definition from {@link #macros} map. If not found then return passed in `macro` itself, otherwise return the macro definition found. **note** if macro definition is not found and the string {@link #isMacro(String) comply to macro name convention}, then a warn level message will be logged. @param macro the macro name @return macro definition or macro itself if no definition found.
[ "Expand", "a", "macro", "." ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/app/RouterRegexMacroLookup.java#L106-L115
161,483
actframework/actframework
src/main/java/act/internal/util/JavaNames.java
JavaNames.isPackageOrClassName
public static boolean isPackageOrClassName(String s) { if (S.blank(s)) { return false; } S.List parts = S.fastSplit(s, "."); if (parts.size() < 2) { return false; } for (String part: parts) { if (!Character.isJavaIdentifierStart(part.charAt(0))) { return false; } for (int i = 1, len = part.length(); i < len; ++i) { if (!Character.isJavaIdentifierPart(part.charAt(i))) { return false; } } } return true; }
java
public static boolean isPackageOrClassName(String s) { if (S.blank(s)) { return false; } S.List parts = S.fastSplit(s, "."); if (parts.size() < 2) { return false; } for (String part: parts) { if (!Character.isJavaIdentifierStart(part.charAt(0))) { return false; } for (int i = 1, len = part.length(); i < len; ++i) { if (!Character.isJavaIdentifierPart(part.charAt(i))) { return false; } } } return true; }
[ "public", "static", "boolean", "isPackageOrClassName", "(", "String", "s", ")", "{", "if", "(", "S", ".", "blank", "(", "s", ")", ")", "{", "return", "false", ";", "}", "S", ".", "List", "parts", "=", "S", ".", "fastSplit", "(", "s", ",", "\".\"", ")", ";", "if", "(", "parts", ".", "size", "(", ")", "<", "2", ")", "{", "return", "false", ";", "}", "for", "(", "String", "part", ":", "parts", ")", "{", "if", "(", "!", "Character", ".", "isJavaIdentifierStart", "(", "part", ".", "charAt", "(", "0", ")", ")", ")", "{", "return", "false", ";", "}", "for", "(", "int", "i", "=", "1", ",", "len", "=", "part", ".", "length", "(", ")", ";", "i", "<", "len", ";", "++", "i", ")", "{", "if", "(", "!", "Character", ".", "isJavaIdentifierPart", "(", "part", ".", "charAt", "(", "i", ")", ")", ")", "{", "return", "false", ";", "}", "}", "}", "return", "true", ";", "}" ]
Check if a given string is a valid java package or class name. This method use the technique documented in [this SO question](https://stackoverflow.com/questions/13557195/how-to-check-if-string-is-a-valid-class-identifier) with the following extensions: * if the string does not contain `.` then assume it is not a valid package or class name @param s the string to be checked @return `true` if `s` is a valid java package or class name
[ "Check", "if", "a", "given", "string", "is", "a", "valid", "java", "package", "or", "class", "name", "." ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/internal/util/JavaNames.java#L45-L64
161,484
actframework/actframework
src/main/java/act/internal/util/JavaNames.java
JavaNames.packageNameOf
public static String packageNameOf(Class<?> clazz) { String name = clazz.getName(); int pos = name.lastIndexOf('.'); E.unexpectedIf(pos < 0, "Class does not have package: " + name); return name.substring(0, pos); }
java
public static String packageNameOf(Class<?> clazz) { String name = clazz.getName(); int pos = name.lastIndexOf('.'); E.unexpectedIf(pos < 0, "Class does not have package: " + name); return name.substring(0, pos); }
[ "public", "static", "String", "packageNameOf", "(", "Class", "<", "?", ">", "clazz", ")", "{", "String", "name", "=", "clazz", ".", "getName", "(", ")", ";", "int", "pos", "=", "name", ".", "lastIndexOf", "(", "'", "'", ")", ";", "E", ".", "unexpectedIf", "(", "pos", "<", "0", ",", "\"Class does not have package: \"", "+", "name", ")", ";", "return", "name", ".", "substring", "(", "0", ",", "pos", ")", ";", "}" ]
Returns package name of a class @param clazz the class @return the package name of the class
[ "Returns", "package", "name", "of", "a", "class" ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/internal/util/JavaNames.java#L74-L79
161,485
actframework/actframework
src/main/java/act/route/RouteInfo.java
RouteInfo.of
public static RouteInfo of(ActionContext context) { H.Method m = context.req().method(); String path = context.req().url(); RequestHandler handler = context.handler(); if (null == handler) { handler = UNKNOWN_HANDLER; } return new RouteInfo(m, path, handler); }
java
public static RouteInfo of(ActionContext context) { H.Method m = context.req().method(); String path = context.req().url(); RequestHandler handler = context.handler(); if (null == handler) { handler = UNKNOWN_HANDLER; } return new RouteInfo(m, path, handler); }
[ "public", "static", "RouteInfo", "of", "(", "ActionContext", "context", ")", "{", "H", ".", "Method", "m", "=", "context", ".", "req", "(", ")", ".", "method", "(", ")", ";", "String", "path", "=", "context", ".", "req", "(", ")", ".", "url", "(", ")", ";", "RequestHandler", "handler", "=", "context", ".", "handler", "(", ")", ";", "if", "(", "null", "==", "handler", ")", "{", "handler", "=", "UNKNOWN_HANDLER", ";", "}", "return", "new", "RouteInfo", "(", "m", ",", "path", ",", "handler", ")", ";", "}" ]
used by Error template
[ "used", "by", "Error", "template" ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/route/RouteInfo.java#L90-L98
161,486
actframework/actframework
src/main/java/act/ws/WebSocketConnectionRegistry.java
WebSocketConnectionRegistry.get
public List<WebSocketConnection> get(String key) { final List<WebSocketConnection> retList = new ArrayList<>(); accept(key, C.F.addTo(retList)); return retList; }
java
public List<WebSocketConnection> get(String key) { final List<WebSocketConnection> retList = new ArrayList<>(); accept(key, C.F.addTo(retList)); return retList; }
[ "public", "List", "<", "WebSocketConnection", ">", "get", "(", "String", "key", ")", "{", "final", "List", "<", "WebSocketConnection", ">", "retList", "=", "new", "ArrayList", "<>", "(", ")", ";", "accept", "(", "key", ",", "C", ".", "F", ".", "addTo", "(", "retList", ")", ")", ";", "return", "retList", ";", "}" ]
Return a list of websocket connection by key @param key the key to find the websocket connection list @return a list of websocket connection or an empty list if no websocket connection found by key
[ "Return", "a", "list", "of", "websocket", "connection", "by", "key" ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/ws/WebSocketConnectionRegistry.java#L50-L54
161,487
actframework/actframework
src/main/java/act/ws/WebSocketConnectionRegistry.java
WebSocketConnectionRegistry.signIn
public void signIn(String key, WebSocketConnection connection) { ConcurrentMap<WebSocketConnection, WebSocketConnection> bag = ensureConnectionList(key); bag.put(connection, connection); }
java
public void signIn(String key, WebSocketConnection connection) { ConcurrentMap<WebSocketConnection, WebSocketConnection> bag = ensureConnectionList(key); bag.put(connection, connection); }
[ "public", "void", "signIn", "(", "String", "key", ",", "WebSocketConnection", "connection", ")", "{", "ConcurrentMap", "<", "WebSocketConnection", ",", "WebSocketConnection", ">", "bag", "=", "ensureConnectionList", "(", "key", ")", ";", "bag", ".", "put", "(", "connection", ",", "connection", ")", ";", "}" ]
Sign in a connection to the registry by key. Note multiple connections can be attached to the same key @param key the key @param connection the websocket connection @see #register(String, WebSocketConnection)
[ "Sign", "in", "a", "connection", "to", "the", "registry", "by", "key", "." ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/ws/WebSocketConnectionRegistry.java#L131-L134
161,488
actframework/actframework
src/main/java/act/ws/WebSocketConnectionRegistry.java
WebSocketConnectionRegistry.signIn
public void signIn(String key, Collection<WebSocketConnection> connections) { if (connections.isEmpty()) { return; } Map<WebSocketConnection, WebSocketConnection> newMap = new HashMap<>(); for (WebSocketConnection conn : connections) { newMap.put(conn, conn); } ConcurrentMap<WebSocketConnection, WebSocketConnection> bag = ensureConnectionList(key); bag.putAll(newMap); }
java
public void signIn(String key, Collection<WebSocketConnection> connections) { if (connections.isEmpty()) { return; } Map<WebSocketConnection, WebSocketConnection> newMap = new HashMap<>(); for (WebSocketConnection conn : connections) { newMap.put(conn, conn); } ConcurrentMap<WebSocketConnection, WebSocketConnection> bag = ensureConnectionList(key); bag.putAll(newMap); }
[ "public", "void", "signIn", "(", "String", "key", ",", "Collection", "<", "WebSocketConnection", ">", "connections", ")", "{", "if", "(", "connections", ".", "isEmpty", "(", ")", ")", "{", "return", ";", "}", "Map", "<", "WebSocketConnection", ",", "WebSocketConnection", ">", "newMap", "=", "new", "HashMap", "<>", "(", ")", ";", "for", "(", "WebSocketConnection", "conn", ":", "connections", ")", "{", "newMap", ".", "put", "(", "conn", ",", "conn", ")", ";", "}", "ConcurrentMap", "<", "WebSocketConnection", ",", "WebSocketConnection", ">", "bag", "=", "ensureConnectionList", "(", "key", ")", ";", "bag", ".", "putAll", "(", "newMap", ")", ";", "}" ]
Sign in a group of connections to the registry by key @param key the key @param connections a collection of websocket connections
[ "Sign", "in", "a", "group", "of", "connections", "to", "the", "registry", "by", "key" ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/ws/WebSocketConnectionRegistry.java#L156-L166
161,489
actframework/actframework
src/main/java/act/ws/WebSocketConnectionRegistry.java
WebSocketConnectionRegistry.signOff
public void signOff(String key, WebSocketConnection connection) { ConcurrentMap<WebSocketConnection, WebSocketConnection> connections = registry.get(key); if (null == connections) { return; } connections.remove(connection); }
java
public void signOff(String key, WebSocketConnection connection) { ConcurrentMap<WebSocketConnection, WebSocketConnection> connections = registry.get(key); if (null == connections) { return; } connections.remove(connection); }
[ "public", "void", "signOff", "(", "String", "key", ",", "WebSocketConnection", "connection", ")", "{", "ConcurrentMap", "<", "WebSocketConnection", ",", "WebSocketConnection", ">", "connections", "=", "registry", ".", "get", "(", "key", ")", ";", "if", "(", "null", "==", "connections", ")", "{", "return", ";", "}", "connections", ".", "remove", "(", "connection", ")", ";", "}" ]
Detach a connection from a key. @param key the key @param connection the connection
[ "Detach", "a", "connection", "from", "a", "key", "." ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/ws/WebSocketConnectionRegistry.java#L203-L209
161,490
actframework/actframework
src/main/java/act/ws/WebSocketConnectionRegistry.java
WebSocketConnectionRegistry.signOff
public void signOff(WebSocketConnection connection) { for (ConcurrentMap<WebSocketConnection, WebSocketConnection> connections : registry.values()) { connections.remove(connection); } }
java
public void signOff(WebSocketConnection connection) { for (ConcurrentMap<WebSocketConnection, WebSocketConnection> connections : registry.values()) { connections.remove(connection); } }
[ "public", "void", "signOff", "(", "WebSocketConnection", "connection", ")", "{", "for", "(", "ConcurrentMap", "<", "WebSocketConnection", ",", "WebSocketConnection", ">", "connections", ":", "registry", ".", "values", "(", ")", ")", "{", "connections", ".", "remove", "(", "connection", ")", ";", "}", "}" ]
Remove a connection from all keys. @param connection the connection
[ "Remove", "a", "connection", "from", "all", "keys", "." ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/ws/WebSocketConnectionRegistry.java#L229-L233
161,491
actframework/actframework
src/main/java/act/ws/WebSocketConnectionRegistry.java
WebSocketConnectionRegistry.signOff
public void signOff(String key, Collection<WebSocketConnection> connections) { if (connections.isEmpty()) { return; } ConcurrentMap<WebSocketConnection, WebSocketConnection> bag = ensureConnectionList(key); bag.keySet().removeAll(connections); }
java
public void signOff(String key, Collection<WebSocketConnection> connections) { if (connections.isEmpty()) { return; } ConcurrentMap<WebSocketConnection, WebSocketConnection> bag = ensureConnectionList(key); bag.keySet().removeAll(connections); }
[ "public", "void", "signOff", "(", "String", "key", ",", "Collection", "<", "WebSocketConnection", ">", "connections", ")", "{", "if", "(", "connections", ".", "isEmpty", "(", ")", ")", "{", "return", ";", "}", "ConcurrentMap", "<", "WebSocketConnection", ",", "WebSocketConnection", ">", "bag", "=", "ensureConnectionList", "(", "key", ")", ";", "bag", ".", "keySet", "(", ")", ".", "removeAll", "(", "connections", ")", ";", "}" ]
Sign off a group of connections from the registry by key @param key the key @param connections a collection of websocket connections
[ "Sign", "off", "a", "group", "of", "connections", "from", "the", "registry", "by", "key" ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/ws/WebSocketConnectionRegistry.java#L243-L249
161,492
actframework/actframework
src/main/java/act/ws/WebSocketConnectionRegistry.java
WebSocketConnectionRegistry.count
public int count() { int n = 0; for (ConcurrentMap<?, ?> bag : registry.values()) { n += bag.size(); } return n; }
java
public int count() { int n = 0; for (ConcurrentMap<?, ?> bag : registry.values()) { n += bag.size(); } return n; }
[ "public", "int", "count", "(", ")", "{", "int", "n", "=", "0", ";", "for", "(", "ConcurrentMap", "<", "?", ",", "?", ">", "bag", ":", "registry", ".", "values", "(", ")", ")", "{", "n", "+=", "bag", ".", "size", "(", ")", ";", "}", "return", "n", ";", "}" ]
Returns the connection count in this registry. Note it might count connections that are closed but not removed from registry yet @return the connection count
[ "Returns", "the", "connection", "count", "in", "this", "registry", "." ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/ws/WebSocketConnectionRegistry.java#L259-L265
161,493
actframework/actframework
src/main/java/act/ws/WebSocketConnectionRegistry.java
WebSocketConnectionRegistry.count
public int count(String key) { ConcurrentMap<WebSocketConnection, WebSocketConnection> bag = registry.get(key); return null == bag ? 0 : bag.size(); }
java
public int count(String key) { ConcurrentMap<WebSocketConnection, WebSocketConnection> bag = registry.get(key); return null == bag ? 0 : bag.size(); }
[ "public", "int", "count", "(", "String", "key", ")", "{", "ConcurrentMap", "<", "WebSocketConnection", ",", "WebSocketConnection", ">", "bag", "=", "registry", ".", "get", "(", "key", ")", ";", "return", "null", "==", "bag", "?", "0", ":", "bag", ".", "size", "(", ")", ";", "}" ]
Returns the connection count by key specified in this registry Note it might count connections that are closed but not removed from registry yet @param key the key @return connection count by key
[ "Returns", "the", "connection", "count", "by", "key", "specified", "in", "this", "registry" ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/ws/WebSocketConnectionRegistry.java#L276-L279
161,494
actframework/actframework
src/main/java/act/util/ReflectedInvokerHelper.java
ReflectedInvokerHelper.tryGetSingleton
public static Object tryGetSingleton(Class<?> invokerClass, App app) { Object singleton = app.singleton(invokerClass); if (null == singleton) { if (isGlobalOrStateless(invokerClass, new HashSet<Class>())) { singleton = app.getInstance(invokerClass); } } if (null != singleton) { app.registerSingleton(singleton); } return singleton; }
java
public static Object tryGetSingleton(Class<?> invokerClass, App app) { Object singleton = app.singleton(invokerClass); if (null == singleton) { if (isGlobalOrStateless(invokerClass, new HashSet<Class>())) { singleton = app.getInstance(invokerClass); } } if (null != singleton) { app.registerSingleton(singleton); } return singleton; }
[ "public", "static", "Object", "tryGetSingleton", "(", "Class", "<", "?", ">", "invokerClass", ",", "App", "app", ")", "{", "Object", "singleton", "=", "app", ".", "singleton", "(", "invokerClass", ")", ";", "if", "(", "null", "==", "singleton", ")", "{", "if", "(", "isGlobalOrStateless", "(", "invokerClass", ",", "new", "HashSet", "<", "Class", ">", "(", ")", ")", ")", "{", "singleton", "=", "app", ".", "getInstance", "(", "invokerClass", ")", ";", "}", "}", "if", "(", "null", "!=", "singleton", ")", "{", "app", ".", "registerSingleton", "(", "singleton", ")", ";", "}", "return", "singleton", ";", "}" ]
If the `invokerClass` specified is singleton, or without field or all fields are stateless, then return an instance of the invoker class. Otherwise, return null @param invokerClass the invoker class @param app the app @return an instance of the invokerClass or `null` if invoker class is stateful class
[ "If", "the", "invokerClass", "specified", "is", "singleton", "or", "without", "field", "or", "all", "fields", "are", "stateless", "then", "return", "an", "instance", "of", "the", "invoker", "class", ".", "Otherwise", "return", "null" ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/util/ReflectedInvokerHelper.java#L56-L67
161,495
actframework/actframework
src/main/java/act/util/JsonUtilConfig.java
JsonUtilConfig.writeJson
private static final void writeJson(Writer os, // Object object, // SerializeConfig config, // SerializeFilter[] filters, // DateFormat dateFormat, // int defaultFeatures, // SerializerFeature... features) { SerializeWriter writer = new SerializeWriter(os, defaultFeatures, features); try { JSONSerializer serializer = new JSONSerializer(writer, config); if (dateFormat != null) { serializer.setDateFormat(dateFormat); serializer.config(SerializerFeature.WriteDateUseDateFormat, true); } if (filters != null) { for (SerializeFilter filter : filters) { serializer.addFilter(filter); } } serializer.write(object); } finally { writer.close(); } }
java
private static final void writeJson(Writer os, // Object object, // SerializeConfig config, // SerializeFilter[] filters, // DateFormat dateFormat, // int defaultFeatures, // SerializerFeature... features) { SerializeWriter writer = new SerializeWriter(os, defaultFeatures, features); try { JSONSerializer serializer = new JSONSerializer(writer, config); if (dateFormat != null) { serializer.setDateFormat(dateFormat); serializer.config(SerializerFeature.WriteDateUseDateFormat, true); } if (filters != null) { for (SerializeFilter filter : filters) { serializer.addFilter(filter); } } serializer.write(object); } finally { writer.close(); } }
[ "private", "static", "final", "void", "writeJson", "(", "Writer", "os", ",", "//", "Object", "object", ",", "//", "SerializeConfig", "config", ",", "//", "SerializeFilter", "[", "]", "filters", ",", "//", "DateFormat", "dateFormat", ",", "//", "int", "defaultFeatures", ",", "//", "SerializerFeature", "...", "features", ")", "{", "SerializeWriter", "writer", "=", "new", "SerializeWriter", "(", "os", ",", "defaultFeatures", ",", "features", ")", ";", "try", "{", "JSONSerializer", "serializer", "=", "new", "JSONSerializer", "(", "writer", ",", "config", ")", ";", "if", "(", "dateFormat", "!=", "null", ")", "{", "serializer", ".", "setDateFormat", "(", "dateFormat", ")", ";", "serializer", ".", "config", "(", "SerializerFeature", ".", "WriteDateUseDateFormat", ",", "true", ")", ";", "}", "if", "(", "filters", "!=", "null", ")", "{", "for", "(", "SerializeFilter", "filter", ":", "filters", ")", "{", "serializer", ".", "addFilter", "(", "filter", ")", ";", "}", "}", "serializer", ".", "write", "(", "object", ")", ";", "}", "finally", "{", "writer", ".", "close", "(", ")", ";", "}", "}" ]
FastJSON does not provide the API so we have to create our own
[ "FastJSON", "does", "not", "provide", "the", "API", "so", "we", "have", "to", "create", "our", "own" ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/util/JsonUtilConfig.java#L235-L261
161,496
actframework/actframework
src/main/java/act/db/DbService.java
DbService.entityClasses
public Set<Class> entityClasses() { EntityMetaInfoRepo repo = app().entityMetaInfoRepo().forDb(id); return null == repo ? C.<Class>set() : repo.entityClasses(); }
java
public Set<Class> entityClasses() { EntityMetaInfoRepo repo = app().entityMetaInfoRepo().forDb(id); return null == repo ? C.<Class>set() : repo.entityClasses(); }
[ "public", "Set", "<", "Class", ">", "entityClasses", "(", ")", "{", "EntityMetaInfoRepo", "repo", "=", "app", "(", ")", ".", "entityMetaInfoRepo", "(", ")", ".", "forDb", "(", "id", ")", ";", "return", "null", "==", "repo", "?", "C", ".", "<", "Class", ">", "set", "(", ")", ":", "repo", ".", "entityClasses", "(", ")", ";", "}" ]
Returns all model classes registered on this datasource @return model classes talk to this datasource
[ "Returns", "all", "model", "classes", "registered", "on", "this", "datasource" ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/db/DbService.java#L71-L74
161,497
actframework/actframework
src/main/java/act/ws/WebSocketContext.java
WebSocketContext.messageReceived
public WebSocketContext messageReceived(String receivedMessage) { this.stringMessage = S.string(receivedMessage).trim(); isJson = stringMessage.startsWith("{") || stringMessage.startsWith("]"); tryParseQueryParams(); return this; }
java
public WebSocketContext messageReceived(String receivedMessage) { this.stringMessage = S.string(receivedMessage).trim(); isJson = stringMessage.startsWith("{") || stringMessage.startsWith("]"); tryParseQueryParams(); return this; }
[ "public", "WebSocketContext", "messageReceived", "(", "String", "receivedMessage", ")", "{", "this", ".", "stringMessage", "=", "S", ".", "string", "(", "receivedMessage", ")", ".", "trim", "(", ")", ";", "isJson", "=", "stringMessage", ".", "startsWith", "(", "\"{\"", ")", "||", "stringMessage", ".", "startsWith", "(", "\"]\"", ")", ";", "tryParseQueryParams", "(", ")", ";", "return", "this", ";", "}" ]
Called when remote end send a message to this connection @param receivedMessage the message received @return this context
[ "Called", "when", "remote", "end", "send", "a", "message", "to", "this", "connection" ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/ws/WebSocketContext.java#L98-L103
161,498
actframework/actframework
src/main/java/act/ws/WebSocketContext.java
WebSocketContext.reTag
public WebSocketContext reTag(String label) { WebSocketConnectionRegistry registry = manager.tagRegistry(); registry.signOff(connection); registry.signIn(label, connection); return this; }
java
public WebSocketContext reTag(String label) { WebSocketConnectionRegistry registry = manager.tagRegistry(); registry.signOff(connection); registry.signIn(label, connection); return this; }
[ "public", "WebSocketContext", "reTag", "(", "String", "label", ")", "{", "WebSocketConnectionRegistry", "registry", "=", "manager", ".", "tagRegistry", "(", ")", ";", "registry", ".", "signOff", "(", "connection", ")", ";", "registry", ".", "signIn", "(", "label", ",", "connection", ")", ";", "return", "this", ";", "}" ]
Re-Tag the websocket connection hold by this context with label specified. This method will remove all previous tags on the websocket connection and then tag it with the new label. @param label the label. @return this websocket conext.
[ "Re", "-", "Tag", "the", "websocket", "connection", "hold", "by", "this", "context", "with", "label", "specified", ".", "This", "method", "will", "remove", "all", "previous", "tags", "on", "the", "websocket", "connection", "and", "then", "tag", "it", "with", "the", "new", "label", "." ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/ws/WebSocketContext.java#L122-L127
161,499
actframework/actframework
src/main/java/act/ws/WebSocketContext.java
WebSocketContext.sendToPeers
public WebSocketContext sendToPeers(String message, boolean excludeSelf) { return sendToConnections(message, url, manager.urlRegistry(), excludeSelf); }
java
public WebSocketContext sendToPeers(String message, boolean excludeSelf) { return sendToConnections(message, url, manager.urlRegistry(), excludeSelf); }
[ "public", "WebSocketContext", "sendToPeers", "(", "String", "message", ",", "boolean", "excludeSelf", ")", "{", "return", "sendToConnections", "(", "message", ",", "url", ",", "manager", ".", "urlRegistry", "(", ")", ",", "excludeSelf", ")", ";", "}" ]
Send message to all connections connected to the same URL of this context @param message the message to be sent @param excludeSelf whether the connection of this context should be sent to @return this context
[ "Send", "message", "to", "all", "connections", "connected", "to", "the", "same", "URL", "of", "this", "context" ]
55a8f8b45e71159a79ec6e157c02f71700f8cd54
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/ws/WebSocketContext.java#L185-L187