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
10,500
DigitalPebble/TextClassification
src/main/java/com/digitalpebble/classification/Lexicon.java
Lexicon.compact
public Map<Integer, Integer> compact() { Map<Integer, Integer> equiv = new HashMap<Integer, Integer>(); TreeMap<Integer, int[]> newIndex2docfreq = new TreeMap<Integer, int[]>(); // iterate on the map token -> Id and change the latter Iterator<Entry<String, int[]>> iter = tokenForm2index.entrySet().iterator(); nextAttributeID = 1; while (iter.hasNext()) { Entry<String, int[]> entry = iter.next(); int oldIndex = entry.getValue()[0]; int newIndex = nextAttributeID; entry.setValue(new int[] { newIndex }); // store the equivalence in the map equiv.put(oldIndex, newIndex); // populate the doc freq int[] docFreq = index2docfreq.get(oldIndex); newIndex2docfreq.put(newIndex, docFreq); nextAttributeID++; } // swap the doc freq index2docfreq = newIndex2docfreq; return equiv; }
java
public Map<Integer, Integer> compact() { Map<Integer, Integer> equiv = new HashMap<Integer, Integer>(); TreeMap<Integer, int[]> newIndex2docfreq = new TreeMap<Integer, int[]>(); // iterate on the map token -> Id and change the latter Iterator<Entry<String, int[]>> iter = tokenForm2index.entrySet().iterator(); nextAttributeID = 1; while (iter.hasNext()) { Entry<String, int[]> entry = iter.next(); int oldIndex = entry.getValue()[0]; int newIndex = nextAttributeID; entry.setValue(new int[] { newIndex }); // store the equivalence in the map equiv.put(oldIndex, newIndex); // populate the doc freq int[] docFreq = index2docfreq.get(oldIndex); newIndex2docfreq.put(newIndex, docFreq); nextAttributeID++; } // swap the doc freq index2docfreq = newIndex2docfreq; return equiv; }
[ "public", "Map", "<", "Integer", ",", "Integer", ">", "compact", "(", ")", "{", "Map", "<", "Integer", ",", "Integer", ">", "equiv", "=", "new", "HashMap", "<", "Integer", ",", "Integer", ">", "(", ")", ";", "TreeMap", "<", "Integer", ",", "int", "[", "]", ">", "newIndex2docfreq", "=", "new", "TreeMap", "<", "Integer", ",", "int", "[", "]", ">", "(", ")", ";", "// iterate on the map token -> Id and change the latter", "Iterator", "<", "Entry", "<", "String", ",", "int", "[", "]", ">", ">", "iter", "=", "tokenForm2index", ".", "entrySet", "(", ")", ".", "iterator", "(", ")", ";", "nextAttributeID", "=", "1", ";", "while", "(", "iter", ".", "hasNext", "(", ")", ")", "{", "Entry", "<", "String", ",", "int", "[", "]", ">", "entry", "=", "iter", ".", "next", "(", ")", ";", "int", "oldIndex", "=", "entry", ".", "getValue", "(", ")", "[", "0", "]", ";", "int", "newIndex", "=", "nextAttributeID", ";", "entry", ".", "setValue", "(", "new", "int", "[", "]", "{", "newIndex", "}", ")", ";", "// store the equivalence in the map", "equiv", ".", "put", "(", "oldIndex", ",", "newIndex", ")", ";", "// populate the doc freq", "int", "[", "]", "docFreq", "=", "index2docfreq", ".", "get", "(", "oldIndex", ")", ";", "newIndex2docfreq", ".", "put", "(", "newIndex", ",", "docFreq", ")", ";", "nextAttributeID", "++", ";", "}", "// swap the doc freq", "index2docfreq", "=", "newIndex2docfreq", ";", "return", "equiv", ";", "}" ]
Adjust the indices of the attributes so that maxAttributeID == getAttributesNum. Returns a Map containing the mapping between the old indices and the new ones.
[ "Adjust", "the", "indices", "of", "the", "attributes", "so", "that", "maxAttributeID", "==", "getAttributesNum", ".", "Returns", "a", "Map", "containing", "the", "mapping", "between", "the", "old", "indices", "and", "the", "new", "ones", "." ]
c510719c31633841af2bf393a20707d4624f865d
https://github.com/DigitalPebble/TextClassification/blob/c510719c31633841af2bf393a20707d4624f865d/src/main/java/com/digitalpebble/classification/Lexicon.java#L94-L119
10,501
DigitalPebble/TextClassification
src/main/java/com/digitalpebble/classification/Lexicon.java
Lexicon.getMethod
public WeightingMethod getMethod(String fieldName) { WeightingMethod method = this.customWeights.get(fieldName); if (method != null) return method; return this.method_used; }
java
public WeightingMethod getMethod(String fieldName) { WeightingMethod method = this.customWeights.get(fieldName); if (method != null) return method; return this.method_used; }
[ "public", "WeightingMethod", "getMethod", "(", "String", "fieldName", ")", "{", "WeightingMethod", "method", "=", "this", ".", "customWeights", ".", "get", "(", "fieldName", ")", ";", "if", "(", "method", "!=", "null", ")", "return", "method", ";", "return", "this", ".", "method_used", ";", "}" ]
Returns the weighting scheme used for a specific field or the default one if nothing has been specified for it
[ "Returns", "the", "weighting", "scheme", "used", "for", "a", "specific", "field", "or", "the", "default", "one", "if", "nothing", "has", "been", "specified", "for", "it" ]
c510719c31633841af2bf393a20707d4624f865d
https://github.com/DigitalPebble/TextClassification/blob/c510719c31633841af2bf393a20707d4624f865d/src/main/java/com/digitalpebble/classification/Lexicon.java#L125-L130
10,502
DigitalPebble/TextClassification
src/main/java/com/digitalpebble/classification/Lexicon.java
Lexicon.getIndex
public int getIndex(String tokenForm) { // tokenForm = tokenForm.replaceAll("\\W+", "_"); int[] index = (int[]) tokenForm2index.get(tokenForm); if (index == null) return -1; return index[0]; }
java
public int getIndex(String tokenForm) { // tokenForm = tokenForm.replaceAll("\\W+", "_"); int[] index = (int[]) tokenForm2index.get(tokenForm); if (index == null) return -1; return index[0]; }
[ "public", "int", "getIndex", "(", "String", "tokenForm", ")", "{", "// tokenForm = tokenForm.replaceAll(\"\\\\W+\", \"_\");", "int", "[", "]", "index", "=", "(", "int", "[", "]", ")", "tokenForm2index", ".", "get", "(", "tokenForm", ")", ";", "if", "(", "index", "==", "null", ")", "return", "-", "1", ";", "return", "index", "[", "0", "]", ";", "}" ]
returns the position of a given tokenform or -1 if the tokenform is unknown or has been filtered out @param tokenForm @return
[ "returns", "the", "position", "of", "a", "given", "tokenform", "or", "-", "1", "if", "the", "tokenform", "is", "unknown", "or", "has", "been", "filtered", "out" ]
c510719c31633841af2bf393a20707d4624f865d
https://github.com/DigitalPebble/TextClassification/blob/c510719c31633841af2bf393a20707d4624f865d/src/main/java/com/digitalpebble/classification/Lexicon.java#L204-L210
10,503
DigitalPebble/TextClassification
src/main/java/com/digitalpebble/classification/Lexicon.java
Lexicon.createIndex
public int createIndex(String tokenForm) { int[] index = (int[]) tokenForm2index.get(tokenForm); if (index == null) { index = new int[] { nextAttributeID }; tokenForm2index.put(tokenForm, index); nextAttributeID++; } // add information about number of documents // for the term Integer integ = Integer.valueOf(index[0]); int[] docfreq = (int[]) this.index2docfreq.get(integ); if (docfreq == null) { docfreq = new int[] { 0 }; index2docfreq.put(integ, docfreq); } docfreq[0]++; return index[0]; }
java
public int createIndex(String tokenForm) { int[] index = (int[]) tokenForm2index.get(tokenForm); if (index == null) { index = new int[] { nextAttributeID }; tokenForm2index.put(tokenForm, index); nextAttributeID++; } // add information about number of documents // for the term Integer integ = Integer.valueOf(index[0]); int[] docfreq = (int[]) this.index2docfreq.get(integ); if (docfreq == null) { docfreq = new int[] { 0 }; index2docfreq.put(integ, docfreq); } docfreq[0]++; return index[0]; }
[ "public", "int", "createIndex", "(", "String", "tokenForm", ")", "{", "int", "[", "]", "index", "=", "(", "int", "[", "]", ")", "tokenForm2index", ".", "get", "(", "tokenForm", ")", ";", "if", "(", "index", "==", "null", ")", "{", "index", "=", "new", "int", "[", "]", "{", "nextAttributeID", "}", ";", "tokenForm2index", ".", "put", "(", "tokenForm", ",", "index", ")", ";", "nextAttributeID", "++", ";", "}", "// add information about number of documents", "// for the term", "Integer", "integ", "=", "Integer", ".", "valueOf", "(", "index", "[", "0", "]", ")", ";", "int", "[", "]", "docfreq", "=", "(", "int", "[", "]", ")", "this", ".", "index2docfreq", ".", "get", "(", "integ", ")", ";", "if", "(", "docfreq", "==", "null", ")", "{", "docfreq", "=", "new", "int", "[", "]", "{", "0", "}", ";", "index2docfreq", ".", "put", "(", "integ", ",", "docfreq", ")", ";", "}", "docfreq", "[", "0", "]", "++", ";", "return", "index", "[", "0", "]", ";", "}" ]
called from Document
[ "called", "from", "Document" ]
c510719c31633841af2bf393a20707d4624f865d
https://github.com/DigitalPebble/TextClassification/blob/c510719c31633841af2bf393a20707d4624f865d/src/main/java/com/digitalpebble/classification/Lexicon.java#L278-L295
10,504
DigitalPebble/TextClassification
src/main/java/com/digitalpebble/classification/FileTrainingCorpus.java
FileTrainingCorpus.addDocument
public void addDocument(Document doc) throws IOException { // needs to differenciate SimpleDocuments from MultiField ones // each class has its own way of serializing String serial = doc.getStringSerialization(); raw_file_buffer.write(serial); }
java
public void addDocument(Document doc) throws IOException { // needs to differenciate SimpleDocuments from MultiField ones // each class has its own way of serializing String serial = doc.getStringSerialization(); raw_file_buffer.write(serial); }
[ "public", "void", "addDocument", "(", "Document", "doc", ")", "throws", "IOException", "{", "// needs to differenciate SimpleDocuments from MultiField ones", "// each class has its own way of serializing", "String", "serial", "=", "doc", ".", "getStringSerialization", "(", ")", ";", "raw_file_buffer", ".", "write", "(", "serial", ")", ";", "}" ]
there is exactly one document per line
[ "there", "is", "exactly", "one", "document", "per", "line" ]
c510719c31633841af2bf393a20707d4624f865d
https://github.com/DigitalPebble/TextClassification/blob/c510719c31633841af2bf393a20707d4624f865d/src/main/java/com/digitalpebble/classification/FileTrainingCorpus.java#L67-L72
10,505
DigitalPebble/TextClassification
src/main/java/com/digitalpebble/classification/util/ModelUtils.java
ModelUtils.getAttributeScores
public static void getAttributeScores(String modelPath, String lexiconF, int topAttributesNumber) throws IOException { // load the model + the lexicon // try to see if we can get a list of the best scores from the model // works only for liblinear Lexicon lexicon = new Lexicon(lexiconF); Model liblinearModel = Model.load(new File(modelPath)); double[] weights = liblinearModel.getFeatureWeights(); // dump all the weights int numClasses = liblinearModel.getNrClass(); int numFeatures = liblinearModel.getNrFeature(); Map<Integer, String> invertedAttributeIndex = lexicon .getInvertedIndex(); Map<String, WeightedAttributeQueue> topAttributesPerLabel = new HashMap<String, WeightedAttributeQueue>( numClasses); // for (int i = 0; i < nr_w; i++) { // double contrib = w[(idx - 1) * nr_w + i] * lx.getValue(); // } // // idx 1 in class 1 -> 0 x 22 + 0 = 0 // idx 2 in class 1 -> 1 x 22 + 0 = 22 // idx 1 in class 2 -> 0 x 22 + 1 = 1 // idx 2 in class 2 -> 1 x 22 + 1 = 23 // initialise the queues if (topAttributesNumber != -1) { for (int classNum = 0; classNum < numClasses; classNum++) { String classLabel = lexicon.getLabel(classNum); WeightedAttributeQueue queue = new WeightedAttributeQueue( topAttributesNumber); topAttributesPerLabel.put(classLabel, queue); } } for (int classNum = 0; classNum < numClasses; classNum++) { String classLabel = lexicon.getLabel(classNum); WeightedAttributeQueue queue = topAttributesPerLabel .get(classLabel); for (int featNum = 0; featNum < numFeatures; featNum++) { int pos = featNum * numClasses + classNum; double featWeight = weights[pos]; String attLabel = invertedAttributeIndex.get(featNum + 1); // display the values between -0.001 and +0.001 as 0 if (featWeight < 0.001 && featWeight > -0.001) featWeight = 0; // want to limit to the top n terms? if (topAttributesNumber != -1) { WeightedAttribute wa = new WeightedAttribute(attLabel, featWeight); queue.insertWithOverflow(wa); continue; } System.out.println(attLabel + "\t" + classLabel + "\t" + featWeight); } } // dump the attributes per label if (topAttributesNumber < 1) return; Iterator<String> labelIter = topAttributesPerLabel.keySet().iterator(); while (labelIter.hasNext()) { String label = (String) labelIter.next(); System.out.println("LABEL : " + label); WeightedAttributeQueue queue = topAttributesPerLabel.get(label); // revert the order String[] sorted = new String[queue.size()]; for (int i = queue.size() - 1; i >= 0; i--) { WeightedAttribute wa = queue.pop(); sorted[i] = wa.label + " : " + wa.weight; } for (int j = 0; j < sorted.length; j++) { System.out.println(j + 1 + "\t" + sorted[j]); } } }
java
public static void getAttributeScores(String modelPath, String lexiconF, int topAttributesNumber) throws IOException { // load the model + the lexicon // try to see if we can get a list of the best scores from the model // works only for liblinear Lexicon lexicon = new Lexicon(lexiconF); Model liblinearModel = Model.load(new File(modelPath)); double[] weights = liblinearModel.getFeatureWeights(); // dump all the weights int numClasses = liblinearModel.getNrClass(); int numFeatures = liblinearModel.getNrFeature(); Map<Integer, String> invertedAttributeIndex = lexicon .getInvertedIndex(); Map<String, WeightedAttributeQueue> topAttributesPerLabel = new HashMap<String, WeightedAttributeQueue>( numClasses); // for (int i = 0; i < nr_w; i++) { // double contrib = w[(idx - 1) * nr_w + i] * lx.getValue(); // } // // idx 1 in class 1 -> 0 x 22 + 0 = 0 // idx 2 in class 1 -> 1 x 22 + 0 = 22 // idx 1 in class 2 -> 0 x 22 + 1 = 1 // idx 2 in class 2 -> 1 x 22 + 1 = 23 // initialise the queues if (topAttributesNumber != -1) { for (int classNum = 0; classNum < numClasses; classNum++) { String classLabel = lexicon.getLabel(classNum); WeightedAttributeQueue queue = new WeightedAttributeQueue( topAttributesNumber); topAttributesPerLabel.put(classLabel, queue); } } for (int classNum = 0; classNum < numClasses; classNum++) { String classLabel = lexicon.getLabel(classNum); WeightedAttributeQueue queue = topAttributesPerLabel .get(classLabel); for (int featNum = 0; featNum < numFeatures; featNum++) { int pos = featNum * numClasses + classNum; double featWeight = weights[pos]; String attLabel = invertedAttributeIndex.get(featNum + 1); // display the values between -0.001 and +0.001 as 0 if (featWeight < 0.001 && featWeight > -0.001) featWeight = 0; // want to limit to the top n terms? if (topAttributesNumber != -1) { WeightedAttribute wa = new WeightedAttribute(attLabel, featWeight); queue.insertWithOverflow(wa); continue; } System.out.println(attLabel + "\t" + classLabel + "\t" + featWeight); } } // dump the attributes per label if (topAttributesNumber < 1) return; Iterator<String> labelIter = topAttributesPerLabel.keySet().iterator(); while (labelIter.hasNext()) { String label = (String) labelIter.next(); System.out.println("LABEL : " + label); WeightedAttributeQueue queue = topAttributesPerLabel.get(label); // revert the order String[] sorted = new String[queue.size()]; for (int i = queue.size() - 1; i >= 0; i--) { WeightedAttribute wa = queue.pop(); sorted[i] = wa.label + " : " + wa.weight; } for (int j = 0; j < sorted.length; j++) { System.out.println(j + 1 + "\t" + sorted[j]); } } }
[ "public", "static", "void", "getAttributeScores", "(", "String", "modelPath", ",", "String", "lexiconF", ",", "int", "topAttributesNumber", ")", "throws", "IOException", "{", "// load the model + the lexicon", "// try to see if we can get a list of the best scores from the model", "// works only for liblinear", "Lexicon", "lexicon", "=", "new", "Lexicon", "(", "lexiconF", ")", ";", "Model", "liblinearModel", "=", "Model", ".", "load", "(", "new", "File", "(", "modelPath", ")", ")", ";", "double", "[", "]", "weights", "=", "liblinearModel", ".", "getFeatureWeights", "(", ")", ";", "// dump all the weights", "int", "numClasses", "=", "liblinearModel", ".", "getNrClass", "(", ")", ";", "int", "numFeatures", "=", "liblinearModel", ".", "getNrFeature", "(", ")", ";", "Map", "<", "Integer", ",", "String", ">", "invertedAttributeIndex", "=", "lexicon", ".", "getInvertedIndex", "(", ")", ";", "Map", "<", "String", ",", "WeightedAttributeQueue", ">", "topAttributesPerLabel", "=", "new", "HashMap", "<", "String", ",", "WeightedAttributeQueue", ">", "(", "numClasses", ")", ";", "// for (int i = 0; i < nr_w; i++) {", "// double contrib = w[(idx - 1) * nr_w + i] * lx.getValue();", "// }", "//", "// idx 1 in class 1 -> 0 x 22 + 0 = 0", "// idx 2 in class 1 -> 1 x 22 + 0 = 22", "// idx 1 in class 2 -> 0 x 22 + 1 = 1", "// idx 2 in class 2 -> 1 x 22 + 1 = 23", "// initialise the queues", "if", "(", "topAttributesNumber", "!=", "-", "1", ")", "{", "for", "(", "int", "classNum", "=", "0", ";", "classNum", "<", "numClasses", ";", "classNum", "++", ")", "{", "String", "classLabel", "=", "lexicon", ".", "getLabel", "(", "classNum", ")", ";", "WeightedAttributeQueue", "queue", "=", "new", "WeightedAttributeQueue", "(", "topAttributesNumber", ")", ";", "topAttributesPerLabel", ".", "put", "(", "classLabel", ",", "queue", ")", ";", "}", "}", "for", "(", "int", "classNum", "=", "0", ";", "classNum", "<", "numClasses", ";", "classNum", "++", ")", "{", "String", "classLabel", "=", "lexicon", ".", "getLabel", "(", "classNum", ")", ";", "WeightedAttributeQueue", "queue", "=", "topAttributesPerLabel", ".", "get", "(", "classLabel", ")", ";", "for", "(", "int", "featNum", "=", "0", ";", "featNum", "<", "numFeatures", ";", "featNum", "++", ")", "{", "int", "pos", "=", "featNum", "*", "numClasses", "+", "classNum", ";", "double", "featWeight", "=", "weights", "[", "pos", "]", ";", "String", "attLabel", "=", "invertedAttributeIndex", ".", "get", "(", "featNum", "+", "1", ")", ";", "// display the values between -0.001 and +0.001 as 0", "if", "(", "featWeight", "<", "0.001", "&&", "featWeight", ">", "-", "0.001", ")", "featWeight", "=", "0", ";", "// want to limit to the top n terms?", "if", "(", "topAttributesNumber", "!=", "-", "1", ")", "{", "WeightedAttribute", "wa", "=", "new", "WeightedAttribute", "(", "attLabel", ",", "featWeight", ")", ";", "queue", ".", "insertWithOverflow", "(", "wa", ")", ";", "continue", ";", "}", "System", ".", "out", ".", "println", "(", "attLabel", "+", "\"\\t\"", "+", "classLabel", "+", "\"\\t\"", "+", "featWeight", ")", ";", "}", "}", "// dump the attributes per label", "if", "(", "topAttributesNumber", "<", "1", ")", "return", ";", "Iterator", "<", "String", ">", "labelIter", "=", "topAttributesPerLabel", ".", "keySet", "(", ")", ".", "iterator", "(", ")", ";", "while", "(", "labelIter", ".", "hasNext", "(", ")", ")", "{", "String", "label", "=", "(", "String", ")", "labelIter", ".", "next", "(", ")", ";", "System", ".", "out", ".", "println", "(", "\"LABEL : \"", "+", "label", ")", ";", "WeightedAttributeQueue", "queue", "=", "topAttributesPerLabel", ".", "get", "(", "label", ")", ";", "// revert the order", "String", "[", "]", "sorted", "=", "new", "String", "[", "queue", ".", "size", "(", ")", "]", ";", "for", "(", "int", "i", "=", "queue", ".", "size", "(", ")", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "WeightedAttribute", "wa", "=", "queue", ".", "pop", "(", ")", ";", "sorted", "[", "i", "]", "=", "wa", ".", "label", "+", "\" : \"", "+", "wa", ".", "weight", ";", "}", "for", "(", "int", "j", "=", "0", ";", "j", "<", "sorted", ".", "length", ";", "j", "++", ")", "{", "System", ".", "out", ".", "println", "(", "j", "+", "1", "+", "\"\\t\"", "+", "sorted", "[", "j", "]", ")", ";", "}", "}", "}" ]
Prints out the attributes and their weights from the models generated by liblinear. This is different from CorpusUtils.dumpBestAttributes which computes a score for the attributes regardless of the model.
[ "Prints", "out", "the", "attributes", "and", "their", "weights", "from", "the", "models", "generated", "by", "liblinear", ".", "This", "is", "different", "from", "CorpusUtils", ".", "dumpBestAttributes", "which", "computes", "a", "score", "for", "the", "attributes", "regardless", "of", "the", "model", "." ]
c510719c31633841af2bf393a20707d4624f865d
https://github.com/DigitalPebble/TextClassification/blob/c510719c31633841af2bf393a20707d4624f865d/src/main/java/com/digitalpebble/classification/util/ModelUtils.java#L44-L127
10,506
DigitalPebble/TextClassification
src/main/java/com/digitalpebble/classification/util/ModelUtils.java
WeightedAttribute.compareTo
public int compareTo(WeightedAttribute att) { double absoltarget = att.weight; // if (absoltarget < 0) // absoltarget = -absoltarget; double absolsource = this.weight; // if (absolsource < 0) // absolsource = -absolsource; double diff = absolsource - absoltarget; if (diff < 0) return -1; if (diff > 0) return +1; return 0; }
java
public int compareTo(WeightedAttribute att) { double absoltarget = att.weight; // if (absoltarget < 0) // absoltarget = -absoltarget; double absolsource = this.weight; // if (absolsource < 0) // absolsource = -absolsource; double diff = absolsource - absoltarget; if (diff < 0) return -1; if (diff > 0) return +1; return 0; }
[ "public", "int", "compareTo", "(", "WeightedAttribute", "att", ")", "{", "double", "absoltarget", "=", "att", ".", "weight", ";", "// if (absoltarget < 0)", "// absoltarget = -absoltarget;", "double", "absolsource", "=", "this", ".", "weight", ";", "// if (absolsource < 0)", "// absolsource = -absolsource;", "double", "diff", "=", "absolsource", "-", "absoltarget", ";", "if", "(", "diff", "<", "0", ")", "return", "-", "1", ";", "if", "(", "diff", ">", "0", ")", "return", "+", "1", ";", "return", "0", ";", "}" ]
rank the attributes based on weight
[ "rank", "the", "attributes", "based", "on", "weight" ]
c510719c31633841af2bf393a20707d4624f865d
https://github.com/DigitalPebble/TextClassification/blob/c510719c31633841af2bf393a20707d4624f865d/src/main/java/com/digitalpebble/classification/util/ModelUtils.java#L218-L231
10,507
forge/furnace
container-api/src/main/java/org/jboss/forge/furnace/versions/Versions.java
Versions.isSnapshot
public static boolean isSnapshot(Version version) { Assert.notNull(version, "Version must not be null."); return version.toString().endsWith(SNAPSHOT_SUFFIX); }
java
public static boolean isSnapshot(Version version) { Assert.notNull(version, "Version must not be null."); return version.toString().endsWith(SNAPSHOT_SUFFIX); }
[ "public", "static", "boolean", "isSnapshot", "(", "Version", "version", ")", "{", "Assert", ".", "notNull", "(", "version", ",", "\"Version must not be null.\"", ")", ";", "return", "version", ".", "toString", "(", ")", ".", "endsWith", "(", "SNAPSHOT_SUFFIX", ")", ";", "}" ]
Returns if the version specified is a SNAPSHOT @param version cannot be null @return true if the version is a SNAPSHOT, false otherwise
[ "Returns", "if", "the", "version", "specified", "is", "a", "SNAPSHOT" ]
bbe6deaa3c0d85ba43daa3e2f7d486f2dad21e0a
https://github.com/forge/furnace/blob/bbe6deaa3c0d85ba43daa3e2f7d486f2dad21e0a/container-api/src/main/java/org/jboss/forge/furnace/versions/Versions.java#L259-L263
10,508
protobufel/protobuf-el
protobufel-grammar/src/main/java/com/github/protobufel/grammar/FileDescriptorEx.java
FileDescriptorEx.isCanonical
private boolean isCanonical(final FileDescriptor file) { final FileDescriptorProto proto = file.toProto(); if (proto.hasOptions() && proto.getOptions().getUninterpretedOptionCount() > 0) { return false; } for (final FieldDescriptorProto field : proto.getExtensionList()) { if (!isFieldCanonical(field)) { return false; } } for (final ServiceDescriptorProto serviceProto : proto.getServiceList()) { if (!isCanonical(serviceProto)) { return false; } } for (final EnumDescriptorProto enumProto : proto.getEnumTypeList()) { if (!isCanonical(enumProto)) { return false; } } for (final DescriptorProto message : proto.getMessageTypeList()) { if (!isMessageRefsCanonical(message)) { return false; } } return true; }
java
private boolean isCanonical(final FileDescriptor file) { final FileDescriptorProto proto = file.toProto(); if (proto.hasOptions() && proto.getOptions().getUninterpretedOptionCount() > 0) { return false; } for (final FieldDescriptorProto field : proto.getExtensionList()) { if (!isFieldCanonical(field)) { return false; } } for (final ServiceDescriptorProto serviceProto : proto.getServiceList()) { if (!isCanonical(serviceProto)) { return false; } } for (final EnumDescriptorProto enumProto : proto.getEnumTypeList()) { if (!isCanonical(enumProto)) { return false; } } for (final DescriptorProto message : proto.getMessageTypeList()) { if (!isMessageRefsCanonical(message)) { return false; } } return true; }
[ "private", "boolean", "isCanonical", "(", "final", "FileDescriptor", "file", ")", "{", "final", "FileDescriptorProto", "proto", "=", "file", ".", "toProto", "(", ")", ";", "if", "(", "proto", ".", "hasOptions", "(", ")", "&&", "proto", ".", "getOptions", "(", ")", ".", "getUninterpretedOptionCount", "(", ")", ">", "0", ")", "{", "return", "false", ";", "}", "for", "(", "final", "FieldDescriptorProto", "field", ":", "proto", ".", "getExtensionList", "(", ")", ")", "{", "if", "(", "!", "isFieldCanonical", "(", "field", ")", ")", "{", "return", "false", ";", "}", "}", "for", "(", "final", "ServiceDescriptorProto", "serviceProto", ":", "proto", ".", "getServiceList", "(", ")", ")", "{", "if", "(", "!", "isCanonical", "(", "serviceProto", ")", ")", "{", "return", "false", ";", "}", "}", "for", "(", "final", "EnumDescriptorProto", "enumProto", ":", "proto", ".", "getEnumTypeList", "(", ")", ")", "{", "if", "(", "!", "isCanonical", "(", "enumProto", ")", ")", "{", "return", "false", ";", "}", "}", "for", "(", "final", "DescriptorProto", "message", ":", "proto", ".", "getMessageTypeList", "(", ")", ")", "{", "if", "(", "!", "isMessageRefsCanonical", "(", "message", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
very consuming and problematic!
[ "very", "consuming", "and", "problematic!" ]
3a600e2f7a8e74b637f44eee0331ef6e57e7441c
https://github.com/protobufel/protobuf-el/blob/3a600e2f7a8e74b637f44eee0331ef6e57e7441c/protobufel-grammar/src/main/java/com/github/protobufel/grammar/FileDescriptorEx.java#L451-L483
10,509
protobufel/protobuf-el
protobufel/src/main/java/com/github/protobufel/RepeatedFieldBuilder.java
RepeatedFieldBuilder.ensureBuilders
private void ensureBuilders() { if (this.builders == null) { this.builders = new ArrayList<SingleFieldBuilder<MType, BType, IType>>(messages.size()); for (int i = 0; i < messages.size(); i++) { builders.add(null); } } }
java
private void ensureBuilders() { if (this.builders == null) { this.builders = new ArrayList<SingleFieldBuilder<MType, BType, IType>>(messages.size()); for (int i = 0; i < messages.size(); i++) { builders.add(null); } } }
[ "private", "void", "ensureBuilders", "(", ")", "{", "if", "(", "this", ".", "builders", "==", "null", ")", "{", "this", ".", "builders", "=", "new", "ArrayList", "<", "SingleFieldBuilder", "<", "MType", ",", "BType", ",", "IType", ">", ">", "(", "messages", ".", "size", "(", ")", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "messages", ".", "size", "(", ")", ";", "i", "++", ")", "{", "builders", ".", "add", "(", "null", ")", ";", "}", "}", "}" ]
Ensures that the list of builders is not null. If it's null, the list is created and initialized to be the same size as the messages list with null entries.
[ "Ensures", "that", "the", "list", "of", "builders", "is", "not", "null", ".", "If", "it", "s", "null", "the", "list", "is", "created", "and", "initialized", "to", "be", "the", "same", "size", "as", "the", "messages", "list", "with", "null", "entries", "." ]
3a600e2f7a8e74b637f44eee0331ef6e57e7441c
https://github.com/protobufel/protobuf-el/blob/3a600e2f7a8e74b637f44eee0331ef6e57e7441c/protobufel/src/main/java/com/github/protobufel/RepeatedFieldBuilder.java#L168-L175
10,510
protobufel/protobuf-el
protobufel/src/main/java/com/github/protobufel/RepeatedFieldBuilder.java
RepeatedFieldBuilder.addAllMessages
public RepeatedFieldBuilder<MType, BType, IType> addAllMessages( final Iterable<? extends MType> values) { for (final MType value : values) { if (value == null) { throw new NullPointerException(); } } if (values instanceof Collection) { @SuppressWarnings("unchecked") final Collection<MType> collection = (Collection<MType>) values; if (collection.size() == 0) { return this; } ensureMutableMessageList(); for (final MType value : values) { addMessage(value); } } else { ensureMutableMessageList(); for (final MType value : values) { addMessage(value); } } onChanged(); incrementModCounts(); return this; }
java
public RepeatedFieldBuilder<MType, BType, IType> addAllMessages( final Iterable<? extends MType> values) { for (final MType value : values) { if (value == null) { throw new NullPointerException(); } } if (values instanceof Collection) { @SuppressWarnings("unchecked") final Collection<MType> collection = (Collection<MType>) values; if (collection.size() == 0) { return this; } ensureMutableMessageList(); for (final MType value : values) { addMessage(value); } } else { ensureMutableMessageList(); for (final MType value : values) { addMessage(value); } } onChanged(); incrementModCounts(); return this; }
[ "public", "RepeatedFieldBuilder", "<", "MType", ",", "BType", ",", "IType", ">", "addAllMessages", "(", "final", "Iterable", "<", "?", "extends", "MType", ">", "values", ")", "{", "for", "(", "final", "MType", "value", ":", "values", ")", "{", "if", "(", "value", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", ")", ";", "}", "}", "if", "(", "values", "instanceof", "Collection", ")", "{", "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "final", "Collection", "<", "MType", ">", "collection", "=", "(", "Collection", "<", "MType", ">", ")", "values", ";", "if", "(", "collection", ".", "size", "(", ")", "==", "0", ")", "{", "return", "this", ";", "}", "ensureMutableMessageList", "(", ")", ";", "for", "(", "final", "MType", "value", ":", "values", ")", "{", "addMessage", "(", "value", ")", ";", "}", "}", "else", "{", "ensureMutableMessageList", "(", ")", ";", "for", "(", "final", "MType", "value", ":", "values", ")", "{", "addMessage", "(", "value", ")", ";", "}", "}", "onChanged", "(", ")", ";", "incrementModCounts", "(", ")", ";", "return", "this", ";", "}" ]
Appends all of the messages in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator. @param values the messages to add @return the builder
[ "Appends", "all", "of", "the", "messages", "in", "the", "specified", "collection", "to", "the", "end", "of", "this", "list", "in", "the", "order", "that", "they", "are", "returned", "by", "the", "specified", "collection", "s", "iterator", "." ]
3a600e2f7a8e74b637f44eee0331ef6e57e7441c
https://github.com/protobufel/protobuf-el/blob/3a600e2f7a8e74b637f44eee0331ef6e57e7441c/protobufel/src/main/java/com/github/protobufel/RepeatedFieldBuilder.java#L355-L381
10,511
protobufel/protobuf-el
protobufel/src/main/java/com/github/protobufel/RepeatedFieldBuilder.java
RepeatedFieldBuilder.addBuilder
public BType addBuilder(final MType message) { ensureMutableMessageList(); ensureBuilders(); final SingleFieldBuilder<MType, BType, IType> builder = newSingleFieldBuilder(message, this, isClean); messages.add(null); builders.add(builder); onChanged(); incrementModCounts(); return builder.getBuilder(); }
java
public BType addBuilder(final MType message) { ensureMutableMessageList(); ensureBuilders(); final SingleFieldBuilder<MType, BType, IType> builder = newSingleFieldBuilder(message, this, isClean); messages.add(null); builders.add(builder); onChanged(); incrementModCounts(); return builder.getBuilder(); }
[ "public", "BType", "addBuilder", "(", "final", "MType", "message", ")", "{", "ensureMutableMessageList", "(", ")", ";", "ensureBuilders", "(", ")", ";", "final", "SingleFieldBuilder", "<", "MType", ",", "BType", ",", "IType", ">", "builder", "=", "newSingleFieldBuilder", "(", "message", ",", "this", ",", "isClean", ")", ";", "messages", ".", "add", "(", "null", ")", ";", "builders", ".", "add", "(", "builder", ")", ";", "onChanged", "(", ")", ";", "incrementModCounts", "(", ")", ";", "return", "builder", ".", "getBuilder", "(", ")", ";", "}" ]
Appends a new builder to the end of this list and returns the builder. @param message the message to add which is the basis of the builder @return the new builder
[ "Appends", "a", "new", "builder", "to", "the", "end", "of", "this", "list", "and", "returns", "the", "builder", "." ]
3a600e2f7a8e74b637f44eee0331ef6e57e7441c
https://github.com/protobufel/protobuf-el/blob/3a600e2f7a8e74b637f44eee0331ef6e57e7441c/protobufel/src/main/java/com/github/protobufel/RepeatedFieldBuilder.java#L389-L399
10,512
protobufel/protobuf-el
protobufel/src/main/java/com/github/protobufel/RepeatedFieldBuilder.java
RepeatedFieldBuilder.getMessageList
public List<MType> getMessageList() { if (externalMessageList == null) { externalMessageList = new MessageExternalList<MType, BType, IType>(this); } return externalMessageList; }
java
public List<MType> getMessageList() { if (externalMessageList == null) { externalMessageList = new MessageExternalList<MType, BType, IType>(this); } return externalMessageList; }
[ "public", "List", "<", "MType", ">", "getMessageList", "(", ")", "{", "if", "(", "externalMessageList", "==", "null", ")", "{", "externalMessageList", "=", "new", "MessageExternalList", "<", "MType", ",", "BType", ",", "IType", ">", "(", "this", ")", ";", "}", "return", "externalMessageList", ";", "}" ]
Gets a view of the builder as a list of messages. The returned list is live and will reflect any changes to the underlying builder. @return the messages in the list
[ "Gets", "a", "view", "of", "the", "builder", "as", "a", "list", "of", "messages", ".", "The", "returned", "list", "is", "live", "and", "will", "reflect", "any", "changes", "to", "the", "underlying", "builder", "." ]
3a600e2f7a8e74b637f44eee0331ef6e57e7441c
https://github.com/protobufel/protobuf-el/blob/3a600e2f7a8e74b637f44eee0331ef6e57e7441c/protobufel/src/main/java/com/github/protobufel/RepeatedFieldBuilder.java#L515-L520
10,513
protobufel/protobuf-el
protobufel/src/main/java/com/github/protobufel/RepeatedFieldBuilder.java
RepeatedFieldBuilder.getBuilderList
public List<BType> getBuilderList() { if (externalBuilderList == null) { externalBuilderList = new BuilderExternalList<MType, BType, IType>(this); } return externalBuilderList; }
java
public List<BType> getBuilderList() { if (externalBuilderList == null) { externalBuilderList = new BuilderExternalList<MType, BType, IType>(this); } return externalBuilderList; }
[ "public", "List", "<", "BType", ">", "getBuilderList", "(", ")", "{", "if", "(", "externalBuilderList", "==", "null", ")", "{", "externalBuilderList", "=", "new", "BuilderExternalList", "<", "MType", ",", "BType", ",", "IType", ">", "(", "this", ")", ";", "}", "return", "externalBuilderList", ";", "}" ]
Gets a view of the builder as a list of builders. This returned list is live and will reflect any changes to the underlying builder. @return the builders in the list
[ "Gets", "a", "view", "of", "the", "builder", "as", "a", "list", "of", "builders", ".", "This", "returned", "list", "is", "live", "and", "will", "reflect", "any", "changes", "to", "the", "underlying", "builder", "." ]
3a600e2f7a8e74b637f44eee0331ef6e57e7441c
https://github.com/protobufel/protobuf-el/blob/3a600e2f7a8e74b637f44eee0331ef6e57e7441c/protobufel/src/main/java/com/github/protobufel/RepeatedFieldBuilder.java#L528-L533
10,514
protobufel/protobuf-el
protobufel/src/main/java/com/github/protobufel/RepeatedFieldBuilder.java
RepeatedFieldBuilder.getMessageOrBuilderList
public List<IType> getMessageOrBuilderList() { if (externalMessageOrBuilderList == null) { externalMessageOrBuilderList = new MessageOrBuilderExternalList<MType, BType, IType>(this); } return externalMessageOrBuilderList; }
java
public List<IType> getMessageOrBuilderList() { if (externalMessageOrBuilderList == null) { externalMessageOrBuilderList = new MessageOrBuilderExternalList<MType, BType, IType>(this); } return externalMessageOrBuilderList; }
[ "public", "List", "<", "IType", ">", "getMessageOrBuilderList", "(", ")", "{", "if", "(", "externalMessageOrBuilderList", "==", "null", ")", "{", "externalMessageOrBuilderList", "=", "new", "MessageOrBuilderExternalList", "<", "MType", ",", "BType", ",", "IType", ">", "(", "this", ")", ";", "}", "return", "externalMessageOrBuilderList", ";", "}" ]
Gets a view of the builder as a list of MessageOrBuilders. This returned list is live and will reflect any changes to the underlying builder. @return the builders in the list
[ "Gets", "a", "view", "of", "the", "builder", "as", "a", "list", "of", "MessageOrBuilders", ".", "This", "returned", "list", "is", "live", "and", "will", "reflect", "any", "changes", "to", "the", "underlying", "builder", "." ]
3a600e2f7a8e74b637f44eee0331ef6e57e7441c
https://github.com/protobufel/protobuf-el/blob/3a600e2f7a8e74b637f44eee0331ef6e57e7441c/protobufel/src/main/java/com/github/protobufel/RepeatedFieldBuilder.java#L541-L546
10,515
protobufel/protobuf-el
protobufel/src/main/java/com/github/protobufel/RepeatedFieldBuilder.java
RepeatedFieldBuilder.incrementModCounts
private void incrementModCounts() { if (externalMessageList != null) { externalMessageList.incrementModCount(); } if (externalBuilderList != null) { externalBuilderList.incrementModCount(); } if (externalMessageOrBuilderList != null) { externalMessageOrBuilderList.incrementModCount(); } }
java
private void incrementModCounts() { if (externalMessageList != null) { externalMessageList.incrementModCount(); } if (externalBuilderList != null) { externalBuilderList.incrementModCount(); } if (externalMessageOrBuilderList != null) { externalMessageOrBuilderList.incrementModCount(); } }
[ "private", "void", "incrementModCounts", "(", ")", "{", "if", "(", "externalMessageList", "!=", "null", ")", "{", "externalMessageList", ".", "incrementModCount", "(", ")", ";", "}", "if", "(", "externalBuilderList", "!=", "null", ")", "{", "externalBuilderList", ".", "incrementModCount", "(", ")", ";", "}", "if", "(", "externalMessageOrBuilderList", "!=", "null", ")", "{", "externalMessageOrBuilderList", ".", "incrementModCount", "(", ")", ";", "}", "}" ]
Increments the mod counts so that an ConcurrentModificationException can be thrown if calling code tries to modify the builder while its iterating the list.
[ "Increments", "the", "mod", "counts", "so", "that", "an", "ConcurrentModificationException", "can", "be", "thrown", "if", "calling", "code", "tries", "to", "modify", "the", "builder", "while", "its", "iterating", "the", "list", "." ]
3a600e2f7a8e74b637f44eee0331ef6e57e7441c
https://github.com/protobufel/protobuf-el/blob/3a600e2f7a8e74b637f44eee0331ef6e57e7441c/protobufel/src/main/java/com/github/protobufel/RepeatedFieldBuilder.java#L571-L581
10,516
forge/furnace
manager/impl/src/main/java/org/jboss/forge/furnace/manager/impl/AddonManagerImpl.java
AddonManagerImpl.collectRequiredAddons
private void collectRequiredAddons(AddonInfo addonInfo, List<AddonInfo> addons) { // Move this addon to the top of the list addons.remove(addonInfo); addons.add(0, addonInfo); for (AddonId addonId : addonInfo.getRequiredAddons()) { if (!addons.contains(addonId) && (!isDeployed(addonId) || !isEnabled(addonId))) { AddonInfo childInfo = info(addonId); collectRequiredAddons(childInfo, addons); } } }
java
private void collectRequiredAddons(AddonInfo addonInfo, List<AddonInfo> addons) { // Move this addon to the top of the list addons.remove(addonInfo); addons.add(0, addonInfo); for (AddonId addonId : addonInfo.getRequiredAddons()) { if (!addons.contains(addonId) && (!isDeployed(addonId) || !isEnabled(addonId))) { AddonInfo childInfo = info(addonId); collectRequiredAddons(childInfo, addons); } } }
[ "private", "void", "collectRequiredAddons", "(", "AddonInfo", "addonInfo", ",", "List", "<", "AddonInfo", ">", "addons", ")", "{", "// Move this addon to the top of the list", "addons", ".", "remove", "(", "addonInfo", ")", ";", "addons", ".", "add", "(", "0", ",", "addonInfo", ")", ";", "for", "(", "AddonId", "addonId", ":", "addonInfo", ".", "getRequiredAddons", "(", ")", ")", "{", "if", "(", "!", "addons", ".", "contains", "(", "addonId", ")", "&&", "(", "!", "isDeployed", "(", "addonId", ")", "||", "!", "isEnabled", "(", "addonId", ")", ")", ")", "{", "AddonInfo", "childInfo", "=", "info", "(", "addonId", ")", ";", "collectRequiredAddons", "(", "childInfo", ",", "addons", ")", ";", "}", "}", "}" ]
Collect all required addons for a specific addon. It traverses the whole graph @param addonInfo @param addons
[ "Collect", "all", "required", "addons", "for", "a", "specific", "addon", "." ]
bbe6deaa3c0d85ba43daa3e2f7d486f2dad21e0a
https://github.com/forge/furnace/blob/bbe6deaa3c0d85ba43daa3e2f7d486f2dad21e0a/manager/impl/src/main/java/org/jboss/forge/furnace/manager/impl/AddonManagerImpl.java#L256-L269
10,517
grahamedgecombe/jterminal
src/main/java/com/grahamedgecombe/jterminal/vt100/AnsiControlSequenceParser.java
AnsiControlSequenceParser.parse
public void parse(String str) { if (buffer.length() > 0) { str = buffer.toString().concat(str); buffer = new StringBuilder(); } Reader reader = new StringReader(str); try { try { parse(reader); } finally { reader.close(); } } catch (IOException ex) { /* ignore */ } }
java
public void parse(String str) { if (buffer.length() > 0) { str = buffer.toString().concat(str); buffer = new StringBuilder(); } Reader reader = new StringReader(str); try { try { parse(reader); } finally { reader.close(); } } catch (IOException ex) { /* ignore */ } }
[ "public", "void", "parse", "(", "String", "str", ")", "{", "if", "(", "buffer", ".", "length", "(", ")", ">", "0", ")", "{", "str", "=", "buffer", ".", "toString", "(", ")", ".", "concat", "(", "str", ")", ";", "buffer", "=", "new", "StringBuilder", "(", ")", ";", "}", "Reader", "reader", "=", "new", "StringReader", "(", "str", ")", ";", "try", "{", "try", "{", "parse", "(", "reader", ")", ";", "}", "finally", "{", "reader", ".", "close", "(", ")", ";", "}", "}", "catch", "(", "IOException", "ex", ")", "{", "/* ignore */", "}", "}" ]
Parses the specified string. @param str The string to parse.
[ "Parses", "the", "specified", "string", "." ]
751142d9d2cafbde0ec36a80f73bb25bf297f2f3
https://github.com/grahamedgecombe/jterminal/blob/751142d9d2cafbde0ec36a80f73bb25bf297f2f3/src/main/java/com/grahamedgecombe/jterminal/vt100/AnsiControlSequenceParser.java#L68-L83
10,518
grahamedgecombe/jterminal
src/main/java/com/grahamedgecombe/jterminal/vt100/AnsiControlSequenceParser.java
AnsiControlSequenceParser.parse
private void parse(Reader reader) throws IOException { StringBuilder text = new StringBuilder(); int character; while ((character = reader.read()) != -1) { boolean introducedControlSequence = false; if (character == SINGLE_CSI) { introducedControlSequence = true; } else if (character == MULTI_CSI[0]) { int nextCharacter = reader.read(); if (nextCharacter == -1) { buffer.append((char) character); break; } else if (nextCharacter == MULTI_CSI[1]) { introducedControlSequence = true; } else { text.append((char) character); text.append((char) nextCharacter); } } else { text.append((char) character); } if (introducedControlSequence) { if (text.length() > 0) { listener.parsedString(text.toString()); text = new StringBuilder(); } parseControlSequence(reader); } } if (text.length() > 0) { listener.parsedString(text.toString()); } }
java
private void parse(Reader reader) throws IOException { StringBuilder text = new StringBuilder(); int character; while ((character = reader.read()) != -1) { boolean introducedControlSequence = false; if (character == SINGLE_CSI) { introducedControlSequence = true; } else if (character == MULTI_CSI[0]) { int nextCharacter = reader.read(); if (nextCharacter == -1) { buffer.append((char) character); break; } else if (nextCharacter == MULTI_CSI[1]) { introducedControlSequence = true; } else { text.append((char) character); text.append((char) nextCharacter); } } else { text.append((char) character); } if (introducedControlSequence) { if (text.length() > 0) { listener.parsedString(text.toString()); text = new StringBuilder(); } parseControlSequence(reader); } } if (text.length() > 0) { listener.parsedString(text.toString()); } }
[ "private", "void", "parse", "(", "Reader", "reader", ")", "throws", "IOException", "{", "StringBuilder", "text", "=", "new", "StringBuilder", "(", ")", ";", "int", "character", ";", "while", "(", "(", "character", "=", "reader", ".", "read", "(", ")", ")", "!=", "-", "1", ")", "{", "boolean", "introducedControlSequence", "=", "false", ";", "if", "(", "character", "==", "SINGLE_CSI", ")", "{", "introducedControlSequence", "=", "true", ";", "}", "else", "if", "(", "character", "==", "MULTI_CSI", "[", "0", "]", ")", "{", "int", "nextCharacter", "=", "reader", ".", "read", "(", ")", ";", "if", "(", "nextCharacter", "==", "-", "1", ")", "{", "buffer", ".", "append", "(", "(", "char", ")", "character", ")", ";", "break", ";", "}", "else", "if", "(", "nextCharacter", "==", "MULTI_CSI", "[", "1", "]", ")", "{", "introducedControlSequence", "=", "true", ";", "}", "else", "{", "text", ".", "append", "(", "(", "char", ")", "character", ")", ";", "text", ".", "append", "(", "(", "char", ")", "nextCharacter", ")", ";", "}", "}", "else", "{", "text", ".", "append", "(", "(", "char", ")", "character", ")", ";", "}", "if", "(", "introducedControlSequence", ")", "{", "if", "(", "text", ".", "length", "(", ")", ">", "0", ")", "{", "listener", ".", "parsedString", "(", "text", ".", "toString", "(", ")", ")", ";", "text", "=", "new", "StringBuilder", "(", ")", ";", "}", "parseControlSequence", "(", "reader", ")", ";", "}", "}", "if", "(", "text", ".", "length", "(", ")", ">", "0", ")", "{", "listener", ".", "parsedString", "(", "text", ".", "toString", "(", ")", ")", ";", "}", "}" ]
Parses characters from the specified character reader. @param reader The character reader. @throws IOException if an I/O error occurs.
[ "Parses", "characters", "from", "the", "specified", "character", "reader", "." ]
751142d9d2cafbde0ec36a80f73bb25bf297f2f3
https://github.com/grahamedgecombe/jterminal/blob/751142d9d2cafbde0ec36a80f73bb25bf297f2f3/src/main/java/com/grahamedgecombe/jterminal/vt100/AnsiControlSequenceParser.java#L90-L124
10,519
grahamedgecombe/jterminal
src/main/java/com/grahamedgecombe/jterminal/vt100/AnsiControlSequenceParser.java
AnsiControlSequenceParser.parseControlSequence
private void parseControlSequence(Reader reader) throws IOException { boolean finishedSequence = false; StringBuilder parameters = new StringBuilder(); int character; while ((character = reader.read()) != -1) { if ((character >= 'a' && character <= 'z') || (character >= 'A' && character <= 'Z')) { String[] array = parameters.toString().split(";"); AnsiControlSequence seq = new AnsiControlSequence((char) character, array); listener.parsedControlSequence(seq); finishedSequence = true; break; } else { parameters.append((char) character); } } if (!finishedSequence) { // not an ideal solution if they used the two byte CSI, but it's // easier and cleaner than keeping track of it buffer.append((char) SINGLE_CSI); buffer.append(parameters); } }
java
private void parseControlSequence(Reader reader) throws IOException { boolean finishedSequence = false; StringBuilder parameters = new StringBuilder(); int character; while ((character = reader.read()) != -1) { if ((character >= 'a' && character <= 'z') || (character >= 'A' && character <= 'Z')) { String[] array = parameters.toString().split(";"); AnsiControlSequence seq = new AnsiControlSequence((char) character, array); listener.parsedControlSequence(seq); finishedSequence = true; break; } else { parameters.append((char) character); } } if (!finishedSequence) { // not an ideal solution if they used the two byte CSI, but it's // easier and cleaner than keeping track of it buffer.append((char) SINGLE_CSI); buffer.append(parameters); } }
[ "private", "void", "parseControlSequence", "(", "Reader", "reader", ")", "throws", "IOException", "{", "boolean", "finishedSequence", "=", "false", ";", "StringBuilder", "parameters", "=", "new", "StringBuilder", "(", ")", ";", "int", "character", ";", "while", "(", "(", "character", "=", "reader", ".", "read", "(", ")", ")", "!=", "-", "1", ")", "{", "if", "(", "(", "character", ">=", "'", "'", "&&", "character", "<=", "'", "'", ")", "||", "(", "character", ">=", "'", "'", "&&", "character", "<=", "'", "'", ")", ")", "{", "String", "[", "]", "array", "=", "parameters", ".", "toString", "(", ")", ".", "split", "(", "\";\"", ")", ";", "AnsiControlSequence", "seq", "=", "new", "AnsiControlSequence", "(", "(", "char", ")", "character", ",", "array", ")", ";", "listener", ".", "parsedControlSequence", "(", "seq", ")", ";", "finishedSequence", "=", "true", ";", "break", ";", "}", "else", "{", "parameters", ".", "append", "(", "(", "char", ")", "character", ")", ";", "}", "}", "if", "(", "!", "finishedSequence", ")", "{", "// not an ideal solution if they used the two byte CSI, but it's", "// easier and cleaner than keeping track of it", "buffer", ".", "append", "(", "(", "char", ")", "SINGLE_CSI", ")", ";", "buffer", ".", "append", "(", "parameters", ")", ";", "}", "}" ]
Parses a control sequence. @param reader The character reader. @throws IOException if an I/O error occurs.
[ "Parses", "a", "control", "sequence", "." ]
751142d9d2cafbde0ec36a80f73bb25bf297f2f3
https://github.com/grahamedgecombe/jterminal/blob/751142d9d2cafbde0ec36a80f73bb25bf297f2f3/src/main/java/com/grahamedgecombe/jterminal/vt100/AnsiControlSequenceParser.java#L131-L153
10,520
jiaqi/jcli
src/main/java/org/cyclopsgroup/jcli/ArgumentProcessor.java
ArgumentProcessor.newInstance
public static <T> ArgumentProcessor<T> newInstance(Class<? extends T> beanType, CommandLineParser parser) { return ArgumentProcessorFactory.getInstance().newProcessor(beanType, parser); }
java
public static <T> ArgumentProcessor<T> newInstance(Class<? extends T> beanType, CommandLineParser parser) { return ArgumentProcessorFactory.getInstance().newProcessor(beanType, parser); }
[ "public", "static", "<", "T", ">", "ArgumentProcessor", "<", "T", ">", "newInstance", "(", "Class", "<", "?", "extends", "T", ">", "beanType", ",", "CommandLineParser", "parser", ")", "{", "return", "ArgumentProcessorFactory", ".", "getInstance", "(", ")", ".", "newProcessor", "(", "beanType", ",", "parser", ")", ";", "}" ]
Create new instance with given bean type and command line parser that describes command line sytnax. @param <T> type of bean @param beanType Type of bean @param parser command line parser that is aware of command line syntax @return instance of an implementation of argument processor.
[ "Create", "new", "instance", "with", "given", "bean", "type", "and", "command", "line", "parser", "that", "describes", "command", "line", "sytnax", "." ]
3854b3bb3c26bbe7407bf1b6600d8b25592d398e
https://github.com/jiaqi/jcli/blob/3854b3bb3c26bbe7407bf1b6600d8b25592d398e/src/main/java/org/cyclopsgroup/jcli/ArgumentProcessor.java#L43-L46
10,521
jiaqi/jcli
src/main/java/org/cyclopsgroup/jcli/ArgumentProcessor.java
ArgumentProcessor.process
public T process(String[] arguments, T bean) { return process(Arrays.asList(arguments), bean); }
java
public T process(String[] arguments, T bean) { return process(Arrays.asList(arguments), bean); }
[ "public", "T", "process", "(", "String", "[", "]", "arguments", ",", "T", "bean", ")", "{", "return", "process", "(", "Arrays", ".", "asList", "(", "arguments", ")", ",", "bean", ")", ";", "}" ]
Process argument array and pass values to given bean @param arguments Arary of arguments @param bean Bean to pass values to @return the processed bean.
[ "Process", "argument", "array", "and", "pass", "values", "to", "given", "bean" ]
3854b3bb3c26bbe7407bf1b6600d8b25592d398e
https://github.com/jiaqi/jcli/blob/3854b3bb3c26bbe7407bf1b6600d8b25592d398e/src/main/java/org/cyclopsgroup/jcli/ArgumentProcessor.java#L85-L87
10,522
StanKocken/EfficientAdapter
efficientadapter/src/main/java/com/skocken/efficientadapter/lib/adapter/AdapterHelper.java
AdapterHelper.onBindViewHolder
public void onBindViewHolder(EfficientViewHolder<T> viewHolder, int position, EfficientAdapter<T> adapter) { T object = get(position); viewHolder.onBindView(object, position); viewHolder.setAdapter(adapter); setClickListenerOnView(viewHolder); setLongClickListenerOnView(viewHolder); }
java
public void onBindViewHolder(EfficientViewHolder<T> viewHolder, int position, EfficientAdapter<T> adapter) { T object = get(position); viewHolder.onBindView(object, position); viewHolder.setAdapter(adapter); setClickListenerOnView(viewHolder); setLongClickListenerOnView(viewHolder); }
[ "public", "void", "onBindViewHolder", "(", "EfficientViewHolder", "<", "T", ">", "viewHolder", ",", "int", "position", ",", "EfficientAdapter", "<", "T", ">", "adapter", ")", "{", "T", "object", "=", "get", "(", "position", ")", ";", "viewHolder", ".", "onBindView", "(", "object", ",", "position", ")", ";", "viewHolder", ".", "setAdapter", "(", "adapter", ")", ";", "setClickListenerOnView", "(", "viewHolder", ")", ";", "setLongClickListenerOnView", "(", "viewHolder", ")", ";", "}" ]
Called by the view to display the data at the specified position. <p>The default implementation of this method will call {@link EfficientViewHolder#onBindView(Object, int)} on the {@link EfficientViewHolder} and set the click listeners if necessary.</p> @param viewHolder The ViewHolder which should be updated to represent the contents of the item at the given position in the data set. @param position The position of the item within the adapter's data set. @param adapter The adapter source
[ "Called", "by", "the", "view", "to", "display", "the", "data", "at", "the", "specified", "position", "." ]
0bcc3a20182cbce9d7901e1e2a9104251637167d
https://github.com/StanKocken/EfficientAdapter/blob/0bcc3a20182cbce9d7901e1e2a9104251637167d/efficientadapter/src/main/java/com/skocken/efficientadapter/lib/adapter/AdapterHelper.java#L91-L99
10,523
StanKocken/EfficientAdapter
efficientadapter/src/main/java/com/skocken/efficientadapter/lib/adapter/AdapterHelper.java
AdapterHelper.remove
int remove(T object) { int positionOfRemove = mObjects.indexOf(object); if (positionOfRemove >= 0) { T objectRemoved = removeAt(positionOfRemove); if (objectRemoved != null) { return positionOfRemove; } } return -1; }
java
int remove(T object) { int positionOfRemove = mObjects.indexOf(object); if (positionOfRemove >= 0) { T objectRemoved = removeAt(positionOfRemove); if (objectRemoved != null) { return positionOfRemove; } } return -1; }
[ "int", "remove", "(", "T", "object", ")", "{", "int", "positionOfRemove", "=", "mObjects", ".", "indexOf", "(", "object", ")", ";", "if", "(", "positionOfRemove", ">=", "0", ")", "{", "T", "objectRemoved", "=", "removeAt", "(", "positionOfRemove", ")", ";", "if", "(", "objectRemoved", "!=", "null", ")", "{", "return", "positionOfRemove", ";", "}", "}", "return", "-", "1", ";", "}" ]
Remove the specified object of the array. @param object The object to add at the end of the array.
[ "Remove", "the", "specified", "object", "of", "the", "array", "." ]
0bcc3a20182cbce9d7901e1e2a9104251637167d
https://github.com/StanKocken/EfficientAdapter/blob/0bcc3a20182cbce9d7901e1e2a9104251637167d/efficientadapter/src/main/java/com/skocken/efficientadapter/lib/adapter/AdapterHelper.java#L222-L231
10,524
kazocsaba/imageviewer
src/main/java/hu/kazocsaba/imageviewer/PixelMarkerOverlay.java
PixelMarkerOverlay.addPoint
public void addPoint(Point p) { if (p == null) throw new NullPointerException(); points.add(new Point(p)); repaint(); }
java
public void addPoint(Point p) { if (p == null) throw new NullPointerException(); points.add(new Point(p)); repaint(); }
[ "public", "void", "addPoint", "(", "Point", "p", ")", "{", "if", "(", "p", "==", "null", ")", "throw", "new", "NullPointerException", "(", ")", ";", "points", ".", "add", "(", "new", "Point", "(", "p", ")", ")", ";", "repaint", "(", ")", ";", "}" ]
Adds a point to the list of pixels marked by this overlay. @param p a new point @throws NullPointerException if {@code p} is {@code null}
[ "Adds", "a", "point", "to", "the", "list", "of", "pixels", "marked", "by", "this", "overlay", "." ]
59b8834c9dbf87bd9ca0898da3458ae592e3851e
https://github.com/kazocsaba/imageviewer/blob/59b8834c9dbf87bd9ca0898da3458ae592e3851e/src/main/java/hu/kazocsaba/imageviewer/PixelMarkerOverlay.java#L56-L60
10,525
kazocsaba/imageviewer
src/main/java/hu/kazocsaba/imageviewer/PixelMarkerOverlay.java
PixelMarkerOverlay.setPoint
public void setPoint(Point p) { points.clear(); if (p!=null) { points.add(new Point(p)); } repaint(); }
java
public void setPoint(Point p) { points.clear(); if (p!=null) { points.add(new Point(p)); } repaint(); }
[ "public", "void", "setPoint", "(", "Point", "p", ")", "{", "points", ".", "clear", "(", ")", ";", "if", "(", "p", "!=", "null", ")", "{", "points", ".", "add", "(", "new", "Point", "(", "p", ")", ")", ";", "}", "repaint", "(", ")", ";", "}" ]
Sets the argument as the only point marked by this overlay. @param p the point to mark; if {@code null}, then no points will be selected
[ "Sets", "the", "argument", "as", "the", "only", "point", "marked", "by", "this", "overlay", "." ]
59b8834c9dbf87bd9ca0898da3458ae592e3851e
https://github.com/kazocsaba/imageviewer/blob/59b8834c9dbf87bd9ca0898da3458ae592e3851e/src/main/java/hu/kazocsaba/imageviewer/PixelMarkerOverlay.java#L66-L72
10,526
kazocsaba/imageviewer
src/main/java/hu/kazocsaba/imageviewer/PixelMarkerOverlay.java
PixelMarkerOverlay.setPoints
public void setPoints(Iterable<Point> points) { if (points==null) throw new NullPointerException(); this.points.clear(); for (Point p : points) { this.points.add(new Point(p)); } repaint(); }
java
public void setPoints(Iterable<Point> points) { if (points==null) throw new NullPointerException(); this.points.clear(); for (Point p : points) { this.points.add(new Point(p)); } repaint(); }
[ "public", "void", "setPoints", "(", "Iterable", "<", "Point", ">", "points", ")", "{", "if", "(", "points", "==", "null", ")", "throw", "new", "NullPointerException", "(", ")", ";", "this", ".", "points", ".", "clear", "(", ")", ";", "for", "(", "Point", "p", ":", "points", ")", "{", "this", ".", "points", ".", "add", "(", "new", "Point", "(", "p", ")", ")", ";", "}", "repaint", "(", ")", ";", "}" ]
Sets the marked pixels. @param points an iterable of all the pixels that should be selected @throws NullPointerException if {@code points} or any individual point is {@code null}
[ "Sets", "the", "marked", "pixels", "." ]
59b8834c9dbf87bd9ca0898da3458ae592e3851e
https://github.com/kazocsaba/imageviewer/blob/59b8834c9dbf87bd9ca0898da3458ae592e3851e/src/main/java/hu/kazocsaba/imageviewer/PixelMarkerOverlay.java#L79-L86
10,527
StanKocken/EfficientAdapter
efficientadapter/src/main/java/com/skocken/efficientadapter/lib/util/ViewHelper.java
ViewHelper.setVisibility
public static void setVisibility(EfficientCacheView cacheView, int viewId, int visibility) { View view = cacheView.findViewByIdEfficient(viewId); if (view != null) { view.setVisibility(visibility); } }
java
public static void setVisibility(EfficientCacheView cacheView, int viewId, int visibility) { View view = cacheView.findViewByIdEfficient(viewId); if (view != null) { view.setVisibility(visibility); } }
[ "public", "static", "void", "setVisibility", "(", "EfficientCacheView", "cacheView", ",", "int", "viewId", ",", "int", "visibility", ")", "{", "View", "view", "=", "cacheView", ".", "findViewByIdEfficient", "(", "viewId", ")", ";", "if", "(", "view", "!=", "null", ")", "{", "view", ".", "setVisibility", "(", "visibility", ")", ";", "}", "}" ]
Equivalent to calling View.setVisibility @param cacheView The cache of views to get the view from @param viewId The id of the view whose visibility should change @param visibility The new visibility for the view
[ "Equivalent", "to", "calling", "View", ".", "setVisibility" ]
0bcc3a20182cbce9d7901e1e2a9104251637167d
https://github.com/StanKocken/EfficientAdapter/blob/0bcc3a20182cbce9d7901e1e2a9104251637167d/efficientadapter/src/main/java/com/skocken/efficientadapter/lib/util/ViewHelper.java#L24-L29
10,528
StanKocken/EfficientAdapter
efficientadapter/src/main/java/com/skocken/efficientadapter/lib/util/ViewHelper.java
ViewHelper.setBackground
public static void setBackground(EfficientCacheView cacheView, int viewId, Drawable drawable) { View view = cacheView.findViewByIdEfficient(viewId); if (view != null) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { view.setBackgroundDrawable(drawable); } else { view.setBackground(drawable); } } }
java
public static void setBackground(EfficientCacheView cacheView, int viewId, Drawable drawable) { View view = cacheView.findViewByIdEfficient(viewId); if (view != null) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { view.setBackgroundDrawable(drawable); } else { view.setBackground(drawable); } } }
[ "public", "static", "void", "setBackground", "(", "EfficientCacheView", "cacheView", ",", "int", "viewId", ",", "Drawable", "drawable", ")", "{", "View", "view", "=", "cacheView", ".", "findViewByIdEfficient", "(", "viewId", ")", ";", "if", "(", "view", "!=", "null", ")", "{", "if", "(", "Build", ".", "VERSION", ".", "SDK_INT", "<", "Build", ".", "VERSION_CODES", ".", "JELLY_BEAN", ")", "{", "view", ".", "setBackgroundDrawable", "(", "drawable", ")", ";", "}", "else", "{", "view", ".", "setBackground", "(", "drawable", ")", ";", "}", "}", "}" ]
Equivalent to calling View.setBackground @param cacheView The cache of views to get the view from @param viewId The id of the view whose background should change @param drawable The new background for the view
[ "Equivalent", "to", "calling", "View", ".", "setBackground" ]
0bcc3a20182cbce9d7901e1e2a9104251637167d
https://github.com/StanKocken/EfficientAdapter/blob/0bcc3a20182cbce9d7901e1e2a9104251637167d/efficientadapter/src/main/java/com/skocken/efficientadapter/lib/util/ViewHelper.java#L38-L47
10,529
StanKocken/EfficientAdapter
efficientadapter/src/main/java/com/skocken/efficientadapter/lib/util/ViewHelper.java
ViewHelper.setImageDrawable
public static void setImageDrawable(EfficientCacheView cacheView, int viewId, Drawable drawable) { View view = cacheView.findViewByIdEfficient(viewId); if (view instanceof ImageView) { ((ImageView) view).setImageDrawable(drawable); } }
java
public static void setImageDrawable(EfficientCacheView cacheView, int viewId, Drawable drawable) { View view = cacheView.findViewByIdEfficient(viewId); if (view instanceof ImageView) { ((ImageView) view).setImageDrawable(drawable); } }
[ "public", "static", "void", "setImageDrawable", "(", "EfficientCacheView", "cacheView", ",", "int", "viewId", ",", "Drawable", "drawable", ")", "{", "View", "view", "=", "cacheView", ".", "findViewByIdEfficient", "(", "viewId", ")", ";", "if", "(", "view", "instanceof", "ImageView", ")", "{", "(", "(", "ImageView", ")", "view", ")", ".", "setImageDrawable", "(", "drawable", ")", ";", "}", "}" ]
Equivalent to calling ImageView.setImageDrawable @param cacheView The cache of views to get the view from @param viewId The id of the view whose image should change @param drawable the Drawable to set, or {@code null} to clear the content
[ "Equivalent", "to", "calling", "ImageView", ".", "setImageDrawable" ]
0bcc3a20182cbce9d7901e1e2a9104251637167d
https://github.com/StanKocken/EfficientAdapter/blob/0bcc3a20182cbce9d7901e1e2a9104251637167d/efficientadapter/src/main/java/com/skocken/efficientadapter/lib/util/ViewHelper.java#L202-L208
10,530
StanKocken/EfficientAdapter
efficientadapter/src/main/java/com/skocken/efficientadapter/lib/util/ViewHelper.java
ViewHelper.setImageBitmap
public static void setImageBitmap(EfficientCacheView cacheView, int viewId, Bitmap bm) { View view = cacheView.findViewByIdEfficient(viewId); if (view instanceof ImageView) { ((ImageView) view).setImageBitmap(bm); } }
java
public static void setImageBitmap(EfficientCacheView cacheView, int viewId, Bitmap bm) { View view = cacheView.findViewByIdEfficient(viewId); if (view instanceof ImageView) { ((ImageView) view).setImageBitmap(bm); } }
[ "public", "static", "void", "setImageBitmap", "(", "EfficientCacheView", "cacheView", ",", "int", "viewId", ",", "Bitmap", "bm", ")", "{", "View", "view", "=", "cacheView", ".", "findViewByIdEfficient", "(", "viewId", ")", ";", "if", "(", "view", "instanceof", "ImageView", ")", "{", "(", "(", "ImageView", ")", "view", ")", ".", "setImageBitmap", "(", "bm", ")", ";", "}", "}" ]
Equivalent to calling ImageView.setImageBitmap @param cacheView The cache of views to get the view from @param viewId The id of the view whose image should change @param bm The bitmap to set
[ "Equivalent", "to", "calling", "ImageView", ".", "setImageBitmap" ]
0bcc3a20182cbce9d7901e1e2a9104251637167d
https://github.com/StanKocken/EfficientAdapter/blob/0bcc3a20182cbce9d7901e1e2a9104251637167d/efficientadapter/src/main/java/com/skocken/efficientadapter/lib/util/ViewHelper.java#L231-L236
10,531
grahamedgecombe/jterminal
src/main/java/com/grahamedgecombe/jterminal/JTerminal.java
JTerminal.init
private void init() { setLayout(new BorderLayout(0, 0)); int rows = model.getRows(); int bufferSize = model.getBufferSize(); if (bufferSize > rows) { scrollBar = new JScrollBar(JScrollBar.VERTICAL, 0, rows, 0, bufferSize + 1); scrollBar.addAdjustmentListener(new AdjustmentListener() { @Override public void adjustmentValueChanged(AdjustmentEvent evt) { repaint(); } }); add(BorderLayout.LINE_END, scrollBar); } add(BorderLayout.CENTER, new Terminal()); repaint(); }
java
private void init() { setLayout(new BorderLayout(0, 0)); int rows = model.getRows(); int bufferSize = model.getBufferSize(); if (bufferSize > rows) { scrollBar = new JScrollBar(JScrollBar.VERTICAL, 0, rows, 0, bufferSize + 1); scrollBar.addAdjustmentListener(new AdjustmentListener() { @Override public void adjustmentValueChanged(AdjustmentEvent evt) { repaint(); } }); add(BorderLayout.LINE_END, scrollBar); } add(BorderLayout.CENTER, new Terminal()); repaint(); }
[ "private", "void", "init", "(", ")", "{", "setLayout", "(", "new", "BorderLayout", "(", "0", ",", "0", ")", ")", ";", "int", "rows", "=", "model", ".", "getRows", "(", ")", ";", "int", "bufferSize", "=", "model", ".", "getBufferSize", "(", ")", ";", "if", "(", "bufferSize", ">", "rows", ")", "{", "scrollBar", "=", "new", "JScrollBar", "(", "JScrollBar", ".", "VERTICAL", ",", "0", ",", "rows", ",", "0", ",", "bufferSize", "+", "1", ")", ";", "scrollBar", ".", "addAdjustmentListener", "(", "new", "AdjustmentListener", "(", ")", "{", "@", "Override", "public", "void", "adjustmentValueChanged", "(", "AdjustmentEvent", "evt", ")", "{", "repaint", "(", ")", ";", "}", "}", ")", ";", "add", "(", "BorderLayout", ".", "LINE_END", ",", "scrollBar", ")", ";", "}", "add", "(", "BorderLayout", ".", "CENTER", ",", "new", "Terminal", "(", ")", ")", ";", "repaint", "(", ")", ";", "}" ]
Initializes the terminal.
[ "Initializes", "the", "terminal", "." ]
751142d9d2cafbde0ec36a80f73bb25bf297f2f3
https://github.com/grahamedgecombe/jterminal/blob/751142d9d2cafbde0ec36a80f73bb25bf297f2f3/src/main/java/com/grahamedgecombe/jterminal/JTerminal.java#L161-L181
10,532
StanKocken/EfficientAdapter
efficientadapter/src/main/java/com/skocken/efficientadapter/lib/util/EfficientCacheView.java
EfficientCacheView.clearViewCached
public void clearViewCached(int parentId, int viewId) { SparseArray<View> sparseArrayViewsParent = mSparseSparseArrayView.get(parentId); if (sparseArrayViewsParent != null) { sparseArrayViewsParent.remove(viewId); } }
java
public void clearViewCached(int parentId, int viewId) { SparseArray<View> sparseArrayViewsParent = mSparseSparseArrayView.get(parentId); if (sparseArrayViewsParent != null) { sparseArrayViewsParent.remove(viewId); } }
[ "public", "void", "clearViewCached", "(", "int", "parentId", ",", "int", "viewId", ")", "{", "SparseArray", "<", "View", ">", "sparseArrayViewsParent", "=", "mSparseSparseArrayView", ".", "get", "(", "parentId", ")", ";", "if", "(", "sparseArrayViewsParent", "!=", "null", ")", "{", "sparseArrayViewsParent", ".", "remove", "(", "viewId", ")", ";", "}", "}" ]
Clear the cache for the view specify @param parentId the parent id of the view to remove (if the view was retrieve with this parent id) @param viewId id of the view to remove from the cache
[ "Clear", "the", "cache", "for", "the", "view", "specify" ]
0bcc3a20182cbce9d7901e1e2a9104251637167d
https://github.com/StanKocken/EfficientAdapter/blob/0bcc3a20182cbce9d7901e1e2a9104251637167d/efficientadapter/src/main/java/com/skocken/efficientadapter/lib/util/EfficientCacheView.java#L43-L48
10,533
jiaqi/jcli
src/main/java/org/cyclopsgroup/jcli/spi/CommandLineBuilder.java
CommandLineBuilder.withLongOption
public CommandLineBuilder withLongOption(String name, String value) { cl.addOptionValue(name, value, false); return this; }
java
public CommandLineBuilder withLongOption(String name, String value) { cl.addOptionValue(name, value, false); return this; }
[ "public", "CommandLineBuilder", "withLongOption", "(", "String", "name", ",", "String", "value", ")", "{", "cl", ".", "addOptionValue", "(", "name", ",", "value", ",", "false", ")", ";", "return", "this", ";", "}" ]
Add an option with its long name @param name Long name of the option to add @param value Value of the option to add @return Builder itself
[ "Add", "an", "option", "with", "its", "long", "name" ]
3854b3bb3c26bbe7407bf1b6600d8b25592d398e
https://github.com/jiaqi/jcli/blob/3854b3bb3c26bbe7407bf1b6600d8b25592d398e/src/main/java/org/cyclopsgroup/jcli/spi/CommandLineBuilder.java#L60-L63
10,534
jiaqi/jcli
src/main/java/org/cyclopsgroup/jcli/spi/CommandLineBuilder.java
CommandLineBuilder.withShortOption
public CommandLineBuilder withShortOption(String name, String value) { cl.addOptionValue(name, value, true); return this; }
java
public CommandLineBuilder withShortOption(String name, String value) { cl.addOptionValue(name, value, true); return this; }
[ "public", "CommandLineBuilder", "withShortOption", "(", "String", "name", ",", "String", "value", ")", "{", "cl", ".", "addOptionValue", "(", "name", ",", "value", ",", "true", ")", ";", "return", "this", ";", "}" ]
Add an option with its short name @param name Short name of the option to add @param value Value of option to add @return Builder itself
[ "Add", "an", "option", "with", "its", "short", "name" ]
3854b3bb3c26bbe7407bf1b6600d8b25592d398e
https://github.com/jiaqi/jcli/blob/3854b3bb3c26bbe7407bf1b6600d8b25592d398e/src/main/java/org/cyclopsgroup/jcli/spi/CommandLineBuilder.java#L83-L86
10,535
jiaqi/jcli
src/main/java/org/cyclopsgroup/jcli/impl/MultiValueReference.java
MultiValueReference.setValues
@SuppressWarnings("unchecked") <P> void setValues(T bean, List<String> values) { Collection<P> col; try { col = (Collection<P>) listType.newInstance(); } catch (InstantiationException e) { throw new RuntimeException("Can't instantiate " + listType, e); } catch (IllegalAccessException e) { throw new RuntimeException("Can't access default constructor of " + listType); } for (String value : values) { col.add((P) converter.fromCharacters(value)); } ref.writeValue(col, bean); }
java
@SuppressWarnings("unchecked") <P> void setValues(T bean, List<String> values) { Collection<P> col; try { col = (Collection<P>) listType.newInstance(); } catch (InstantiationException e) { throw new RuntimeException("Can't instantiate " + listType, e); } catch (IllegalAccessException e) { throw new RuntimeException("Can't access default constructor of " + listType); } for (String value : values) { col.add((P) converter.fromCharacters(value)); } ref.writeValue(col, bean); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "<", "P", ">", "void", "setValues", "(", "T", "bean", ",", "List", "<", "String", ">", "values", ")", "{", "Collection", "<", "P", ">", "col", ";", "try", "{", "col", "=", "(", "Collection", "<", "P", ">", ")", "listType", ".", "newInstance", "(", ")", ";", "}", "catch", "(", "InstantiationException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "\"Can't instantiate \"", "+", "listType", ",", "e", ")", ";", "}", "catch", "(", "IllegalAccessException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "\"Can't access default constructor of \"", "+", "listType", ")", ";", "}", "for", "(", "String", "value", ":", "values", ")", "{", "col", ".", "add", "(", "(", "P", ")", "converter", ".", "fromCharacters", "(", "value", ")", ")", ";", "}", "ref", ".", "writeValue", "(", "col", ",", "bean", ")", ";", "}" ]
Write multi value to bean @param <P> Type of value to convert @param bean Bean to set values @param values List of values to set
[ "Write", "multi", "value", "to", "bean" ]
3854b3bb3c26bbe7407bf1b6600d8b25592d398e
https://github.com/jiaqi/jcli/blob/3854b3bb3c26bbe7407bf1b6600d8b25592d398e/src/main/java/org/cyclopsgroup/jcli/impl/MultiValueReference.java#L25-L39
10,536
jiaqi/jcli
src/main/java/org/cyclopsgroup/jcli/impl/ParsingContextBuilder.java
ParsingContextBuilder.getAnnotation
@Nullable private static <A extends Annotation> A getAnnotation(PropertyDescriptor descriptor, Class<A> type) { A a = null; if (descriptor.getWriteMethod() != null) { a = descriptor.getWriteMethod().getAnnotation(type); } if (a == null && descriptor.getReadMethod() != null) { a = descriptor.getReadMethod().getAnnotation(type); } return a; }
java
@Nullable private static <A extends Annotation> A getAnnotation(PropertyDescriptor descriptor, Class<A> type) { A a = null; if (descriptor.getWriteMethod() != null) { a = descriptor.getWriteMethod().getAnnotation(type); } if (a == null && descriptor.getReadMethod() != null) { a = descriptor.getReadMethod().getAnnotation(type); } return a; }
[ "@", "Nullable", "private", "static", "<", "A", "extends", "Annotation", ">", "A", "getAnnotation", "(", "PropertyDescriptor", "descriptor", ",", "Class", "<", "A", ">", "type", ")", "{", "A", "a", "=", "null", ";", "if", "(", "descriptor", ".", "getWriteMethod", "(", ")", "!=", "null", ")", "{", "a", "=", "descriptor", ".", "getWriteMethod", "(", ")", ".", "getAnnotation", "(", "type", ")", ";", "}", "if", "(", "a", "==", "null", "&&", "descriptor", ".", "getReadMethod", "(", ")", "!=", "null", ")", "{", "a", "=", "descriptor", ".", "getReadMethod", "(", ")", ".", "getAnnotation", "(", "type", ")", ";", "}", "return", "a", ";", "}" ]
Get annotation from either writer or reader of a Java property @param <A> Type of annotation @param descriptor Field descriptor from which annotation is searched @param type Type of annotation @return Annotation or null if it's not found
[ "Get", "annotation", "from", "either", "writer", "or", "reader", "of", "a", "Java", "property" ]
3854b3bb3c26bbe7407bf1b6600d8b25592d398e
https://github.com/jiaqi/jcli/blob/3854b3bb3c26bbe7407bf1b6600d8b25592d398e/src/main/java/org/cyclopsgroup/jcli/impl/ParsingContextBuilder.java#L56-L67
10,537
kazocsaba/imageviewer
src/main/java/hu/kazocsaba/imageviewer/PixelInfoStatusBar.java
PixelInfoStatusBar.setModel
public final void setModel(PixelModel newModel) { if (newModel == null) throw new NullPointerException(); if (model != newModel) { if (model != null) model.removeChangeListener(modelListener); model = newModel; model.addChangeListener(modelListener); update(); } }
java
public final void setModel(PixelModel newModel) { if (newModel == null) throw new NullPointerException(); if (model != newModel) { if (model != null) model.removeChangeListener(modelListener); model = newModel; model.addChangeListener(modelListener); update(); } }
[ "public", "final", "void", "setModel", "(", "PixelModel", "newModel", ")", "{", "if", "(", "newModel", "==", "null", ")", "throw", "new", "NullPointerException", "(", ")", ";", "if", "(", "model", "!=", "newModel", ")", "{", "if", "(", "model", "!=", "null", ")", "model", ".", "removeChangeListener", "(", "modelListener", ")", ";", "model", "=", "newModel", ";", "model", ".", "addChangeListener", "(", "modelListener", ")", ";", "update", "(", ")", ";", "}", "}" ]
Sets the model dictating the pixel shown by this status bar. @param newModel the new model @throws NullPointerException if {@code newModel} is {@code null}
[ "Sets", "the", "model", "dictating", "the", "pixel", "shown", "by", "this", "status", "bar", "." ]
59b8834c9dbf87bd9ca0898da3458ae592e3851e
https://github.com/kazocsaba/imageviewer/blob/59b8834c9dbf87bd9ca0898da3458ae592e3851e/src/main/java/hu/kazocsaba/imageviewer/PixelInfoStatusBar.java#L67-L77
10,538
kazocsaba/imageviewer
src/main/java/hu/kazocsaba/imageviewer/PixelInfoStatusBar.java
PixelInfoStatusBar.update
protected final void update() { BufferedImage image=getImageViewer()==null ? null : getImageViewer().getImage(); if (image==null || model.isInvalid() || model.getX()>=image.getWidth() || model.getY()>=image.getHeight()) updateLabelNoData(); else updateLabel(image, model.getX(), model.getY(), statusBar.getWidth()-statusBarInsets.left-statusBarInsets.right); }
java
protected final void update() { BufferedImage image=getImageViewer()==null ? null : getImageViewer().getImage(); if (image==null || model.isInvalid() || model.getX()>=image.getWidth() || model.getY()>=image.getHeight()) updateLabelNoData(); else updateLabel(image, model.getX(), model.getY(), statusBar.getWidth()-statusBarInsets.left-statusBarInsets.right); }
[ "protected", "final", "void", "update", "(", ")", "{", "BufferedImage", "image", "=", "getImageViewer", "(", ")", "==", "null", "?", "null", ":", "getImageViewer", "(", ")", ".", "getImage", "(", ")", ";", "if", "(", "image", "==", "null", "||", "model", ".", "isInvalid", "(", ")", "||", "model", ".", "getX", "(", ")", ">=", "image", ".", "getWidth", "(", ")", "||", "model", ".", "getY", "(", ")", ">=", "image", ".", "getHeight", "(", ")", ")", "updateLabelNoData", "(", ")", ";", "else", "updateLabel", "(", "image", ",", "model", ".", "getX", "(", ")", ",", "model", ".", "getY", "(", ")", ",", "statusBar", ".", "getWidth", "(", ")", "-", "statusBarInsets", ".", "left", "-", "statusBarInsets", ".", "right", ")", ";", "}" ]
Updates the info label. This function is called when either the selected pixel or the image shown in the viewer is changed. You can call this method to indicate that the message should be updated for some different reason.
[ "Updates", "the", "info", "label", ".", "This", "function", "is", "called", "when", "either", "the", "selected", "pixel", "or", "the", "image", "shown", "in", "the", "viewer", "is", "changed", ".", "You", "can", "call", "this", "method", "to", "indicate", "that", "the", "message", "should", "be", "updated", "for", "some", "different", "reason", "." ]
59b8834c9dbf87bd9ca0898da3458ae592e3851e
https://github.com/kazocsaba/imageviewer/blob/59b8834c9dbf87bd9ca0898da3458ae592e3851e/src/main/java/hu/kazocsaba/imageviewer/PixelInfoStatusBar.java#L107-L113
10,539
kazocsaba/imageviewer
src/main/java/hu/kazocsaba/imageviewer/ImageSequenceViewer.java
ImageSequenceViewer.setPosition
public void setPosition(int pos) { if (pos < 0 || pos >= number) throw new IllegalArgumentException("Position " + pos + " out of range"); position = pos; updateLocationDefinition(position); forwardButton.setEnabled(position < number - 1); backwardButton.setEnabled(position > 0); if (panel.getParent()!=null) positionChanged(); }
java
public void setPosition(int pos) { if (pos < 0 || pos >= number) throw new IllegalArgumentException("Position " + pos + " out of range"); position = pos; updateLocationDefinition(position); forwardButton.setEnabled(position < number - 1); backwardButton.setEnabled(position > 0); if (panel.getParent()!=null) positionChanged(); }
[ "public", "void", "setPosition", "(", "int", "pos", ")", "{", "if", "(", "pos", "<", "0", "||", "pos", ">=", "number", ")", "throw", "new", "IllegalArgumentException", "(", "\"Position \"", "+", "pos", "+", "\" out of range\"", ")", ";", "position", "=", "pos", ";", "updateLocationDefinition", "(", "position", ")", ";", "forwardButton", ".", "setEnabled", "(", "position", "<", "number", "-", "1", ")", ";", "backwardButton", ".", "setEnabled", "(", "position", ">", "0", ")", ";", "if", "(", "panel", ".", "getParent", "(", ")", "!=", "null", ")", "positionChanged", "(", ")", ";", "}" ]
Sets the position of the viewer. @param pos the new position of the viewer @throws IllegalArgumentException if the position is not valid
[ "Sets", "the", "position", "of", "the", "viewer", "." ]
59b8834c9dbf87bd9ca0898da3458ae592e3851e
https://github.com/kazocsaba/imageviewer/blob/59b8834c9dbf87bd9ca0898da3458ae592e3851e/src/main/java/hu/kazocsaba/imageviewer/ImageSequenceViewer.java#L114-L122
10,540
kazocsaba/imageviewer
src/main/java/hu/kazocsaba/imageviewer/ImageViewer.java
ImageViewer.setStatusBarVisible
public void setStatusBarVisible(boolean statusBarVisible) { if (this.statusBarVisible == statusBarVisible) return; if (statusBar!=null) { if (statusBarVisible) panel.add(statusBar.getComponent(), BorderLayout.SOUTH); else panel.remove(statusBar.getComponent()); panel.revalidate(); panel.repaint(); } boolean prev = this.statusBarVisible; this.statusBarVisible = statusBarVisible; synchronizer.statusBarVisibilityChanged(this); propertyChangeSupport.firePropertyChange("statusBarVisible", prev, statusBarVisible); }
java
public void setStatusBarVisible(boolean statusBarVisible) { if (this.statusBarVisible == statusBarVisible) return; if (statusBar!=null) { if (statusBarVisible) panel.add(statusBar.getComponent(), BorderLayout.SOUTH); else panel.remove(statusBar.getComponent()); panel.revalidate(); panel.repaint(); } boolean prev = this.statusBarVisible; this.statusBarVisible = statusBarVisible; synchronizer.statusBarVisibilityChanged(this); propertyChangeSupport.firePropertyChange("statusBarVisible", prev, statusBarVisible); }
[ "public", "void", "setStatusBarVisible", "(", "boolean", "statusBarVisible", ")", "{", "if", "(", "this", ".", "statusBarVisible", "==", "statusBarVisible", ")", "return", ";", "if", "(", "statusBar", "!=", "null", ")", "{", "if", "(", "statusBarVisible", ")", "panel", ".", "add", "(", "statusBar", ".", "getComponent", "(", ")", ",", "BorderLayout", ".", "SOUTH", ")", ";", "else", "panel", ".", "remove", "(", "statusBar", ".", "getComponent", "(", ")", ")", ";", "panel", ".", "revalidate", "(", ")", ";", "panel", ".", "repaint", "(", ")", ";", "}", "boolean", "prev", "=", "this", ".", "statusBarVisible", ";", "this", ".", "statusBarVisible", "=", "statusBarVisible", ";", "synchronizer", ".", "statusBarVisibilityChanged", "(", "this", ")", ";", "propertyChangeSupport", ".", "firePropertyChange", "(", "\"statusBarVisible\"", ",", "prev", ",", "statusBarVisible", ")", ";", "}" ]
Sets whether the status bar is visible. The status bar is hidden by default. @param statusBarVisible true, if the status bar should be visible; false otherwise
[ "Sets", "whether", "the", "status", "bar", "is", "visible", ".", "The", "status", "bar", "is", "hidden", "by", "default", "." ]
59b8834c9dbf87bd9ca0898da3458ae592e3851e
https://github.com/kazocsaba/imageviewer/blob/59b8834c9dbf87bd9ca0898da3458ae592e3851e/src/main/java/hu/kazocsaba/imageviewer/ImageViewer.java#L173-L187
10,541
StanKocken/EfficientAdapter
efficientadapter/src/main/java/com/skocken/efficientadapter/lib/viewholder/EfficientViewHolder.java
EfficientViewHolder.getOnClickListener
public View.OnClickListener getOnClickListener(boolean adapterHasListener) { if (isClickable() && adapterHasListener) { if (mViewHolderClickListener == null) { mViewHolderClickListener = new ViewHolderClickListener<>(this); } } else { mViewHolderClickListener = null; } return mViewHolderClickListener; }
java
public View.OnClickListener getOnClickListener(boolean adapterHasListener) { if (isClickable() && adapterHasListener) { if (mViewHolderClickListener == null) { mViewHolderClickListener = new ViewHolderClickListener<>(this); } } else { mViewHolderClickListener = null; } return mViewHolderClickListener; }
[ "public", "View", ".", "OnClickListener", "getOnClickListener", "(", "boolean", "adapterHasListener", ")", "{", "if", "(", "isClickable", "(", ")", "&&", "adapterHasListener", ")", "{", "if", "(", "mViewHolderClickListener", "==", "null", ")", "{", "mViewHolderClickListener", "=", "new", "ViewHolderClickListener", "<>", "(", "this", ")", ";", "}", "}", "else", "{", "mViewHolderClickListener", "=", "null", ";", "}", "return", "mViewHolderClickListener", ";", "}" ]
Get the OnClickListener to call when the user click on the item. @param adapterHasListener true if the calling adapter has a global listener on the item. @return the click listener to be put into the view.
[ "Get", "the", "OnClickListener", "to", "call", "when", "the", "user", "click", "on", "the", "item", "." ]
0bcc3a20182cbce9d7901e1e2a9104251637167d
https://github.com/StanKocken/EfficientAdapter/blob/0bcc3a20182cbce9d7901e1e2a9104251637167d/efficientadapter/src/main/java/com/skocken/efficientadapter/lib/viewholder/EfficientViewHolder.java#L173-L182
10,542
StanKocken/EfficientAdapter
efficientadapter/src/main/java/com/skocken/efficientadapter/lib/viewholder/EfficientViewHolder.java
EfficientViewHolder.getOnLongClickListener
public View.OnLongClickListener getOnLongClickListener(boolean adapterHasListener) { if (isLongClickable() && adapterHasListener) { if (mViewHolderLongClickListener == null) { mViewHolderLongClickListener = new ViewHolderLongClickListener<>(this); } } else { mViewHolderLongClickListener = null; } return mViewHolderLongClickListener; }
java
public View.OnLongClickListener getOnLongClickListener(boolean adapterHasListener) { if (isLongClickable() && adapterHasListener) { if (mViewHolderLongClickListener == null) { mViewHolderLongClickListener = new ViewHolderLongClickListener<>(this); } } else { mViewHolderLongClickListener = null; } return mViewHolderLongClickListener; }
[ "public", "View", ".", "OnLongClickListener", "getOnLongClickListener", "(", "boolean", "adapterHasListener", ")", "{", "if", "(", "isLongClickable", "(", ")", "&&", "adapterHasListener", ")", "{", "if", "(", "mViewHolderLongClickListener", "==", "null", ")", "{", "mViewHolderLongClickListener", "=", "new", "ViewHolderLongClickListener", "<>", "(", "this", ")", ";", "}", "}", "else", "{", "mViewHolderLongClickListener", "=", "null", ";", "}", "return", "mViewHolderLongClickListener", ";", "}" ]
Get the OnLongClickListener to call when the user long-click on the item. @param adapterHasListener true if the calling adapter has a global listener on the item. @return the long-click listener to be put into the view.
[ "Get", "the", "OnLongClickListener", "to", "call", "when", "the", "user", "long", "-", "click", "on", "the", "item", "." ]
0bcc3a20182cbce9d7901e1e2a9104251637167d
https://github.com/StanKocken/EfficientAdapter/blob/0bcc3a20182cbce9d7901e1e2a9104251637167d/efficientadapter/src/main/java/com/skocken/efficientadapter/lib/viewholder/EfficientViewHolder.java#L189-L198
10,543
jiaqi/jcli
src/main/java/org/cyclopsgroup/jcli/impl/AnnotationParsingContext.java
AnnotationParsingContext.lookupReference
Reference<T> lookupReference(String name, boolean isLongName) { if (isLongName) { for (Reference<T> r : referenceMap.values()) { if (r.longName.equals(name)) { return r; } } return null; } return referenceMap.get(name); }
java
Reference<T> lookupReference(String name, boolean isLongName) { if (isLongName) { for (Reference<T> r : referenceMap.values()) { if (r.longName.equals(name)) { return r; } } return null; } return referenceMap.get(name); }
[ "Reference", "<", "T", ">", "lookupReference", "(", "String", "name", ",", "boolean", "isLongName", ")", "{", "if", "(", "isLongName", ")", "{", "for", "(", "Reference", "<", "T", ">", "r", ":", "referenceMap", ".", "values", "(", ")", ")", "{", "if", "(", "r", ".", "longName", ".", "equals", "(", "name", ")", ")", "{", "return", "r", ";", "}", "}", "return", "null", ";", "}", "return", "referenceMap", ".", "get", "(", "name", ")", ";", "}" ]
Find reference with given name of option or argument @param name Name of option or argument @param isLongName True if name is a long name @return Reference that matches name or NULL
[ "Find", "reference", "with", "given", "name", "of", "option", "or", "argument" ]
3854b3bb3c26bbe7407bf1b6600d8b25592d398e
https://github.com/jiaqi/jcli/blob/3854b3bb3c26bbe7407bf1b6600d8b25592d398e/src/main/java/org/cyclopsgroup/jcli/impl/AnnotationParsingContext.java#L52-L62
10,544
jiaqi/jcli
src/main/java/org/cyclopsgroup/jcli/jline/ArgumentsInspector.java
ArgumentsInspector.end
void end() { switch (state) { case OPTION: currentOption = context.optionWithShortName(currentValue.substring(1)); case LONG_OPTION: if (state == ArgumentsInspectorState.LONG_OPTION) { currentOption = context.optionWithLongName(currentValue.substring(2)); } if (currentOption != null && !currentOption.isMultiValue()) { remainingOptions.remove(currentOption); } if (currentOption == null || currentOption.isFlag()) { state = ArgumentsInspectorState.ARGUMENT; } else { state = ArgumentsInspectorState.OPTION_VALUE; } break; default: state = ArgumentsInspectorState.READY; } currentValue = null; }
java
void end() { switch (state) { case OPTION: currentOption = context.optionWithShortName(currentValue.substring(1)); case LONG_OPTION: if (state == ArgumentsInspectorState.LONG_OPTION) { currentOption = context.optionWithLongName(currentValue.substring(2)); } if (currentOption != null && !currentOption.isMultiValue()) { remainingOptions.remove(currentOption); } if (currentOption == null || currentOption.isFlag()) { state = ArgumentsInspectorState.ARGUMENT; } else { state = ArgumentsInspectorState.OPTION_VALUE; } break; default: state = ArgumentsInspectorState.READY; } currentValue = null; }
[ "void", "end", "(", ")", "{", "switch", "(", "state", ")", "{", "case", "OPTION", ":", "currentOption", "=", "context", ".", "optionWithShortName", "(", "currentValue", ".", "substring", "(", "1", ")", ")", ";", "case", "LONG_OPTION", ":", "if", "(", "state", "==", "ArgumentsInspectorState", ".", "LONG_OPTION", ")", "{", "currentOption", "=", "context", ".", "optionWithLongName", "(", "currentValue", ".", "substring", "(", "2", ")", ")", ";", "}", "if", "(", "currentOption", "!=", "null", "&&", "!", "currentOption", ".", "isMultiValue", "(", ")", ")", "{", "remainingOptions", ".", "remove", "(", "currentOption", ")", ";", "}", "if", "(", "currentOption", "==", "null", "||", "currentOption", ".", "isFlag", "(", ")", ")", "{", "state", "=", "ArgumentsInspectorState", ".", "ARGUMENT", ";", "}", "else", "{", "state", "=", "ArgumentsInspectorState", ".", "OPTION_VALUE", ";", "}", "break", ";", "default", ":", "state", "=", "ArgumentsInspectorState", ".", "READY", ";", "}", "currentValue", "=", "null", ";", "}" ]
End the process
[ "End", "the", "process" ]
3854b3bb3c26bbe7407bf1b6600d8b25592d398e
https://github.com/jiaqi/jcli/blob/3854b3bb3c26bbe7407bf1b6600d8b25592d398e/src/main/java/org/cyclopsgroup/jcli/jline/ArgumentsInspector.java#L76-L97
10,545
jiaqi/jcli
src/main/java/org/cyclopsgroup/jcli/impl/SingleValueReference.java
SingleValueReference.setValue
void setValue(T bean, String value) { ref.writeValue(converter.fromCharacters(value), bean); }
java
void setValue(T bean, String value) { ref.writeValue(converter.fromCharacters(value), bean); }
[ "void", "setValue", "(", "T", "bean", ",", "String", "value", ")", "{", "ref", ".", "writeValue", "(", "converter", ".", "fromCharacters", "(", "value", ")", ",", "bean", ")", ";", "}" ]
Set a string value to bean based on known conversion rule and value reference @param bean Bean to set value to @param value String expression of value to set
[ "Set", "a", "string", "value", "to", "bean", "based", "on", "known", "conversion", "rule", "and", "value", "reference" ]
3854b3bb3c26bbe7407bf1b6600d8b25592d398e
https://github.com/jiaqi/jcli/blob/3854b3bb3c26bbe7407bf1b6600d8b25592d398e/src/main/java/org/cyclopsgroup/jcli/impl/SingleValueReference.java#L18-L20
10,546
kazocsaba/imageviewer
src/main/java/hu/kazocsaba/imageviewer/PixelModel.java
PixelModel.fireChange
protected void fireChange() { Object[] listeners = listenerList.getListenerList(); ChangeEvent event = new ChangeEvent(this); for (int i = listeners.length - 2; i >= 0; i -= 2) { if (listeners[i] == ChangeListener.class) { ((ChangeListener)listeners[i + 1]).stateChanged(event); } } }
java
protected void fireChange() { Object[] listeners = listenerList.getListenerList(); ChangeEvent event = new ChangeEvent(this); for (int i = listeners.length - 2; i >= 0; i -= 2) { if (listeners[i] == ChangeListener.class) { ((ChangeListener)listeners[i + 1]).stateChanged(event); } } }
[ "protected", "void", "fireChange", "(", ")", "{", "Object", "[", "]", "listeners", "=", "listenerList", ".", "getListenerList", "(", ")", ";", "ChangeEvent", "event", "=", "new", "ChangeEvent", "(", "this", ")", ";", "for", "(", "int", "i", "=", "listeners", ".", "length", "-", "2", ";", "i", ">=", "0", ";", "i", "-=", "2", ")", "{", "if", "(", "listeners", "[", "i", "]", "==", "ChangeListener", ".", "class", ")", "{", "(", "(", "ChangeListener", ")", "listeners", "[", "i", "+", "1", "]", ")", ".", "stateChanged", "(", "event", ")", ";", "}", "}", "}" ]
Notifies the registered listeners that the model has changed.
[ "Notifies", "the", "registered", "listeners", "that", "the", "model", "has", "changed", "." ]
59b8834c9dbf87bd9ca0898da3458ae592e3851e
https://github.com/kazocsaba/imageviewer/blob/59b8834c9dbf87bd9ca0898da3458ae592e3851e/src/main/java/hu/kazocsaba/imageviewer/PixelModel.java#L36-L44
10,547
kazocsaba/imageviewer
src/main/java/hu/kazocsaba/imageviewer/LayeredImageView.java
LayeredImageView.addOverlay
public void addOverlay(Overlay overlay, int layer) { if (overlay==null) throw new NullPointerException(); OverlayComponent c=new OverlayComponent(overlay, theImage); overlay.addOverlayComponent(c); layeredPane.add(c, Integer.valueOf(layer)); layeredPane.revalidate(); layeredPane.repaint(); }
java
public void addOverlay(Overlay overlay, int layer) { if (overlay==null) throw new NullPointerException(); OverlayComponent c=new OverlayComponent(overlay, theImage); overlay.addOverlayComponent(c); layeredPane.add(c, Integer.valueOf(layer)); layeredPane.revalidate(); layeredPane.repaint(); }
[ "public", "void", "addOverlay", "(", "Overlay", "overlay", ",", "int", "layer", ")", "{", "if", "(", "overlay", "==", "null", ")", "throw", "new", "NullPointerException", "(", ")", ";", "OverlayComponent", "c", "=", "new", "OverlayComponent", "(", "overlay", ",", "theImage", ")", ";", "overlay", ".", "addOverlayComponent", "(", "c", ")", ";", "layeredPane", ".", "add", "(", "c", ",", "Integer", ".", "valueOf", "(", "layer", ")", ")", ";", "layeredPane", ".", "revalidate", "(", ")", ";", "layeredPane", ".", "repaint", "(", ")", ";", "}" ]
Adds an overlay as the specified layer. @param overlay the overlay to add @param layer the layer to add the overlay to; higher layers are on top of lower layers; the image resides in layer 0
[ "Adds", "an", "overlay", "as", "the", "specified", "layer", "." ]
59b8834c9dbf87bd9ca0898da3458ae592e3851e
https://github.com/kazocsaba/imageviewer/blob/59b8834c9dbf87bd9ca0898da3458ae592e3851e/src/main/java/hu/kazocsaba/imageviewer/LayeredImageView.java#L40-L47
10,548
kazocsaba/imageviewer
src/main/java/hu/kazocsaba/imageviewer/LayeredImageView.java
LayeredImageView.removeOverlay
public void removeOverlay(Overlay overlay) { if (overlay==null) throw new NullPointerException(); for (Component c: layeredPane.getComponents()) { if (c instanceof OverlayComponent && ((OverlayComponent)c).overlay==overlay) { overlay.removeOverlayComponent((OverlayComponent)c); layeredPane.remove(c); layeredPane.revalidate(); layeredPane.repaint(); return; } } throw new IllegalArgumentException("Overlay not part of this viewer"); }
java
public void removeOverlay(Overlay overlay) { if (overlay==null) throw new NullPointerException(); for (Component c: layeredPane.getComponents()) { if (c instanceof OverlayComponent && ((OverlayComponent)c).overlay==overlay) { overlay.removeOverlayComponent((OverlayComponent)c); layeredPane.remove(c); layeredPane.revalidate(); layeredPane.repaint(); return; } } throw new IllegalArgumentException("Overlay not part of this viewer"); }
[ "public", "void", "removeOverlay", "(", "Overlay", "overlay", ")", "{", "if", "(", "overlay", "==", "null", ")", "throw", "new", "NullPointerException", "(", ")", ";", "for", "(", "Component", "c", ":", "layeredPane", ".", "getComponents", "(", ")", ")", "{", "if", "(", "c", "instanceof", "OverlayComponent", "&&", "(", "(", "OverlayComponent", ")", "c", ")", ".", "overlay", "==", "overlay", ")", "{", "overlay", ".", "removeOverlayComponent", "(", "(", "OverlayComponent", ")", "c", ")", ";", "layeredPane", ".", "remove", "(", "c", ")", ";", "layeredPane", ".", "revalidate", "(", ")", ";", "layeredPane", ".", "repaint", "(", ")", ";", "return", ";", "}", "}", "throw", "new", "IllegalArgumentException", "(", "\"Overlay not part of this viewer\"", ")", ";", "}" ]
Removes an overlay from the image viewer. @param overlay the overlay to remove @throws IllegalArgumentException if the overlay is not in the image viewer
[ "Removes", "an", "overlay", "from", "the", "image", "viewer", "." ]
59b8834c9dbf87bd9ca0898da3458ae592e3851e
https://github.com/kazocsaba/imageviewer/blob/59b8834c9dbf87bd9ca0898da3458ae592e3851e/src/main/java/hu/kazocsaba/imageviewer/LayeredImageView.java#L53-L65
10,549
gitblit/fathom
fathom-security/src/main/java/fathom/realm/MemoryRealm.java
MemoryRealm.parseDefinedRoles
protected Map<String, Role> parseDefinedRoles(Config config) { // Parse the defined Roles Map<String, Role> roleMap = new HashMap<>(); if (!config.hasPath("roles")) { log.trace("'{}' has no roles", config); } else if (config.hasPath("roles")) { log.trace("Parsing Role definitions"); Config roleConfig = config.getConfig("roles"); for (Map.Entry<String, ConfigValue> entry : roleConfig.entrySet()) { String name = entry.getKey(); List<String> permissions = roleConfig.getStringList(name); Role role = new Role(name, permissions.toArray(new String[permissions.size()])); roleMap.put(role.getName(), role); } } return Collections.unmodifiableMap(roleMap); }
java
protected Map<String, Role> parseDefinedRoles(Config config) { // Parse the defined Roles Map<String, Role> roleMap = new HashMap<>(); if (!config.hasPath("roles")) { log.trace("'{}' has no roles", config); } else if (config.hasPath("roles")) { log.trace("Parsing Role definitions"); Config roleConfig = config.getConfig("roles"); for (Map.Entry<String, ConfigValue> entry : roleConfig.entrySet()) { String name = entry.getKey(); List<String> permissions = roleConfig.getStringList(name); Role role = new Role(name, permissions.toArray(new String[permissions.size()])); roleMap.put(role.getName(), role); } } return Collections.unmodifiableMap(roleMap); }
[ "protected", "Map", "<", "String", ",", "Role", ">", "parseDefinedRoles", "(", "Config", "config", ")", "{", "// Parse the defined Roles", "Map", "<", "String", ",", "Role", ">", "roleMap", "=", "new", "HashMap", "<>", "(", ")", ";", "if", "(", "!", "config", ".", "hasPath", "(", "\"roles\"", ")", ")", "{", "log", ".", "trace", "(", "\"'{}' has no roles\"", ",", "config", ")", ";", "}", "else", "if", "(", "config", ".", "hasPath", "(", "\"roles\"", ")", ")", "{", "log", ".", "trace", "(", "\"Parsing Role definitions\"", ")", ";", "Config", "roleConfig", "=", "config", ".", "getConfig", "(", "\"roles\"", ")", ";", "for", "(", "Map", ".", "Entry", "<", "String", ",", "ConfigValue", ">", "entry", ":", "roleConfig", ".", "entrySet", "(", ")", ")", "{", "String", "name", "=", "entry", ".", "getKey", "(", ")", ";", "List", "<", "String", ">", "permissions", "=", "roleConfig", ".", "getStringList", "(", "name", ")", ";", "Role", "role", "=", "new", "Role", "(", "name", ",", "permissions", ".", "toArray", "(", "new", "String", "[", "permissions", ".", "size", "(", ")", "]", ")", ")", ";", "roleMap", ".", "put", "(", "role", ".", "getName", "(", ")", ",", "role", ")", ";", "}", "}", "return", "Collections", ".", "unmodifiableMap", "(", "roleMap", ")", ";", "}" ]
Parse the Roles specified in the Config object. @param config @return a map of Name-Role
[ "Parse", "the", "Roles", "specified", "in", "the", "Config", "object", "." ]
f2f820eb16e9fea1e36ad4eda4ed51b35f056538
https://github.com/gitblit/fathom/blob/f2f820eb16e9fea1e36ad4eda4ed51b35f056538/fathom-security/src/main/java/fathom/realm/MemoryRealm.java#L168-L185
10,550
gitblit/fathom
fathom-core/src/main/java/fathom/utils/ClassUtil.java
ClassUtil.getClasses
public static Collection<Class<?>> getClasses(String... packageNames) { List<Class<?>> classes = new ArrayList<>(); for (String packageName : packageNames) { final String packagePath = packageName.replace('.', '/'); final String packagePrefix = packageName + '.'; List<URL> packageUrls = getResources(packagePath); for (URL packageUrl : packageUrls) { if (packageUrl.getProtocol().equals("jar")) { log.debug("Scanning jar {} for classes", packageUrl); try { String jar = packageUrl.toString().substring("jar:".length()).split("!")[0]; File file = new File(new URI(jar)); try (JarInputStream is = new JarInputStream(new FileInputStream(file))) { JarEntry entry = null; while ((entry = is.getNextJarEntry()) != null) { if (!entry.isDirectory() && entry.getName().endsWith(".class")) { String className = entry.getName().replace(".class", "").replace('/', '.'); if (className.startsWith(packagePrefix)) { Class<?> aClass = getClass(className); classes.add(aClass); } } } } } catch (URISyntaxException | IOException e) { throw new FathomException(e, "Failed to get classes for package '{}'", packageName); } } else { log.debug("Scanning filesystem {} for classes", packageUrl); log.debug(packageUrl.getProtocol()); try (InputStream is = packageUrl.openStream()) { Preconditions.checkNotNull(is, "Package url %s stream is null!", packageUrl); try (BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) { classes.addAll(reader.lines() .filter(line -> line != null && line.endsWith(".class")) .map(line -> { String className = line.replace(".class", "").replace('/', '.'); try { Class<?> aClass = getClass(packagePrefix + className); return aClass; } catch (Exception e) { log.error("Failed to find {}", line, e); } return null; }) .collect(Collectors.toList())); } } catch (IOException e) { throw new FathomException(e, "Failed to get classes for package '{}'", packageName); } } } } return Collections.unmodifiableCollection(classes); }
java
public static Collection<Class<?>> getClasses(String... packageNames) { List<Class<?>> classes = new ArrayList<>(); for (String packageName : packageNames) { final String packagePath = packageName.replace('.', '/'); final String packagePrefix = packageName + '.'; List<URL> packageUrls = getResources(packagePath); for (URL packageUrl : packageUrls) { if (packageUrl.getProtocol().equals("jar")) { log.debug("Scanning jar {} for classes", packageUrl); try { String jar = packageUrl.toString().substring("jar:".length()).split("!")[0]; File file = new File(new URI(jar)); try (JarInputStream is = new JarInputStream(new FileInputStream(file))) { JarEntry entry = null; while ((entry = is.getNextJarEntry()) != null) { if (!entry.isDirectory() && entry.getName().endsWith(".class")) { String className = entry.getName().replace(".class", "").replace('/', '.'); if (className.startsWith(packagePrefix)) { Class<?> aClass = getClass(className); classes.add(aClass); } } } } } catch (URISyntaxException | IOException e) { throw new FathomException(e, "Failed to get classes for package '{}'", packageName); } } else { log.debug("Scanning filesystem {} for classes", packageUrl); log.debug(packageUrl.getProtocol()); try (InputStream is = packageUrl.openStream()) { Preconditions.checkNotNull(is, "Package url %s stream is null!", packageUrl); try (BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) { classes.addAll(reader.lines() .filter(line -> line != null && line.endsWith(".class")) .map(line -> { String className = line.replace(".class", "").replace('/', '.'); try { Class<?> aClass = getClass(packagePrefix + className); return aClass; } catch (Exception e) { log.error("Failed to find {}", line, e); } return null; }) .collect(Collectors.toList())); } } catch (IOException e) { throw new FathomException(e, "Failed to get classes for package '{}'", packageName); } } } } return Collections.unmodifiableCollection(classes); }
[ "public", "static", "Collection", "<", "Class", "<", "?", ">", ">", "getClasses", "(", "String", "...", "packageNames", ")", "{", "List", "<", "Class", "<", "?", ">", ">", "classes", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "String", "packageName", ":", "packageNames", ")", "{", "final", "String", "packagePath", "=", "packageName", ".", "replace", "(", "'", "'", ",", "'", "'", ")", ";", "final", "String", "packagePrefix", "=", "packageName", "+", "'", "'", ";", "List", "<", "URL", ">", "packageUrls", "=", "getResources", "(", "packagePath", ")", ";", "for", "(", "URL", "packageUrl", ":", "packageUrls", ")", "{", "if", "(", "packageUrl", ".", "getProtocol", "(", ")", ".", "equals", "(", "\"jar\"", ")", ")", "{", "log", ".", "debug", "(", "\"Scanning jar {} for classes\"", ",", "packageUrl", ")", ";", "try", "{", "String", "jar", "=", "packageUrl", ".", "toString", "(", ")", ".", "substring", "(", "\"jar:\"", ".", "length", "(", ")", ")", ".", "split", "(", "\"!\"", ")", "[", "0", "]", ";", "File", "file", "=", "new", "File", "(", "new", "URI", "(", "jar", ")", ")", ";", "try", "(", "JarInputStream", "is", "=", "new", "JarInputStream", "(", "new", "FileInputStream", "(", "file", ")", ")", ")", "{", "JarEntry", "entry", "=", "null", ";", "while", "(", "(", "entry", "=", "is", ".", "getNextJarEntry", "(", ")", ")", "!=", "null", ")", "{", "if", "(", "!", "entry", ".", "isDirectory", "(", ")", "&&", "entry", ".", "getName", "(", ")", ".", "endsWith", "(", "\".class\"", ")", ")", "{", "String", "className", "=", "entry", ".", "getName", "(", ")", ".", "replace", "(", "\".class\"", ",", "\"\"", ")", ".", "replace", "(", "'", "'", ",", "'", "'", ")", ";", "if", "(", "className", ".", "startsWith", "(", "packagePrefix", ")", ")", "{", "Class", "<", "?", ">", "aClass", "=", "getClass", "(", "className", ")", ";", "classes", ".", "add", "(", "aClass", ")", ";", "}", "}", "}", "}", "}", "catch", "(", "URISyntaxException", "|", "IOException", "e", ")", "{", "throw", "new", "FathomException", "(", "e", ",", "\"Failed to get classes for package '{}'\"", ",", "packageName", ")", ";", "}", "}", "else", "{", "log", ".", "debug", "(", "\"Scanning filesystem {} for classes\"", ",", "packageUrl", ")", ";", "log", ".", "debug", "(", "packageUrl", ".", "getProtocol", "(", ")", ")", ";", "try", "(", "InputStream", "is", "=", "packageUrl", ".", "openStream", "(", ")", ")", "{", "Preconditions", ".", "checkNotNull", "(", "is", ",", "\"Package url %s stream is null!\"", ",", "packageUrl", ")", ";", "try", "(", "BufferedReader", "reader", "=", "new", "BufferedReader", "(", "new", "InputStreamReader", "(", "is", ",", "StandardCharsets", ".", "UTF_8", ")", ")", ")", "{", "classes", ".", "addAll", "(", "reader", ".", "lines", "(", ")", ".", "filter", "(", "line", "->", "line", "!=", "null", "&&", "line", ".", "endsWith", "(", "\".class\"", ")", ")", ".", "map", "(", "line", "->", "{", "String", "className", "=", "line", ".", "replace", "(", "\".class\"", ",", "\"\"", ")", ".", "replace", "(", "'", "'", ",", "'", "'", ")", ";", "try", "{", "Class", "<", "?", ">", "aClass", "=", "getClass", "(", "packagePrefix", "+", "className", ")", ";", "return", "aClass", ";", "}", "catch", "(", "Exception", "e", ")", "{", "log", ".", "error", "(", "\"Failed to find {}\"", ",", "line", ",", "e", ")", ";", "}", "return", "null", ";", "}", ")", ".", "collect", "(", "Collectors", ".", "toList", "(", ")", ")", ")", ";", "}", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "FathomException", "(", "e", ",", "\"Failed to get classes for package '{}'\"", ",", "packageName", ")", ";", "}", "}", "}", "}", "return", "Collections", ".", "unmodifiableCollection", "(", "classes", ")", ";", "}" ]
Returns the list of all classes within a package. @param packageNames @return a collection of classes
[ "Returns", "the", "list", "of", "all", "classes", "within", "a", "package", "." ]
f2f820eb16e9fea1e36ad4eda4ed51b35f056538
https://github.com/gitblit/fathom/blob/f2f820eb16e9fea1e36ad4eda4ed51b35f056538/fathom-core/src/main/java/fathom/utils/ClassUtil.java#L109-L163
10,551
gitblit/fathom
fathom-core/src/main/java/fathom/utils/ClassUtil.java
ClassUtil.getAnnotation
public static <T extends Annotation> T getAnnotation(Method method, Class<T> annotationClass) { T t = method.getAnnotation(annotationClass); if (t == null) { t = getAnnotation(method.getDeclaringClass(), annotationClass); } return t; }
java
public static <T extends Annotation> T getAnnotation(Method method, Class<T> annotationClass) { T t = method.getAnnotation(annotationClass); if (t == null) { t = getAnnotation(method.getDeclaringClass(), annotationClass); } return t; }
[ "public", "static", "<", "T", "extends", "Annotation", ">", "T", "getAnnotation", "(", "Method", "method", ",", "Class", "<", "T", ">", "annotationClass", ")", "{", "T", "t", "=", "method", ".", "getAnnotation", "(", "annotationClass", ")", ";", "if", "(", "t", "==", "null", ")", "{", "t", "=", "getAnnotation", "(", "method", ".", "getDeclaringClass", "(", ")", ",", "annotationClass", ")", ";", "}", "return", "t", ";", "}" ]
Extract the annotation from the method or the declaring class. @param method @param annotationClass @param <T> @return the annotation or null
[ "Extract", "the", "annotation", "from", "the", "method", "or", "the", "declaring", "class", "." ]
f2f820eb16e9fea1e36ad4eda4ed51b35f056538
https://github.com/gitblit/fathom/blob/f2f820eb16e9fea1e36ad4eda4ed51b35f056538/fathom-core/src/main/java/fathom/utils/ClassUtil.java#L180-L186
10,552
gitblit/fathom
fathom-security-redis/src/main/java/fathom/realm/redis/RedisRealm.java
RedisRealm.executeScript
protected void executeScript(String scriptPath) { URL scriptUrl = null; try { if (scriptPath.startsWith("classpath:")) { String script = scriptPath.substring("classpath:".length()); scriptUrl = ClassUtil.getResource(script); if (scriptUrl == null) { log.warn("Script '{}' not found!", scriptPath); } } else { File file = new File(scriptPath); if (file.exists()) { scriptUrl = file.toURI().toURL(); } else { log.warn("Script '{}' not found!", scriptPath); } } // execute the script if (scriptUrl != null) { executeScript(scriptUrl); } } catch (Exception e) { log.error("Failed to parse '{}' as a url", scriptPath); } }
java
protected void executeScript(String scriptPath) { URL scriptUrl = null; try { if (scriptPath.startsWith("classpath:")) { String script = scriptPath.substring("classpath:".length()); scriptUrl = ClassUtil.getResource(script); if (scriptUrl == null) { log.warn("Script '{}' not found!", scriptPath); } } else { File file = new File(scriptPath); if (file.exists()) { scriptUrl = file.toURI().toURL(); } else { log.warn("Script '{}' not found!", scriptPath); } } // execute the script if (scriptUrl != null) { executeScript(scriptUrl); } } catch (Exception e) { log.error("Failed to parse '{}' as a url", scriptPath); } }
[ "protected", "void", "executeScript", "(", "String", "scriptPath", ")", "{", "URL", "scriptUrl", "=", "null", ";", "try", "{", "if", "(", "scriptPath", ".", "startsWith", "(", "\"classpath:\"", ")", ")", "{", "String", "script", "=", "scriptPath", ".", "substring", "(", "\"classpath:\"", ".", "length", "(", ")", ")", ";", "scriptUrl", "=", "ClassUtil", ".", "getResource", "(", "script", ")", ";", "if", "(", "scriptUrl", "==", "null", ")", "{", "log", ".", "warn", "(", "\"Script '{}' not found!\"", ",", "scriptPath", ")", ";", "}", "}", "else", "{", "File", "file", "=", "new", "File", "(", "scriptPath", ")", ";", "if", "(", "file", ".", "exists", "(", ")", ")", "{", "scriptUrl", "=", "file", ".", "toURI", "(", ")", ".", "toURL", "(", ")", ";", "}", "else", "{", "log", ".", "warn", "(", "\"Script '{}' not found!\"", ",", "scriptPath", ")", ";", "}", "}", "// execute the script", "if", "(", "scriptUrl", "!=", "null", ")", "{", "executeScript", "(", "scriptUrl", ")", ";", "}", "}", "catch", "(", "Exception", "e", ")", "{", "log", ".", "error", "(", "\"Failed to parse '{}' as a url\"", ",", "scriptPath", ")", ";", "}", "}" ]
Execute a script located either in the classpath or on the filesystem. @param scriptPath
[ "Execute", "a", "script", "located", "either", "in", "the", "classpath", "or", "on", "the", "filesystem", "." ]
f2f820eb16e9fea1e36ad4eda4ed51b35f056538
https://github.com/gitblit/fathom/blob/f2f820eb16e9fea1e36ad4eda4ed51b35f056538/fathom-security-redis/src/main/java/fathom/realm/redis/RedisRealm.java#L242-L268
10,553
Tirasa/ADSDDL
src/main/java/net/tirasa/adsddl/ntsd/controls/SDFlagsControl.java
SDFlagsControl.berEncodedValue
private byte[] berEncodedValue() { final ByteBuffer buff = ByteBuffer.allocate(5); buff.put((byte) 0x30); // (Ber.ASN_SEQUENCE | Ber.ASN_CONSTRUCTOR); buff.put((byte) 0x03); // size buff.put((byte) 0x02); // 4bytes int tag buff.put((byte) 0x01); // int size buff.put(NumberFacility.leftTrim(NumberFacility.getBytes(flags))); // value return buff.array(); }
java
private byte[] berEncodedValue() { final ByteBuffer buff = ByteBuffer.allocate(5); buff.put((byte) 0x30); // (Ber.ASN_SEQUENCE | Ber.ASN_CONSTRUCTOR); buff.put((byte) 0x03); // size buff.put((byte) 0x02); // 4bytes int tag buff.put((byte) 0x01); // int size buff.put(NumberFacility.leftTrim(NumberFacility.getBytes(flags))); // value return buff.array(); }
[ "private", "byte", "[", "]", "berEncodedValue", "(", ")", "{", "final", "ByteBuffer", "buff", "=", "ByteBuffer", ".", "allocate", "(", "5", ")", ";", "buff", ".", "put", "(", "(", "byte", ")", "0x30", ")", ";", "// (Ber.ASN_SEQUENCE | Ber.ASN_CONSTRUCTOR);", "buff", ".", "put", "(", "(", "byte", ")", "0x03", ")", ";", "// size", "buff", ".", "put", "(", "(", "byte", ")", "0x02", ")", ";", "// 4bytes int tag", "buff", ".", "put", "(", "(", "byte", ")", "0x01", ")", ";", "// int size", "buff", ".", "put", "(", "NumberFacility", ".", "leftTrim", "(", "NumberFacility", ".", "getBytes", "(", "flags", ")", ")", ")", ";", "// value", "return", "buff", ".", "array", "(", ")", ";", "}" ]
BER encode the flags. @return flags BER encoded.
[ "BER", "encode", "the", "flags", "." ]
16dad53e1222c7faa904c64394af94ba18f6d09c
https://github.com/Tirasa/ADSDDL/blob/16dad53e1222c7faa904c64394af94ba18f6d09c/src/main/java/net/tirasa/adsddl/ntsd/controls/SDFlagsControl.java#L120-L128
10,554
Tirasa/ADSDDL
src/main/java/net/tirasa/adsddl/ntsd/utils/Hex.java
Hex.getEscaped
public static String getEscaped(byte... bytes) { final StringBuilder bld = new StringBuilder(); for (byte b : bytes) { bld.append("\\").append(Hex.get(b)); } return bld.toString(); }
java
public static String getEscaped(byte... bytes) { final StringBuilder bld = new StringBuilder(); for (byte b : bytes) { bld.append("\\").append(Hex.get(b)); } return bld.toString(); }
[ "public", "static", "String", "getEscaped", "(", "byte", "...", "bytes", ")", "{", "final", "StringBuilder", "bld", "=", "new", "StringBuilder", "(", ")", ";", "for", "(", "byte", "b", ":", "bytes", ")", "{", "bld", ".", "append", "(", "\"\\\\\"", ")", ".", "append", "(", "Hex", ".", "get", "(", "b", ")", ")", ";", "}", "return", "bld", ".", "toString", "(", ")", ";", "}" ]
Gets escaped hex string corresponding to the given bytes. @param bytes bytes. @return escaped hex string
[ "Gets", "escaped", "hex", "string", "corresponding", "to", "the", "given", "bytes", "." ]
16dad53e1222c7faa904c64394af94ba18f6d09c
https://github.com/Tirasa/ADSDDL/blob/16dad53e1222c7faa904c64394af94ba18f6d09c/src/main/java/net/tirasa/adsddl/ntsd/utils/Hex.java#L59-L65
10,555
Tirasa/ADSDDL
src/main/java/net/tirasa/adsddl/ntsd/utils/Hex.java
Hex.reverse
public static byte[] reverse(byte... bytes) { byte[] res = new byte[bytes.length]; int j = 0; for (int i = bytes.length - 1; i >= 0; i--) { res[j] = bytes[i]; j++; } return res; }
java
public static byte[] reverse(byte... bytes) { byte[] res = new byte[bytes.length]; int j = 0; for (int i = bytes.length - 1; i >= 0; i--) { res[j] = bytes[i]; j++; } return res; }
[ "public", "static", "byte", "[", "]", "reverse", "(", "byte", "...", "bytes", ")", "{", "byte", "[", "]", "res", "=", "new", "byte", "[", "bytes", ".", "length", "]", ";", "int", "j", "=", "0", ";", "for", "(", "int", "i", "=", "bytes", ".", "length", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "res", "[", "j", "]", "=", "bytes", "[", "i", "]", ";", "j", "++", ";", "}", "return", "res", ";", "}" ]
Reverses bytes. @param bytes bytes. @return reversed byte array.
[ "Reverses", "bytes", "." ]
16dad53e1222c7faa904c64394af94ba18f6d09c
https://github.com/Tirasa/ADSDDL/blob/16dad53e1222c7faa904c64394af94ba18f6d09c/src/main/java/net/tirasa/adsddl/ntsd/utils/Hex.java#L83-L91
10,556
Tirasa/ADSDDL
src/main/java/net/tirasa/adsddl/ntsd/SID.java
SID.newInstance
public static SID newInstance(final byte[] identifier) { final SID sid = new SID(); sid.setRevision((byte) 0x01); sid.setIdentifierAuthority(identifier); return sid; }
java
public static SID newInstance(final byte[] identifier) { final SID sid = new SID(); sid.setRevision((byte) 0x01); sid.setIdentifierAuthority(identifier); return sid; }
[ "public", "static", "SID", "newInstance", "(", "final", "byte", "[", "]", "identifier", ")", "{", "final", "SID", "sid", "=", "new", "SID", "(", ")", ";", "sid", ".", "setRevision", "(", "(", "byte", ")", "0x01", ")", ";", "sid", ".", "setIdentifierAuthority", "(", "identifier", ")", ";", "return", "sid", ";", "}" ]
Instances a new SID with the given identifier authority. @param identifier identifier authority (6 bytes only). @return the SID instance.
[ "Instances", "a", "new", "SID", "with", "the", "given", "identifier", "authority", "." ]
16dad53e1222c7faa904c64394af94ba18f6d09c
https://github.com/Tirasa/ADSDDL/blob/16dad53e1222c7faa904c64394af94ba18f6d09c/src/main/java/net/tirasa/adsddl/ntsd/SID.java#L89-L94
10,557
Tirasa/ADSDDL
src/main/java/net/tirasa/adsddl/ntsd/SID.java
SID.parse
public static SID parse(final byte[] src) { final ByteBuffer sddlBuffer = ByteBuffer.wrap(src); final SID sid = new SID(); sid.parse(sddlBuffer.asIntBuffer(), 0); return sid; }
java
public static SID parse(final byte[] src) { final ByteBuffer sddlBuffer = ByteBuffer.wrap(src); final SID sid = new SID(); sid.parse(sddlBuffer.asIntBuffer(), 0); return sid; }
[ "public", "static", "SID", "parse", "(", "final", "byte", "[", "]", "src", ")", "{", "final", "ByteBuffer", "sddlBuffer", "=", "ByteBuffer", ".", "wrap", "(", "src", ")", ";", "final", "SID", "sid", "=", "new", "SID", "(", ")", ";", "sid", ".", "parse", "(", "sddlBuffer", ".", "asIntBuffer", "(", ")", ",", "0", ")", ";", "return", "sid", ";", "}" ]
Instances a SID instance of the given byte array. @param src SID as byte array. @return SID instance.
[ "Instances", "a", "SID", "instance", "of", "the", "given", "byte", "array", "." ]
16dad53e1222c7faa904c64394af94ba18f6d09c
https://github.com/Tirasa/ADSDDL/blob/16dad53e1222c7faa904c64394af94ba18f6d09c/src/main/java/net/tirasa/adsddl/ntsd/SID.java#L102-L107
10,558
Tirasa/ADSDDL
src/main/java/net/tirasa/adsddl/ntsd/SID.java
SID.parse
int parse(final IntBuffer buff, final int start) { int pos = start; // Check for a SID (http://msdn.microsoft.com/en-us/library/cc230371.aspx) final byte[] sidHeader = NumberFacility.getBytes(buff.get(pos)); // Revision(1 byte): An 8-bit unsigned integer that specifies the revision level of the SID. // This value MUST be set to 0x01. revision = sidHeader[0]; //SubAuthorityCount (1 byte): An 8-bit unsigned integer that specifies the number of elements //in the SubAuthority array. The maximum number of elements allowed is 15. int subAuthorityCount = NumberFacility.getInt(sidHeader[1]); // IdentifierAuthority (6 bytes): A SID_IDENTIFIER_AUTHORITY structure that indicates the // authority under which the SID was created. It describes the entity that created the SID. // The Identifier Authority value {0,0,0,0,0,5} denotes SIDs created by the NT SID authority. identifierAuthority = new byte[6]; System.arraycopy(sidHeader, 2, identifierAuthority, 0, 2); pos++; System.arraycopy(NumberFacility.getBytes(buff.get(pos)), 0, identifierAuthority, 2, 4); // SubAuthority (variable): A variable length array of unsigned 32-bit integers that uniquely // identifies a principal relative to the IdentifierAuthority. Its length is determined by // SubAuthorityCount. for (int j = 0; j < subAuthorityCount; j++) { pos++; subAuthorities.add(Hex.reverse(NumberFacility.getBytes(buff.get(pos)))); } return pos; }
java
int parse(final IntBuffer buff, final int start) { int pos = start; // Check for a SID (http://msdn.microsoft.com/en-us/library/cc230371.aspx) final byte[] sidHeader = NumberFacility.getBytes(buff.get(pos)); // Revision(1 byte): An 8-bit unsigned integer that specifies the revision level of the SID. // This value MUST be set to 0x01. revision = sidHeader[0]; //SubAuthorityCount (1 byte): An 8-bit unsigned integer that specifies the number of elements //in the SubAuthority array. The maximum number of elements allowed is 15. int subAuthorityCount = NumberFacility.getInt(sidHeader[1]); // IdentifierAuthority (6 bytes): A SID_IDENTIFIER_AUTHORITY structure that indicates the // authority under which the SID was created. It describes the entity that created the SID. // The Identifier Authority value {0,0,0,0,0,5} denotes SIDs created by the NT SID authority. identifierAuthority = new byte[6]; System.arraycopy(sidHeader, 2, identifierAuthority, 0, 2); pos++; System.arraycopy(NumberFacility.getBytes(buff.get(pos)), 0, identifierAuthority, 2, 4); // SubAuthority (variable): A variable length array of unsigned 32-bit integers that uniquely // identifies a principal relative to the IdentifierAuthority. Its length is determined by // SubAuthorityCount. for (int j = 0; j < subAuthorityCount; j++) { pos++; subAuthorities.add(Hex.reverse(NumberFacility.getBytes(buff.get(pos)))); } return pos; }
[ "int", "parse", "(", "final", "IntBuffer", "buff", ",", "final", "int", "start", ")", "{", "int", "pos", "=", "start", ";", "// Check for a SID (http://msdn.microsoft.com/en-us/library/cc230371.aspx)", "final", "byte", "[", "]", "sidHeader", "=", "NumberFacility", ".", "getBytes", "(", "buff", ".", "get", "(", "pos", ")", ")", ";", "// Revision(1 byte): An 8-bit unsigned integer that specifies the revision level of the SID.", "// This value MUST be set to 0x01.", "revision", "=", "sidHeader", "[", "0", "]", ";", "//SubAuthorityCount (1 byte): An 8-bit unsigned integer that specifies the number of elements ", "//in the SubAuthority array. The maximum number of elements allowed is 15.", "int", "subAuthorityCount", "=", "NumberFacility", ".", "getInt", "(", "sidHeader", "[", "1", "]", ")", ";", "// IdentifierAuthority (6 bytes): A SID_IDENTIFIER_AUTHORITY structure that indicates the ", "// authority under which the SID was created. It describes the entity that created the SID. ", "// The Identifier Authority value {0,0,0,0,0,5} denotes SIDs created by the NT SID authority.", "identifierAuthority", "=", "new", "byte", "[", "6", "]", ";", "System", ".", "arraycopy", "(", "sidHeader", ",", "2", ",", "identifierAuthority", ",", "0", ",", "2", ")", ";", "pos", "++", ";", "System", ".", "arraycopy", "(", "NumberFacility", ".", "getBytes", "(", "buff", ".", "get", "(", "pos", ")", ")", ",", "0", ",", "identifierAuthority", ",", "2", ",", "4", ")", ";", "// SubAuthority (variable): A variable length array of unsigned 32-bit integers that uniquely ", "// identifies a principal relative to the IdentifierAuthority. Its length is determined by ", "// SubAuthorityCount.", "for", "(", "int", "j", "=", "0", ";", "j", "<", "subAuthorityCount", ";", "j", "++", ")", "{", "pos", "++", ";", "subAuthorities", ".", "add", "(", "Hex", ".", "reverse", "(", "NumberFacility", ".", "getBytes", "(", "buff", ".", "get", "(", "pos", ")", ")", ")", ")", ";", "}", "return", "pos", ";", "}" ]
Load the SID from the buffer returning the last SID segment position into the buffer. @param buff source buffer. @param start start loading position. @return last loading position.
[ "Load", "the", "SID", "from", "the", "buffer", "returning", "the", "last", "SID", "segment", "position", "into", "the", "buffer", "." ]
16dad53e1222c7faa904c64394af94ba18f6d09c
https://github.com/Tirasa/ADSDDL/blob/16dad53e1222c7faa904c64394af94ba18f6d09c/src/main/java/net/tirasa/adsddl/ntsd/SID.java#L116-L149
10,559
Tirasa/ADSDDL
src/main/java/net/tirasa/adsddl/ntsd/utils/SDDLHelper.java
SDDLHelper.isUserCannotChangePassword
public static boolean isUserCannotChangePassword(final SDDL sddl) { boolean res = false; final List<ACE> aces = sddl.getDacl().getAces(); for (int i = 0; !res && i < aces.size(); i++) { final ACE ace = aces.get(i); if (ace.getType() == AceType.ACCESS_DENIED_OBJECT_ACE_TYPE && ace.getObjectFlags().getFlags().contains(AceObjectFlags.Flag.ACE_OBJECT_TYPE_PRESENT)) { if (GUID.getGuidAsString(ace.getObjectType()).equals(UCP_OBJECT_GUID)) { final SID sid = ace.getSid(); if (sid.getSubAuthorities().size() == 1) { if ((Arrays.equals( sid.getIdentifierAuthority(), new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 }) && Arrays.equals( sid.getSubAuthorities().get(0), new byte[] { 0x00, 0x00, 0x00, 0x00 })) || (Arrays.equals( sid.getIdentifierAuthority(), new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x05 }) && Arrays.equals( sid.getSubAuthorities().get(0), new byte[] { 0x00, 0x00, 0x00, 0x0a }))) { res = true; } } } } } return res; }
java
public static boolean isUserCannotChangePassword(final SDDL sddl) { boolean res = false; final List<ACE> aces = sddl.getDacl().getAces(); for (int i = 0; !res && i < aces.size(); i++) { final ACE ace = aces.get(i); if (ace.getType() == AceType.ACCESS_DENIED_OBJECT_ACE_TYPE && ace.getObjectFlags().getFlags().contains(AceObjectFlags.Flag.ACE_OBJECT_TYPE_PRESENT)) { if (GUID.getGuidAsString(ace.getObjectType()).equals(UCP_OBJECT_GUID)) { final SID sid = ace.getSid(); if (sid.getSubAuthorities().size() == 1) { if ((Arrays.equals( sid.getIdentifierAuthority(), new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 }) && Arrays.equals( sid.getSubAuthorities().get(0), new byte[] { 0x00, 0x00, 0x00, 0x00 })) || (Arrays.equals( sid.getIdentifierAuthority(), new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x05 }) && Arrays.equals( sid.getSubAuthorities().get(0), new byte[] { 0x00, 0x00, 0x00, 0x0a }))) { res = true; } } } } } return res; }
[ "public", "static", "boolean", "isUserCannotChangePassword", "(", "final", "SDDL", "sddl", ")", "{", "boolean", "res", "=", "false", ";", "final", "List", "<", "ACE", ">", "aces", "=", "sddl", ".", "getDacl", "(", ")", ".", "getAces", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "!", "res", "&&", "i", "<", "aces", ".", "size", "(", ")", ";", "i", "++", ")", "{", "final", "ACE", "ace", "=", "aces", ".", "get", "(", "i", ")", ";", "if", "(", "ace", ".", "getType", "(", ")", "==", "AceType", ".", "ACCESS_DENIED_OBJECT_ACE_TYPE", "&&", "ace", ".", "getObjectFlags", "(", ")", ".", "getFlags", "(", ")", ".", "contains", "(", "AceObjectFlags", ".", "Flag", ".", "ACE_OBJECT_TYPE_PRESENT", ")", ")", "{", "if", "(", "GUID", ".", "getGuidAsString", "(", "ace", ".", "getObjectType", "(", ")", ")", ".", "equals", "(", "UCP_OBJECT_GUID", ")", ")", "{", "final", "SID", "sid", "=", "ace", ".", "getSid", "(", ")", ";", "if", "(", "sid", ".", "getSubAuthorities", "(", ")", ".", "size", "(", ")", "==", "1", ")", "{", "if", "(", "(", "Arrays", ".", "equals", "(", "sid", ".", "getIdentifierAuthority", "(", ")", ",", "new", "byte", "[", "]", "{", "0x00", ",", "0x00", ",", "0x00", ",", "0x00", ",", "0x00", ",", "0x01", "}", ")", "&&", "Arrays", ".", "equals", "(", "sid", ".", "getSubAuthorities", "(", ")", ".", "get", "(", "0", ")", ",", "new", "byte", "[", "]", "{", "0x00", ",", "0x00", ",", "0x00", ",", "0x00", "}", ")", ")", "||", "(", "Arrays", ".", "equals", "(", "sid", ".", "getIdentifierAuthority", "(", ")", ",", "new", "byte", "[", "]", "{", "0x00", ",", "0x00", ",", "0x00", ",", "0x00", ",", "0x00", ",", "0x05", "}", ")", "&&", "Arrays", ".", "equals", "(", "sid", ".", "getSubAuthorities", "(", ")", ".", "get", "(", "0", ")", ",", "new", "byte", "[", "]", "{", "0x00", ",", "0x00", ",", "0x00", ",", "0x0a", "}", ")", ")", ")", "{", "res", "=", "true", ";", "}", "}", "}", "}", "}", "return", "res", ";", "}" ]
Check if user canot change password. @param sddl SSDL. @return <tt>true</tt> if user cannot change password: <tt>false</tt> otherwise.
[ "Check", "if", "user", "canot", "change", "password", "." ]
16dad53e1222c7faa904c64394af94ba18f6d09c
https://github.com/Tirasa/ADSDDL/blob/16dad53e1222c7faa904c64394af94ba18f6d09c/src/main/java/net/tirasa/adsddl/ntsd/utils/SDDLHelper.java#L44-L73
10,560
gitblit/fathom
fathom-rest-security/src/main/java/fathom/rest/security/StandardCredentialsHandler.java
StandardCredentialsHandler.isAuthenticated
protected final boolean isAuthenticated(Context context) { Account account = context.getSession(AuthConstants.ACCOUNT_ATTRIBUTE); if (account == null) { account = context.getLocal(AuthConstants.ACCOUNT_ATTRIBUTE); } return account != null && account.isAuthenticated(); }
java
protected final boolean isAuthenticated(Context context) { Account account = context.getSession(AuthConstants.ACCOUNT_ATTRIBUTE); if (account == null) { account = context.getLocal(AuthConstants.ACCOUNT_ATTRIBUTE); } return account != null && account.isAuthenticated(); }
[ "protected", "final", "boolean", "isAuthenticated", "(", "Context", "context", ")", "{", "Account", "account", "=", "context", ".", "getSession", "(", "AuthConstants", ".", "ACCOUNT_ATTRIBUTE", ")", ";", "if", "(", "account", "==", "null", ")", "{", "account", "=", "context", ".", "getLocal", "(", "AuthConstants", ".", "ACCOUNT_ATTRIBUTE", ")", ";", "}", "return", "account", "!=", "null", "&&", "account", ".", "isAuthenticated", "(", ")", ";", "}" ]
Determines if the current Context has already been authenticated. @param context @return true if this Context is authenticated.
[ "Determines", "if", "the", "current", "Context", "has", "already", "been", "authenticated", "." ]
f2f820eb16e9fea1e36ad4eda4ed51b35f056538
https://github.com/gitblit/fathom/blob/f2f820eb16e9fea1e36ad4eda4ed51b35f056538/fathom-rest-security/src/main/java/fathom/rest/security/StandardCredentialsHandler.java#L44-L50
10,561
Tirasa/ADSDDL
src/main/java/net/tirasa/adsddl/ntsd/controls/DirSyncControl.java
DirSyncControl.berEncodedValue
private byte[] berEncodedValue() { final byte[] cookieSize = NumberFacility.leftTrim(NumberFacility.getBytes(cookie.length)); final byte[] size = NumberFacility.leftTrim(NumberFacility.getBytes(14 + cookieSize.length + cookie.length)); final ByteBuffer buff = ByteBuffer.allocate(1 + 1 + size.length + 14 + cookieSize.length + cookie.length); buff.put((byte) 0x30); // (Ber.ASN_SEQUENCE | Ber.ASN_CONSTRUCTOR); buff.put((byte) (size.length == 1 ? 0x81 : size.length == 2 ? 0x82 : 0x83)); // size type (short or long form) buff.put(size); // sequence size buff.put((byte) 0x02); // 4bytes int tag buff.put((byte) 0x04); // int size buff.putInt(flags); // flags buff.put((byte) 0x02); // 4bytes int tag buff.put((byte) 0x04); // int size buff.putInt(Integer.MAX_VALUE); // max attribute count buff.put((byte) 0x04); // byte array tag buff.put((byte) (cookieSize.length == 1 ? 0x81 : cookieSize.length == 2 ? 0x82 : 0x83)); // short or long form buff.put(cookieSize); // byte array size if (cookie.length > 0) { buff.put(cookie); // (cookie, Ber.ASN_OCTET_STR); } return buff.array(); }
java
private byte[] berEncodedValue() { final byte[] cookieSize = NumberFacility.leftTrim(NumberFacility.getBytes(cookie.length)); final byte[] size = NumberFacility.leftTrim(NumberFacility.getBytes(14 + cookieSize.length + cookie.length)); final ByteBuffer buff = ByteBuffer.allocate(1 + 1 + size.length + 14 + cookieSize.length + cookie.length); buff.put((byte) 0x30); // (Ber.ASN_SEQUENCE | Ber.ASN_CONSTRUCTOR); buff.put((byte) (size.length == 1 ? 0x81 : size.length == 2 ? 0x82 : 0x83)); // size type (short or long form) buff.put(size); // sequence size buff.put((byte) 0x02); // 4bytes int tag buff.put((byte) 0x04); // int size buff.putInt(flags); // flags buff.put((byte) 0x02); // 4bytes int tag buff.put((byte) 0x04); // int size buff.putInt(Integer.MAX_VALUE); // max attribute count buff.put((byte) 0x04); // byte array tag buff.put((byte) (cookieSize.length == 1 ? 0x81 : cookieSize.length == 2 ? 0x82 : 0x83)); // short or long form buff.put(cookieSize); // byte array size if (cookie.length > 0) { buff.put(cookie); // (cookie, Ber.ASN_OCTET_STR); } return buff.array(); }
[ "private", "byte", "[", "]", "berEncodedValue", "(", ")", "{", "final", "byte", "[", "]", "cookieSize", "=", "NumberFacility", ".", "leftTrim", "(", "NumberFacility", ".", "getBytes", "(", "cookie", ".", "length", ")", ")", ";", "final", "byte", "[", "]", "size", "=", "NumberFacility", ".", "leftTrim", "(", "NumberFacility", ".", "getBytes", "(", "14", "+", "cookieSize", ".", "length", "+", "cookie", ".", "length", ")", ")", ";", "final", "ByteBuffer", "buff", "=", "ByteBuffer", ".", "allocate", "(", "1", "+", "1", "+", "size", ".", "length", "+", "14", "+", "cookieSize", ".", "length", "+", "cookie", ".", "length", ")", ";", "buff", ".", "put", "(", "(", "byte", ")", "0x30", ")", ";", "// (Ber.ASN_SEQUENCE | Ber.ASN_CONSTRUCTOR);", "buff", ".", "put", "(", "(", "byte", ")", "(", "size", ".", "length", "==", "1", "?", "0x81", ":", "size", ".", "length", "==", "2", "?", "0x82", ":", "0x83", ")", ")", ";", "// size type (short or long form)", "buff", ".", "put", "(", "size", ")", ";", "// sequence size", "buff", ".", "put", "(", "(", "byte", ")", "0x02", ")", ";", "// 4bytes int tag", "buff", ".", "put", "(", "(", "byte", ")", "0x04", ")", ";", "// int size", "buff", ".", "putInt", "(", "flags", ")", ";", "// flags", "buff", ".", "put", "(", "(", "byte", ")", "0x02", ")", ";", "// 4bytes int tag", "buff", ".", "put", "(", "(", "byte", ")", "0x04", ")", ";", "// int size", "buff", ".", "putInt", "(", "Integer", ".", "MAX_VALUE", ")", ";", "// max attribute count", "buff", ".", "put", "(", "(", "byte", ")", "0x04", ")", ";", "// byte array tag", "buff", ".", "put", "(", "(", "byte", ")", "(", "cookieSize", ".", "length", "==", "1", "?", "0x81", ":", "cookieSize", ".", "length", "==", "2", "?", "0x82", ":", "0x83", ")", ")", ";", "// short or long form", "buff", ".", "put", "(", "cookieSize", ")", ";", "// byte array size", "if", "(", "cookie", ".", "length", ">", "0", ")", "{", "buff", ".", "put", "(", "cookie", ")", ";", "// (cookie, Ber.ASN_OCTET_STR);", "}", "return", "buff", ".", "array", "(", ")", ";", "}" ]
BER encode the cookie value. @param cookie cookie value to be encoded. @return ber encoded cookie value.
[ "BER", "encode", "the", "cookie", "value", "." ]
16dad53e1222c7faa904c64394af94ba18f6d09c
https://github.com/Tirasa/ADSDDL/blob/16dad53e1222c7faa904c64394af94ba18f6d09c/src/main/java/net/tirasa/adsddl/ntsd/controls/DirSyncControl.java#L86-L108
10,562
Tirasa/ADSDDL
src/main/java/net/tirasa/adsddl/ntsd/SDDL.java
SDDL.parse
private int parse(final IntBuffer buff, final int start) { int pos = start; /** * Revision (1 byte): An unsigned 8-bit value that specifies the revision of the SECURITY_DESCRIPTOR * structure. This field MUST be set to one. */ final byte[] header = NumberFacility.getBytes(buff.get(pos)); revision = header[0]; /** * Control (2 bytes): An unsigned 16-bit field that specifies control access bit flags. The Self Relative * (SR) bit MUST be set when the security descriptor is in self-relative format. */ controlFlags = new byte[] { header[3], header[2] }; final boolean[] controlFlag = NumberFacility.getBits(controlFlags); pos++; /** * OffsetOwner (4 bytes): An unsigned 32-bit integer that specifies the offset to the SID. This SID * specifies the owner of the object to which the security descriptor is associated. This must be a valid * offset if the OD flag is not set. If this field is set to zero, the OwnerSid field MUST not be present. */ if (!controlFlag[15]) { offsetOwner = NumberFacility.getReverseUInt(buff.get(pos)); } else { offsetOwner = 0; } pos++; /** * OffsetGroup (4 bytes): An unsigned 32-bit integer that specifies the offset to the SID. This SID * specifies the group of the object to which the security descriptor is associated. This must be a valid * offset if the GD flag is not set. If this field is set to zero, the GroupSid field MUST not be present. */ if (!controlFlag[14]) { offsetGroup = NumberFacility.getReverseUInt(buff.get(pos)); } else { offsetGroup = 0; } pos++; /** * OffsetSacl (4 bytes): An unsigned 32-bit integer that specifies the offset to the ACL that contains * system ACEs. Typically, the system ACL contains auditing ACEs (such as SYSTEM_AUDIT_ACE, * SYSTEM_AUDIT_CALLBACK_ACE, or SYSTEM_AUDIT_CALLBACK_OBJECT_ACE), and at most one Label ACE (as specified * in section 2.4.4.13). This must be a valid offset if the SP flag is set; if the SP flag is not set, this * field MUST be set to zero. If this field is set to zero, the Sacl field MUST not be present. */ if (controlFlag[11]) { offsetSACL = NumberFacility.getReverseUInt(buff.get(pos)); } else { offsetSACL = 0; } pos++; /** * OffsetDacl (4 bytes): An unsigned 32-bit integer that specifies the offset to the ACL that contains ACEs * that control access. Typically, the DACL contains ACEs that grant or deny access to principals or groups. * This must be a valid offset if the DP flag is set; if the DP flag is not set, this field MUST be set to * zero. If this field is set to zero, the Dacl field MUST not be present. */ if (controlFlag[13]) { offsetDACL = NumberFacility.getReverseUInt(buff.get(pos)); } else { offsetDACL = 0; } /** * OwnerSid (variable): The SID of the owner of the object. The length of the SID MUST be a multiple of 4. * This field MUST be present if the OffsetOwner field is not zero. */ if (offsetOwner > 0) { pos = (int) (offsetOwner / 4); // read for OwnerSid owner = new SID(); pos = owner.parse(buff, pos); } /** * GroupSid (variable): The SID of the group of the object. The length of the SID MUST be a multiple of 4. * This field MUST be present if the GroupOwner field is not zero. */ if (offsetGroup > 0) { // read for GroupSid pos = (int) (offsetGroup / 4); group = new SID(); pos = group.parse(buff, pos); } /** * Sacl (variable): The SACL of the object. The length of the SID MUST be a multiple of 4. This field MUST * be present if the SP flag is set. */ if (offsetSACL > 0) { // read for Sacl pos = (int) (offsetSACL / 4); sacl = new ACL(); pos = sacl.parse(buff, pos); } /** * Dacl (variable): The DACL of the object. The length of the SID MUST be a multiple of 4. This field MUST * be present if the DP flag is set. */ if (offsetDACL > 0) { pos = (int) (offsetDACL / 4); dacl = new ACL(); pos = dacl.parse(buff, pos); } return pos; }
java
private int parse(final IntBuffer buff, final int start) { int pos = start; /** * Revision (1 byte): An unsigned 8-bit value that specifies the revision of the SECURITY_DESCRIPTOR * structure. This field MUST be set to one. */ final byte[] header = NumberFacility.getBytes(buff.get(pos)); revision = header[0]; /** * Control (2 bytes): An unsigned 16-bit field that specifies control access bit flags. The Self Relative * (SR) bit MUST be set when the security descriptor is in self-relative format. */ controlFlags = new byte[] { header[3], header[2] }; final boolean[] controlFlag = NumberFacility.getBits(controlFlags); pos++; /** * OffsetOwner (4 bytes): An unsigned 32-bit integer that specifies the offset to the SID. This SID * specifies the owner of the object to which the security descriptor is associated. This must be a valid * offset if the OD flag is not set. If this field is set to zero, the OwnerSid field MUST not be present. */ if (!controlFlag[15]) { offsetOwner = NumberFacility.getReverseUInt(buff.get(pos)); } else { offsetOwner = 0; } pos++; /** * OffsetGroup (4 bytes): An unsigned 32-bit integer that specifies the offset to the SID. This SID * specifies the group of the object to which the security descriptor is associated. This must be a valid * offset if the GD flag is not set. If this field is set to zero, the GroupSid field MUST not be present. */ if (!controlFlag[14]) { offsetGroup = NumberFacility.getReverseUInt(buff.get(pos)); } else { offsetGroup = 0; } pos++; /** * OffsetSacl (4 bytes): An unsigned 32-bit integer that specifies the offset to the ACL that contains * system ACEs. Typically, the system ACL contains auditing ACEs (such as SYSTEM_AUDIT_ACE, * SYSTEM_AUDIT_CALLBACK_ACE, or SYSTEM_AUDIT_CALLBACK_OBJECT_ACE), and at most one Label ACE (as specified * in section 2.4.4.13). This must be a valid offset if the SP flag is set; if the SP flag is not set, this * field MUST be set to zero. If this field is set to zero, the Sacl field MUST not be present. */ if (controlFlag[11]) { offsetSACL = NumberFacility.getReverseUInt(buff.get(pos)); } else { offsetSACL = 0; } pos++; /** * OffsetDacl (4 bytes): An unsigned 32-bit integer that specifies the offset to the ACL that contains ACEs * that control access. Typically, the DACL contains ACEs that grant or deny access to principals or groups. * This must be a valid offset if the DP flag is set; if the DP flag is not set, this field MUST be set to * zero. If this field is set to zero, the Dacl field MUST not be present. */ if (controlFlag[13]) { offsetDACL = NumberFacility.getReverseUInt(buff.get(pos)); } else { offsetDACL = 0; } /** * OwnerSid (variable): The SID of the owner of the object. The length of the SID MUST be a multiple of 4. * This field MUST be present if the OffsetOwner field is not zero. */ if (offsetOwner > 0) { pos = (int) (offsetOwner / 4); // read for OwnerSid owner = new SID(); pos = owner.parse(buff, pos); } /** * GroupSid (variable): The SID of the group of the object. The length of the SID MUST be a multiple of 4. * This field MUST be present if the GroupOwner field is not zero. */ if (offsetGroup > 0) { // read for GroupSid pos = (int) (offsetGroup / 4); group = new SID(); pos = group.parse(buff, pos); } /** * Sacl (variable): The SACL of the object. The length of the SID MUST be a multiple of 4. This field MUST * be present if the SP flag is set. */ if (offsetSACL > 0) { // read for Sacl pos = (int) (offsetSACL / 4); sacl = new ACL(); pos = sacl.parse(buff, pos); } /** * Dacl (variable): The DACL of the object. The length of the SID MUST be a multiple of 4. This field MUST * be present if the DP flag is set. */ if (offsetDACL > 0) { pos = (int) (offsetDACL / 4); dacl = new ACL(); pos = dacl.parse(buff, pos); } return pos; }
[ "private", "int", "parse", "(", "final", "IntBuffer", "buff", ",", "final", "int", "start", ")", "{", "int", "pos", "=", "start", ";", "/**\n * Revision (1 byte): An unsigned 8-bit value that specifies the revision of the SECURITY_DESCRIPTOR\n * structure. This field MUST be set to one.\n */", "final", "byte", "[", "]", "header", "=", "NumberFacility", ".", "getBytes", "(", "buff", ".", "get", "(", "pos", ")", ")", ";", "revision", "=", "header", "[", "0", "]", ";", "/**\n * Control (2 bytes): An unsigned 16-bit field that specifies control access bit flags. The Self Relative\n * (SR) bit MUST be set when the security descriptor is in self-relative format.\n */", "controlFlags", "=", "new", "byte", "[", "]", "{", "header", "[", "3", "]", ",", "header", "[", "2", "]", "}", ";", "final", "boolean", "[", "]", "controlFlag", "=", "NumberFacility", ".", "getBits", "(", "controlFlags", ")", ";", "pos", "++", ";", "/**\n * OffsetOwner (4 bytes): An unsigned 32-bit integer that specifies the offset to the SID. This SID\n * specifies the owner of the object to which the security descriptor is associated. This must be a valid\n * offset if the OD flag is not set. If this field is set to zero, the OwnerSid field MUST not be present.\n */", "if", "(", "!", "controlFlag", "[", "15", "]", ")", "{", "offsetOwner", "=", "NumberFacility", ".", "getReverseUInt", "(", "buff", ".", "get", "(", "pos", ")", ")", ";", "}", "else", "{", "offsetOwner", "=", "0", ";", "}", "pos", "++", ";", "/**\n * OffsetGroup (4 bytes): An unsigned 32-bit integer that specifies the offset to the SID. This SID\n * specifies the group of the object to which the security descriptor is associated. This must be a valid\n * offset if the GD flag is not set. If this field is set to zero, the GroupSid field MUST not be present.\n */", "if", "(", "!", "controlFlag", "[", "14", "]", ")", "{", "offsetGroup", "=", "NumberFacility", ".", "getReverseUInt", "(", "buff", ".", "get", "(", "pos", ")", ")", ";", "}", "else", "{", "offsetGroup", "=", "0", ";", "}", "pos", "++", ";", "/**\n * OffsetSacl (4 bytes): An unsigned 32-bit integer that specifies the offset to the ACL that contains\n * system ACEs. Typically, the system ACL contains auditing ACEs (such as SYSTEM_AUDIT_ACE,\n * SYSTEM_AUDIT_CALLBACK_ACE, or SYSTEM_AUDIT_CALLBACK_OBJECT_ACE), and at most one Label ACE (as specified\n * in section 2.4.4.13). This must be a valid offset if the SP flag is set; if the SP flag is not set, this\n * field MUST be set to zero. If this field is set to zero, the Sacl field MUST not be present.\n */", "if", "(", "controlFlag", "[", "11", "]", ")", "{", "offsetSACL", "=", "NumberFacility", ".", "getReverseUInt", "(", "buff", ".", "get", "(", "pos", ")", ")", ";", "}", "else", "{", "offsetSACL", "=", "0", ";", "}", "pos", "++", ";", "/**\n * OffsetDacl (4 bytes): An unsigned 32-bit integer that specifies the offset to the ACL that contains ACEs\n * that control access. Typically, the DACL contains ACEs that grant or deny access to principals or groups.\n * This must be a valid offset if the DP flag is set; if the DP flag is not set, this field MUST be set to\n * zero. If this field is set to zero, the Dacl field MUST not be present.\n */", "if", "(", "controlFlag", "[", "13", "]", ")", "{", "offsetDACL", "=", "NumberFacility", ".", "getReverseUInt", "(", "buff", ".", "get", "(", "pos", ")", ")", ";", "}", "else", "{", "offsetDACL", "=", "0", ";", "}", "/**\n * OwnerSid (variable): The SID of the owner of the object. The length of the SID MUST be a multiple of 4.\n * This field MUST be present if the OffsetOwner field is not zero.\n */", "if", "(", "offsetOwner", ">", "0", ")", "{", "pos", "=", "(", "int", ")", "(", "offsetOwner", "/", "4", ")", ";", "// read for OwnerSid", "owner", "=", "new", "SID", "(", ")", ";", "pos", "=", "owner", ".", "parse", "(", "buff", ",", "pos", ")", ";", "}", "/**\n * GroupSid (variable): The SID of the group of the object. The length of the SID MUST be a multiple of 4.\n * This field MUST be present if the GroupOwner field is not zero.\n */", "if", "(", "offsetGroup", ">", "0", ")", "{", "// read for GroupSid", "pos", "=", "(", "int", ")", "(", "offsetGroup", "/", "4", ")", ";", "group", "=", "new", "SID", "(", ")", ";", "pos", "=", "group", ".", "parse", "(", "buff", ",", "pos", ")", ";", "}", "/**\n * Sacl (variable): The SACL of the object. The length of the SID MUST be a multiple of 4. This field MUST\n * be present if the SP flag is set.\n */", "if", "(", "offsetSACL", ">", "0", ")", "{", "// read for Sacl", "pos", "=", "(", "int", ")", "(", "offsetSACL", "/", "4", ")", ";", "sacl", "=", "new", "ACL", "(", ")", ";", "pos", "=", "sacl", ".", "parse", "(", "buff", ",", "pos", ")", ";", "}", "/**\n * Dacl (variable): The DACL of the object. The length of the SID MUST be a multiple of 4. This field MUST\n * be present if the DP flag is set.\n */", "if", "(", "offsetDACL", ">", "0", ")", "{", "pos", "=", "(", "int", ")", "(", "offsetDACL", "/", "4", ")", ";", "dacl", "=", "new", "ACL", "(", ")", ";", "pos", "=", "dacl", ".", "parse", "(", "buff", ",", "pos", ")", ";", "}", "return", "pos", ";", "}" ]
Load the SDDL from the buffer returning the last SDDL segment position into the buffer. @param buff source buffer. @param start start loading position. @return last loading position.
[ "Load", "the", "SDDL", "from", "the", "buffer", "returning", "the", "last", "SDDL", "segment", "position", "into", "the", "buffer", "." ]
16dad53e1222c7faa904c64394af94ba18f6d09c
https://github.com/Tirasa/ADSDDL/blob/16dad53e1222c7faa904c64394af94ba18f6d09c/src/main/java/net/tirasa/adsddl/ntsd/SDDL.java#L144-L259
10,563
Tirasa/ADSDDL
src/main/java/net/tirasa/adsddl/ntsd/SDDL.java
SDDL.getSize
public int getSize() { return 20 + (sacl == null ? 0 : sacl.getSize()) + (dacl == null ? 0 : dacl.getSize()) + (owner == null ? 0 : owner.getSize()) + (group == null ? 0 : group.getSize()); }
java
public int getSize() { return 20 + (sacl == null ? 0 : sacl.getSize()) + (dacl == null ? 0 : dacl.getSize()) + (owner == null ? 0 : owner.getSize()) + (group == null ? 0 : group.getSize()); }
[ "public", "int", "getSize", "(", ")", "{", "return", "20", "+", "(", "sacl", "==", "null", "?", "0", ":", "sacl", ".", "getSize", "(", ")", ")", "+", "(", "dacl", "==", "null", "?", "0", ":", "dacl", ".", "getSize", "(", ")", ")", "+", "(", "owner", "==", "null", "?", "0", ":", "owner", ".", "getSize", "(", ")", ")", "+", "(", "group", "==", "null", "?", "0", ":", "group", ".", "getSize", "(", ")", ")", ";", "}" ]
Gets size in terms of number of bytes. @return size.
[ "Gets", "size", "in", "terms", "of", "number", "of", "bytes", "." ]
16dad53e1222c7faa904c64394af94ba18f6d09c
https://github.com/Tirasa/ADSDDL/blob/16dad53e1222c7faa904c64394af94ba18f6d09c/src/main/java/net/tirasa/adsddl/ntsd/SDDL.java#L266-L271
10,564
Tirasa/ADSDDL
src/main/java/net/tirasa/adsddl/ntsd/SDDL.java
SDDL.toByteArray
public byte[] toByteArray() { final ByteBuffer buff = ByteBuffer.allocate(getSize()); // add revision buff.put(revision); // add reserved buff.put((byte) 0x00); // add contro flags buff.put(controlFlags[1]); buff.put(controlFlags[0]); // add offset owner buff.position(4); int nextAvailablePosition = 20; // add owner SID if (owner == null) { buff.putInt(0); } else { buff.put(Hex.reverse(NumberFacility.getBytes(nextAvailablePosition))); buff.position(nextAvailablePosition); buff.put(owner.toByteArray()); nextAvailablePosition += owner.getSize(); } // add offset group buff.position(8); // add group SID if (group == null) { buff.putInt(0); } else { buff.put(Hex.reverse(NumberFacility.getBytes(nextAvailablePosition))); buff.position(nextAvailablePosition); buff.put(group.toByteArray()); nextAvailablePosition += group.getSize(); } // add offset sacl buff.position(12); // add SACL if (sacl == null) { buff.putInt(0); } else { buff.put(Hex.reverse(NumberFacility.getBytes(nextAvailablePosition))); buff.position(nextAvailablePosition); buff.put(sacl.toByteArray()); nextAvailablePosition += sacl.getSize(); } // add offset dacl buff.position(16); // add DACL if (dacl == null) { buff.putInt(0); } else { buff.put(Hex.reverse(NumberFacility.getBytes(nextAvailablePosition))); buff.position(nextAvailablePosition); buff.put(dacl.toByteArray()); } return buff.array(); }
java
public byte[] toByteArray() { final ByteBuffer buff = ByteBuffer.allocate(getSize()); // add revision buff.put(revision); // add reserved buff.put((byte) 0x00); // add contro flags buff.put(controlFlags[1]); buff.put(controlFlags[0]); // add offset owner buff.position(4); int nextAvailablePosition = 20; // add owner SID if (owner == null) { buff.putInt(0); } else { buff.put(Hex.reverse(NumberFacility.getBytes(nextAvailablePosition))); buff.position(nextAvailablePosition); buff.put(owner.toByteArray()); nextAvailablePosition += owner.getSize(); } // add offset group buff.position(8); // add group SID if (group == null) { buff.putInt(0); } else { buff.put(Hex.reverse(NumberFacility.getBytes(nextAvailablePosition))); buff.position(nextAvailablePosition); buff.put(group.toByteArray()); nextAvailablePosition += group.getSize(); } // add offset sacl buff.position(12); // add SACL if (sacl == null) { buff.putInt(0); } else { buff.put(Hex.reverse(NumberFacility.getBytes(nextAvailablePosition))); buff.position(nextAvailablePosition); buff.put(sacl.toByteArray()); nextAvailablePosition += sacl.getSize(); } // add offset dacl buff.position(16); // add DACL if (dacl == null) { buff.putInt(0); } else { buff.put(Hex.reverse(NumberFacility.getBytes(nextAvailablePosition))); buff.position(nextAvailablePosition); buff.put(dacl.toByteArray()); } return buff.array(); }
[ "public", "byte", "[", "]", "toByteArray", "(", ")", "{", "final", "ByteBuffer", "buff", "=", "ByteBuffer", ".", "allocate", "(", "getSize", "(", ")", ")", ";", "// add revision", "buff", ".", "put", "(", "revision", ")", ";", "// add reserved", "buff", ".", "put", "(", "(", "byte", ")", "0x00", ")", ";", "// add contro flags", "buff", ".", "put", "(", "controlFlags", "[", "1", "]", ")", ";", "buff", ".", "put", "(", "controlFlags", "[", "0", "]", ")", ";", "// add offset owner", "buff", ".", "position", "(", "4", ")", ";", "int", "nextAvailablePosition", "=", "20", ";", "// add owner SID", "if", "(", "owner", "==", "null", ")", "{", "buff", ".", "putInt", "(", "0", ")", ";", "}", "else", "{", "buff", ".", "put", "(", "Hex", ".", "reverse", "(", "NumberFacility", ".", "getBytes", "(", "nextAvailablePosition", ")", ")", ")", ";", "buff", ".", "position", "(", "nextAvailablePosition", ")", ";", "buff", ".", "put", "(", "owner", ".", "toByteArray", "(", ")", ")", ";", "nextAvailablePosition", "+=", "owner", ".", "getSize", "(", ")", ";", "}", "// add offset group", "buff", ".", "position", "(", "8", ")", ";", "// add group SID", "if", "(", "group", "==", "null", ")", "{", "buff", ".", "putInt", "(", "0", ")", ";", "}", "else", "{", "buff", ".", "put", "(", "Hex", ".", "reverse", "(", "NumberFacility", ".", "getBytes", "(", "nextAvailablePosition", ")", ")", ")", ";", "buff", ".", "position", "(", "nextAvailablePosition", ")", ";", "buff", ".", "put", "(", "group", ".", "toByteArray", "(", ")", ")", ";", "nextAvailablePosition", "+=", "group", ".", "getSize", "(", ")", ";", "}", "// add offset sacl", "buff", ".", "position", "(", "12", ")", ";", "// add SACL", "if", "(", "sacl", "==", "null", ")", "{", "buff", ".", "putInt", "(", "0", ")", ";", "}", "else", "{", "buff", ".", "put", "(", "Hex", ".", "reverse", "(", "NumberFacility", ".", "getBytes", "(", "nextAvailablePosition", ")", ")", ")", ";", "buff", ".", "position", "(", "nextAvailablePosition", ")", ";", "buff", ".", "put", "(", "sacl", ".", "toByteArray", "(", ")", ")", ";", "nextAvailablePosition", "+=", "sacl", ".", "getSize", "(", ")", ";", "}", "// add offset dacl", "buff", ".", "position", "(", "16", ")", ";", "// add DACL", "if", "(", "dacl", "==", "null", ")", "{", "buff", ".", "putInt", "(", "0", ")", ";", "}", "else", "{", "buff", ".", "put", "(", "Hex", ".", "reverse", "(", "NumberFacility", ".", "getBytes", "(", "nextAvailablePosition", ")", ")", ")", ";", "buff", ".", "position", "(", "nextAvailablePosition", ")", ";", "buff", ".", "put", "(", "dacl", ".", "toByteArray", "(", ")", ")", ";", "}", "return", "buff", ".", "array", "(", ")", ";", "}" ]
Serializes SDDL as byte array. @return SDL as byte array.
[ "Serializes", "SDDL", "as", "byte", "array", "." ]
16dad53e1222c7faa904c64394af94ba18f6d09c
https://github.com/Tirasa/ADSDDL/blob/16dad53e1222c7faa904c64394af94ba18f6d09c/src/main/java/net/tirasa/adsddl/ntsd/SDDL.java#L332-L398
10,565
gitblit/fathom
fathom-security-ldap/src/main/java/fathom/realm/ldap/LdapRealm.java
LdapRealm.setAdminAttribute
private void setAdminAttribute(Account account) { if (adminGroups != null) { for (String adminGroup : adminGroups) { if (adminGroup.startsWith("@") && account.getUsername().equalsIgnoreCase(adminGroup.substring(1))) { // admin user account.getAuthorizations().addPermission("*"); } else if (account.hasRole(adminGroup)) { // admin role account.getAuthorizations().addPermission("*"); } } } }
java
private void setAdminAttribute(Account account) { if (adminGroups != null) { for (String adminGroup : adminGroups) { if (adminGroup.startsWith("@") && account.getUsername().equalsIgnoreCase(adminGroup.substring(1))) { // admin user account.getAuthorizations().addPermission("*"); } else if (account.hasRole(adminGroup)) { // admin role account.getAuthorizations().addPermission("*"); } } } }
[ "private", "void", "setAdminAttribute", "(", "Account", "account", ")", "{", "if", "(", "adminGroups", "!=", "null", ")", "{", "for", "(", "String", "adminGroup", ":", "adminGroups", ")", "{", "if", "(", "adminGroup", ".", "startsWith", "(", "\"@\"", ")", "&&", "account", ".", "getUsername", "(", ")", ".", "equalsIgnoreCase", "(", "adminGroup", ".", "substring", "(", "1", ")", ")", ")", "{", "// admin user", "account", ".", "getAuthorizations", "(", ")", ".", "addPermission", "(", "\"*\"", ")", ";", "}", "else", "if", "(", "account", ".", "hasRole", "(", "adminGroup", ")", ")", "{", "// admin role", "account", ".", "getAuthorizations", "(", ")", ".", "addPermission", "(", "\"*\"", ")", ";", "}", "}", "}", "}" ]
Set the admin attribute from group memberships retrieved from LDAP. @param account
[ "Set", "the", "admin", "attribute", "from", "group", "memberships", "retrieved", "from", "LDAP", "." ]
f2f820eb16e9fea1e36ad4eda4ed51b35f056538
https://github.com/gitblit/fathom/blob/f2f820eb16e9fea1e36ad4eda4ed51b35f056538/fathom-security-ldap/src/main/java/fathom/realm/ldap/LdapRealm.java#L433-L445
10,566
gitblit/fathom
fathom-rest/src/main/java/fathom/rest/route/CORSFilter.java
CORSFilter.setAllowOrigin
public void setAllowOrigin(String... origin) { allowOriginSet.clear(); allowOriginSet.addAll(Arrays.asList(origin)); allowOrigin = Joiner.on(",").join(origin); }
java
public void setAllowOrigin(String... origin) { allowOriginSet.clear(); allowOriginSet.addAll(Arrays.asList(origin)); allowOrigin = Joiner.on(",").join(origin); }
[ "public", "void", "setAllowOrigin", "(", "String", "...", "origin", ")", "{", "allowOriginSet", ".", "clear", "(", ")", ";", "allowOriginSet", ".", "addAll", "(", "Arrays", ".", "asList", "(", "origin", ")", ")", ";", "allowOrigin", "=", "Joiner", ".", "on", "(", "\",\"", ")", ".", "join", "(", "origin", ")", ";", "}" ]
Set the list of request origins that are permitted to access the protected routes. Multiple origins may be specified and they must be complete scheme, domain, & port specifications. Alternatively, you can specify the wildcard origin "*" to accept from all origins. setAllowOrigin("*"); setAllowOrigin("http://mydomain.com:8080", http://myotherdomain.com:8080"); @param origin
[ "Set", "the", "list", "of", "request", "origins", "that", "are", "permitted", "to", "access", "the", "protected", "routes", "." ]
f2f820eb16e9fea1e36ad4eda4ed51b35f056538
https://github.com/gitblit/fathom/blob/f2f820eb16e9fea1e36ad4eda4ed51b35f056538/fathom-rest/src/main/java/fathom/rest/route/CORSFilter.java#L110-L114
10,567
gitblit/fathom
fathom-rest/src/main/java/fathom/rest/route/CORSFilter.java
CORSFilter.setAllowMethods
public void setAllowMethods(String... methods) { allowMethodsSet.clear(); for (String method : methods) { allowMethodsSet.add(method.toUpperCase()); } allowMethods = Joiner.on(",").join(allowMethodsSet); }
java
public void setAllowMethods(String... methods) { allowMethodsSet.clear(); for (String method : methods) { allowMethodsSet.add(method.toUpperCase()); } allowMethods = Joiner.on(",").join(allowMethodsSet); }
[ "public", "void", "setAllowMethods", "(", "String", "...", "methods", ")", "{", "allowMethodsSet", ".", "clear", "(", ")", ";", "for", "(", "String", "method", ":", "methods", ")", "{", "allowMethodsSet", ".", "add", "(", "method", ".", "toUpperCase", "(", ")", ")", ";", "}", "allowMethods", "=", "Joiner", ".", "on", "(", "\",\"", ")", ".", "join", "(", "allowMethodsSet", ")", ";", "}" ]
Set the list of request methods that may be sent by the browser for a CORS request. setAllowMethods("GET", "PUT", "PATCH"); @param methods
[ "Set", "the", "list", "of", "request", "methods", "that", "may", "be", "sent", "by", "the", "browser", "for", "a", "CORS", "request", "." ]
f2f820eb16e9fea1e36ad4eda4ed51b35f056538
https://github.com/gitblit/fathom/blob/f2f820eb16e9fea1e36ad4eda4ed51b35f056538/fathom-rest/src/main/java/fathom/rest/route/CORSFilter.java#L123-L129
10,568
gitblit/fathom
fathom-rest/src/main/java/fathom/rest/route/CORSFilter.java
CORSFilter.setAllowHeaders
public void setAllowHeaders(String... headers) { allowHeadersSet.clear(); for (String header : headers) { allowHeadersSet.add(header.toLowerCase()); } allowHeaders = Joiner.on(",").join(headers); }
java
public void setAllowHeaders(String... headers) { allowHeadersSet.clear(); for (String header : headers) { allowHeadersSet.add(header.toLowerCase()); } allowHeaders = Joiner.on(",").join(headers); }
[ "public", "void", "setAllowHeaders", "(", "String", "...", "headers", ")", "{", "allowHeadersSet", ".", "clear", "(", ")", ";", "for", "(", "String", "header", ":", "headers", ")", "{", "allowHeadersSet", ".", "add", "(", "header", ".", "toLowerCase", "(", ")", ")", ";", "}", "allowHeaders", "=", "Joiner", ".", "on", "(", "\",\"", ")", ".", "join", "(", "headers", ")", ";", "}" ]
Set the list of headers that may be sent by the browser for a CORS request. setAllowHeaders("Content-Type", "api_key", "Csrf-Token"); @param headers
[ "Set", "the", "list", "of", "headers", "that", "may", "be", "sent", "by", "the", "browser", "for", "a", "CORS", "request", "." ]
f2f820eb16e9fea1e36ad4eda4ed51b35f056538
https://github.com/gitblit/fathom/blob/f2f820eb16e9fea1e36ad4eda4ed51b35f056538/fathom-rest/src/main/java/fathom/rest/route/CORSFilter.java#L138-L144
10,569
gitblit/fathom
fathom-rest/src/main/java/fathom/rest/controller/ControllerScanner.java
ControllerScanner.sortMethods
protected Collection<Method> sortMethods(Collection<Method> methods) { List<Method> list = new ArrayList<>(methods); Collections.sort(list, (m1, m2) -> { int o1 = Integer.MAX_VALUE; Order order1 = ClassUtil.getAnnotation(m1, Order.class); if (order1 != null) { o1 = order1.value(); } int o2 = Integer.MAX_VALUE; Order order2 = ClassUtil.getAnnotation(m2, Order.class); if (order2 != null) { o2 = order2.value(); } if (o1 == o2) { // same or unsorted, compare controller+method String s1 = Util.toString(m1); String s2 = Util.toString(m2); return s1.compareTo(s2); } if (o1 < o2) { return -1; } else { return 1; } }); return list; }
java
protected Collection<Method> sortMethods(Collection<Method> methods) { List<Method> list = new ArrayList<>(methods); Collections.sort(list, (m1, m2) -> { int o1 = Integer.MAX_VALUE; Order order1 = ClassUtil.getAnnotation(m1, Order.class); if (order1 != null) { o1 = order1.value(); } int o2 = Integer.MAX_VALUE; Order order2 = ClassUtil.getAnnotation(m2, Order.class); if (order2 != null) { o2 = order2.value(); } if (o1 == o2) { // same or unsorted, compare controller+method String s1 = Util.toString(m1); String s2 = Util.toString(m2); return s1.compareTo(s2); } if (o1 < o2) { return -1; } else { return 1; } }); return list; }
[ "protected", "Collection", "<", "Method", ">", "sortMethods", "(", "Collection", "<", "Method", ">", "methods", ")", "{", "List", "<", "Method", ">", "list", "=", "new", "ArrayList", "<>", "(", "methods", ")", ";", "Collections", ".", "sort", "(", "list", ",", "(", "m1", ",", "m2", ")", "->", "{", "int", "o1", "=", "Integer", ".", "MAX_VALUE", ";", "Order", "order1", "=", "ClassUtil", ".", "getAnnotation", "(", "m1", ",", "Order", ".", "class", ")", ";", "if", "(", "order1", "!=", "null", ")", "{", "o1", "=", "order1", ".", "value", "(", ")", ";", "}", "int", "o2", "=", "Integer", ".", "MAX_VALUE", ";", "Order", "order2", "=", "ClassUtil", ".", "getAnnotation", "(", "m2", ",", "Order", ".", "class", ")", ";", "if", "(", "order2", "!=", "null", ")", "{", "o2", "=", "order2", ".", "value", "(", ")", ";", "}", "if", "(", "o1", "==", "o2", ")", "{", "// same or unsorted, compare controller+method", "String", "s1", "=", "Util", ".", "toString", "(", "m1", ")", ";", "String", "s2", "=", "Util", ".", "toString", "(", "m2", ")", ";", "return", "s1", ".", "compareTo", "(", "s2", ")", ";", "}", "if", "(", "o1", "<", "o2", ")", "{", "return", "-", "1", ";", "}", "else", "{", "return", "1", ";", "}", "}", ")", ";", "return", "list", ";", "}" ]
Sort the methods by their preferred order, if specified. @param methods @return a sorted list of methods
[ "Sort", "the", "methods", "by", "their", "preferred", "order", "if", "specified", "." ]
f2f820eb16e9fea1e36ad4eda4ed51b35f056538
https://github.com/gitblit/fathom/blob/f2f820eb16e9fea1e36ad4eda4ed51b35f056538/fathom-rest/src/main/java/fathom/rest/controller/ControllerScanner.java#L104-L134
10,570
Tirasa/ADSDDL
src/main/java/net/tirasa/adsddl/ntsd/utils/NumberFacility.java
NumberFacility.leftTrim
@SuppressWarnings("empty-statement") public static byte[] leftTrim(final byte... bytes) { int pos = 0; for (; pos < bytes.length && bytes[pos] == 0x00; pos++); if (pos < bytes.length) { return Arrays.copyOfRange(bytes, pos, bytes.length); } else { return new byte[] { 0x00 }; } }
java
@SuppressWarnings("empty-statement") public static byte[] leftTrim(final byte... bytes) { int pos = 0; for (; pos < bytes.length && bytes[pos] == 0x00; pos++); if (pos < bytes.length) { return Arrays.copyOfRange(bytes, pos, bytes.length); } else { return new byte[] { 0x00 }; } }
[ "@", "SuppressWarnings", "(", "\"empty-statement\"", ")", "public", "static", "byte", "[", "]", "leftTrim", "(", "final", "byte", "...", "bytes", ")", "{", "int", "pos", "=", "0", ";", "for", "(", ";", "pos", "<", "bytes", ".", "length", "&&", "bytes", "[", "pos", "]", "==", "0x00", ";", "pos", "++", ")", ";", "if", "(", "pos", "<", "bytes", ".", "length", ")", "{", "return", "Arrays", ".", "copyOfRange", "(", "bytes", ",", "pos", ",", "bytes", ".", "length", ")", ";", "}", "else", "{", "return", "new", "byte", "[", "]", "{", "0x00", "}", ";", "}", "}" ]
Remove 0x00 bytes from left side. @param bytes source array. @return trimmed array.
[ "Remove", "0x00", "bytes", "from", "left", "side", "." ]
16dad53e1222c7faa904c64394af94ba18f6d09c
https://github.com/Tirasa/ADSDDL/blob/16dad53e1222c7faa904c64394af94ba18f6d09c/src/main/java/net/tirasa/adsddl/ntsd/utils/NumberFacility.java#L64-L74
10,571
Tirasa/ADSDDL
src/main/java/net/tirasa/adsddl/ntsd/utils/NumberFacility.java
NumberFacility.getBits
public static boolean[] getBits(final byte... bytes) { if (bytes.length > 4) { throw new InvalidParameterException("Invalid number of bytes"); } final boolean[] res = new boolean[bytes.length * 8]; int pos = 0; for (byte b : bytes) { for (boolean bool : getBits(b)) { res[pos] = bool; pos++; } } return res; }
java
public static boolean[] getBits(final byte... bytes) { if (bytes.length > 4) { throw new InvalidParameterException("Invalid number of bytes"); } final boolean[] res = new boolean[bytes.length * 8]; int pos = 0; for (byte b : bytes) { for (boolean bool : getBits(b)) { res[pos] = bool; pos++; } } return res; }
[ "public", "static", "boolean", "[", "]", "getBits", "(", "final", "byte", "...", "bytes", ")", "{", "if", "(", "bytes", ".", "length", ">", "4", ")", "{", "throw", "new", "InvalidParameterException", "(", "\"Invalid number of bytes\"", ")", ";", "}", "final", "boolean", "[", "]", "res", "=", "new", "boolean", "[", "bytes", ".", "length", "*", "8", "]", ";", "int", "pos", "=", "0", ";", "for", "(", "byte", "b", ":", "bytes", ")", "{", "for", "(", "boolean", "bool", ":", "getBits", "(", "b", ")", ")", "{", "res", "[", "pos", "]", "=", "bool", ";", "pos", "++", ";", "}", "}", "return", "res", ";", "}" ]
Gets bits as boolean array from a given byte array. @param bytes bytes. @return bits.
[ "Gets", "bits", "as", "boolean", "array", "from", "a", "given", "byte", "array", "." ]
16dad53e1222c7faa904c64394af94ba18f6d09c
https://github.com/Tirasa/ADSDDL/blob/16dad53e1222c7faa904c64394af94ba18f6d09c/src/main/java/net/tirasa/adsddl/ntsd/utils/NumberFacility.java#L92-L109
10,572
Tirasa/ADSDDL
src/main/java/net/tirasa/adsddl/ntsd/utils/NumberFacility.java
NumberFacility.getBits
public static boolean[] getBits(final byte b) { final boolean[] res = new boolean[8]; for (int i = 0; i < 8; i++) { res[7 - i] = (b & (1 << i)) != 0; } return res; }
java
public static boolean[] getBits(final byte b) { final boolean[] res = new boolean[8]; for (int i = 0; i < 8; i++) { res[7 - i] = (b & (1 << i)) != 0; } return res; }
[ "public", "static", "boolean", "[", "]", "getBits", "(", "final", "byte", "b", ")", "{", "final", "boolean", "[", "]", "res", "=", "new", "boolean", "[", "8", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "8", ";", "i", "++", ")", "{", "res", "[", "7", "-", "i", "]", "=", "(", "b", "&", "(", "1", "<<", "i", ")", ")", "!=", "0", ";", "}", "return", "res", ";", "}" ]
Gets bits as boolean array from a given byte. @param b byte. @return bits.
[ "Gets", "bits", "as", "boolean", "array", "from", "a", "given", "byte", "." ]
16dad53e1222c7faa904c64394af94ba18f6d09c
https://github.com/Tirasa/ADSDDL/blob/16dad53e1222c7faa904c64394af94ba18f6d09c/src/main/java/net/tirasa/adsddl/ntsd/utils/NumberFacility.java#L117-L123
10,573
Tirasa/ADSDDL
src/main/java/net/tirasa/adsddl/ntsd/utils/NumberFacility.java
NumberFacility.getUInt
public static long getUInt(final byte... bytes) { if (bytes.length > 4) { throw new InvalidParameterException("Invalid number of bytes"); } long res = 0; for (int i = 0; i < bytes.length; i++) { res |= bytes[i] & 0xFF; if (i < bytes.length - 1) { res <<= 8; } } return res; }
java
public static long getUInt(final byte... bytes) { if (bytes.length > 4) { throw new InvalidParameterException("Invalid number of bytes"); } long res = 0; for (int i = 0; i < bytes.length; i++) { res |= bytes[i] & 0xFF; if (i < bytes.length - 1) { res <<= 8; } } return res; }
[ "public", "static", "long", "getUInt", "(", "final", "byte", "...", "bytes", ")", "{", "if", "(", "bytes", ".", "length", ">", "4", ")", "{", "throw", "new", "InvalidParameterException", "(", "\"Invalid number of bytes\"", ")", ";", "}", "long", "res", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "bytes", ".", "length", ";", "i", "++", ")", "{", "res", "|=", "bytes", "[", "i", "]", "&", "0xFF", ";", "if", "(", "i", "<", "bytes", ".", "length", "-", "1", ")", "{", "res", "<<=", "8", ";", "}", "}", "return", "res", ";", "}" ]
Gets unsigned integer value corresponding to the given bytes. @param bytes bytes. @return unsigned integer.
[ "Gets", "unsigned", "integer", "value", "corresponding", "to", "the", "given", "bytes", "." ]
16dad53e1222c7faa904c64394af94ba18f6d09c
https://github.com/Tirasa/ADSDDL/blob/16dad53e1222c7faa904c64394af94ba18f6d09c/src/main/java/net/tirasa/adsddl/ntsd/utils/NumberFacility.java#L183-L197
10,574
gitblit/fathom
fathom-security-jdbc/src/main/java/fathom/realm/jdbc/JdbcRealm.java
JdbcRealm.toSet
private Set<String> toSet(String value, String delimiter) { if (Strings.isNullOrEmpty(value)) { return Collections.emptySet(); } else { Set<String> stringSet = new LinkedHashSet<>(); String[] values = value.split(delimiter); for (String stringValue : values) { if (!Strings.isNullOrEmpty(stringValue)) { stringSet.add(stringValue.trim()); } } return stringSet; } }
java
private Set<String> toSet(String value, String delimiter) { if (Strings.isNullOrEmpty(value)) { return Collections.emptySet(); } else { Set<String> stringSet = new LinkedHashSet<>(); String[] values = value.split(delimiter); for (String stringValue : values) { if (!Strings.isNullOrEmpty(stringValue)) { stringSet.add(stringValue.trim()); } } return stringSet; } }
[ "private", "Set", "<", "String", ">", "toSet", "(", "String", "value", ",", "String", "delimiter", ")", "{", "if", "(", "Strings", ".", "isNullOrEmpty", "(", "value", ")", ")", "{", "return", "Collections", ".", "emptySet", "(", ")", ";", "}", "else", "{", "Set", "<", "String", ">", "stringSet", "=", "new", "LinkedHashSet", "<>", "(", ")", ";", "String", "[", "]", "values", "=", "value", ".", "split", "(", "delimiter", ")", ";", "for", "(", "String", "stringValue", ":", "values", ")", "{", "if", "(", "!", "Strings", ".", "isNullOrEmpty", "(", "stringValue", ")", ")", "{", "stringSet", ".", "add", "(", "stringValue", ".", "trim", "(", ")", ")", ";", "}", "}", "return", "stringSet", ";", "}", "}" ]
Creates an ordered set from a comma or semi-colon delimited string. Empty values are discarded. @param value @return a set of strings
[ "Creates", "an", "ordered", "set", "from", "a", "comma", "or", "semi", "-", "colon", "delimited", "string", ".", "Empty", "values", "are", "discarded", "." ]
f2f820eb16e9fea1e36ad4eda4ed51b35f056538
https://github.com/gitblit/fathom/blob/f2f820eb16e9fea1e36ad4eda4ed51b35f056538/fathom-security-jdbc/src/main/java/fathom/realm/jdbc/JdbcRealm.java#L558-L572
10,575
Tirasa/ADSDDL
src/main/java/net/tirasa/adsddl/ntsd/ACL.java
ACL.parse
int parse(final IntBuffer buff, final int start) { int pos = start; // read for Dacl byte[] bytes = NumberFacility.getBytes(buff.get(pos)); revision = AclRevision.parseValue(bytes[0]); pos++; bytes = NumberFacility.getBytes(buff.get(pos)); final int aceCount = NumberFacility.getInt(bytes[1], bytes[0]); for (int i = 0; i < aceCount; i++) { pos++; final ACE ace = new ACE(); aces.add(ace); pos = ace.parse(buff, pos); } return pos; }
java
int parse(final IntBuffer buff, final int start) { int pos = start; // read for Dacl byte[] bytes = NumberFacility.getBytes(buff.get(pos)); revision = AclRevision.parseValue(bytes[0]); pos++; bytes = NumberFacility.getBytes(buff.get(pos)); final int aceCount = NumberFacility.getInt(bytes[1], bytes[0]); for (int i = 0; i < aceCount; i++) { pos++; final ACE ace = new ACE(); aces.add(ace); pos = ace.parse(buff, pos); } return pos; }
[ "int", "parse", "(", "final", "IntBuffer", "buff", ",", "final", "int", "start", ")", "{", "int", "pos", "=", "start", ";", "// read for Dacl", "byte", "[", "]", "bytes", "=", "NumberFacility", ".", "getBytes", "(", "buff", ".", "get", "(", "pos", ")", ")", ";", "revision", "=", "AclRevision", ".", "parseValue", "(", "bytes", "[", "0", "]", ")", ";", "pos", "++", ";", "bytes", "=", "NumberFacility", ".", "getBytes", "(", "buff", ".", "get", "(", "pos", ")", ")", ";", "final", "int", "aceCount", "=", "NumberFacility", ".", "getInt", "(", "bytes", "[", "1", "]", ",", "bytes", "[", "0", "]", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "aceCount", ";", "i", "++", ")", "{", "pos", "++", ";", "final", "ACE", "ace", "=", "new", "ACE", "(", ")", ";", "aces", ".", "add", "(", "ace", ")", ";", "pos", "=", "ace", ".", "parse", "(", "buff", ",", "pos", ")", ";", "}", "return", "pos", ";", "}" ]
Load the ACL from the buffer returning the last ACL segment position into the buffer. @param buff source buffer. @param start start loading position. @return last loading position.
[ "Load", "the", "ACL", "from", "the", "buffer", "returning", "the", "last", "ACL", "segment", "position", "into", "the", "buffer", "." ]
16dad53e1222c7faa904c64394af94ba18f6d09c
https://github.com/Tirasa/ADSDDL/blob/16dad53e1222c7faa904c64394af94ba18f6d09c/src/main/java/net/tirasa/adsddl/ntsd/ACL.java#L90-L110
10,576
gitblit/fathom
fathom-core/src/main/java/fathom/utils/RequireUtil.java
RequireUtil.allowInstance
public static boolean allowInstance(Settings settings, Object object) { Preconditions.checkNotNull(object, "Can not check runtime permissions on a null instance!"); if (object instanceof Method) { return allowMethod(settings, (Method) object); } return allowClass(settings, object.getClass()); }
java
public static boolean allowInstance(Settings settings, Object object) { Preconditions.checkNotNull(object, "Can not check runtime permissions on a null instance!"); if (object instanceof Method) { return allowMethod(settings, (Method) object); } return allowClass(settings, object.getClass()); }
[ "public", "static", "boolean", "allowInstance", "(", "Settings", "settings", ",", "Object", "object", ")", "{", "Preconditions", ".", "checkNotNull", "(", "object", ",", "\"Can not check runtime permissions on a null instance!\"", ")", ";", "if", "(", "object", "instanceof", "Method", ")", "{", "return", "allowMethod", "(", "settings", ",", "(", "Method", ")", "object", ")", ";", "}", "return", "allowClass", "(", "settings", ",", "object", ".", "getClass", "(", ")", ")", ";", "}" ]
Determines if this object may be used in the current runtime environment. Fathom settings are considered as well as runtime modes. @param settings @param object @return true if the object may be used
[ "Determines", "if", "this", "object", "may", "be", "used", "in", "the", "current", "runtime", "environment", ".", "Fathom", "settings", "are", "considered", "as", "well", "as", "runtime", "modes", "." ]
f2f820eb16e9fea1e36ad4eda4ed51b35f056538
https://github.com/gitblit/fathom/blob/f2f820eb16e9fea1e36ad4eda4ed51b35f056538/fathom-core/src/main/java/fathom/utils/RequireUtil.java#L55-L64
10,577
gitblit/fathom
fathom-core/src/main/java/fathom/utils/RequireUtil.java
RequireUtil.allowClass
public static boolean allowClass(Settings settings, Class<?> aClass) { // Settings-based class exclusions/inclusions if (aClass.isAnnotationPresent(RequireSettings.class)) { // multiple keys required RequireSetting[] requireSettings = aClass.getAnnotation(RequireSettings.class).value(); StringJoiner joiner = new StringJoiner(", "); Arrays.asList(requireSettings).forEach((require) -> { if (!settings.hasSetting(require.value())) { joiner.add(require.value()); } }); String requiredSettings = joiner.toString(); if (!requiredSettings.isEmpty()) { log.warn("skipping {}, it requires the following {} mode settings: {}", aClass.getName(), settings.getMode(), requiredSettings); return false; } }
java
public static boolean allowClass(Settings settings, Class<?> aClass) { // Settings-based class exclusions/inclusions if (aClass.isAnnotationPresent(RequireSettings.class)) { // multiple keys required RequireSetting[] requireSettings = aClass.getAnnotation(RequireSettings.class).value(); StringJoiner joiner = new StringJoiner(", "); Arrays.asList(requireSettings).forEach((require) -> { if (!settings.hasSetting(require.value())) { joiner.add(require.value()); } }); String requiredSettings = joiner.toString(); if (!requiredSettings.isEmpty()) { log.warn("skipping {}, it requires the following {} mode settings: {}", aClass.getName(), settings.getMode(), requiredSettings); return false; } }
[ "public", "static", "boolean", "allowClass", "(", "Settings", "settings", ",", "Class", "<", "?", ">", "aClass", ")", "{", "// Settings-based class exclusions/inclusions", "if", "(", "aClass", ".", "isAnnotationPresent", "(", "RequireSettings", ".", "class", ")", ")", "{", "// multiple keys required", "RequireSetting", "[", "]", "requireSettings", "=", "aClass", ".", "getAnnotation", "(", "RequireSettings", ".", "class", ")", ".", "value", "(", ")", ";", "StringJoiner", "joiner", "=", "new", "StringJoiner", "(", "\", \"", ")", ";", "Arrays", ".", "asList", "(", "requireSettings", ")", ".", "forEach", "(", "(", "require", ")", "-", ">", "{", "if", "(", "!", "settings", ".", "hasSetting", "(", "require", ".", "value", "(", ")", ")", ")", "{", "joiner", ".", "add", "(", "require", ".", "value", "(", ")", ")", ";", "}", "}", ")", ";", "String", "requiredSettings", "=", "joiner", ".", "toString", "(", ")", ";", "if", "(", "!", "requiredSettings", ".", "isEmpty", "(", ")", ")", "{", "log", ".", "warn", "(", "\"skipping {}, it requires the following {} mode settings: {}\"", ",", "aClass", ".", "getName", "(", ")", ",", "settings", ".", "getMode", "(", ")", ",", "requiredSettings", ")", ";", "return", "false", ";", "}", "}" ]
Determines if this class may be used in the current runtime environment. Fathom settings are considered as well as runtime modes. @param settings @param aClass @return true if the class may be used
[ "Determines", "if", "this", "class", "may", "be", "used", "in", "the", "current", "runtime", "environment", ".", "Fathom", "settings", "are", "considered", "as", "well", "as", "runtime", "modes", "." ]
f2f820eb16e9fea1e36ad4eda4ed51b35f056538
https://github.com/gitblit/fathom/blob/f2f820eb16e9fea1e36ad4eda4ed51b35f056538/fathom-core/src/main/java/fathom/utils/RequireUtil.java#L74-L93
10,578
Tirasa/ADSDDL
src/main/java/net/tirasa/adsddl/ntsd/utils/GUID.java
GUID.getGuidAsString
public static String getGuidAsString(byte[] GUID) { final StringBuilder res = new StringBuilder(); res.append(AddLeadingZero((int) GUID[3] & 0xFF)); res.append(AddLeadingZero((int) GUID[2] & 0xFF)); res.append(AddLeadingZero((int) GUID[1] & 0xFF)); res.append(AddLeadingZero((int) GUID[0] & 0xFF)); res.append("-"); res.append(AddLeadingZero((int) GUID[5] & 0xFF)); res.append(AddLeadingZero((int) GUID[4] & 0xFF)); res.append("-"); res.append(AddLeadingZero((int) GUID[7] & 0xFF)); res.append(AddLeadingZero((int) GUID[6] & 0xFF)); res.append("-"); res.append(AddLeadingZero((int) GUID[8] & 0xFF)); res.append(AddLeadingZero((int) GUID[9] & 0xFF)); res.append("-"); res.append(AddLeadingZero((int) GUID[10] & 0xFF)); res.append(AddLeadingZero((int) GUID[11] & 0xFF)); res.append(AddLeadingZero((int) GUID[12] & 0xFF)); res.append(AddLeadingZero((int) GUID[13] & 0xFF)); res.append(AddLeadingZero((int) GUID[14] & 0xFF)); res.append(AddLeadingZero((int) GUID[15] & 0xFF)); return res.toString(); }
java
public static String getGuidAsString(byte[] GUID) { final StringBuilder res = new StringBuilder(); res.append(AddLeadingZero((int) GUID[3] & 0xFF)); res.append(AddLeadingZero((int) GUID[2] & 0xFF)); res.append(AddLeadingZero((int) GUID[1] & 0xFF)); res.append(AddLeadingZero((int) GUID[0] & 0xFF)); res.append("-"); res.append(AddLeadingZero((int) GUID[5] & 0xFF)); res.append(AddLeadingZero((int) GUID[4] & 0xFF)); res.append("-"); res.append(AddLeadingZero((int) GUID[7] & 0xFF)); res.append(AddLeadingZero((int) GUID[6] & 0xFF)); res.append("-"); res.append(AddLeadingZero((int) GUID[8] & 0xFF)); res.append(AddLeadingZero((int) GUID[9] & 0xFF)); res.append("-"); res.append(AddLeadingZero((int) GUID[10] & 0xFF)); res.append(AddLeadingZero((int) GUID[11] & 0xFF)); res.append(AddLeadingZero((int) GUID[12] & 0xFF)); res.append(AddLeadingZero((int) GUID[13] & 0xFF)); res.append(AddLeadingZero((int) GUID[14] & 0xFF)); res.append(AddLeadingZero((int) GUID[15] & 0xFF)); return res.toString(); }
[ "public", "static", "String", "getGuidAsString", "(", "byte", "[", "]", "GUID", ")", "{", "final", "StringBuilder", "res", "=", "new", "StringBuilder", "(", ")", ";", "res", ".", "append", "(", "AddLeadingZero", "(", "(", "int", ")", "GUID", "[", "3", "]", "&", "0xFF", ")", ")", ";", "res", ".", "append", "(", "AddLeadingZero", "(", "(", "int", ")", "GUID", "[", "2", "]", "&", "0xFF", ")", ")", ";", "res", ".", "append", "(", "AddLeadingZero", "(", "(", "int", ")", "GUID", "[", "1", "]", "&", "0xFF", ")", ")", ";", "res", ".", "append", "(", "AddLeadingZero", "(", "(", "int", ")", "GUID", "[", "0", "]", "&", "0xFF", ")", ")", ";", "res", ".", "append", "(", "\"-\"", ")", ";", "res", ".", "append", "(", "AddLeadingZero", "(", "(", "int", ")", "GUID", "[", "5", "]", "&", "0xFF", ")", ")", ";", "res", ".", "append", "(", "AddLeadingZero", "(", "(", "int", ")", "GUID", "[", "4", "]", "&", "0xFF", ")", ")", ";", "res", ".", "append", "(", "\"-\"", ")", ";", "res", ".", "append", "(", "AddLeadingZero", "(", "(", "int", ")", "GUID", "[", "7", "]", "&", "0xFF", ")", ")", ";", "res", ".", "append", "(", "AddLeadingZero", "(", "(", "int", ")", "GUID", "[", "6", "]", "&", "0xFF", ")", ")", ";", "res", ".", "append", "(", "\"-\"", ")", ";", "res", ".", "append", "(", "AddLeadingZero", "(", "(", "int", ")", "GUID", "[", "8", "]", "&", "0xFF", ")", ")", ";", "res", ".", "append", "(", "AddLeadingZero", "(", "(", "int", ")", "GUID", "[", "9", "]", "&", "0xFF", ")", ")", ";", "res", ".", "append", "(", "\"-\"", ")", ";", "res", ".", "append", "(", "AddLeadingZero", "(", "(", "int", ")", "GUID", "[", "10", "]", "&", "0xFF", ")", ")", ";", "res", ".", "append", "(", "AddLeadingZero", "(", "(", "int", ")", "GUID", "[", "11", "]", "&", "0xFF", ")", ")", ";", "res", ".", "append", "(", "AddLeadingZero", "(", "(", "int", ")", "GUID", "[", "12", "]", "&", "0xFF", ")", ")", ";", "res", ".", "append", "(", "AddLeadingZero", "(", "(", "int", ")", "GUID", "[", "13", "]", "&", "0xFF", ")", ")", ";", "res", ".", "append", "(", "AddLeadingZero", "(", "(", "int", ")", "GUID", "[", "14", "]", "&", "0xFF", ")", ")", ";", "res", ".", "append", "(", "AddLeadingZero", "(", "(", "int", ")", "GUID", "[", "15", "]", "&", "0xFF", ")", ")", ";", "return", "res", ".", "toString", "(", ")", ";", "}" ]
Gets GUID as string. @param GUID GUID. @return GUID as string.
[ "Gets", "GUID", "as", "string", "." ]
16dad53e1222c7faa904c64394af94ba18f6d09c
https://github.com/Tirasa/ADSDDL/blob/16dad53e1222c7faa904c64394af94ba18f6d09c/src/main/java/net/tirasa/adsddl/ntsd/utils/GUID.java#L36-L62
10,579
Tirasa/ADSDDL
src/main/java/net/tirasa/adsddl/ntsd/utils/GUID.java
GUID.getGuidAsByteArray
public static byte[] getGuidAsByteArray(final String GUID) { final UUID uuid = UUID.fromString(GUID); final ByteBuffer buff = ByteBuffer.wrap(new byte[16]); buff.putLong(uuid.getMostSignificantBits()); buff.putLong(uuid.getLeastSignificantBits()); byte[] res = new byte[] { buff.get(3), buff.get(2), buff.get(1), buff.get(0), buff.get(5), buff.get(4), buff.get(7), buff.get(6), buff.get(8), buff.get(9), buff.get(10), buff.get(11), buff.get(12), buff.get(13), buff.get(14), buff.get(15), }; return res; }
java
public static byte[] getGuidAsByteArray(final String GUID) { final UUID uuid = UUID.fromString(GUID); final ByteBuffer buff = ByteBuffer.wrap(new byte[16]); buff.putLong(uuid.getMostSignificantBits()); buff.putLong(uuid.getLeastSignificantBits()); byte[] res = new byte[] { buff.get(3), buff.get(2), buff.get(1), buff.get(0), buff.get(5), buff.get(4), buff.get(7), buff.get(6), buff.get(8), buff.get(9), buff.get(10), buff.get(11), buff.get(12), buff.get(13), buff.get(14), buff.get(15), }; return res; }
[ "public", "static", "byte", "[", "]", "getGuidAsByteArray", "(", "final", "String", "GUID", ")", "{", "final", "UUID", "uuid", "=", "UUID", ".", "fromString", "(", "GUID", ")", ";", "final", "ByteBuffer", "buff", "=", "ByteBuffer", ".", "wrap", "(", "new", "byte", "[", "16", "]", ")", ";", "buff", ".", "putLong", "(", "uuid", ".", "getMostSignificantBits", "(", ")", ")", ";", "buff", ".", "putLong", "(", "uuid", ".", "getLeastSignificantBits", "(", ")", ")", ";", "byte", "[", "]", "res", "=", "new", "byte", "[", "]", "{", "buff", ".", "get", "(", "3", ")", ",", "buff", ".", "get", "(", "2", ")", ",", "buff", ".", "get", "(", "1", ")", ",", "buff", ".", "get", "(", "0", ")", ",", "buff", ".", "get", "(", "5", ")", ",", "buff", ".", "get", "(", "4", ")", ",", "buff", ".", "get", "(", "7", ")", ",", "buff", ".", "get", "(", "6", ")", ",", "buff", ".", "get", "(", "8", ")", ",", "buff", ".", "get", "(", "9", ")", ",", "buff", ".", "get", "(", "10", ")", ",", "buff", ".", "get", "(", "11", ")", ",", "buff", ".", "get", "(", "12", ")", ",", "buff", ".", "get", "(", "13", ")", ",", "buff", ".", "get", "(", "14", ")", ",", "buff", ".", "get", "(", "15", ")", ",", "}", ";", "return", "res", ";", "}" ]
Gets GUID as byte array. @param GUID GUID. @return GUID as byte array.
[ "Gets", "GUID", "as", "byte", "array", "." ]
16dad53e1222c7faa904c64394af94ba18f6d09c
https://github.com/Tirasa/ADSDDL/blob/16dad53e1222c7faa904c64394af94ba18f6d09c/src/main/java/net/tirasa/adsddl/ntsd/utils/GUID.java#L70-L96
10,580
gitblit/fathom
fathom-security/src/main/java/fathom/authz/Authorizations.java
Authorizations.setRoles
public Authorizations setRoles(Set<Role> roles) { this.roles.clear(); this.aggregatePermissions = null; addRoles(roles); return this; }
java
public Authorizations setRoles(Set<Role> roles) { this.roles.clear(); this.aggregatePermissions = null; addRoles(roles); return this; }
[ "public", "Authorizations", "setRoles", "(", "Set", "<", "Role", ">", "roles", ")", "{", "this", ".", "roles", ".", "clear", "(", ")", ";", "this", ".", "aggregatePermissions", "=", "null", ";", "addRoles", "(", "roles", ")", ";", "return", "this", ";", "}" ]
Sets the roles assigned to the Account. @param roles the roles assigned to the Account.
[ "Sets", "the", "roles", "assigned", "to", "the", "Account", "." ]
f2f820eb16e9fea1e36ad4eda4ed51b35f056538
https://github.com/gitblit/fathom/blob/f2f820eb16e9fea1e36ad4eda4ed51b35f056538/fathom-security/src/main/java/fathom/authz/Authorizations.java#L92-L98
10,581
gitblit/fathom
fathom-security/src/main/java/fathom/authz/Authorizations.java
Authorizations.addRoles
public Authorizations addRoles(String... roles) { for (String role : roles) { addRole(new Role(role)); } return this; }
java
public Authorizations addRoles(String... roles) { for (String role : roles) { addRole(new Role(role)); } return this; }
[ "public", "Authorizations", "addRoles", "(", "String", "...", "roles", ")", "{", "for", "(", "String", "role", ":", "roles", ")", "{", "addRole", "(", "new", "Role", "(", "role", ")", ")", ";", "}", "return", "this", ";", "}" ]
Adds roles to the Account Authorizations. @param roles the roles to add.
[ "Adds", "roles", "to", "the", "Account", "Authorizations", "." ]
f2f820eb16e9fea1e36ad4eda4ed51b35f056538
https://github.com/gitblit/fathom/blob/f2f820eb16e9fea1e36ad4eda4ed51b35f056538/fathom-security/src/main/java/fathom/authz/Authorizations.java#L105-L111
10,582
gitblit/fathom
fathom-security/src/main/java/fathom/authz/Authorizations.java
Authorizations.getAggregatePermissions
public Collection<Permission> getAggregatePermissions() { if (aggregatePermissions == null) { Set<Permission> perms = new LinkedHashSet<>(); perms.addAll(permissions); for (Role role : roles) { perms.addAll(role.getPermissions()); } if (perms.isEmpty()) { aggregatePermissions = Collections.emptySet(); } else { aggregatePermissions = Collections.unmodifiableSet(perms); } } return aggregatePermissions; }
java
public Collection<Permission> getAggregatePermissions() { if (aggregatePermissions == null) { Set<Permission> perms = new LinkedHashSet<>(); perms.addAll(permissions); for (Role role : roles) { perms.addAll(role.getPermissions()); } if (perms.isEmpty()) { aggregatePermissions = Collections.emptySet(); } else { aggregatePermissions = Collections.unmodifiableSet(perms); } } return aggregatePermissions; }
[ "public", "Collection", "<", "Permission", ">", "getAggregatePermissions", "(", ")", "{", "if", "(", "aggregatePermissions", "==", "null", ")", "{", "Set", "<", "Permission", ">", "perms", "=", "new", "LinkedHashSet", "<>", "(", ")", ";", "perms", ".", "addAll", "(", "permissions", ")", ";", "for", "(", "Role", "role", ":", "roles", ")", "{", "perms", ".", "addAll", "(", "role", ".", "getPermissions", "(", ")", ")", ";", "}", "if", "(", "perms", ".", "isEmpty", "(", ")", ")", "{", "aggregatePermissions", "=", "Collections", ".", "emptySet", "(", ")", ";", "}", "else", "{", "aggregatePermissions", "=", "Collections", ".", "unmodifiableSet", "(", "perms", ")", ";", "}", "}", "return", "aggregatePermissions", ";", "}" ]
Gets the collection of permissions including the role permissions and discrete permissions. @return a collection of aggregate permissions
[ "Gets", "the", "collection", "of", "permissions", "including", "the", "role", "permissions", "and", "discrete", "permissions", "." ]
f2f820eb16e9fea1e36ad4eda4ed51b35f056538
https://github.com/gitblit/fathom/blob/f2f820eb16e9fea1e36ad4eda4ed51b35f056538/fathom-security/src/main/java/fathom/authz/Authorizations.java#L337-L353
10,583
gitblit/fathom
fathom-rest/src/main/java/fathom/rest/controller/ControllerHandler.java
ControllerHandler.findMethod
protected Method findMethod(Class<?> controllerClass, String name) { // identify first method which matches the name Method controllerMethod = null; for (Method method : controllerClass.getMethods()) { if (method.getName().equals(name)) { if (controllerMethod == null) { controllerMethod = method; } else { throw new FatalException("Found overloaded controller method '{}'. Method names must be unique!", Util.toString(method)); } } } return controllerMethod; }
java
protected Method findMethod(Class<?> controllerClass, String name) { // identify first method which matches the name Method controllerMethod = null; for (Method method : controllerClass.getMethods()) { if (method.getName().equals(name)) { if (controllerMethod == null) { controllerMethod = method; } else { throw new FatalException("Found overloaded controller method '{}'. Method names must be unique!", Util.toString(method)); } } } return controllerMethod; }
[ "protected", "Method", "findMethod", "(", "Class", "<", "?", ">", "controllerClass", ",", "String", "name", ")", "{", "// identify first method which matches the name", "Method", "controllerMethod", "=", "null", ";", "for", "(", "Method", "method", ":", "controllerClass", ".", "getMethods", "(", ")", ")", "{", "if", "(", "method", ".", "getName", "(", ")", ".", "equals", "(", "name", ")", ")", "{", "if", "(", "controllerMethod", "==", "null", ")", "{", "controllerMethod", "=", "method", ";", "}", "else", "{", "throw", "new", "FatalException", "(", "\"Found overloaded controller method '{}'. Method names must be unique!\"", ",", "Util", ".", "toString", "(", "method", ")", ")", ";", "}", "}", "}", "return", "controllerMethod", ";", "}" ]
Finds the named controller method. @param controllerClass @param name @return the controller method or null
[ "Finds", "the", "named", "controller", "method", "." ]
f2f820eb16e9fea1e36ad4eda4ed51b35f056538
https://github.com/gitblit/fathom/blob/f2f820eb16e9fea1e36ad4eda4ed51b35f056538/fathom-rest/src/main/java/fathom/rest/controller/ControllerHandler.java#L275-L290
10,584
gitblit/fathom
fathom-rest/src/main/java/fathom/rest/controller/ControllerHandler.java
ControllerHandler.configureContentTypeSuffixes
protected Set<String> configureContentTypeSuffixes(ContentTypeEngines engines) { if (null == ClassUtil.getAnnotation(method, ContentTypeBySuffix.class)) { return Collections.emptySet(); } Set<String> suffixes = new TreeSet<>(); for (String suffix : engines.getContentTypeSuffixes()) { String contentType = engines.getContentTypeEngine(suffix).getContentType(); if (declaredProduces.contains(contentType)) { suffixes.add(suffix); } } return suffixes; }
java
protected Set<String> configureContentTypeSuffixes(ContentTypeEngines engines) { if (null == ClassUtil.getAnnotation(method, ContentTypeBySuffix.class)) { return Collections.emptySet(); } Set<String> suffixes = new TreeSet<>(); for (String suffix : engines.getContentTypeSuffixes()) { String contentType = engines.getContentTypeEngine(suffix).getContentType(); if (declaredProduces.contains(contentType)) { suffixes.add(suffix); } } return suffixes; }
[ "protected", "Set", "<", "String", ">", "configureContentTypeSuffixes", "(", "ContentTypeEngines", "engines", ")", "{", "if", "(", "null", "==", "ClassUtil", ".", "getAnnotation", "(", "method", ",", "ContentTypeBySuffix", ".", "class", ")", ")", "{", "return", "Collections", ".", "emptySet", "(", ")", ";", "}", "Set", "<", "String", ">", "suffixes", "=", "new", "TreeSet", "<>", "(", ")", ";", "for", "(", "String", "suffix", ":", "engines", ".", "getContentTypeSuffixes", "(", ")", ")", "{", "String", "contentType", "=", "engines", ".", "getContentTypeEngine", "(", "suffix", ")", ".", "getContentType", "(", ")", ";", "if", "(", "declaredProduces", ".", "contains", "(", "contentType", ")", ")", "{", "suffixes", ".", "add", "(", "suffix", ")", ";", "}", "}", "return", "suffixes", ";", "}" ]
Configures the content-type suffixes @param engines @return acceptable content-type suffixes
[ "Configures", "the", "content", "-", "type", "suffixes" ]
f2f820eb16e9fea1e36ad4eda4ed51b35f056538
https://github.com/gitblit/fathom/blob/f2f820eb16e9fea1e36ad4eda4ed51b35f056538/fathom-rest/src/main/java/fathom/rest/controller/ControllerHandler.java#L298-L311
10,585
gitblit/fathom
fathom-rest/src/main/java/fathom/rest/controller/ControllerHandler.java
ControllerHandler.configureMethodArgs
protected void configureMethodArgs(Injector injector) { Class<?>[] types = method.getParameterTypes(); extractors = new ArgumentExtractor[types.length]; patterns = new String[types.length]; for (int i = 0; i < types.length; i++) { final Parameter parameter = method.getParameters()[i]; final Class<? extends Collection> collectionType; final Class<?> objectType; if (Collection.class.isAssignableFrom(types[i])) { collectionType = (Class<? extends Collection>) types[i]; objectType = getParameterGenericType(parameter); } else { collectionType = null; objectType = types[i]; } // determine the appropriate extractor Class<? extends ArgumentExtractor> extractorType; if (FileItem.class == objectType) { extractorType = FileItemExtractor.class; } else { extractorType = ControllerUtil.getArgumentExtractor(parameter); } // instantiate the extractor extractors[i] = injector.getInstance(extractorType); // configure the extractor if (extractors[i] instanceof ConfigurableExtractor<?>) { ConfigurableExtractor extractor = (ConfigurableExtractor) extractors[i]; Annotation annotation = ClassUtil.getAnnotation(parameter, extractor.getAnnotationClass()); if (annotation != null) { extractor.configure(annotation); } } if (extractors[i] instanceof SuffixExtractor) { // the last parameter can be assigned content type suffixes SuffixExtractor extractor = (SuffixExtractor) extractors[i]; extractor.setSuffixes(contentTypeSuffixes); } if (collectionType != null) { if (extractors[i] instanceof CollectionExtractor) { CollectionExtractor extractor = (CollectionExtractor) extractors[i]; extractor.setCollectionType(collectionType); } else { throw new FatalException( "Controller method '{}' parameter {} of type '{}' does not specify an argument extractor that supports collections!", Util.toString(method), i + 1, Util.toString(collectionType, objectType)); } } if (extractors[i] instanceof TypedExtractor) { TypedExtractor extractor = (TypedExtractor) extractors[i]; extractor.setObjectType(objectType); } if (extractors[i] instanceof NamedExtractor) { // ensure that the extractor has a proper name NamedExtractor namedExtractor = (NamedExtractor) extractors[i]; if (Strings.isNullOrEmpty(namedExtractor.getName())) { // parameter is not named via annotation // try looking for the parameter name in the compiled .class file if (parameter.isNamePresent()) { namedExtractor.setName(parameter.getName()); } else { log.error("Properly annotate your controller methods OR specify the '-parameters' flag for your Java compiler!"); throw new FatalException( "Controller method '{}' parameter {} of type '{}' does not specify a name!", Util.toString(method), i + 1, Util.toString(collectionType, objectType)); } } } } }
java
protected void configureMethodArgs(Injector injector) { Class<?>[] types = method.getParameterTypes(); extractors = new ArgumentExtractor[types.length]; patterns = new String[types.length]; for (int i = 0; i < types.length; i++) { final Parameter parameter = method.getParameters()[i]; final Class<? extends Collection> collectionType; final Class<?> objectType; if (Collection.class.isAssignableFrom(types[i])) { collectionType = (Class<? extends Collection>) types[i]; objectType = getParameterGenericType(parameter); } else { collectionType = null; objectType = types[i]; } // determine the appropriate extractor Class<? extends ArgumentExtractor> extractorType; if (FileItem.class == objectType) { extractorType = FileItemExtractor.class; } else { extractorType = ControllerUtil.getArgumentExtractor(parameter); } // instantiate the extractor extractors[i] = injector.getInstance(extractorType); // configure the extractor if (extractors[i] instanceof ConfigurableExtractor<?>) { ConfigurableExtractor extractor = (ConfigurableExtractor) extractors[i]; Annotation annotation = ClassUtil.getAnnotation(parameter, extractor.getAnnotationClass()); if (annotation != null) { extractor.configure(annotation); } } if (extractors[i] instanceof SuffixExtractor) { // the last parameter can be assigned content type suffixes SuffixExtractor extractor = (SuffixExtractor) extractors[i]; extractor.setSuffixes(contentTypeSuffixes); } if (collectionType != null) { if (extractors[i] instanceof CollectionExtractor) { CollectionExtractor extractor = (CollectionExtractor) extractors[i]; extractor.setCollectionType(collectionType); } else { throw new FatalException( "Controller method '{}' parameter {} of type '{}' does not specify an argument extractor that supports collections!", Util.toString(method), i + 1, Util.toString(collectionType, objectType)); } } if (extractors[i] instanceof TypedExtractor) { TypedExtractor extractor = (TypedExtractor) extractors[i]; extractor.setObjectType(objectType); } if (extractors[i] instanceof NamedExtractor) { // ensure that the extractor has a proper name NamedExtractor namedExtractor = (NamedExtractor) extractors[i]; if (Strings.isNullOrEmpty(namedExtractor.getName())) { // parameter is not named via annotation // try looking for the parameter name in the compiled .class file if (parameter.isNamePresent()) { namedExtractor.setName(parameter.getName()); } else { log.error("Properly annotate your controller methods OR specify the '-parameters' flag for your Java compiler!"); throw new FatalException( "Controller method '{}' parameter {} of type '{}' does not specify a name!", Util.toString(method), i + 1, Util.toString(collectionType, objectType)); } } } } }
[ "protected", "void", "configureMethodArgs", "(", "Injector", "injector", ")", "{", "Class", "<", "?", ">", "[", "]", "types", "=", "method", ".", "getParameterTypes", "(", ")", ";", "extractors", "=", "new", "ArgumentExtractor", "[", "types", ".", "length", "]", ";", "patterns", "=", "new", "String", "[", "types", ".", "length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "types", ".", "length", ";", "i", "++", ")", "{", "final", "Parameter", "parameter", "=", "method", ".", "getParameters", "(", ")", "[", "i", "]", ";", "final", "Class", "<", "?", "extends", "Collection", ">", "collectionType", ";", "final", "Class", "<", "?", ">", "objectType", ";", "if", "(", "Collection", ".", "class", ".", "isAssignableFrom", "(", "types", "[", "i", "]", ")", ")", "{", "collectionType", "=", "(", "Class", "<", "?", "extends", "Collection", ">", ")", "types", "[", "i", "]", ";", "objectType", "=", "getParameterGenericType", "(", "parameter", ")", ";", "}", "else", "{", "collectionType", "=", "null", ";", "objectType", "=", "types", "[", "i", "]", ";", "}", "// determine the appropriate extractor", "Class", "<", "?", "extends", "ArgumentExtractor", ">", "extractorType", ";", "if", "(", "FileItem", ".", "class", "==", "objectType", ")", "{", "extractorType", "=", "FileItemExtractor", ".", "class", ";", "}", "else", "{", "extractorType", "=", "ControllerUtil", ".", "getArgumentExtractor", "(", "parameter", ")", ";", "}", "// instantiate the extractor", "extractors", "[", "i", "]", "=", "injector", ".", "getInstance", "(", "extractorType", ")", ";", "// configure the extractor", "if", "(", "extractors", "[", "i", "]", "instanceof", "ConfigurableExtractor", "<", "?", ">", ")", "{", "ConfigurableExtractor", "extractor", "=", "(", "ConfigurableExtractor", ")", "extractors", "[", "i", "]", ";", "Annotation", "annotation", "=", "ClassUtil", ".", "getAnnotation", "(", "parameter", ",", "extractor", ".", "getAnnotationClass", "(", ")", ")", ";", "if", "(", "annotation", "!=", "null", ")", "{", "extractor", ".", "configure", "(", "annotation", ")", ";", "}", "}", "if", "(", "extractors", "[", "i", "]", "instanceof", "SuffixExtractor", ")", "{", "// the last parameter can be assigned content type suffixes", "SuffixExtractor", "extractor", "=", "(", "SuffixExtractor", ")", "extractors", "[", "i", "]", ";", "extractor", ".", "setSuffixes", "(", "contentTypeSuffixes", ")", ";", "}", "if", "(", "collectionType", "!=", "null", ")", "{", "if", "(", "extractors", "[", "i", "]", "instanceof", "CollectionExtractor", ")", "{", "CollectionExtractor", "extractor", "=", "(", "CollectionExtractor", ")", "extractors", "[", "i", "]", ";", "extractor", ".", "setCollectionType", "(", "collectionType", ")", ";", "}", "else", "{", "throw", "new", "FatalException", "(", "\"Controller method '{}' parameter {} of type '{}' does not specify an argument extractor that supports collections!\"", ",", "Util", ".", "toString", "(", "method", ")", ",", "i", "+", "1", ",", "Util", ".", "toString", "(", "collectionType", ",", "objectType", ")", ")", ";", "}", "}", "if", "(", "extractors", "[", "i", "]", "instanceof", "TypedExtractor", ")", "{", "TypedExtractor", "extractor", "=", "(", "TypedExtractor", ")", "extractors", "[", "i", "]", ";", "extractor", ".", "setObjectType", "(", "objectType", ")", ";", "}", "if", "(", "extractors", "[", "i", "]", "instanceof", "NamedExtractor", ")", "{", "// ensure that the extractor has a proper name", "NamedExtractor", "namedExtractor", "=", "(", "NamedExtractor", ")", "extractors", "[", "i", "]", ";", "if", "(", "Strings", ".", "isNullOrEmpty", "(", "namedExtractor", ".", "getName", "(", ")", ")", ")", "{", "// parameter is not named via annotation", "// try looking for the parameter name in the compiled .class file", "if", "(", "parameter", ".", "isNamePresent", "(", ")", ")", "{", "namedExtractor", ".", "setName", "(", "parameter", ".", "getName", "(", ")", ")", ";", "}", "else", "{", "log", ".", "error", "(", "\"Properly annotate your controller methods OR specify the '-parameters' flag for your Java compiler!\"", ")", ";", "throw", "new", "FatalException", "(", "\"Controller method '{}' parameter {} of type '{}' does not specify a name!\"", ",", "Util", ".", "toString", "(", "method", ")", ",", "i", "+", "1", ",", "Util", ".", "toString", "(", "collectionType", ",", "objectType", ")", ")", ";", "}", "}", "}", "}", "}" ]
Configures the controller method arguments. @param injector
[ "Configures", "the", "controller", "method", "arguments", "." ]
f2f820eb16e9fea1e36ad4eda4ed51b35f056538
https://github.com/gitblit/fathom/blob/f2f820eb16e9fea1e36ad4eda4ed51b35f056538/fathom-rest/src/main/java/fathom/rest/controller/ControllerHandler.java#L318-L394
10,586
gitblit/fathom
fathom-rest/src/main/java/fathom/rest/controller/ControllerHandler.java
ControllerHandler.validateMethodArgs
public void validateMethodArgs(String uriPattern) { Set<String> namedParameters = new LinkedHashSet<>(); for (ArgumentExtractor extractor : extractors) { if (extractor instanceof NamedExtractor) { NamedExtractor namedExtractor = (NamedExtractor) extractor; namedParameters.add(namedExtractor.getName()); } } // validate the url specification and method signature agree on required parameters List<String> requiredParameters = getParameterNames(uriPattern); if (!namedParameters.containsAll(requiredParameters)) { throw new FatalException("Controller method '{}' declares parameters {} but the URL specification requires {}", Util.toString(method), namedParameters, requiredParameters); } }
java
public void validateMethodArgs(String uriPattern) { Set<String> namedParameters = new LinkedHashSet<>(); for (ArgumentExtractor extractor : extractors) { if (extractor instanceof NamedExtractor) { NamedExtractor namedExtractor = (NamedExtractor) extractor; namedParameters.add(namedExtractor.getName()); } } // validate the url specification and method signature agree on required parameters List<String> requiredParameters = getParameterNames(uriPattern); if (!namedParameters.containsAll(requiredParameters)) { throw new FatalException("Controller method '{}' declares parameters {} but the URL specification requires {}", Util.toString(method), namedParameters, requiredParameters); } }
[ "public", "void", "validateMethodArgs", "(", "String", "uriPattern", ")", "{", "Set", "<", "String", ">", "namedParameters", "=", "new", "LinkedHashSet", "<>", "(", ")", ";", "for", "(", "ArgumentExtractor", "extractor", ":", "extractors", ")", "{", "if", "(", "extractor", "instanceof", "NamedExtractor", ")", "{", "NamedExtractor", "namedExtractor", "=", "(", "NamedExtractor", ")", "extractor", ";", "namedParameters", ".", "add", "(", "namedExtractor", ".", "getName", "(", ")", ")", ";", "}", "}", "// validate the url specification and method signature agree on required parameters", "List", "<", "String", ">", "requiredParameters", "=", "getParameterNames", "(", "uriPattern", ")", ";", "if", "(", "!", "namedParameters", ".", "containsAll", "(", "requiredParameters", ")", ")", "{", "throw", "new", "FatalException", "(", "\"Controller method '{}' declares parameters {} but the URL specification requires {}\"", ",", "Util", ".", "toString", "(", "method", ")", ",", "namedParameters", ",", "requiredParameters", ")", ";", "}", "}" ]
Validate that the parameters specified in the uri pattern are declared in the method signature. @param uriPattern @throws FatalException if the controller method does not declare all named uri parameters
[ "Validate", "that", "the", "parameters", "specified", "in", "the", "uri", "pattern", "are", "declared", "in", "the", "method", "signature", "." ]
f2f820eb16e9fea1e36ad4eda4ed51b35f056538
https://github.com/gitblit/fathom/blob/f2f820eb16e9fea1e36ad4eda4ed51b35f056538/fathom-rest/src/main/java/fathom/rest/controller/ControllerHandler.java#L402-L417
10,587
gitblit/fathom
fathom-rest/src/main/java/fathom/rest/controller/ControllerHandler.java
ControllerHandler.validateConsumes
protected void validateConsumes(Collection<String> fathomContentTypes) { Set<String> ignoreConsumes = new TreeSet<>(); ignoreConsumes.add(Consumes.ALL); // these are handled by the TemplateEngine ignoreConsumes.add(Consumes.HTML); ignoreConsumes.add(Consumes.XHTML); // these are handled by the Servlet layer ignoreConsumes.add(Consumes.FORM); ignoreConsumes.add(Consumes.MULTIPART); for (String declaredConsume : declaredConsumes) { if (ignoreConsumes.contains(declaredConsume)) { continue; } String consume = declaredConsume; int fuzz = consume.indexOf('*'); if (fuzz > -1) { // strip fuzz, we must have a registered engine for the unfuzzed content-type consume = consume.substring(0, fuzz); } if (!fathomContentTypes.contains(consume)) { if (consume.equals(declaredConsume)) { throw new FatalException("{} declares @{}(\"{}\") but there is no registered ContentTypeEngine for that type!", Util.toString(method), Consumes.class.getSimpleName(), declaredConsume); } else { throw new FatalException("{} declares @{}(\"{}\") but there is no registered ContentTypeEngine for \"{}\"!", Util.toString(method), Consumes.class.getSimpleName(), declaredConsume, consume); } } } }
java
protected void validateConsumes(Collection<String> fathomContentTypes) { Set<String> ignoreConsumes = new TreeSet<>(); ignoreConsumes.add(Consumes.ALL); // these are handled by the TemplateEngine ignoreConsumes.add(Consumes.HTML); ignoreConsumes.add(Consumes.XHTML); // these are handled by the Servlet layer ignoreConsumes.add(Consumes.FORM); ignoreConsumes.add(Consumes.MULTIPART); for (String declaredConsume : declaredConsumes) { if (ignoreConsumes.contains(declaredConsume)) { continue; } String consume = declaredConsume; int fuzz = consume.indexOf('*'); if (fuzz > -1) { // strip fuzz, we must have a registered engine for the unfuzzed content-type consume = consume.substring(0, fuzz); } if (!fathomContentTypes.contains(consume)) { if (consume.equals(declaredConsume)) { throw new FatalException("{} declares @{}(\"{}\") but there is no registered ContentTypeEngine for that type!", Util.toString(method), Consumes.class.getSimpleName(), declaredConsume); } else { throw new FatalException("{} declares @{}(\"{}\") but there is no registered ContentTypeEngine for \"{}\"!", Util.toString(method), Consumes.class.getSimpleName(), declaredConsume, consume); } } } }
[ "protected", "void", "validateConsumes", "(", "Collection", "<", "String", ">", "fathomContentTypes", ")", "{", "Set", "<", "String", ">", "ignoreConsumes", "=", "new", "TreeSet", "<>", "(", ")", ";", "ignoreConsumes", ".", "add", "(", "Consumes", ".", "ALL", ")", ";", "// these are handled by the TemplateEngine", "ignoreConsumes", ".", "add", "(", "Consumes", ".", "HTML", ")", ";", "ignoreConsumes", ".", "add", "(", "Consumes", ".", "XHTML", ")", ";", "// these are handled by the Servlet layer", "ignoreConsumes", ".", "add", "(", "Consumes", ".", "FORM", ")", ";", "ignoreConsumes", ".", "add", "(", "Consumes", ".", "MULTIPART", ")", ";", "for", "(", "String", "declaredConsume", ":", "declaredConsumes", ")", "{", "if", "(", "ignoreConsumes", ".", "contains", "(", "declaredConsume", ")", ")", "{", "continue", ";", "}", "String", "consume", "=", "declaredConsume", ";", "int", "fuzz", "=", "consume", ".", "indexOf", "(", "'", "'", ")", ";", "if", "(", "fuzz", ">", "-", "1", ")", "{", "// strip fuzz, we must have a registered engine for the unfuzzed content-type", "consume", "=", "consume", ".", "substring", "(", "0", ",", "fuzz", ")", ";", "}", "if", "(", "!", "fathomContentTypes", ".", "contains", "(", "consume", ")", ")", "{", "if", "(", "consume", ".", "equals", "(", "declaredConsume", ")", ")", "{", "throw", "new", "FatalException", "(", "\"{} declares @{}(\\\"{}\\\") but there is no registered ContentTypeEngine for that type!\"", ",", "Util", ".", "toString", "(", "method", ")", ",", "Consumes", ".", "class", ".", "getSimpleName", "(", ")", ",", "declaredConsume", ")", ";", "}", "else", "{", "throw", "new", "FatalException", "(", "\"{} declares @{}(\\\"{}\\\") but there is no registered ContentTypeEngine for \\\"{}\\\"!\"", ",", "Util", ".", "toString", "(", "method", ")", ",", "Consumes", ".", "class", ".", "getSimpleName", "(", ")", ",", "declaredConsume", ",", "consume", ")", ";", "}", "}", "}", "}" ]
Validates that the declared consumes can actually be processed by Fathom. @param fathomContentTypes
[ "Validates", "that", "the", "declared", "consumes", "can", "actually", "be", "processed", "by", "Fathom", "." ]
f2f820eb16e9fea1e36ad4eda4ed51b35f056538
https://github.com/gitblit/fathom/blob/f2f820eb16e9fea1e36ad4eda4ed51b35f056538/fathom-rest/src/main/java/fathom/rest/controller/ControllerHandler.java#L448-L482
10,588
gitblit/fathom
fathom-rest/src/main/java/fathom/rest/controller/ControllerHandler.java
ControllerHandler.validateProduces
protected void validateProduces(Collection<String> fathomContentTypes) { Set<String> ignoreProduces = new TreeSet<>(); ignoreProduces.add(Produces.TEXT); ignoreProduces.add(Produces.HTML); ignoreProduces.add(Produces.XHTML); for (String produces : declaredProduces) { if (ignoreProduces.contains(produces)) { continue; } if (!fathomContentTypes.contains(produces)) { throw new FatalException("{} declares @{}(\"{}\") but there is no registered ContentTypeEngine for that type!", Util.toString(method), Produces.class.getSimpleName(), produces); } } }
java
protected void validateProduces(Collection<String> fathomContentTypes) { Set<String> ignoreProduces = new TreeSet<>(); ignoreProduces.add(Produces.TEXT); ignoreProduces.add(Produces.HTML); ignoreProduces.add(Produces.XHTML); for (String produces : declaredProduces) { if (ignoreProduces.contains(produces)) { continue; } if (!fathomContentTypes.contains(produces)) { throw new FatalException("{} declares @{}(\"{}\") but there is no registered ContentTypeEngine for that type!", Util.toString(method), Produces.class.getSimpleName(), produces); } } }
[ "protected", "void", "validateProduces", "(", "Collection", "<", "String", ">", "fathomContentTypes", ")", "{", "Set", "<", "String", ">", "ignoreProduces", "=", "new", "TreeSet", "<>", "(", ")", ";", "ignoreProduces", ".", "add", "(", "Produces", ".", "TEXT", ")", ";", "ignoreProduces", ".", "add", "(", "Produces", ".", "HTML", ")", ";", "ignoreProduces", ".", "add", "(", "Produces", ".", "XHTML", ")", ";", "for", "(", "String", "produces", ":", "declaredProduces", ")", "{", "if", "(", "ignoreProduces", ".", "contains", "(", "produces", ")", ")", "{", "continue", ";", "}", "if", "(", "!", "fathomContentTypes", ".", "contains", "(", "produces", ")", ")", "{", "throw", "new", "FatalException", "(", "\"{} declares @{}(\\\"{}\\\") but there is no registered ContentTypeEngine for that type!\"", ",", "Util", ".", "toString", "(", "method", ")", ",", "Produces", ".", "class", ".", "getSimpleName", "(", ")", ",", "produces", ")", ";", "}", "}", "}" ]
Validates that the declared content-types can actually be generated by Fathom. @param fathomContentTypes
[ "Validates", "that", "the", "declared", "content", "-", "types", "can", "actually", "be", "generated", "by", "Fathom", "." ]
f2f820eb16e9fea1e36ad4eda4ed51b35f056538
https://github.com/gitblit/fathom/blob/f2f820eb16e9fea1e36ad4eda4ed51b35f056538/fathom-rest/src/main/java/fathom/rest/controller/ControllerHandler.java#L489-L505
10,589
gitblit/fathom
fathom-rest/src/main/java/fathom/rest/controller/ControllerHandler.java
ControllerHandler.validateDeclaredReturns
protected void validateDeclaredReturns() { boolean returnsObject = void.class != method.getReturnType(); if (returnsObject) { for (Return declaredReturn : declaredReturns) { if (declaredReturn.code() >= 200 && declaredReturn.code() < 300) { return; } } throw new FatalException("{} returns an object but does not declare a successful @{}(code=200, onResult={}.class)", Util.toString(method), Return.class.getSimpleName(), method.getReturnType().getSimpleName()); } }
java
protected void validateDeclaredReturns() { boolean returnsObject = void.class != method.getReturnType(); if (returnsObject) { for (Return declaredReturn : declaredReturns) { if (declaredReturn.code() >= 200 && declaredReturn.code() < 300) { return; } } throw new FatalException("{} returns an object but does not declare a successful @{}(code=200, onResult={}.class)", Util.toString(method), Return.class.getSimpleName(), method.getReturnType().getSimpleName()); } }
[ "protected", "void", "validateDeclaredReturns", "(", ")", "{", "boolean", "returnsObject", "=", "void", ".", "class", "!=", "method", ".", "getReturnType", "(", ")", ";", "if", "(", "returnsObject", ")", "{", "for", "(", "Return", "declaredReturn", ":", "declaredReturns", ")", "{", "if", "(", "declaredReturn", ".", "code", "(", ")", ">=", "200", "&&", "declaredReturn", ".", "code", "(", ")", "<", "300", ")", "{", "return", ";", "}", "}", "throw", "new", "FatalException", "(", "\"{} returns an object but does not declare a successful @{}(code=200, onResult={}.class)\"", ",", "Util", ".", "toString", "(", "method", ")", ",", "Return", ".", "class", ".", "getSimpleName", "(", ")", ",", "method", ".", "getReturnType", "(", ")", ".", "getSimpleName", "(", ")", ")", ";", "}", "}" ]
Validates the declared Returns of the controller method. If the controller method returns an object then it must also declare a successful @Return with a status code in the 200 range.
[ "Validates", "the", "declared", "Returns", "of", "the", "controller", "method", ".", "If", "the", "controller", "method", "returns", "an", "object", "then", "it", "must", "also", "declare", "a", "successful" ]
f2f820eb16e9fea1e36ad4eda4ed51b35f056538
https://github.com/gitblit/fathom/blob/f2f820eb16e9fea1e36ad4eda4ed51b35f056538/fathom-rest/src/main/java/fathom/rest/controller/ControllerHandler.java#L512-L523
10,590
gitblit/fathom
fathom-core/src/main/java/fathom/Constants.java
Constants.getVersion
public static String getVersion() { String FATHOM_PROPERTIES = "fathom/version.properties"; String version = null; URL url = ClassUtil.getResource(FATHOM_PROPERTIES); Preconditions.checkNotNull(url, "Failed to find " + FATHOM_PROPERTIES); try (InputStream stream = url.openStream()) { Properties prop = new Properties(); prop.load(stream); version = prop.getProperty("version"); } catch (IOException e) { LoggerFactory.getLogger(Constants.class).error("Failed to read '{}'", FATHOM_PROPERTIES, e); } Preconditions.checkNotNull(version, "The Fathom version is null!"); return version; }
java
public static String getVersion() { String FATHOM_PROPERTIES = "fathom/version.properties"; String version = null; URL url = ClassUtil.getResource(FATHOM_PROPERTIES); Preconditions.checkNotNull(url, "Failed to find " + FATHOM_PROPERTIES); try (InputStream stream = url.openStream()) { Properties prop = new Properties(); prop.load(stream); version = prop.getProperty("version"); } catch (IOException e) { LoggerFactory.getLogger(Constants.class).error("Failed to read '{}'", FATHOM_PROPERTIES, e); } Preconditions.checkNotNull(version, "The Fathom version is null!"); return version; }
[ "public", "static", "String", "getVersion", "(", ")", "{", "String", "FATHOM_PROPERTIES", "=", "\"fathom/version.properties\"", ";", "String", "version", "=", "null", ";", "URL", "url", "=", "ClassUtil", ".", "getResource", "(", "FATHOM_PROPERTIES", ")", ";", "Preconditions", ".", "checkNotNull", "(", "url", ",", "\"Failed to find \"", "+", "FATHOM_PROPERTIES", ")", ";", "try", "(", "InputStream", "stream", "=", "url", ".", "openStream", "(", ")", ")", "{", "Properties", "prop", "=", "new", "Properties", "(", ")", ";", "prop", ".", "load", "(", "stream", ")", ";", "version", "=", "prop", ".", "getProperty", "(", "\"version\"", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "LoggerFactory", ".", "getLogger", "(", "Constants", ".", "class", ")", ".", "error", "(", "\"Failed to read '{}'\"", ",", "FATHOM_PROPERTIES", ",", "e", ")", ";", "}", "Preconditions", ".", "checkNotNull", "(", "version", ",", "\"The Fathom version is null!\"", ")", ";", "return", "version", ";", "}" ]
Returns the running Fathom version. @return the running Fathom version
[ "Returns", "the", "running", "Fathom", "version", "." ]
f2f820eb16e9fea1e36ad4eda4ed51b35f056538
https://github.com/gitblit/fathom/blob/f2f820eb16e9fea1e36ad4eda4ed51b35f056538/fathom-core/src/main/java/fathom/Constants.java#L78-L99
10,591
gitblit/fathom
fathom-security/src/main/java/fathom/security/SecurityManager.java
SecurityManager.clearCache
public void clearCache() { if (accountCache != null) { accountCache.invalidateAll(); } for (Realm realm : allRealms) { if (realm instanceof CachingRealm) { CachingRealm cachingRealm = (CachingRealm) realm; cachingRealm.clearCache(); } } }
java
public void clearCache() { if (accountCache != null) { accountCache.invalidateAll(); } for (Realm realm : allRealms) { if (realm instanceof CachingRealm) { CachingRealm cachingRealm = (CachingRealm) realm; cachingRealm.clearCache(); } } }
[ "public", "void", "clearCache", "(", ")", "{", "if", "(", "accountCache", "!=", "null", ")", "{", "accountCache", ".", "invalidateAll", "(", ")", ";", "}", "for", "(", "Realm", "realm", ":", "allRealms", ")", "{", "if", "(", "realm", "instanceof", "CachingRealm", ")", "{", "CachingRealm", "cachingRealm", "=", "(", "CachingRealm", ")", "realm", ";", "cachingRealm", ".", "clearCache", "(", ")", ";", "}", "}", "}" ]
Clears the SecurityManager account cache and any CachingRealm's cache. MemoryRealms are not affected by this call.
[ "Clears", "the", "SecurityManager", "account", "cache", "and", "any", "CachingRealm", "s", "cache", ".", "MemoryRealms", "are", "not", "affected", "by", "this", "call", "." ]
f2f820eb16e9fea1e36ad4eda4ed51b35f056538
https://github.com/gitblit/fathom/blob/f2f820eb16e9fea1e36ad4eda4ed51b35f056538/fathom-security/src/main/java/fathom/security/SecurityManager.java#L228-L238
10,592
gitblit/fathom
fathom-security/src/main/java/fathom/security/SecurityManager.java
SecurityManager.parseDefinedRealms
protected Collection<Realm> parseDefinedRealms(Config config) { List<Realm> realms = new ArrayList<>(); // Parse the Realms if (config.hasPath("realms")) { log.trace("Parsing Realm definitions"); for (Config realmConfig : config.getConfigList("realms")) { // define the realm name and type String realmType = Strings.emptyToNull(realmConfig.getString("type")); Preconditions.checkNotNull(realmType, "Realm 'type' is null!"); if (ClassUtil.doesClassExist(realmType)) { Class<? extends Realm> realmClass = ClassUtil.getClass(realmType); if (RequireUtil.allowClass(settings, realmClass)) { try { Realm realm = injector.getInstance(realmClass); realm.setup(realmConfig); realms.add(realm); log.debug("Created '{}' named '{}'", realmType, realm.getRealmName()); } catch (Exception e) { log.error("Failed to create '{}' realm", realmType, e); } } } else { throw new FathomException("Unknown realm type '{}'!", realmType); } } } return Collections.unmodifiableList(realms); }
java
protected Collection<Realm> parseDefinedRealms(Config config) { List<Realm> realms = new ArrayList<>(); // Parse the Realms if (config.hasPath("realms")) { log.trace("Parsing Realm definitions"); for (Config realmConfig : config.getConfigList("realms")) { // define the realm name and type String realmType = Strings.emptyToNull(realmConfig.getString("type")); Preconditions.checkNotNull(realmType, "Realm 'type' is null!"); if (ClassUtil.doesClassExist(realmType)) { Class<? extends Realm> realmClass = ClassUtil.getClass(realmType); if (RequireUtil.allowClass(settings, realmClass)) { try { Realm realm = injector.getInstance(realmClass); realm.setup(realmConfig); realms.add(realm); log.debug("Created '{}' named '{}'", realmType, realm.getRealmName()); } catch (Exception e) { log.error("Failed to create '{}' realm", realmType, e); } } } else { throw new FathomException("Unknown realm type '{}'!", realmType); } } } return Collections.unmodifiableList(realms); }
[ "protected", "Collection", "<", "Realm", ">", "parseDefinedRealms", "(", "Config", "config", ")", "{", "List", "<", "Realm", ">", "realms", "=", "new", "ArrayList", "<>", "(", ")", ";", "// Parse the Realms", "if", "(", "config", ".", "hasPath", "(", "\"realms\"", ")", ")", "{", "log", ".", "trace", "(", "\"Parsing Realm definitions\"", ")", ";", "for", "(", "Config", "realmConfig", ":", "config", ".", "getConfigList", "(", "\"realms\"", ")", ")", "{", "// define the realm name and type", "String", "realmType", "=", "Strings", ".", "emptyToNull", "(", "realmConfig", ".", "getString", "(", "\"type\"", ")", ")", ";", "Preconditions", ".", "checkNotNull", "(", "realmType", ",", "\"Realm 'type' is null!\"", ")", ";", "if", "(", "ClassUtil", ".", "doesClassExist", "(", "realmType", ")", ")", "{", "Class", "<", "?", "extends", "Realm", ">", "realmClass", "=", "ClassUtil", ".", "getClass", "(", "realmType", ")", ";", "if", "(", "RequireUtil", ".", "allowClass", "(", "settings", ",", "realmClass", ")", ")", "{", "try", "{", "Realm", "realm", "=", "injector", ".", "getInstance", "(", "realmClass", ")", ";", "realm", ".", "setup", "(", "realmConfig", ")", ";", "realms", ".", "add", "(", "realm", ")", ";", "log", ".", "debug", "(", "\"Created '{}' named '{}'\"", ",", "realmType", ",", "realm", ".", "getRealmName", "(", ")", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "log", ".", "error", "(", "\"Failed to create '{}' realm\"", ",", "realmType", ",", "e", ")", ";", "}", "}", "}", "else", "{", "throw", "new", "FathomException", "(", "\"Unknown realm type '{}'!\"", ",", "realmType", ")", ";", "}", "}", "}", "return", "Collections", ".", "unmodifiableList", "(", "realms", ")", ";", "}" ]
Parse the Realms from the Config object. @param config @return an ordered collection of Realms
[ "Parse", "the", "Realms", "from", "the", "Config", "object", "." ]
f2f820eb16e9fea1e36ad4eda4ed51b35f056538
https://github.com/gitblit/fathom/blob/f2f820eb16e9fea1e36ad4eda4ed51b35f056538/fathom-security/src/main/java/fathom/security/SecurityManager.java#L256-L288
10,593
gitblit/fathom
fathom-rest-swagger/src/main/java/fathom/rest/swagger/SwaggerBuilder.java
SwaggerBuilder.generateJSON
public String generateJSON(Collection<Route> routes) { Swagger swagger = build(routes); String json = Json.pretty(swagger); return json; }
java
public String generateJSON(Collection<Route> routes) { Swagger swagger = build(routes); String json = Json.pretty(swagger); return json; }
[ "public", "String", "generateJSON", "(", "Collection", "<", "Route", ">", "routes", ")", "{", "Swagger", "swagger", "=", "build", "(", "routes", ")", ";", "String", "json", "=", "Json", ".", "pretty", "(", "swagger", ")", ";", "return", "json", ";", "}" ]
Generates a Swagger 2.0 JSON specification from the collection of routes. @param routes @return a Swagger 2.0 JSON specification
[ "Generates", "a", "Swagger", "2", ".", "0", "JSON", "specification", "from", "the", "collection", "of", "routes", "." ]
f2f820eb16e9fea1e36ad4eda4ed51b35f056538
https://github.com/gitblit/fathom/blob/f2f820eb16e9fea1e36ad4eda4ed51b35f056538/fathom-rest-swagger/src/main/java/fathom/rest/swagger/SwaggerBuilder.java#L164-L168
10,594
gitblit/fathom
fathom-rest-swagger/src/main/java/fathom/rest/swagger/SwaggerBuilder.java
SwaggerBuilder.canRegister
protected boolean canRegister(Route route, ControllerHandler handler) { if (!METHODS.contains(route.getRequestMethod().toUpperCase())) { log.debug("Skip {} {}, {} Swagger does not support specified HTTP method", route.getRequestMethod(), route.getUriPattern(), Util.toString(handler.getControllerMethod())); return false; } List<String> produces = handler.getDeclaredProduces(); if (produces.isEmpty()) { log.debug("Skip {} {}, {} does not declare @Produces", route.getRequestMethod(), route.getUriPattern(), Util.toString(handler.getControllerMethod())); return false; } if (handler.getDeclaredReturns().isEmpty()) { log.debug("Skip {} {}, {} does not declare expected @Returns", route.getRequestMethod(), route.getUriPattern(), Util.toString(handler.getControllerMethod())); return false; } if (handler.getControllerMethod().isAnnotationPresent(Undocumented.class) || handler.getControllerMethod().getDeclaringClass().isAnnotationPresent(Undocumented.class)) { log.debug("Skip {} {}, {} is annotated as @Undocumented", route.getRequestMethod(), route.getUriPattern(), Util.toString(handler.getControllerMethod())); return false; } if (!route.getUriPattern().startsWith(relativeSwaggerBasePath)) { log.debug("Skip {} {}, {} route is not within Swagger basePath '{}'", route.getRequestMethod(), route.getUriPattern(), Util.toString(handler.getControllerMethod()), relativeSwaggerBasePath); return false; } return true; }
java
protected boolean canRegister(Route route, ControllerHandler handler) { if (!METHODS.contains(route.getRequestMethod().toUpperCase())) { log.debug("Skip {} {}, {} Swagger does not support specified HTTP method", route.getRequestMethod(), route.getUriPattern(), Util.toString(handler.getControllerMethod())); return false; } List<String> produces = handler.getDeclaredProduces(); if (produces.isEmpty()) { log.debug("Skip {} {}, {} does not declare @Produces", route.getRequestMethod(), route.getUriPattern(), Util.toString(handler.getControllerMethod())); return false; } if (handler.getDeclaredReturns().isEmpty()) { log.debug("Skip {} {}, {} does not declare expected @Returns", route.getRequestMethod(), route.getUriPattern(), Util.toString(handler.getControllerMethod())); return false; } if (handler.getControllerMethod().isAnnotationPresent(Undocumented.class) || handler.getControllerMethod().getDeclaringClass().isAnnotationPresent(Undocumented.class)) { log.debug("Skip {} {}, {} is annotated as @Undocumented", route.getRequestMethod(), route.getUriPattern(), Util.toString(handler.getControllerMethod())); return false; } if (!route.getUriPattern().startsWith(relativeSwaggerBasePath)) { log.debug("Skip {} {}, {} route is not within Swagger basePath '{}'", route.getRequestMethod(), route.getUriPattern(), Util.toString(handler.getControllerMethod()), relativeSwaggerBasePath); return false; } return true; }
[ "protected", "boolean", "canRegister", "(", "Route", "route", ",", "ControllerHandler", "handler", ")", "{", "if", "(", "!", "METHODS", ".", "contains", "(", "route", ".", "getRequestMethod", "(", ")", ".", "toUpperCase", "(", ")", ")", ")", "{", "log", ".", "debug", "(", "\"Skip {} {}, {} Swagger does not support specified HTTP method\"", ",", "route", ".", "getRequestMethod", "(", ")", ",", "route", ".", "getUriPattern", "(", ")", ",", "Util", ".", "toString", "(", "handler", ".", "getControllerMethod", "(", ")", ")", ")", ";", "return", "false", ";", "}", "List", "<", "String", ">", "produces", "=", "handler", ".", "getDeclaredProduces", "(", ")", ";", "if", "(", "produces", ".", "isEmpty", "(", ")", ")", "{", "log", ".", "debug", "(", "\"Skip {} {}, {} does not declare @Produces\"", ",", "route", ".", "getRequestMethod", "(", ")", ",", "route", ".", "getUriPattern", "(", ")", ",", "Util", ".", "toString", "(", "handler", ".", "getControllerMethod", "(", ")", ")", ")", ";", "return", "false", ";", "}", "if", "(", "handler", ".", "getDeclaredReturns", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "log", ".", "debug", "(", "\"Skip {} {}, {} does not declare expected @Returns\"", ",", "route", ".", "getRequestMethod", "(", ")", ",", "route", ".", "getUriPattern", "(", ")", ",", "Util", ".", "toString", "(", "handler", ".", "getControllerMethod", "(", ")", ")", ")", ";", "return", "false", ";", "}", "if", "(", "handler", ".", "getControllerMethod", "(", ")", ".", "isAnnotationPresent", "(", "Undocumented", ".", "class", ")", "||", "handler", ".", "getControllerMethod", "(", ")", ".", "getDeclaringClass", "(", ")", ".", "isAnnotationPresent", "(", "Undocumented", ".", "class", ")", ")", "{", "log", ".", "debug", "(", "\"Skip {} {}, {} is annotated as @Undocumented\"", ",", "route", ".", "getRequestMethod", "(", ")", ",", "route", ".", "getUriPattern", "(", ")", ",", "Util", ".", "toString", "(", "handler", ".", "getControllerMethod", "(", ")", ")", ")", ";", "return", "false", ";", "}", "if", "(", "!", "route", ".", "getUriPattern", "(", ")", ".", "startsWith", "(", "relativeSwaggerBasePath", ")", ")", "{", "log", ".", "debug", "(", "\"Skip {} {}, {} route is not within Swagger basePath '{}'\"", ",", "route", ".", "getRequestMethod", "(", ")", ",", "route", ".", "getUriPattern", "(", ")", ",", "Util", ".", "toString", "(", "handler", ".", "getControllerMethod", "(", ")", ")", ",", "relativeSwaggerBasePath", ")", ";", "return", "false", ";", "}", "return", "true", ";", "}" ]
Determines if this controller handler can be registered in the Swagger specification. @param route @param handler @return true if the controller handler can be registered in the Swagger specification
[ "Determines", "if", "this", "controller", "handler", "can", "be", "registered", "in", "the", "Swagger", "specification", "." ]
f2f820eb16e9fea1e36ad4eda4ed51b35f056538
https://github.com/gitblit/fathom/blob/f2f820eb16e9fea1e36ad4eda4ed51b35f056538/fathom-rest-swagger/src/main/java/fathom/rest/swagger/SwaggerBuilder.java#L273-L309
10,595
gitblit/fathom
fathom-rest-swagger/src/main/java/fathom/rest/swagger/SwaggerBuilder.java
SwaggerBuilder.registerResponses
protected void registerResponses(Swagger swagger, Operation operation, Method method) { for (Return aReturn : ControllerUtil.getReturns(method)) { registerResponse(swagger, operation, aReturn); } }
java
protected void registerResponses(Swagger swagger, Operation operation, Method method) { for (Return aReturn : ControllerUtil.getReturns(method)) { registerResponse(swagger, operation, aReturn); } }
[ "protected", "void", "registerResponses", "(", "Swagger", "swagger", ",", "Operation", "operation", ",", "Method", "method", ")", "{", "for", "(", "Return", "aReturn", ":", "ControllerUtil", ".", "getReturns", "(", "method", ")", ")", "{", "registerResponse", "(", "swagger", ",", "operation", ",", "aReturn", ")", ";", "}", "}" ]
Registers the declared responses for the operation. @param swagger @param operation @param method
[ "Registers", "the", "declared", "responses", "for", "the", "operation", "." ]
f2f820eb16e9fea1e36ad4eda4ed51b35f056538
https://github.com/gitblit/fathom/blob/f2f820eb16e9fea1e36ad4eda4ed51b35f056538/fathom-rest-swagger/src/main/java/fathom/rest/swagger/SwaggerBuilder.java#L446-L450
10,596
gitblit/fathom
fathom-rest-swagger/src/main/java/fathom/rest/swagger/SwaggerBuilder.java
SwaggerBuilder.registerResponse
protected void registerResponse(Swagger swagger, Operation operation, Return aReturn) { Response response = new Response(); response.setDescription(translate(aReturn.descriptionKey(), aReturn.description())); Class<?> resultType = aReturn.onResult(); if (Exception.class.isAssignableFrom(resultType)) { Property errorProperty = registerErrorModel(swagger); response.setSchema(errorProperty); } else if (Void.class != resultType) { // Return type if (resultType.isArray()) { // ARRAY[] Class<?> componentClass = resultType.getComponentType(); ArrayProperty arrayProperty = new ArrayProperty(); Property componentProperty = getSwaggerProperty(swagger, componentClass); arrayProperty.setItems(componentProperty); response.setSchema(arrayProperty); } else { // Object Property returnProperty = getSwaggerProperty(swagger, resultType); response.setSchema(returnProperty); } } for (Class<? extends ReturnHeader> returnHeader : aReturn.headers()) { Tag headerTag = getModelTag(returnHeader); ReturnHeader header = ClassUtil.newInstance(returnHeader); Property property = getSwaggerProperty(swagger, header.getHeaderType()); if (property instanceof ArrayProperty) { // FIXME swagger-core has incomplete response header specification methods :( ArrayProperty arrayProperty = (ArrayProperty) property; } property.setName(headerTag.getName()); property.setDescription(headerTag.getDescription()); response.addHeader(property.getName(), property); } operation.response(aReturn.code(), response); }
java
protected void registerResponse(Swagger swagger, Operation operation, Return aReturn) { Response response = new Response(); response.setDescription(translate(aReturn.descriptionKey(), aReturn.description())); Class<?> resultType = aReturn.onResult(); if (Exception.class.isAssignableFrom(resultType)) { Property errorProperty = registerErrorModel(swagger); response.setSchema(errorProperty); } else if (Void.class != resultType) { // Return type if (resultType.isArray()) { // ARRAY[] Class<?> componentClass = resultType.getComponentType(); ArrayProperty arrayProperty = new ArrayProperty(); Property componentProperty = getSwaggerProperty(swagger, componentClass); arrayProperty.setItems(componentProperty); response.setSchema(arrayProperty); } else { // Object Property returnProperty = getSwaggerProperty(swagger, resultType); response.setSchema(returnProperty); } } for (Class<? extends ReturnHeader> returnHeader : aReturn.headers()) { Tag headerTag = getModelTag(returnHeader); ReturnHeader header = ClassUtil.newInstance(returnHeader); Property property = getSwaggerProperty(swagger, header.getHeaderType()); if (property instanceof ArrayProperty) { // FIXME swagger-core has incomplete response header specification methods :( ArrayProperty arrayProperty = (ArrayProperty) property; } property.setName(headerTag.getName()); property.setDescription(headerTag.getDescription()); response.addHeader(property.getName(), property); } operation.response(aReturn.code(), response); }
[ "protected", "void", "registerResponse", "(", "Swagger", "swagger", ",", "Operation", "operation", ",", "Return", "aReturn", ")", "{", "Response", "response", "=", "new", "Response", "(", ")", ";", "response", ".", "setDescription", "(", "translate", "(", "aReturn", ".", "descriptionKey", "(", ")", ",", "aReturn", ".", "description", "(", ")", ")", ")", ";", "Class", "<", "?", ">", "resultType", "=", "aReturn", ".", "onResult", "(", ")", ";", "if", "(", "Exception", ".", "class", ".", "isAssignableFrom", "(", "resultType", ")", ")", "{", "Property", "errorProperty", "=", "registerErrorModel", "(", "swagger", ")", ";", "response", ".", "setSchema", "(", "errorProperty", ")", ";", "}", "else", "if", "(", "Void", ".", "class", "!=", "resultType", ")", "{", "// Return type", "if", "(", "resultType", ".", "isArray", "(", ")", ")", "{", "// ARRAY[]", "Class", "<", "?", ">", "componentClass", "=", "resultType", ".", "getComponentType", "(", ")", ";", "ArrayProperty", "arrayProperty", "=", "new", "ArrayProperty", "(", ")", ";", "Property", "componentProperty", "=", "getSwaggerProperty", "(", "swagger", ",", "componentClass", ")", ";", "arrayProperty", ".", "setItems", "(", "componentProperty", ")", ";", "response", ".", "setSchema", "(", "arrayProperty", ")", ";", "}", "else", "{", "// Object", "Property", "returnProperty", "=", "getSwaggerProperty", "(", "swagger", ",", "resultType", ")", ";", "response", ".", "setSchema", "(", "returnProperty", ")", ";", "}", "}", "for", "(", "Class", "<", "?", "extends", "ReturnHeader", ">", "returnHeader", ":", "aReturn", ".", "headers", "(", ")", ")", "{", "Tag", "headerTag", "=", "getModelTag", "(", "returnHeader", ")", ";", "ReturnHeader", "header", "=", "ClassUtil", ".", "newInstance", "(", "returnHeader", ")", ";", "Property", "property", "=", "getSwaggerProperty", "(", "swagger", ",", "header", ".", "getHeaderType", "(", ")", ")", ";", "if", "(", "property", "instanceof", "ArrayProperty", ")", "{", "// FIXME swagger-core has incomplete response header specification methods :(", "ArrayProperty", "arrayProperty", "=", "(", "ArrayProperty", ")", "property", ";", "}", "property", ".", "setName", "(", "headerTag", ".", "getName", "(", ")", ")", ";", "property", ".", "setDescription", "(", "headerTag", ".", "getDescription", "(", ")", ")", ";", "response", ".", "addHeader", "(", "property", ".", "getName", "(", ")", ",", "property", ")", ";", "}", "operation", ".", "response", "(", "aReturn", ".", "code", "(", ")", ",", "response", ")", ";", "}" ]
Registers a declared response for the operation. @param swagger @param operation @param aReturn
[ "Registers", "a", "declared", "response", "for", "the", "operation", "." ]
f2f820eb16e9fea1e36ad4eda4ed51b35f056538
https://github.com/gitblit/fathom/blob/f2f820eb16e9fea1e36ad4eda4ed51b35f056538/fathom-rest-swagger/src/main/java/fathom/rest/swagger/SwaggerBuilder.java#L459-L497
10,597
gitblit/fathom
fathom-rest-swagger/src/main/java/fathom/rest/swagger/SwaggerBuilder.java
SwaggerBuilder.registerErrorModel
protected RefProperty registerErrorModel(Swagger swagger) { String ref = Error.class.getSimpleName(); if (swagger.getDefinitions() != null && swagger.getDefinitions().containsKey(ref)) { // model already registered return new RefProperty(ref); } ModelImpl model = new ModelImpl(); swagger.addDefinition(ref, model); model.setDescription("an error message"); model.addProperty("statusCode", new IntegerProperty().readOnly().description("http status code")); model.addProperty("statusMessage", new StringProperty().readOnly().description("description of the http status code")); model.addProperty("requestMethod", new StringProperty().readOnly().description("http request method")); model.addProperty("requestUri", new StringProperty().readOnly().description("http request path")); model.addProperty("message", new StringProperty().readOnly().description("application message")); if (settings.isDev()) { // in DEV mode the stacktrace is returned in the error message model.addProperty("stacktrace", new StringProperty().readOnly().description("application stacktrace")); } return new RefProperty(ref); }
java
protected RefProperty registerErrorModel(Swagger swagger) { String ref = Error.class.getSimpleName(); if (swagger.getDefinitions() != null && swagger.getDefinitions().containsKey(ref)) { // model already registered return new RefProperty(ref); } ModelImpl model = new ModelImpl(); swagger.addDefinition(ref, model); model.setDescription("an error message"); model.addProperty("statusCode", new IntegerProperty().readOnly().description("http status code")); model.addProperty("statusMessage", new StringProperty().readOnly().description("description of the http status code")); model.addProperty("requestMethod", new StringProperty().readOnly().description("http request method")); model.addProperty("requestUri", new StringProperty().readOnly().description("http request path")); model.addProperty("message", new StringProperty().readOnly().description("application message")); if (settings.isDev()) { // in DEV mode the stacktrace is returned in the error message model.addProperty("stacktrace", new StringProperty().readOnly().description("application stacktrace")); } return new RefProperty(ref); }
[ "protected", "RefProperty", "registerErrorModel", "(", "Swagger", "swagger", ")", "{", "String", "ref", "=", "Error", ".", "class", ".", "getSimpleName", "(", ")", ";", "if", "(", "swagger", ".", "getDefinitions", "(", ")", "!=", "null", "&&", "swagger", ".", "getDefinitions", "(", ")", ".", "containsKey", "(", "ref", ")", ")", "{", "// model already registered", "return", "new", "RefProperty", "(", "ref", ")", ";", "}", "ModelImpl", "model", "=", "new", "ModelImpl", "(", ")", ";", "swagger", ".", "addDefinition", "(", "ref", ",", "model", ")", ";", "model", ".", "setDescription", "(", "\"an error message\"", ")", ";", "model", ".", "addProperty", "(", "\"statusCode\"", ",", "new", "IntegerProperty", "(", ")", ".", "readOnly", "(", ")", ".", "description", "(", "\"http status code\"", ")", ")", ";", "model", ".", "addProperty", "(", "\"statusMessage\"", ",", "new", "StringProperty", "(", ")", ".", "readOnly", "(", ")", ".", "description", "(", "\"description of the http status code\"", ")", ")", ";", "model", ".", "addProperty", "(", "\"requestMethod\"", ",", "new", "StringProperty", "(", ")", ".", "readOnly", "(", ")", ".", "description", "(", "\"http request method\"", ")", ")", ";", "model", ".", "addProperty", "(", "\"requestUri\"", ",", "new", "StringProperty", "(", ")", ".", "readOnly", "(", ")", ".", "description", "(", "\"http request path\"", ")", ")", ";", "model", ".", "addProperty", "(", "\"message\"", ",", "new", "StringProperty", "(", ")", ".", "readOnly", "(", ")", ".", "description", "(", "\"application message\"", ")", ")", ";", "if", "(", "settings", ".", "isDev", "(", ")", ")", "{", "// in DEV mode the stacktrace is returned in the error message", "model", ".", "addProperty", "(", "\"stacktrace\"", ",", "new", "StringProperty", "(", ")", ".", "readOnly", "(", ")", ".", "description", "(", "\"application stacktrace\"", ")", ")", ";", "}", "return", "new", "RefProperty", "(", "ref", ")", ";", "}" ]
Manually register the Pippo Error class as Swagger model. @param swagger @return a ref for the Error model
[ "Manually", "register", "the", "Pippo", "Error", "class", "as", "Swagger", "model", "." ]
f2f820eb16e9fea1e36ad4eda4ed51b35f056538
https://github.com/gitblit/fathom/blob/f2f820eb16e9fea1e36ad4eda4ed51b35f056538/fathom-rest-swagger/src/main/java/fathom/rest/swagger/SwaggerBuilder.java#L597-L621
10,598
gitblit/fathom
fathom-rest-swagger/src/main/java/fathom/rest/swagger/SwaggerBuilder.java
SwaggerBuilder.registerSecurity
protected void registerSecurity(Swagger swagger, Operation operation, Method method) { RequireToken requireToken = ClassUtil.getAnnotation(method, RequireToken.class); if (requireToken != null) { String apiKeyName = requireToken.value(); if (swagger.getSecurityDefinitions() == null || !swagger.getSecurityDefinitions().containsKey(apiKeyName)) { ApiKeyAuthDefinition security = new ApiKeyAuthDefinition(); security.setName(apiKeyName); security.setIn(In.HEADER); security.setType("apiKey"); swagger.addSecurityDefinition(apiKeyName, security); } operation.addSecurity(apiKeyName, Collections.emptyList()); } BasicAuth basicAuth = ClassUtil.getAnnotation(method, BasicAuth.class); if (basicAuth != null) { if (swagger.getSecurityDefinitions() == null || !swagger.getSecurityDefinitions().containsKey("basic")) { BasicAuthDefinition security = new BasicAuthDefinition(); swagger.addSecurityDefinition("basic", security); } operation.addSecurity("basic", Collections.emptyList()); } }
java
protected void registerSecurity(Swagger swagger, Operation operation, Method method) { RequireToken requireToken = ClassUtil.getAnnotation(method, RequireToken.class); if (requireToken != null) { String apiKeyName = requireToken.value(); if (swagger.getSecurityDefinitions() == null || !swagger.getSecurityDefinitions().containsKey(apiKeyName)) { ApiKeyAuthDefinition security = new ApiKeyAuthDefinition(); security.setName(apiKeyName); security.setIn(In.HEADER); security.setType("apiKey"); swagger.addSecurityDefinition(apiKeyName, security); } operation.addSecurity(apiKeyName, Collections.emptyList()); } BasicAuth basicAuth = ClassUtil.getAnnotation(method, BasicAuth.class); if (basicAuth != null) { if (swagger.getSecurityDefinitions() == null || !swagger.getSecurityDefinitions().containsKey("basic")) { BasicAuthDefinition security = new BasicAuthDefinition(); swagger.addSecurityDefinition("basic", security); } operation.addSecurity("basic", Collections.emptyList()); } }
[ "protected", "void", "registerSecurity", "(", "Swagger", "swagger", ",", "Operation", "operation", ",", "Method", "method", ")", "{", "RequireToken", "requireToken", "=", "ClassUtil", ".", "getAnnotation", "(", "method", ",", "RequireToken", ".", "class", ")", ";", "if", "(", "requireToken", "!=", "null", ")", "{", "String", "apiKeyName", "=", "requireToken", ".", "value", "(", ")", ";", "if", "(", "swagger", ".", "getSecurityDefinitions", "(", ")", "==", "null", "||", "!", "swagger", ".", "getSecurityDefinitions", "(", ")", ".", "containsKey", "(", "apiKeyName", ")", ")", "{", "ApiKeyAuthDefinition", "security", "=", "new", "ApiKeyAuthDefinition", "(", ")", ";", "security", ".", "setName", "(", "apiKeyName", ")", ";", "security", ".", "setIn", "(", "In", ".", "HEADER", ")", ";", "security", ".", "setType", "(", "\"apiKey\"", ")", ";", "swagger", ".", "addSecurityDefinition", "(", "apiKeyName", ",", "security", ")", ";", "}", "operation", ".", "addSecurity", "(", "apiKeyName", ",", "Collections", ".", "emptyList", "(", ")", ")", ";", "}", "BasicAuth", "basicAuth", "=", "ClassUtil", ".", "getAnnotation", "(", "method", ",", "BasicAuth", ".", "class", ")", ";", "if", "(", "basicAuth", "!=", "null", ")", "{", "if", "(", "swagger", ".", "getSecurityDefinitions", "(", ")", "==", "null", "||", "!", "swagger", ".", "getSecurityDefinitions", "(", ")", ".", "containsKey", "(", "\"basic\"", ")", ")", "{", "BasicAuthDefinition", "security", "=", "new", "BasicAuthDefinition", "(", ")", ";", "swagger", ".", "addSecurityDefinition", "(", "\"basic\"", ",", "security", ")", ";", "}", "operation", ".", "addSecurity", "(", "\"basic\"", ",", "Collections", ".", "emptyList", "(", ")", ")", ";", "}", "}" ]
Register authentication security. @param swagger @param operation @param method
[ "Register", "authentication", "security", "." ]
f2f820eb16e9fea1e36ad4eda4ed51b35f056538
https://github.com/gitblit/fathom/blob/f2f820eb16e9fea1e36ad4eda4ed51b35f056538/fathom-rest-swagger/src/main/java/fathom/rest/swagger/SwaggerBuilder.java#L630-L654
10,599
gitblit/fathom
fathom-rest-swagger/src/main/java/fathom/rest/swagger/SwaggerBuilder.java
SwaggerBuilder.getSwaggerProperty
protected Property getSwaggerProperty(Swagger swagger, Class<?> objectClass) { Property swaggerProperty = null; if (byte.class == objectClass || Byte.class == objectClass) { // STRING swaggerProperty = new StringProperty("byte"); } else if (char.class == objectClass || Character.class == objectClass) { // CHAR is STRING LEN 1 StringProperty property = new StringProperty(); property.setMaxLength(1); swaggerProperty = property; } else if (short.class == objectClass || Short.class == objectClass) { // SHORT is INTEGER with 16-bit max & min IntegerProperty property = new IntegerProperty(); property.setMinimum(BigDecimal.valueOf(Short.MIN_VALUE)); property.setMaximum(BigDecimal.valueOf(Short.MAX_VALUE)); swaggerProperty = property; } else if (int.class == objectClass || Integer.class == objectClass) { // INTEGER swaggerProperty = new IntegerProperty(); } else if (long.class == objectClass || Long.class == objectClass) { // LONG swaggerProperty = new LongProperty(); } else if (float.class == objectClass || Float.class == objectClass) { // FLOAT swaggerProperty = new FloatProperty(); } else if (double.class == objectClass || Double.class == objectClass) { // DOUBLE swaggerProperty = new DoubleProperty(); } else if (BigDecimal.class == objectClass) { // DECIMAL swaggerProperty = new DecimalProperty(); } else if (boolean.class == objectClass || Boolean.class == objectClass) { // BOOLEAN swaggerProperty = new BooleanProperty(); } else if (String.class == objectClass) { // STRING swaggerProperty = new StringProperty(); } else if (Date.class == objectClass || Timestamp.class == objectClass) { // DATETIME swaggerProperty = new DateTimeProperty(); } else if (java.sql.Date.class == objectClass) { // DATE swaggerProperty = new DateProperty(); } else if (java.sql.Time.class == objectClass) { // TIME -> STRING StringProperty property = new StringProperty(); property.setPattern("HH:mm:ss"); swaggerProperty = property; } else if (UUID.class == objectClass) { // UUID swaggerProperty = new UUIDProperty(); } else if (objectClass.isEnum()) { // ENUM StringProperty property = new StringProperty(); List<String> enumValues = new ArrayList<>(); for (Object enumValue : objectClass.getEnumConstants()) { enumValues.add(((Enum) enumValue).name()); } property.setEnum(enumValues); swaggerProperty = property; } else if (FileItem.class == objectClass) { // FILE UPLOAD swaggerProperty = new FileProperty(); } else { // Register a Model class String modelRef = registerModel(swagger, objectClass); swaggerProperty = new RefProperty(modelRef); } return swaggerProperty; }
java
protected Property getSwaggerProperty(Swagger swagger, Class<?> objectClass) { Property swaggerProperty = null; if (byte.class == objectClass || Byte.class == objectClass) { // STRING swaggerProperty = new StringProperty("byte"); } else if (char.class == objectClass || Character.class == objectClass) { // CHAR is STRING LEN 1 StringProperty property = new StringProperty(); property.setMaxLength(1); swaggerProperty = property; } else if (short.class == objectClass || Short.class == objectClass) { // SHORT is INTEGER with 16-bit max & min IntegerProperty property = new IntegerProperty(); property.setMinimum(BigDecimal.valueOf(Short.MIN_VALUE)); property.setMaximum(BigDecimal.valueOf(Short.MAX_VALUE)); swaggerProperty = property; } else if (int.class == objectClass || Integer.class == objectClass) { // INTEGER swaggerProperty = new IntegerProperty(); } else if (long.class == objectClass || Long.class == objectClass) { // LONG swaggerProperty = new LongProperty(); } else if (float.class == objectClass || Float.class == objectClass) { // FLOAT swaggerProperty = new FloatProperty(); } else if (double.class == objectClass || Double.class == objectClass) { // DOUBLE swaggerProperty = new DoubleProperty(); } else if (BigDecimal.class == objectClass) { // DECIMAL swaggerProperty = new DecimalProperty(); } else if (boolean.class == objectClass || Boolean.class == objectClass) { // BOOLEAN swaggerProperty = new BooleanProperty(); } else if (String.class == objectClass) { // STRING swaggerProperty = new StringProperty(); } else if (Date.class == objectClass || Timestamp.class == objectClass) { // DATETIME swaggerProperty = new DateTimeProperty(); } else if (java.sql.Date.class == objectClass) { // DATE swaggerProperty = new DateProperty(); } else if (java.sql.Time.class == objectClass) { // TIME -> STRING StringProperty property = new StringProperty(); property.setPattern("HH:mm:ss"); swaggerProperty = property; } else if (UUID.class == objectClass) { // UUID swaggerProperty = new UUIDProperty(); } else if (objectClass.isEnum()) { // ENUM StringProperty property = new StringProperty(); List<String> enumValues = new ArrayList<>(); for (Object enumValue : objectClass.getEnumConstants()) { enumValues.add(((Enum) enumValue).name()); } property.setEnum(enumValues); swaggerProperty = property; } else if (FileItem.class == objectClass) { // FILE UPLOAD swaggerProperty = new FileProperty(); } else { // Register a Model class String modelRef = registerModel(swagger, objectClass); swaggerProperty = new RefProperty(modelRef); } return swaggerProperty; }
[ "protected", "Property", "getSwaggerProperty", "(", "Swagger", "swagger", ",", "Class", "<", "?", ">", "objectClass", ")", "{", "Property", "swaggerProperty", "=", "null", ";", "if", "(", "byte", ".", "class", "==", "objectClass", "||", "Byte", ".", "class", "==", "objectClass", ")", "{", "// STRING", "swaggerProperty", "=", "new", "StringProperty", "(", "\"byte\"", ")", ";", "}", "else", "if", "(", "char", ".", "class", "==", "objectClass", "||", "Character", ".", "class", "==", "objectClass", ")", "{", "// CHAR is STRING LEN 1", "StringProperty", "property", "=", "new", "StringProperty", "(", ")", ";", "property", ".", "setMaxLength", "(", "1", ")", ";", "swaggerProperty", "=", "property", ";", "}", "else", "if", "(", "short", ".", "class", "==", "objectClass", "||", "Short", ".", "class", "==", "objectClass", ")", "{", "// SHORT is INTEGER with 16-bit max & min", "IntegerProperty", "property", "=", "new", "IntegerProperty", "(", ")", ";", "property", ".", "setMinimum", "(", "BigDecimal", ".", "valueOf", "(", "Short", ".", "MIN_VALUE", ")", ")", ";", "property", ".", "setMaximum", "(", "BigDecimal", ".", "valueOf", "(", "Short", ".", "MAX_VALUE", ")", ")", ";", "swaggerProperty", "=", "property", ";", "}", "else", "if", "(", "int", ".", "class", "==", "objectClass", "||", "Integer", ".", "class", "==", "objectClass", ")", "{", "// INTEGER", "swaggerProperty", "=", "new", "IntegerProperty", "(", ")", ";", "}", "else", "if", "(", "long", ".", "class", "==", "objectClass", "||", "Long", ".", "class", "==", "objectClass", ")", "{", "// LONG", "swaggerProperty", "=", "new", "LongProperty", "(", ")", ";", "}", "else", "if", "(", "float", ".", "class", "==", "objectClass", "||", "Float", ".", "class", "==", "objectClass", ")", "{", "// FLOAT", "swaggerProperty", "=", "new", "FloatProperty", "(", ")", ";", "}", "else", "if", "(", "double", ".", "class", "==", "objectClass", "||", "Double", ".", "class", "==", "objectClass", ")", "{", "// DOUBLE", "swaggerProperty", "=", "new", "DoubleProperty", "(", ")", ";", "}", "else", "if", "(", "BigDecimal", ".", "class", "==", "objectClass", ")", "{", "// DECIMAL", "swaggerProperty", "=", "new", "DecimalProperty", "(", ")", ";", "}", "else", "if", "(", "boolean", ".", "class", "==", "objectClass", "||", "Boolean", ".", "class", "==", "objectClass", ")", "{", "// BOOLEAN", "swaggerProperty", "=", "new", "BooleanProperty", "(", ")", ";", "}", "else", "if", "(", "String", ".", "class", "==", "objectClass", ")", "{", "// STRING", "swaggerProperty", "=", "new", "StringProperty", "(", ")", ";", "}", "else", "if", "(", "Date", ".", "class", "==", "objectClass", "||", "Timestamp", ".", "class", "==", "objectClass", ")", "{", "// DATETIME", "swaggerProperty", "=", "new", "DateTimeProperty", "(", ")", ";", "}", "else", "if", "(", "java", ".", "sql", ".", "Date", ".", "class", "==", "objectClass", ")", "{", "// DATE", "swaggerProperty", "=", "new", "DateProperty", "(", ")", ";", "}", "else", "if", "(", "java", ".", "sql", ".", "Time", ".", "class", "==", "objectClass", ")", "{", "// TIME -> STRING", "StringProperty", "property", "=", "new", "StringProperty", "(", ")", ";", "property", ".", "setPattern", "(", "\"HH:mm:ss\"", ")", ";", "swaggerProperty", "=", "property", ";", "}", "else", "if", "(", "UUID", ".", "class", "==", "objectClass", ")", "{", "// UUID", "swaggerProperty", "=", "new", "UUIDProperty", "(", ")", ";", "}", "else", "if", "(", "objectClass", ".", "isEnum", "(", ")", ")", "{", "// ENUM", "StringProperty", "property", "=", "new", "StringProperty", "(", ")", ";", "List", "<", "String", ">", "enumValues", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "Object", "enumValue", ":", "objectClass", ".", "getEnumConstants", "(", ")", ")", "{", "enumValues", ".", "add", "(", "(", "(", "Enum", ")", "enumValue", ")", ".", "name", "(", ")", ")", ";", "}", "property", ".", "setEnum", "(", "enumValues", ")", ";", "swaggerProperty", "=", "property", ";", "}", "else", "if", "(", "FileItem", ".", "class", "==", "objectClass", ")", "{", "// FILE UPLOAD", "swaggerProperty", "=", "new", "FileProperty", "(", ")", ";", "}", "else", "{", "// Register a Model class", "String", "modelRef", "=", "registerModel", "(", "swagger", ",", "objectClass", ")", ";", "swaggerProperty", "=", "new", "RefProperty", "(", "modelRef", ")", ";", "}", "return", "swaggerProperty", ";", "}" ]
Returns the appropriate Swagger Property instance for a given object class. @param swagger @param objectClass @return a SwaggerProperty instance
[ "Returns", "the", "appropriate", "Swagger", "Property", "instance", "for", "a", "given", "object", "class", "." ]
f2f820eb16e9fea1e36ad4eda4ed51b35f056538
https://github.com/gitblit/fathom/blob/f2f820eb16e9fea1e36ad4eda4ed51b35f056538/fathom-rest-swagger/src/main/java/fathom/rest/swagger/SwaggerBuilder.java#L869-L938