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
9,300
knowm/Datasets
datasets-common/src/main/java/org/knowm/datasets/common/Joiner.java
Joiner.join
public static String join(String separator, List<String> topicsArray) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < topicsArray.size(); i++) { if (sb.length() > 0) { sb.append(","); } sb.append(topicsArray.get(i)); } return sb.toString(); }
java
public static String join(String separator, List<String> topicsArray) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < topicsArray.size(); i++) { if (sb.length() > 0) { sb.append(","); } sb.append(topicsArray.get(i)); } return sb.toString(); }
[ "public", "static", "String", "join", "(", "String", "separator", ",", "List", "<", "String", ">", "topicsArray", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "topicsArray", ".", "size", "(", ")", ";", "i", "++", ")", "{", "if", "(", "sb", ".", "length", "(", ")", ">", "0", ")", "{", "sb", ".", "append", "(", "\",\"", ")", ";", "}", "sb", ".", "append", "(", "topicsArray", ".", "get", "(", "i", ")", ")", ";", "}", "return", "sb", ".", "toString", "(", ")", ";", "}" ]
Joins a list of Strings @param separator @param topicsArray @return
[ "Joins", "a", "list", "of", "Strings" ]
4ea16ccda1d4190a551accff78bbbe05c9c38c79
https://github.com/knowm/Datasets/blob/4ea16ccda1d4190a551accff78bbbe05c9c38c79/datasets-common/src/main/java/org/knowm/datasets/common/Joiner.java#L51-L62
9,301
termsuite/termsuite-core
src/main/java/fr/univnantes/termsuite/utils/TermUtils.java
TermUtils.getPosition
public static int getPosition(Term subTerm, Term term) { int startingIndex = -1; int j = 0; for(int i=0; i<term.getWords().size(); i++) { if(term.getWords().get(i).equals(subTerm.getWords().get(j))) { j++; if(startingIndex == -1) startingIndex = i; } else { startingIndex = -1; j = 0; } if(j == subTerm.getWords().size()) return startingIndex; } return -1; }
java
public static int getPosition(Term subTerm, Term term) { int startingIndex = -1; int j = 0; for(int i=0; i<term.getWords().size(); i++) { if(term.getWords().get(i).equals(subTerm.getWords().get(j))) { j++; if(startingIndex == -1) startingIndex = i; } else { startingIndex = -1; j = 0; } if(j == subTerm.getWords().size()) return startingIndex; } return -1; }
[ "public", "static", "int", "getPosition", "(", "Term", "subTerm", ",", "Term", "term", ")", "{", "int", "startingIndex", "=", "-", "1", ";", "int", "j", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "term", ".", "getWords", "(", ")", ".", "size", "(", ")", ";", "i", "++", ")", "{", "if", "(", "term", ".", "getWords", "(", ")", ".", "get", "(", "i", ")", ".", "equals", "(", "subTerm", ".", "getWords", "(", ")", ".", "get", "(", "j", ")", ")", ")", "{", "j", "++", ";", "if", "(", "startingIndex", "==", "-", "1", ")", "startingIndex", "=", "i", ";", "}", "else", "{", "startingIndex", "=", "-", "1", ";", "j", "=", "0", ";", "}", "if", "(", "j", "==", "subTerm", ".", "getWords", "(", ")", ".", "size", "(", ")", ")", "return", "startingIndex", ";", "}", "return", "-", "1", ";", "}" ]
Finds the index of appearance of a term's sub-term. @param subTerm the inner term, must be included in <code>term</code> @param term the container term. @return the starting index of <code>subTerm</code> in <code>term</code>. -1 otherwise.
[ "Finds", "the", "index", "of", "appearance", "of", "a", "term", "s", "sub", "-", "term", "." ]
731e5d0bc7c14180713c01a9c7dffe1925f26130
https://github.com/termsuite/termsuite-core/blob/731e5d0bc7c14180713c01a9c7dffe1925f26130/src/main/java/fr/univnantes/termsuite/utils/TermUtils.java#L125-L141
9,302
knowm/Datasets
datasets-common/src/main/java/org/knowm/datasets/common/Splitter.java
Splitter.split
public static Iterable<String> split(String separator, String stringToSplit) { String[] StringArray = stringToSplit.split(separator); Iterable<String> iterable = Arrays.asList(StringArray); return iterable; }
java
public static Iterable<String> split(String separator, String stringToSplit) { String[] StringArray = stringToSplit.split(separator); Iterable<String> iterable = Arrays.asList(StringArray); return iterable; }
[ "public", "static", "Iterable", "<", "String", ">", "split", "(", "String", "separator", ",", "String", "stringToSplit", ")", "{", "String", "[", "]", "StringArray", "=", "stringToSplit", ".", "split", "(", "separator", ")", ";", "Iterable", "<", "String", ">", "iterable", "=", "Arrays", ".", "asList", "(", "StringArray", ")", ";", "return", "iterable", ";", "}" ]
Splits a String into an iterable @param separator @param stringToSplit @return
[ "Splits", "a", "String", "into", "an", "iterable" ]
4ea16ccda1d4190a551accff78bbbe05c9c38c79
https://github.com/knowm/Datasets/blob/4ea16ccda1d4190a551accff78bbbe05c9c38c79/datasets-common/src/main/java/org/knowm/datasets/common/Splitter.java#L51-L58
9,303
termsuite/termsuite-core
src/main/java/fr/univnantes/termsuite/uima/readers/QueueRegistry.java
QueueRegistry.getQueue
public BlockingQueue<CollectionDocument> getQueue(String queueName) { Preconditions.checkArgument(registry.containsKey(queueName), "Queue %s does not exist", queueName); return registry.get(queueName); }
java
public BlockingQueue<CollectionDocument> getQueue(String queueName) { Preconditions.checkArgument(registry.containsKey(queueName), "Queue %s does not exist", queueName); return registry.get(queueName); }
[ "public", "BlockingQueue", "<", "CollectionDocument", ">", "getQueue", "(", "String", "queueName", ")", "{", "Preconditions", ".", "checkArgument", "(", "registry", ".", "containsKey", "(", "queueName", ")", ",", "\"Queue %s does not exist\"", ",", "queueName", ")", ";", "return", "registry", ".", "get", "(", "queueName", ")", ";", "}" ]
Retrieves and returns a registered queue by name. @param queueName The name of the queue to retrieve @return The retrieved queue with name <code>queueName</code> @throws IllegalArgumentException if there is queue with the name <code>queueName</code>
[ "Retrieves", "and", "returns", "a", "registered", "queue", "by", "name", "." ]
731e5d0bc7c14180713c01a9c7dffe1925f26130
https://github.com/termsuite/termsuite-core/blob/731e5d0bc7c14180713c01a9c7dffe1925f26130/src/main/java/fr/univnantes/termsuite/uima/readers/QueueRegistry.java#L76-L79
9,304
termsuite/termsuite-core
src/main/java/fr/univnantes/termsuite/io/tbx/TbxExporter.java
TbxExporter.prepareTBXDocument
private Document prepareTBXDocument() throws ParserConfigurationException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document tbxDocument = builder.newDocument(); Element martif = tbxDocument.createElement("martif"); martif.setAttribute("type", "TBX"); tbxDocument.appendChild(martif); Element header = tbxDocument.createElement("martifHeader"); martif.appendChild(header); Element fileDesc = tbxDocument.createElement("fileDesc"); header.appendChild(fileDesc); Element encodingDesc = tbxDocument.createElement("encodingDesc"); header.appendChild(encodingDesc); Element encodingP = tbxDocument.createElement("p"); encodingP.setAttribute("type", "XCSURI"); encodingP.setTextContent("http://ttc-project.googlecode.com/files/ttctbx.xcs"); encodingDesc.appendChild(encodingP); Element sourceDesc = tbxDocument.createElement("sourceDesc"); Element p = tbxDocument.createElement("p"); // p.setTextContent(workingDir.getAbsolutePath()); sourceDesc.appendChild(p); fileDesc.appendChild(sourceDesc); Element text = tbxDocument.createElement("text"); martif.appendChild(text); Element body = tbxDocument.createElement("body"); text.appendChild(body); return tbxDocument; }
java
private Document prepareTBXDocument() throws ParserConfigurationException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document tbxDocument = builder.newDocument(); Element martif = tbxDocument.createElement("martif"); martif.setAttribute("type", "TBX"); tbxDocument.appendChild(martif); Element header = tbxDocument.createElement("martifHeader"); martif.appendChild(header); Element fileDesc = tbxDocument.createElement("fileDesc"); header.appendChild(fileDesc); Element encodingDesc = tbxDocument.createElement("encodingDesc"); header.appendChild(encodingDesc); Element encodingP = tbxDocument.createElement("p"); encodingP.setAttribute("type", "XCSURI"); encodingP.setTextContent("http://ttc-project.googlecode.com/files/ttctbx.xcs"); encodingDesc.appendChild(encodingP); Element sourceDesc = tbxDocument.createElement("sourceDesc"); Element p = tbxDocument.createElement("p"); // p.setTextContent(workingDir.getAbsolutePath()); sourceDesc.appendChild(p); fileDesc.appendChild(sourceDesc); Element text = tbxDocument.createElement("text"); martif.appendChild(text); Element body = tbxDocument.createElement("body"); text.appendChild(body); return tbxDocument; }
[ "private", "Document", "prepareTBXDocument", "(", ")", "throws", "ParserConfigurationException", "{", "DocumentBuilderFactory", "factory", "=", "DocumentBuilderFactory", ".", "newInstance", "(", ")", ";", "DocumentBuilder", "builder", "=", "factory", ".", "newDocumentBuilder", "(", ")", ";", "Document", "tbxDocument", "=", "builder", ".", "newDocument", "(", ")", ";", "Element", "martif", "=", "tbxDocument", ".", "createElement", "(", "\"martif\"", ")", ";", "martif", ".", "setAttribute", "(", "\"type\"", ",", "\"TBX\"", ")", ";", "tbxDocument", ".", "appendChild", "(", "martif", ")", ";", "Element", "header", "=", "tbxDocument", ".", "createElement", "(", "\"martifHeader\"", ")", ";", "martif", ".", "appendChild", "(", "header", ")", ";", "Element", "fileDesc", "=", "tbxDocument", ".", "createElement", "(", "\"fileDesc\"", ")", ";", "header", ".", "appendChild", "(", "fileDesc", ")", ";", "Element", "encodingDesc", "=", "tbxDocument", ".", "createElement", "(", "\"encodingDesc\"", ")", ";", "header", ".", "appendChild", "(", "encodingDesc", ")", ";", "Element", "encodingP", "=", "tbxDocument", ".", "createElement", "(", "\"p\"", ")", ";", "encodingP", ".", "setAttribute", "(", "\"type\"", ",", "\"XCSURI\"", ")", ";", "encodingP", ".", "setTextContent", "(", "\"http://ttc-project.googlecode.com/files/ttctbx.xcs\"", ")", ";", "encodingDesc", ".", "appendChild", "(", "encodingP", ")", ";", "Element", "sourceDesc", "=", "tbxDocument", ".", "createElement", "(", "\"sourceDesc\"", ")", ";", "Element", "p", "=", "tbxDocument", ".", "createElement", "(", "\"p\"", ")", ";", "//\t\tp.setTextContent(workingDir.getAbsolutePath());", "sourceDesc", ".", "appendChild", "(", "p", ")", ";", "fileDesc", ".", "appendChild", "(", "sourceDesc", ")", ";", "Element", "text", "=", "tbxDocument", ".", "createElement", "(", "\"text\"", ")", ";", "martif", ".", "appendChild", "(", "text", ")", ";", "Element", "body", "=", "tbxDocument", ".", "createElement", "(", "\"body\"", ")", ";", "text", ".", "appendChild", "(", "body", ")", ";", "return", "tbxDocument", ";", "}" ]
Prepare the TBX document that will contain the terms.
[ "Prepare", "the", "TBX", "document", "that", "will", "contain", "the", "terms", "." ]
731e5d0bc7c14180713c01a9c7dffe1925f26130
https://github.com/termsuite/termsuite-core/blob/731e5d0bc7c14180713c01a9c7dffe1925f26130/src/main/java/fr/univnantes/termsuite/io/tbx/TbxExporter.java#L89-L124
9,305
termsuite/termsuite-core
src/main/java/fr/univnantes/termsuite/io/tbx/TbxExporter.java
TbxExporter.exportTBXDocument
private void exportTBXDocument(Document tbxDocument, Writer writer) throws TransformerException { // Prepare the transformer to persist the file TransformerFactory transformerFactory = TransformerFactory .newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "http://ttc-project.googlecode.com/files/tbxcore.dtd"); transformer.setOutputProperty(OutputKeys.STANDALONE, "yes"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); try { transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); } catch (IllegalArgumentException e) { throw new TransformerException(e); } // Ignore // Actually persist the file DOMSource source = new DOMSource(tbxDocument); StreamResult result = new StreamResult(writer); transformer.transform(source, result); }
java
private void exportTBXDocument(Document tbxDocument, Writer writer) throws TransformerException { // Prepare the transformer to persist the file TransformerFactory transformerFactory = TransformerFactory .newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "http://ttc-project.googlecode.com/files/tbxcore.dtd"); transformer.setOutputProperty(OutputKeys.STANDALONE, "yes"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); try { transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); } catch (IllegalArgumentException e) { throw new TransformerException(e); } // Ignore // Actually persist the file DOMSource source = new DOMSource(tbxDocument); StreamResult result = new StreamResult(writer); transformer.transform(source, result); }
[ "private", "void", "exportTBXDocument", "(", "Document", "tbxDocument", ",", "Writer", "writer", ")", "throws", "TransformerException", "{", "// Prepare the transformer to persist the file", "TransformerFactory", "transformerFactory", "=", "TransformerFactory", ".", "newInstance", "(", ")", ";", "Transformer", "transformer", "=", "transformerFactory", ".", "newTransformer", "(", ")", ";", "transformer", ".", "setOutputProperty", "(", "OutputKeys", ".", "ENCODING", ",", "\"UTF-8\"", ")", ";", "transformer", ".", "setOutputProperty", "(", "OutputKeys", ".", "DOCTYPE_SYSTEM", ",", "\"http://ttc-project.googlecode.com/files/tbxcore.dtd\"", ")", ";", "transformer", ".", "setOutputProperty", "(", "OutputKeys", ".", "STANDALONE", ",", "\"yes\"", ")", ";", "transformer", ".", "setOutputProperty", "(", "OutputKeys", ".", "INDENT", ",", "\"yes\"", ")", ";", "try", "{", "transformer", ".", "setOutputProperty", "(", "\"{http://xml.apache.org/xslt}indent-amount\"", ",", "\"2\"", ")", ";", "}", "catch", "(", "IllegalArgumentException", "e", ")", "{", "throw", "new", "TransformerException", "(", "e", ")", ";", "}", "// Ignore", "// Actually persist the file", "DOMSource", "source", "=", "new", "DOMSource", "(", "tbxDocument", ")", ";", "StreamResult", "result", "=", "new", "StreamResult", "(", "writer", ")", ";", "transformer", ".", "transform", "(", "source", ",", "result", ")", ";", "}" ]
Export the TBX document to a file specified in parameter. @throws TransformerException
[ "Export", "the", "TBX", "document", "to", "a", "file", "specified", "in", "parameter", "." ]
731e5d0bc7c14180713c01a9c7dffe1925f26130
https://github.com/termsuite/termsuite-core/blob/731e5d0bc7c14180713c01a9c7dffe1925f26130/src/main/java/fr/univnantes/termsuite/io/tbx/TbxExporter.java#L133-L153
9,306
knowm/Datasets
datasets-hja-birdsong/src/main/java/com/musicg/dsp/WindowFunction.java
WindowFunction.generate
public double[] generate(WindowType windowType, int nSamples) { // generate nSamples window function values // for index values 0 .. nSamples - 1 int m = nSamples / 2; double r; double pi = Math.PI; double[] w = new double[nSamples]; switch (windowType) { case BARTLETT: // Bartlett (triangular) window for (int n = 0; n < nSamples; n++) { w[n] = 1.0f - Math.abs(n - m) / m; } break; case HANNING: // Hanning window r = pi / (m + 1); for (int n = -m; n < m; n++) { w[m + n] = 0.5f + 0.5f * Math.cos(n * r); } break; case HAMMING: // Hamming window r = pi / m; for (int n = -m; n < m; n++) { w[m + n] = 0.54f + 0.46f * Math.cos(n * r); } break; case BLACKMAN: // Blackman window r = pi / m; for (int n = -m; n < m; n++) { w[m + n] = 0.42f + 0.5f * Math.cos(n * r) + 0.08f * Math.cos(2 * n * r); } break; default: // Rectangular window function for (int n = 0; n < nSamples; n++) { w[n] = 1.0f; } } return w; }
java
public double[] generate(WindowType windowType, int nSamples) { // generate nSamples window function values // for index values 0 .. nSamples - 1 int m = nSamples / 2; double r; double pi = Math.PI; double[] w = new double[nSamples]; switch (windowType) { case BARTLETT: // Bartlett (triangular) window for (int n = 0; n < nSamples; n++) { w[n] = 1.0f - Math.abs(n - m) / m; } break; case HANNING: // Hanning window r = pi / (m + 1); for (int n = -m; n < m; n++) { w[m + n] = 0.5f + 0.5f * Math.cos(n * r); } break; case HAMMING: // Hamming window r = pi / m; for (int n = -m; n < m; n++) { w[m + n] = 0.54f + 0.46f * Math.cos(n * r); } break; case BLACKMAN: // Blackman window r = pi / m; for (int n = -m; n < m; n++) { w[m + n] = 0.42f + 0.5f * Math.cos(n * r) + 0.08f * Math.cos(2 * n * r); } break; default: // Rectangular window function for (int n = 0; n < nSamples; n++) { w[n] = 1.0f; } } return w; }
[ "public", "double", "[", "]", "generate", "(", "WindowType", "windowType", ",", "int", "nSamples", ")", "{", "// generate nSamples window function values\r", "// for index values 0 .. nSamples - 1\r", "int", "m", "=", "nSamples", "/", "2", ";", "double", "r", ";", "double", "pi", "=", "Math", ".", "PI", ";", "double", "[", "]", "w", "=", "new", "double", "[", "nSamples", "]", ";", "switch", "(", "windowType", ")", "{", "case", "BARTLETT", ":", "// Bartlett (triangular) window\r", "for", "(", "int", "n", "=", "0", ";", "n", "<", "nSamples", ";", "n", "++", ")", "{", "w", "[", "n", "]", "=", "1.0f", "-", "Math", ".", "abs", "(", "n", "-", "m", ")", "/", "m", ";", "}", "break", ";", "case", "HANNING", ":", "// Hanning window\r", "r", "=", "pi", "/", "(", "m", "+", "1", ")", ";", "for", "(", "int", "n", "=", "-", "m", ";", "n", "<", "m", ";", "n", "++", ")", "{", "w", "[", "m", "+", "n", "]", "=", "0.5f", "+", "0.5f", "*", "Math", ".", "cos", "(", "n", "*", "r", ")", ";", "}", "break", ";", "case", "HAMMING", ":", "// Hamming window\r", "r", "=", "pi", "/", "m", ";", "for", "(", "int", "n", "=", "-", "m", ";", "n", "<", "m", ";", "n", "++", ")", "{", "w", "[", "m", "+", "n", "]", "=", "0.54f", "+", "0.46f", "*", "Math", ".", "cos", "(", "n", "*", "r", ")", ";", "}", "break", ";", "case", "BLACKMAN", ":", "// Blackman window\r", "r", "=", "pi", "/", "m", ";", "for", "(", "int", "n", "=", "-", "m", ";", "n", "<", "m", ";", "n", "++", ")", "{", "w", "[", "m", "+", "n", "]", "=", "0.42f", "+", "0.5f", "*", "Math", ".", "cos", "(", "n", "*", "r", ")", "+", "0.08f", "*", "Math", ".", "cos", "(", "2", "*", "n", "*", "r", ")", ";", "}", "break", ";", "default", ":", "// Rectangular window function\r", "for", "(", "int", "n", "=", "0", ";", "n", "<", "nSamples", ";", "n", "++", ")", "{", "w", "[", "n", "]", "=", "1.0f", ";", "}", "}", "return", "w", ";", "}" ]
Generate a window @param windowType @param nSamples size of the window @return window in array
[ "Generate", "a", "window" ]
4ea16ccda1d4190a551accff78bbbe05c9c38c79
https://github.com/knowm/Datasets/blob/4ea16ccda1d4190a551accff78bbbe05c9c38c79/datasets-hja-birdsong/src/main/java/com/musicg/dsp/WindowFunction.java#L37-L75
9,307
termsuite/termsuite-core
src/main/java/fr/univnantes/termsuite/engines/contextualizer/Contextualizer.java
Contextualizer.toAssocRateVector
public void toAssocRateVector(Term t, CrossTable table, AssociationRate assocRateFunction, boolean normalize) { double assocRate; for(Entry coterm:t.getContext().getEntries()) { ContextData contextData = computeContextData(table, t, coterm.getCoTerm()); assocRate = assocRateFunction.getValue(contextData); t.getContext().setAssocRate(coterm.getCoTerm(), assocRate); } if(normalize) t.getContext().normalize(); }
java
public void toAssocRateVector(Term t, CrossTable table, AssociationRate assocRateFunction, boolean normalize) { double assocRate; for(Entry coterm:t.getContext().getEntries()) { ContextData contextData = computeContextData(table, t, coterm.getCoTerm()); assocRate = assocRateFunction.getValue(contextData); t.getContext().setAssocRate(coterm.getCoTerm(), assocRate); } if(normalize) t.getContext().normalize(); }
[ "public", "void", "toAssocRateVector", "(", "Term", "t", ",", "CrossTable", "table", ",", "AssociationRate", "assocRateFunction", ",", "boolean", "normalize", ")", "{", "double", "assocRate", ";", "for", "(", "Entry", "coterm", ":", "t", ".", "getContext", "(", ")", ".", "getEntries", "(", ")", ")", "{", "ContextData", "contextData", "=", "computeContextData", "(", "table", ",", "t", ",", "coterm", ".", "getCoTerm", "(", ")", ")", ";", "assocRate", "=", "assocRateFunction", ".", "getValue", "(", "contextData", ")", ";", "t", ".", "getContext", "(", ")", ".", "setAssocRate", "(", "coterm", ".", "getCoTerm", "(", ")", ",", "assocRate", ")", ";", "}", "if", "(", "normalize", ")", "t", ".", "getContext", "(", ")", ".", "normalize", "(", ")", ";", "}" ]
Normalize this vector according to a cross table and an association rate measure. This method recomputes all <code>{@link Entry}.frequency</code> values with the normalized ones. @param contextVector @param table the pre-computed co-occurrences {@link CrossTable} @param assocRateFunction the {@link AssociationRate} measure implementation @param normalize
[ "Normalize", "this", "vector", "according", "to", "a", "cross", "table", "and", "an", "association", "rate", "measure", "." ]
731e5d0bc7c14180713c01a9c7dffe1925f26130
https://github.com/termsuite/termsuite-core/blob/731e5d0bc7c14180713c01a9c7dffe1925f26130/src/main/java/fr/univnantes/termsuite/engines/contextualizer/Contextualizer.java#L165-L175
9,308
aerogear/aerogear-crypto-java
src/main/java/org/jboss/aerogear/crypto/util/PKCS12.java
PKCS12.validate
public static void validate(byte[] cert, String pass) throws Exception { try { KeyStore keyStore = KeyStore.getInstance(ALGORITHM); keyStore.load(new ByteArrayInputStream(cert), pass.toCharArray()); } catch (Exception e) { throw new Exception("Certificate is not valid!", e); } }
java
public static void validate(byte[] cert, String pass) throws Exception { try { KeyStore keyStore = KeyStore.getInstance(ALGORITHM); keyStore.load(new ByteArrayInputStream(cert), pass.toCharArray()); } catch (Exception e) { throw new Exception("Certificate is not valid!", e); } }
[ "public", "static", "void", "validate", "(", "byte", "[", "]", "cert", ",", "String", "pass", ")", "throws", "Exception", "{", "try", "{", "KeyStore", "keyStore", "=", "KeyStore", ".", "getInstance", "(", "ALGORITHM", ")", ";", "keyStore", ".", "load", "(", "new", "ByteArrayInputStream", "(", "cert", ")", ",", "pass", ".", "toCharArray", "(", ")", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "Exception", "(", "\"Certificate is not valid!\"", ",", "e", ")", ";", "}", "}" ]
Check if the file provide is PKCS12 @param cert certificate to be validated @param pass password to be provided @throws Exception to indicate an invalid certificate
[ "Check", "if", "the", "file", "provide", "is", "PKCS12" ]
3a371780f7deff603f5a7a1dd3de1eeb5e147202
https://github.com/aerogear/aerogear-crypto-java/blob/3a371780f7deff603f5a7a1dd3de1eeb5e147202/src/main/java/org/jboss/aerogear/crypto/util/PKCS12.java#L38-L46
9,309
knowm/Datasets
datasets-reuters-21578/src/main/java/org/knowm/datasets/reuters21578/RawData2DB.java
RawData2DB.getReuters21578StoriesFromFile
private List<Reuters21578> getReuters21578StoriesFromFile(File file) throws IOException { List<Reuters21578> stories = new ArrayList<Reuters21578>(); // 1. Get String from the file // String s = FileUtils.readFileToString(fileName); String s = FileUtils.readFileToString(file, "UTF-8"); // 2. Get a list of stories as Strings, the contecnt between the REUTERS tags List<String> storiesAsString = extractElementAsLines(s, "REUTERS"); for (String storyAsString : storiesAsString) { // System.out.println(storyAsString); Reuters21578 reuters21578Story = getReuters21578StoryFromText(storyAsString); // System.out.println(reuters21578Story.toString()); stories.add(reuters21578Story); } return stories; }
java
private List<Reuters21578> getReuters21578StoriesFromFile(File file) throws IOException { List<Reuters21578> stories = new ArrayList<Reuters21578>(); // 1. Get String from the file // String s = FileUtils.readFileToString(fileName); String s = FileUtils.readFileToString(file, "UTF-8"); // 2. Get a list of stories as Strings, the contecnt between the REUTERS tags List<String> storiesAsString = extractElementAsLines(s, "REUTERS"); for (String storyAsString : storiesAsString) { // System.out.println(storyAsString); Reuters21578 reuters21578Story = getReuters21578StoryFromText(storyAsString); // System.out.println(reuters21578Story.toString()); stories.add(reuters21578Story); } return stories; }
[ "private", "List", "<", "Reuters21578", ">", "getReuters21578StoriesFromFile", "(", "File", "file", ")", "throws", "IOException", "{", "List", "<", "Reuters21578", ">", "stories", "=", "new", "ArrayList", "<", "Reuters21578", ">", "(", ")", ";", "// 1. Get String from the file", "// String s = FileUtils.readFileToString(fileName);", "String", "s", "=", "FileUtils", ".", "readFileToString", "(", "file", ",", "\"UTF-8\"", ")", ";", "// 2. Get a list of stories as Strings, the contecnt between the REUTERS tags", "List", "<", "String", ">", "storiesAsString", "=", "extractElementAsLines", "(", "s", ",", "\"REUTERS\"", ")", ";", "for", "(", "String", "storyAsString", ":", "storiesAsString", ")", "{", "// System.out.println(storyAsString);", "Reuters21578", "reuters21578Story", "=", "getReuters21578StoryFromText", "(", "storyAsString", ")", ";", "// System.out.println(reuters21578Story.toString());", "stories", ".", "add", "(", "reuters21578Story", ")", ";", "}", "return", "stories", ";", "}" ]
Get a List of the Reuters21578Story Beans @param fileName @return @throws IOException
[ "Get", "a", "List", "of", "the", "Reuters21578Story", "Beans" ]
4ea16ccda1d4190a551accff78bbbe05c9c38c79
https://github.com/knowm/Datasets/blob/4ea16ccda1d4190a551accff78bbbe05c9c38c79/datasets-reuters-21578/src/main/java/org/knowm/datasets/reuters21578/RawData2DB.java#L110-L129
9,310
knowm/Datasets
datasets-reuters-21578/src/main/java/org/knowm/datasets/reuters21578/RawData2DB.java
RawData2DB.extractTextBetweenTags
protected String extractTextBetweenTags(String stringContainingText, String tagname) { String openTag = "<" + tagname.toUpperCase() + ">"; String closeTag = "</" + tagname.toUpperCase() + ">"; StringBuilder buf = new StringBuilder(); boolean record = false; for (int i = 0; i < stringContainingText.length() - openTag.length(); i++) { if (stringContainingText.substring(i, i + closeTag.length()).equalsIgnoreCase(closeTag)) { record = false; break; } if (record) { buf.append(stringContainingText.charAt(i)); } if (stringContainingText.substring(i, i + openTag.length()).equalsIgnoreCase(openTag)) { buf = new StringBuilder(); i += openTag.length() - 1; record = true; } } return buf.toString().trim(); }
java
protected String extractTextBetweenTags(String stringContainingText, String tagname) { String openTag = "<" + tagname.toUpperCase() + ">"; String closeTag = "</" + tagname.toUpperCase() + ">"; StringBuilder buf = new StringBuilder(); boolean record = false; for (int i = 0; i < stringContainingText.length() - openTag.length(); i++) { if (stringContainingText.substring(i, i + closeTag.length()).equalsIgnoreCase(closeTag)) { record = false; break; } if (record) { buf.append(stringContainingText.charAt(i)); } if (stringContainingText.substring(i, i + openTag.length()).equalsIgnoreCase(openTag)) { buf = new StringBuilder(); i += openTag.length() - 1; record = true; } } return buf.toString().trim(); }
[ "protected", "String", "extractTextBetweenTags", "(", "String", "stringContainingText", ",", "String", "tagname", ")", "{", "String", "openTag", "=", "\"<\"", "+", "tagname", ".", "toUpperCase", "(", ")", "+", "\">\"", ";", "String", "closeTag", "=", "\"</\"", "+", "tagname", ".", "toUpperCase", "(", ")", "+", "\">\"", ";", "StringBuilder", "buf", "=", "new", "StringBuilder", "(", ")", ";", "boolean", "record", "=", "false", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "stringContainingText", ".", "length", "(", ")", "-", "openTag", ".", "length", "(", ")", ";", "i", "++", ")", "{", "if", "(", "stringContainingText", ".", "substring", "(", "i", ",", "i", "+", "closeTag", ".", "length", "(", ")", ")", ".", "equalsIgnoreCase", "(", "closeTag", ")", ")", "{", "record", "=", "false", ";", "break", ";", "}", "if", "(", "record", ")", "{", "buf", ".", "append", "(", "stringContainingText", ".", "charAt", "(", "i", ")", ")", ";", "}", "if", "(", "stringContainingText", ".", "substring", "(", "i", ",", "i", "+", "openTag", ".", "length", "(", ")", ")", ".", "equalsIgnoreCase", "(", "openTag", ")", ")", "{", "buf", "=", "new", "StringBuilder", "(", ")", ";", "i", "+=", "openTag", ".", "length", "(", ")", "-", "1", ";", "record", "=", "true", ";", "}", "}", "return", "buf", ".", "toString", "(", ")", ".", "trim", "(", ")", ";", "}" ]
Given some stringContainingText, extracts the String between the tags @param stringContainingText @param tagname @return
[ "Given", "some", "stringContainingText", "extracts", "the", "String", "between", "the", "tags" ]
4ea16ccda1d4190a551accff78bbbe05c9c38c79
https://github.com/knowm/Datasets/blob/4ea16ccda1d4190a551accff78bbbe05c9c38c79/datasets-reuters-21578/src/main/java/org/knowm/datasets/reuters21578/RawData2DB.java#L260-L284
9,311
knowm/Datasets
datasets-reuters-21578/src/main/java/org/knowm/datasets/reuters21578/RawData2DB.java
RawData2DB.extractAttribute
protected String extractAttribute(String stringContainingAttributes, String attributeName) { String attributeValue = ""; stringContainingAttributes = stringContainingAttributes.replaceAll("<", "").replaceAll(">", ""); String[] keyValues = stringContainingAttributes.split(" "); for (int i = 0; i < keyValues.length; i++) { String keyValue = keyValues[i].trim(); String[] keyAndValue = keyValue.split("="); if (keyAndValue[0].equalsIgnoreCase(attributeName)) { return keyAndValue[1].substring(1, keyAndValue[1].length() - 1); } } return attributeValue; }
java
protected String extractAttribute(String stringContainingAttributes, String attributeName) { String attributeValue = ""; stringContainingAttributes = stringContainingAttributes.replaceAll("<", "").replaceAll(">", ""); String[] keyValues = stringContainingAttributes.split(" "); for (int i = 0; i < keyValues.length; i++) { String keyValue = keyValues[i].trim(); String[] keyAndValue = keyValue.split("="); if (keyAndValue[0].equalsIgnoreCase(attributeName)) { return keyAndValue[1].substring(1, keyAndValue[1].length() - 1); } } return attributeValue; }
[ "protected", "String", "extractAttribute", "(", "String", "stringContainingAttributes", ",", "String", "attributeName", ")", "{", "String", "attributeValue", "=", "\"\"", ";", "stringContainingAttributes", "=", "stringContainingAttributes", ".", "replaceAll", "(", "\"<\"", ",", "\"\"", ")", ".", "replaceAll", "(", "\">\"", ",", "\"\"", ")", ";", "String", "[", "]", "keyValues", "=", "stringContainingAttributes", ".", "split", "(", "\" \"", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "keyValues", ".", "length", ";", "i", "++", ")", "{", "String", "keyValue", "=", "keyValues", "[", "i", "]", ".", "trim", "(", ")", ";", "String", "[", "]", "keyAndValue", "=", "keyValue", ".", "split", "(", "\"=\"", ")", ";", "if", "(", "keyAndValue", "[", "0", "]", ".", "equalsIgnoreCase", "(", "attributeName", ")", ")", "{", "return", "keyAndValue", "[", "1", "]", ".", "substring", "(", "1", ",", "keyAndValue", "[", "1", "]", ".", "length", "(", ")", "-", "1", ")", ";", "}", "}", "return", "attributeValue", ";", "}" ]
Given a String containing XML-like attributes and a key, it extracts a value @param stringContainingAttributes @param attributeName @return
[ "Given", "a", "String", "containing", "XML", "-", "like", "attributes", "and", "a", "key", "it", "extracts", "a", "value" ]
4ea16ccda1d4190a551accff78bbbe05c9c38c79
https://github.com/knowm/Datasets/blob/4ea16ccda1d4190a551accff78bbbe05c9c38c79/datasets-reuters-21578/src/main/java/org/knowm/datasets/reuters21578/RawData2DB.java#L293-L309
9,312
aerogear/aerogear-crypto-java
src/main/java/org/jboss/aerogear/crypto/RandomUtils.java
RandomUtils.randomBytes
public static byte[] randomBytes(int n) { byte[] buffer = new byte[n]; if (RandomUtils.secureRandom == null) { try { RandomUtils.secureRandom = SecureRandom.getInstance(ALGORITHM); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } } RandomUtils.secureRandom.nextBytes(buffer); return buffer; }
java
public static byte[] randomBytes(int n) { byte[] buffer = new byte[n]; if (RandomUtils.secureRandom == null) { try { RandomUtils.secureRandom = SecureRandom.getInstance(ALGORITHM); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } } RandomUtils.secureRandom.nextBytes(buffer); return buffer; }
[ "public", "static", "byte", "[", "]", "randomBytes", "(", "int", "n", ")", "{", "byte", "[", "]", "buffer", "=", "new", "byte", "[", "n", "]", ";", "if", "(", "RandomUtils", ".", "secureRandom", "==", "null", ")", "{", "try", "{", "RandomUtils", ".", "secureRandom", "=", "SecureRandom", ".", "getInstance", "(", "ALGORITHM", ")", ";", "}", "catch", "(", "NoSuchAlgorithmException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "}", "RandomUtils", ".", "secureRandom", ".", "nextBytes", "(", "buffer", ")", ";", "return", "buffer", ";", "}" ]
Generates a number random bytes specified by the user @return byte array representation of random bytes
[ "Generates", "a", "number", "random", "bytes", "specified", "by", "the", "user" ]
3a371780f7deff603f5a7a1dd3de1eeb5e147202
https://github.com/aerogear/aerogear-crypto-java/blob/3a371780f7deff603f5a7a1dd3de1eeb5e147202/src/main/java/org/jboss/aerogear/crypto/RandomUtils.java#L46-L57
9,313
termsuite/termsuite-core
src/main/java/fr/univnantes/termsuite/api/BilingualAligner.java
BilingualAligner.create
public BilingualAlignmentService create() { Preconditions.checkArgument(sourceCorpus.isPresent(), "No source indexed corpus given"); Preconditions.checkArgument(dico.isPresent(), "No bilingual dictionary given"); Preconditions.checkArgument(targetCorpus.isPresent(), "No target indexed corpus given"); Injector sourceInjector = TermSuiteFactory.createExtractorInjector(sourceCorpus.get()); Injector targetInjector = TermSuiteFactory.createExtractorInjector(targetCorpus.get()); AlignerModule alignerModule = new AlignerModule( sourceInjector, targetInjector, dico.get(), distance ); Injector alignerInjector = Guice.createInjector(alignerModule); BilingualAlignmentService alignService = alignerInjector.getInstance(BilingualAlignmentService.class); return alignService; }
java
public BilingualAlignmentService create() { Preconditions.checkArgument(sourceCorpus.isPresent(), "No source indexed corpus given"); Preconditions.checkArgument(dico.isPresent(), "No bilingual dictionary given"); Preconditions.checkArgument(targetCorpus.isPresent(), "No target indexed corpus given"); Injector sourceInjector = TermSuiteFactory.createExtractorInjector(sourceCorpus.get()); Injector targetInjector = TermSuiteFactory.createExtractorInjector(targetCorpus.get()); AlignerModule alignerModule = new AlignerModule( sourceInjector, targetInjector, dico.get(), distance ); Injector alignerInjector = Guice.createInjector(alignerModule); BilingualAlignmentService alignService = alignerInjector.getInstance(BilingualAlignmentService.class); return alignService; }
[ "public", "BilingualAlignmentService", "create", "(", ")", "{", "Preconditions", ".", "checkArgument", "(", "sourceCorpus", ".", "isPresent", "(", ")", ",", "\"No source indexed corpus given\"", ")", ";", "Preconditions", ".", "checkArgument", "(", "dico", ".", "isPresent", "(", ")", ",", "\"No bilingual dictionary given\"", ")", ";", "Preconditions", ".", "checkArgument", "(", "targetCorpus", ".", "isPresent", "(", ")", ",", "\"No target indexed corpus given\"", ")", ";", "Injector", "sourceInjector", "=", "TermSuiteFactory", ".", "createExtractorInjector", "(", "sourceCorpus", ".", "get", "(", ")", ")", ";", "Injector", "targetInjector", "=", "TermSuiteFactory", ".", "createExtractorInjector", "(", "targetCorpus", ".", "get", "(", ")", ")", ";", "AlignerModule", "alignerModule", "=", "new", "AlignerModule", "(", "sourceInjector", ",", "targetInjector", ",", "dico", ".", "get", "(", ")", ",", "distance", ")", ";", "Injector", "alignerInjector", "=", "Guice", ".", "createInjector", "(", "alignerModule", ")", ";", "BilingualAlignmentService", "alignService", "=", "alignerInjector", ".", "getInstance", "(", "BilingualAlignmentService", ".", "class", ")", ";", "return", "alignService", ";", "}" ]
Creates the bilingual single-word aligner. @return the aligner object
[ "Creates", "the", "bilingual", "single", "-", "word", "aligner", "." ]
731e5d0bc7c14180713c01a9c7dffe1925f26130
https://github.com/termsuite/termsuite-core/blob/731e5d0bc7c14180713c01a9c7dffe1925f26130/src/main/java/fr/univnantes/termsuite/api/BilingualAligner.java#L123-L140
9,314
termsuite/termsuite-core
src/main/java/fr/univnantes/termsuite/uima/engines/preproc/OccurrenceBuffer.java
OccurrenceBuffer.findDuplicates
public Collection<Collection<RegexOccurrence>> findDuplicates() { Collection<Collection<RegexOccurrence>> setToReturn = Lists.newArrayList(); if(! this.occurrences.isEmpty()) { List<RegexOccurrence> sortedOcc = Lists.newArrayList(this.occurrences); Collections.sort(sortedOcc, new Comparator<RegexOccurrence>() { @Override public int compare(RegexOccurrence o1, RegexOccurrence o2) { return ComparisonChain.start() .compare(o1.getBegin(), o2.getBegin()) .compare(o1.getEnd(), o2.getEnd()) .result(); } }); ListIterator<RegexOccurrence> it = sortedOcc.listIterator(); RegexOccurrence current; List<RegexOccurrence> doublons = Lists.newArrayListWithCapacity(3); doublons.add(it.next()); while(it.hasNext()) { current = it.next(); if(current.getBegin() == doublons.get(0).getBegin() && current.getEnd() == doublons.get(0).getEnd()) { doublons.add(current); } else { if(doublons.size()>1) setToReturn.add(doublons); doublons = Lists.newArrayListWithCapacity(3); doublons.add(current); } } if(doublons.size()>1) setToReturn.add(doublons); } return setToReturn; }
java
public Collection<Collection<RegexOccurrence>> findDuplicates() { Collection<Collection<RegexOccurrence>> setToReturn = Lists.newArrayList(); if(! this.occurrences.isEmpty()) { List<RegexOccurrence> sortedOcc = Lists.newArrayList(this.occurrences); Collections.sort(sortedOcc, new Comparator<RegexOccurrence>() { @Override public int compare(RegexOccurrence o1, RegexOccurrence o2) { return ComparisonChain.start() .compare(o1.getBegin(), o2.getBegin()) .compare(o1.getEnd(), o2.getEnd()) .result(); } }); ListIterator<RegexOccurrence> it = sortedOcc.listIterator(); RegexOccurrence current; List<RegexOccurrence> doublons = Lists.newArrayListWithCapacity(3); doublons.add(it.next()); while(it.hasNext()) { current = it.next(); if(current.getBegin() == doublons.get(0).getBegin() && current.getEnd() == doublons.get(0).getEnd()) { doublons.add(current); } else { if(doublons.size()>1) setToReturn.add(doublons); doublons = Lists.newArrayListWithCapacity(3); doublons.add(current); } } if(doublons.size()>1) setToReturn.add(doublons); } return setToReturn; }
[ "public", "Collection", "<", "Collection", "<", "RegexOccurrence", ">", ">", "findDuplicates", "(", ")", "{", "Collection", "<", "Collection", "<", "RegexOccurrence", ">>", "setToReturn", "=", "Lists", ".", "newArrayList", "(", ")", ";", "if", "(", "!", "this", ".", "occurrences", ".", "isEmpty", "(", ")", ")", "{", "List", "<", "RegexOccurrence", ">", "sortedOcc", "=", "Lists", ".", "newArrayList", "(", "this", ".", "occurrences", ")", ";", "Collections", ".", "sort", "(", "sortedOcc", ",", "new", "Comparator", "<", "RegexOccurrence", ">", "(", ")", "{", "@", "Override", "public", "int", "compare", "(", "RegexOccurrence", "o1", ",", "RegexOccurrence", "o2", ")", "{", "return", "ComparisonChain", ".", "start", "(", ")", ".", "compare", "(", "o1", ".", "getBegin", "(", ")", ",", "o2", ".", "getBegin", "(", ")", ")", ".", "compare", "(", "o1", ".", "getEnd", "(", ")", ",", "o2", ".", "getEnd", "(", ")", ")", ".", "result", "(", ")", ";", "}", "}", ")", ";", "ListIterator", "<", "RegexOccurrence", ">", "it", "=", "sortedOcc", ".", "listIterator", "(", ")", ";", "RegexOccurrence", "current", ";", "List", "<", "RegexOccurrence", ">", "doublons", "=", "Lists", ".", "newArrayListWithCapacity", "(", "3", ")", ";", "doublons", ".", "add", "(", "it", ".", "next", "(", ")", ")", ";", "while", "(", "it", ".", "hasNext", "(", ")", ")", "{", "current", "=", "it", ".", "next", "(", ")", ";", "if", "(", "current", ".", "getBegin", "(", ")", "==", "doublons", ".", "get", "(", "0", ")", ".", "getBegin", "(", ")", "&&", "current", ".", "getEnd", "(", ")", "==", "doublons", ".", "get", "(", "0", ")", ".", "getEnd", "(", ")", ")", "{", "doublons", ".", "add", "(", "current", ")", ";", "}", "else", "{", "if", "(", "doublons", ".", "size", "(", ")", ">", "1", ")", "setToReturn", ".", "add", "(", "doublons", ")", ";", "doublons", "=", "Lists", ".", "newArrayListWithCapacity", "(", "3", ")", ";", "doublons", ".", "add", "(", "current", ")", ";", "}", "}", "if", "(", "doublons", ".", "size", "(", ")", ">", "1", ")", "setToReturn", ".", "add", "(", "doublons", ")", ";", "}", "return", "setToReturn", ";", "}" ]
Finds duplicated occurrences in this buffer and returns them as a collection of dups lists. @return
[ "Finds", "duplicated", "occurrences", "in", "this", "buffer", "and", "returns", "them", "as", "a", "collection", "of", "dups", "lists", "." ]
731e5d0bc7c14180713c01a9c7dffe1925f26130
https://github.com/termsuite/termsuite-core/blob/731e5d0bc7c14180713c01a9c7dffe1925f26130/src/main/java/fr/univnantes/termsuite/uima/engines/preproc/OccurrenceBuffer.java#L79-L112
9,315
termsuite/termsuite-core
src/main/java/fr/univnantes/termsuite/utils/TermOccurrenceUtils.java
TermOccurrenceUtils.occurrenceChunkIterator
public static Iterator<List<TermOccurrence>> occurrenceChunkIterator(Collection<TermOccurrence> occurrences) { List<TermOccurrence> asList = Lists.newArrayList(occurrences); Collections.sort(asList, TermOccurrenceUtils.uimaNaturalOrder); final Iterator<TermOccurrence> it = asList.iterator(); return new AbstractIterator<List<TermOccurrence>>() { private List<TermOccurrence> currentChunk = Lists.newArrayList(); @Override protected List<TermOccurrence> computeNext() { while(it.hasNext()) { TermOccurrence next = it.next(); if(currentChunk.isEmpty() || hasOverlappingOffsets(next, currentChunk)) currentChunk.add(next); else { List<TermOccurrence> ret = copyAndReinit(); currentChunk.add(next); return ret; } } if(!currentChunk.isEmpty()) { return copyAndReinit(); } else return endOfData(); } private List<TermOccurrence> copyAndReinit() { List<TermOccurrence> copy = Lists.newArrayList(currentChunk); currentChunk = Lists.newArrayList(); return copy; } }; }
java
public static Iterator<List<TermOccurrence>> occurrenceChunkIterator(Collection<TermOccurrence> occurrences) { List<TermOccurrence> asList = Lists.newArrayList(occurrences); Collections.sort(asList, TermOccurrenceUtils.uimaNaturalOrder); final Iterator<TermOccurrence> it = asList.iterator(); return new AbstractIterator<List<TermOccurrence>>() { private List<TermOccurrence> currentChunk = Lists.newArrayList(); @Override protected List<TermOccurrence> computeNext() { while(it.hasNext()) { TermOccurrence next = it.next(); if(currentChunk.isEmpty() || hasOverlappingOffsets(next, currentChunk)) currentChunk.add(next); else { List<TermOccurrence> ret = copyAndReinit(); currentChunk.add(next); return ret; } } if(!currentChunk.isEmpty()) { return copyAndReinit(); } else return endOfData(); } private List<TermOccurrence> copyAndReinit() { List<TermOccurrence> copy = Lists.newArrayList(currentChunk); currentChunk = Lists.newArrayList(); return copy; } }; }
[ "public", "static", "Iterator", "<", "List", "<", "TermOccurrence", ">", ">", "occurrenceChunkIterator", "(", "Collection", "<", "TermOccurrence", ">", "occurrences", ")", "{", "List", "<", "TermOccurrence", ">", "asList", "=", "Lists", ".", "newArrayList", "(", "occurrences", ")", ";", "Collections", ".", "sort", "(", "asList", ",", "TermOccurrenceUtils", ".", "uimaNaturalOrder", ")", ";", "final", "Iterator", "<", "TermOccurrence", ">", "it", "=", "asList", ".", "iterator", "(", ")", ";", "return", "new", "AbstractIterator", "<", "List", "<", "TermOccurrence", ">", ">", "(", ")", "{", "private", "List", "<", "TermOccurrence", ">", "currentChunk", "=", "Lists", ".", "newArrayList", "(", ")", ";", "@", "Override", "protected", "List", "<", "TermOccurrence", ">", "computeNext", "(", ")", "{", "while", "(", "it", ".", "hasNext", "(", ")", ")", "{", "TermOccurrence", "next", "=", "it", ".", "next", "(", ")", ";", "if", "(", "currentChunk", ".", "isEmpty", "(", ")", "||", "hasOverlappingOffsets", "(", "next", ",", "currentChunk", ")", ")", "currentChunk", ".", "add", "(", "next", ")", ";", "else", "{", "List", "<", "TermOccurrence", ">", "ret", "=", "copyAndReinit", "(", ")", ";", "currentChunk", ".", "add", "(", "next", ")", ";", "return", "ret", ";", "}", "}", "if", "(", "!", "currentChunk", ".", "isEmpty", "(", ")", ")", "{", "return", "copyAndReinit", "(", ")", ";", "}", "else", "return", "endOfData", "(", ")", ";", "}", "private", "List", "<", "TermOccurrence", ">", "copyAndReinit", "(", ")", "{", "List", "<", "TermOccurrence", ">", "copy", "=", "Lists", ".", "newArrayList", "(", "currentChunk", ")", ";", "currentChunk", "=", "Lists", ".", "newArrayList", "(", ")", ";", "return", "copy", ";", "}", "}", ";", "}" ]
Returns a virtual iterator on chunks of an occurrence collection. A occurrence collection's chunk is a list of overlapping {@link TermOccurrence}. Every time there is a gap between two occurrences (i.e. there do not overlap), a new chunk is created. @param occurrences @return
[ "Returns", "a", "virtual", "iterator", "on", "chunks", "of", "an", "occurrence", "collection", "." ]
731e5d0bc7c14180713c01a9c7dffe1925f26130
https://github.com/termsuite/termsuite-core/blob/731e5d0bc7c14180713c01a9c7dffe1925f26130/src/main/java/fr/univnantes/termsuite/utils/TermOccurrenceUtils.java#L69-L100
9,316
termsuite/termsuite-core
src/main/java/fr/univnantes/termsuite/utils/TermOccurrenceUtils.java
TermOccurrenceUtils.removeOverlaps
public static void removeOverlaps(Collection<TermOccurrence> referenceSet, Collection<TermOccurrence> occurrenceSet) { Iterator<TermOccurrence> it = occurrenceSet.iterator(); while(it.hasNext()) { TermOccurrence occ = it.next(); for(TermOccurrence refOcc:referenceSet) { if(occ.getSourceDocument().equals(refOcc.getSourceDocument()) && areOffsetsOverlapping(occ, refOcc)) { it.remove(); break; } } } }
java
public static void removeOverlaps(Collection<TermOccurrence> referenceSet, Collection<TermOccurrence> occurrenceSet) { Iterator<TermOccurrence> it = occurrenceSet.iterator(); while(it.hasNext()) { TermOccurrence occ = it.next(); for(TermOccurrence refOcc:referenceSet) { if(occ.getSourceDocument().equals(refOcc.getSourceDocument()) && areOffsetsOverlapping(occ, refOcc)) { it.remove(); break; } } } }
[ "public", "static", "void", "removeOverlaps", "(", "Collection", "<", "TermOccurrence", ">", "referenceSet", ",", "Collection", "<", "TermOccurrence", ">", "occurrenceSet", ")", "{", "Iterator", "<", "TermOccurrence", ">", "it", "=", "occurrenceSet", ".", "iterator", "(", ")", ";", "while", "(", "it", ".", "hasNext", "(", ")", ")", "{", "TermOccurrence", "occ", "=", "it", ".", "next", "(", ")", ";", "for", "(", "TermOccurrence", "refOcc", ":", "referenceSet", ")", "{", "if", "(", "occ", ".", "getSourceDocument", "(", ")", ".", "equals", "(", "refOcc", ".", "getSourceDocument", "(", ")", ")", "&&", "areOffsetsOverlapping", "(", "occ", ",", "refOcc", ")", ")", "{", "it", ".", "remove", "(", ")", ";", "break", ";", "}", "}", "}", "}" ]
Removes from an occurrence set all occurrences that overlap at least one occurrence in a reference occurrence set. @param referenceSet the reference set, not modified by this method @param occurrenceSet the occurrence set to analyze, will be modified by this method
[ "Removes", "from", "an", "occurrence", "set", "all", "occurrences", "that", "overlap", "at", "least", "one", "occurrence", "in", "a", "reference", "occurrence", "set", "." ]
731e5d0bc7c14180713c01a9c7dffe1925f26130
https://github.com/termsuite/termsuite-core/blob/731e5d0bc7c14180713c01a9c7dffe1925f26130/src/main/java/fr/univnantes/termsuite/utils/TermOccurrenceUtils.java#L112-L124
9,317
termsuite/termsuite-core
src/main/java/fr/univnantes/termsuite/utils/TermOccurrenceUtils.java
TermOccurrenceUtils.hasOverlappingOffsets
public static boolean hasOverlappingOffsets(TermOccurrence theOcc, Collection<TermOccurrence> theOccCollection) { for(TermOccurrence o:theOccCollection) if(areOffsetsOverlapping(theOcc, o)) return true; return false; }
java
public static boolean hasOverlappingOffsets(TermOccurrence theOcc, Collection<TermOccurrence> theOccCollection) { for(TermOccurrence o:theOccCollection) if(areOffsetsOverlapping(theOcc, o)) return true; return false; }
[ "public", "static", "boolean", "hasOverlappingOffsets", "(", "TermOccurrence", "theOcc", ",", "Collection", "<", "TermOccurrence", ">", "theOccCollection", ")", "{", "for", "(", "TermOccurrence", "o", ":", "theOccCollection", ")", "if", "(", "areOffsetsOverlapping", "(", "theOcc", ",", "o", ")", ")", "return", "true", ";", "return", "false", ";", "}" ]
True if an occurrence set contains any element overlapping with the param occurrence. @param theOcc @param theOccCollection @return
[ "True", "if", "an", "occurrence", "set", "contains", "any", "element", "overlapping", "with", "the", "param", "occurrence", "." ]
731e5d0bc7c14180713c01a9c7dffe1925f26130
https://github.com/termsuite/termsuite-core/blob/731e5d0bc7c14180713c01a9c7dffe1925f26130/src/main/java/fr/univnantes/termsuite/utils/TermOccurrenceUtils.java#L135-L140
9,318
termsuite/termsuite-core
src/main/java/fr/univnantes/termsuite/utils/TermOccurrenceUtils.java
TermOccurrenceUtils.areOverlapping
public static boolean areOverlapping(TermOccurrence a, TermOccurrence b) { return a.getSourceDocument().equals(b.getSourceDocument()) && areOffsetsOverlapping(a, b); }
java
public static boolean areOverlapping(TermOccurrence a, TermOccurrence b) { return a.getSourceDocument().equals(b.getSourceDocument()) && areOffsetsOverlapping(a, b); }
[ "public", "static", "boolean", "areOverlapping", "(", "TermOccurrence", "a", ",", "TermOccurrence", "b", ")", "{", "return", "a", ".", "getSourceDocument", "(", ")", ".", "equals", "(", "b", ".", "getSourceDocument", "(", ")", ")", "&&", "areOffsetsOverlapping", "(", "a", ",", "b", ")", ";", "}" ]
Returns true if two occurrences are in the same document and their offsets overlap. @param a @param b @return
[ "Returns", "true", "if", "two", "occurrences", "are", "in", "the", "same", "document", "and", "their", "offsets", "overlap", "." ]
731e5d0bc7c14180713c01a9c7dffe1925f26130
https://github.com/termsuite/termsuite-core/blob/731e5d0bc7c14180713c01a9c7dffe1925f26130/src/main/java/fr/univnantes/termsuite/utils/TermOccurrenceUtils.java#L166-L168
9,319
termsuite/termsuite-core
src/main/java/fr/univnantes/termsuite/utils/TermOccurrenceUtils.java
TermOccurrenceUtils.overlaps
public static boolean overlaps(TermOccurrence o1, TermOccurrence o2) { return o1.getSourceDocument().equals(o2.getSourceDocument()) && o1.getBegin() < o2.getEnd() && o2.getBegin()< o1.getEnd(); }
java
public static boolean overlaps(TermOccurrence o1, TermOccurrence o2) { return o1.getSourceDocument().equals(o2.getSourceDocument()) && o1.getBegin() < o2.getEnd() && o2.getBegin()< o1.getEnd(); }
[ "public", "static", "boolean", "overlaps", "(", "TermOccurrence", "o1", ",", "TermOccurrence", "o2", ")", "{", "return", "o1", ".", "getSourceDocument", "(", ")", ".", "equals", "(", "o2", ".", "getSourceDocument", "(", ")", ")", "&&", "o1", ".", "getBegin", "(", ")", "<", "o2", ".", "getEnd", "(", ")", "&&", "o2", ".", "getBegin", "(", ")", "<", "o1", ".", "getEnd", "(", ")", ";", "}" ]
True if both source documents are the same and if the offsets in the document overlaps. The overlap is interpreted in the sense of opening intervals. I.e if the begin of the second interval is the end of the first interval, this is not an overlap. @param o1 @param o2 @return
[ "True", "if", "both", "source", "documents", "are", "the", "same", "and", "if", "the", "offsets", "in", "the", "document", "overlaps", "." ]
731e5d0bc7c14180713c01a9c7dffe1925f26130
https://github.com/termsuite/termsuite-core/blob/731e5d0bc7c14180713c01a9c7dffe1925f26130/src/main/java/fr/univnantes/termsuite/utils/TermOccurrenceUtils.java#L182-L186
9,320
jboss/jboss-servlet-api_spec
src/main/java/javax/servlet/http/HttpServletRequestWrapper.java
HttpServletRequestWrapper.login
@Override public void login(String username, String password) throws ServletException { this._getHttpServletRequest().login(username,password); }
java
@Override public void login(String username, String password) throws ServletException { this._getHttpServletRequest().login(username,password); }
[ "@", "Override", "public", "void", "login", "(", "String", "username", ",", "String", "password", ")", "throws", "ServletException", "{", "this", ".", "_getHttpServletRequest", "(", ")", ".", "login", "(", "username", ",", "password", ")", ";", "}" ]
The default behavior of this method is to call login on the wrapped request object. @since Servlet 3.0
[ "The", "default", "behavior", "of", "this", "method", "is", "to", "call", "login", "on", "the", "wrapped", "request", "object", "." ]
5bc96f2b833c072baff6eb8ae49bc7b5e503e9b2
https://github.com/jboss/jboss-servlet-api_spec/blob/5bc96f2b833c072baff6eb8ae49bc7b5e503e9b2/src/main/java/javax/servlet/http/HttpServletRequestWrapper.java#L362-L366
9,321
jboss/jboss-servlet-api_spec
src/main/java/javax/servlet/http/HttpServletRequestWrapper.java
HttpServletRequestWrapper.getPart
@Override public Part getPart(String name) throws IOException, ServletException { return this._getHttpServletRequest().getPart(name); }
java
@Override public Part getPart(String name) throws IOException, ServletException { return this._getHttpServletRequest().getPart(name); }
[ "@", "Override", "public", "Part", "getPart", "(", "String", "name", ")", "throws", "IOException", ",", "ServletException", "{", "return", "this", ".", "_getHttpServletRequest", "(", ")", ".", "getPart", "(", "name", ")", ";", "}" ]
The default behavior of this method is to call getPart on the wrapped request object. @since Servlet 3.0
[ "The", "default", "behavior", "of", "this", "method", "is", "to", "call", "getPart", "on", "the", "wrapped", "request", "object", "." ]
5bc96f2b833c072baff6eb8ae49bc7b5e503e9b2
https://github.com/jboss/jboss-servlet-api_spec/blob/5bc96f2b833c072baff6eb8ae49bc7b5e503e9b2/src/main/java/javax/servlet/http/HttpServletRequestWrapper.java#L399-L403
9,322
arakelian/jackson-utils
src/main/java/com/arakelian/jackson/utils/JacksonUtils.java
JacksonUtils.toMap
public static Map toMap(final Object value, final Locale locale) { return builder().locale(locale).build().mapper().convertValue(value, LinkedHashMap.class); }
java
public static Map toMap(final Object value, final Locale locale) { return builder().locale(locale).build().mapper().convertValue(value, LinkedHashMap.class); }
[ "public", "static", "Map", "toMap", "(", "final", "Object", "value", ",", "final", "Locale", "locale", ")", "{", "return", "builder", "(", ")", ".", "locale", "(", "locale", ")", ".", "build", "(", ")", ".", "mapper", "(", ")", ".", "convertValue", "(", "value", ",", "LinkedHashMap", ".", "class", ")", ";", "}" ]
Returns a serialized version of the object as a Map. @param value object value @param locale target locale @return serialized version of the object as a Map.
[ "Returns", "a", "serialized", "version", "of", "the", "object", "as", "a", "Map", "." ]
db0028fe15c55f9dd8272e327bf67f6004011711
https://github.com/arakelian/jackson-utils/blob/db0028fe15c55f9dd8272e327bf67f6004011711/src/main/java/com/arakelian/jackson/utils/JacksonUtils.java#L295-L297
9,323
arakelian/jackson-utils
src/main/java/com/arakelian/jackson/model/GeoPoint.java
GeoPoint.deinterleave
protected static long deinterleave(long value) { value &= MAGIC[0]; value = (value ^ value >>> SHIFT[0]) & MAGIC[1]; value = (value ^ value >>> SHIFT[1]) & MAGIC[2]; value = (value ^ value >>> SHIFT[2]) & MAGIC[3]; value = (value ^ value >>> SHIFT[3]) & MAGIC[4]; value = (value ^ value >>> SHIFT[4]) & MAGIC[5]; return value; }
java
protected static long deinterleave(long value) { value &= MAGIC[0]; value = (value ^ value >>> SHIFT[0]) & MAGIC[1]; value = (value ^ value >>> SHIFT[1]) & MAGIC[2]; value = (value ^ value >>> SHIFT[2]) & MAGIC[3]; value = (value ^ value >>> SHIFT[3]) & MAGIC[4]; value = (value ^ value >>> SHIFT[4]) & MAGIC[5]; return value; }
[ "protected", "static", "long", "deinterleave", "(", "long", "value", ")", "{", "value", "&=", "MAGIC", "[", "0", "]", ";", "value", "=", "(", "value", "^", "value", ">>>", "SHIFT", "[", "0", "]", ")", "&", "MAGIC", "[", "1", "]", ";", "value", "=", "(", "value", "^", "value", ">>>", "SHIFT", "[", "1", "]", ")", "&", "MAGIC", "[", "2", "]", ";", "value", "=", "(", "value", "^", "value", ">>>", "SHIFT", "[", "2", "]", ")", "&", "MAGIC", "[", "3", "]", ";", "value", "=", "(", "value", "^", "value", ">>>", "SHIFT", "[", "3", "]", ")", "&", "MAGIC", "[", "4", "]", ";", "value", "=", "(", "value", "^", "value", ">>>", "SHIFT", "[", "4", "]", ")", "&", "MAGIC", "[", "5", "]", ";", "return", "value", ";", "}" ]
Returns one of two 32-bit values that were previously interleaved to produce a 64-bit value. @param value 64-bit value that was created by interleaving two 32-bit values @return one of two previously interleaved values
[ "Returns", "one", "of", "two", "32", "-", "bit", "values", "that", "were", "previously", "interleaved", "to", "produce", "a", "64", "-", "bit", "value", "." ]
db0028fe15c55f9dd8272e327bf67f6004011711
https://github.com/arakelian/jackson-utils/blob/db0028fe15c55f9dd8272e327bf67f6004011711/src/main/java/com/arakelian/jackson/model/GeoPoint.java#L169-L177
9,324
arakelian/jackson-utils
src/main/java/com/arakelian/jackson/model/Coordinate.java
Coordinate.distance
public double distance(final Coordinate c) { final double dx = getX() - c.getX(); final double dy = getY() - c.getY(); return Math.sqrt(dx * dx + dy * dy); }
java
public double distance(final Coordinate c) { final double dx = getX() - c.getX(); final double dy = getY() - c.getY(); return Math.sqrt(dx * dx + dy * dy); }
[ "public", "double", "distance", "(", "final", "Coordinate", "c", ")", "{", "final", "double", "dx", "=", "getX", "(", ")", "-", "c", ".", "getX", "(", ")", ";", "final", "double", "dy", "=", "getY", "(", ")", "-", "c", ".", "getY", "(", ")", ";", "return", "Math", ".", "sqrt", "(", "dx", "*", "dx", "+", "dy", "*", "dy", ")", ";", "}" ]
Computes the 2-dimensional Euclidean distance to another location. The Z-ordinate is ignored. @param c a point @return the 2-dimensional Euclidean distance between the locations
[ "Computes", "the", "2", "-", "dimensional", "Euclidean", "distance", "to", "another", "location", ".", "The", "Z", "-", "ordinate", "is", "ignored", "." ]
db0028fe15c55f9dd8272e327bf67f6004011711
https://github.com/arakelian/jackson-utils/blob/db0028fe15c55f9dd8272e327bf67f6004011711/src/main/java/com/arakelian/jackson/model/Coordinate.java#L227-L231
9,325
arakelian/jackson-utils
src/main/java/com/arakelian/jackson/model/Coordinate.java
Coordinate.distance3D
public double distance3D(final Coordinate c) { final double dx = getX() - c.getX(); final double dy = getY() - c.getY(); final double dz = getZ() - c.getZ(); return Math.sqrt(dx * dx + dy * dy + dz * dz); }
java
public double distance3D(final Coordinate c) { final double dx = getX() - c.getX(); final double dy = getY() - c.getY(); final double dz = getZ() - c.getZ(); return Math.sqrt(dx * dx + dy * dy + dz * dz); }
[ "public", "double", "distance3D", "(", "final", "Coordinate", "c", ")", "{", "final", "double", "dx", "=", "getX", "(", ")", "-", "c", ".", "getX", "(", ")", ";", "final", "double", "dy", "=", "getY", "(", ")", "-", "c", ".", "getY", "(", ")", ";", "final", "double", "dz", "=", "getZ", "(", ")", "-", "c", ".", "getZ", "(", ")", ";", "return", "Math", ".", "sqrt", "(", "dx", "*", "dx", "+", "dy", "*", "dy", "+", "dz", "*", "dz", ")", ";", "}" ]
Computes the 3-dimensional Euclidean distance to another location. @param c a coordinate @return the 3-dimensional Euclidean distance between the locations
[ "Computes", "the", "3", "-", "dimensional", "Euclidean", "distance", "to", "another", "location", "." ]
db0028fe15c55f9dd8272e327bf67f6004011711
https://github.com/arakelian/jackson-utils/blob/db0028fe15c55f9dd8272e327bf67f6004011711/src/main/java/com/arakelian/jackson/model/Coordinate.java#L240-L245
9,326
arakelian/jackson-utils
src/main/java/com/arakelian/jackson/model/Coordinate.java
Coordinate.equals2D
public boolean equals2D(final Coordinate c, final double tolerance) { if (!equalsWithTolerance(this.getX(), c.getX(), tolerance)) { return false; } if (!equalsWithTolerance(this.getY(), c.getY(), tolerance)) { return false; } return true; }
java
public boolean equals2D(final Coordinate c, final double tolerance) { if (!equalsWithTolerance(this.getX(), c.getX(), tolerance)) { return false; } if (!equalsWithTolerance(this.getY(), c.getY(), tolerance)) { return false; } return true; }
[ "public", "boolean", "equals2D", "(", "final", "Coordinate", "c", ",", "final", "double", "tolerance", ")", "{", "if", "(", "!", "equalsWithTolerance", "(", "this", ".", "getX", "(", ")", ",", "c", ".", "getX", "(", ")", ",", "tolerance", ")", ")", "{", "return", "false", ";", "}", "if", "(", "!", "equalsWithTolerance", "(", "this", ".", "getY", "(", ")", ",", "c", ".", "getY", "(", ")", ",", "tolerance", ")", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}" ]
Tests if another coordinate has the same values for the X and Y ordinates. The Z ordinate is ignored. @param c a <code>Coordinate</code> with which to do the 2D comparison. @param tolerance margin of error @return true if <code>other</code> is a <code>Coordinate</code> with the same values for X and Y.
[ "Tests", "if", "another", "coordinate", "has", "the", "same", "values", "for", "the", "X", "and", "Y", "ordinates", ".", "The", "Z", "ordinate", "is", "ignored", "." ]
db0028fe15c55f9dd8272e327bf67f6004011711
https://github.com/arakelian/jackson-utils/blob/db0028fe15c55f9dd8272e327bf67f6004011711/src/main/java/com/arakelian/jackson/model/Coordinate.java#L271-L279
9,327
arakelian/jackson-utils
src/main/java/com/arakelian/jackson/model/Coordinate.java
Coordinate.equals3D
public boolean equals3D(final Coordinate other) { return getX() == other.getX() && getY() == other.getY() && (getZ() == other.getZ() || Double.isNaN(getZ()) && Double.isNaN(other.getZ())); }
java
public boolean equals3D(final Coordinate other) { return getX() == other.getX() && getY() == other.getY() && (getZ() == other.getZ() || Double.isNaN(getZ()) && Double.isNaN(other.getZ())); }
[ "public", "boolean", "equals3D", "(", "final", "Coordinate", "other", ")", "{", "return", "getX", "(", ")", "==", "other", ".", "getX", "(", ")", "&&", "getY", "(", ")", "==", "other", ".", "getY", "(", ")", "&&", "(", "getZ", "(", ")", "==", "other", ".", "getZ", "(", ")", "||", "Double", ".", "isNaN", "(", "getZ", "(", ")", ")", "&&", "Double", ".", "isNaN", "(", "other", ".", "getZ", "(", ")", ")", ")", ";", "}" ]
Tests if another coordinate has the same values for the X, Y and Z ordinates. @param other a <code>Coordinate</code> with which to do the 3D comparison. @return true if <code>other</code> is a <code>Coordinate</code> with the same values for X, Y and Z.
[ "Tests", "if", "another", "coordinate", "has", "the", "same", "values", "for", "the", "X", "Y", "and", "Z", "ordinates", "." ]
db0028fe15c55f9dd8272e327bf67f6004011711
https://github.com/arakelian/jackson-utils/blob/db0028fe15c55f9dd8272e327bf67f6004011711/src/main/java/com/arakelian/jackson/model/Coordinate.java#L289-L292
9,328
pushtorefresh/java-private-constructor-checker
checker/src/main/java/com/pushtorefresh/private_constructor_checker/PrivateConstructorChecker.java
PrivateConstructorChecker.check
private void check(Class clazz) { final Constructor<?>[] constructors = clazz.getDeclaredConstructors(); if (constructors.length > 1) { throw new AssertionError(clazz + " has more than one constructor"); } final Constructor<?> constructor = constructors[0]; constructor.setAccessible(true); if (!Modifier.isPrivate(constructor.getModifiers())) { throw new AssertionError("Constructor of " + clazz + " must be private"); } final Class<?>[] parameterTypes = constructor.getParameterTypes(); if (parameterTypes.length > 0) { if (expectedParameters == null) { throw new AssertionError(clazz + " has non-default constructor with some parameters"); } else { if (!Arrays.equals(parameterTypes, expectedParameters)) { throw new AssertionError("Expected constructor with parameters " + getReadableClassesOutput(expectedParameters) + " but found constructor with parameters " + getReadableClassesOutput(parameterTypes)); } else { return; } } } try { constructor.newInstance(); } catch (InstantiationException e) { throw new RuntimeException("Can not instantiate instance of " + clazz, e); } catch (IllegalAccessException e) { // Fixed by setAccessible(true) throw new RuntimeException(e); } catch (InvocationTargetException e) { final Throwable cause = e.getCause(); // It's okay case if we expect some exception from this constructor if (expectedTypeOfException != null || expectedExceptionMessage != null) { if (expectedTypeOfException != null && !expectedTypeOfException.equals(cause.getClass())) { throw new IllegalStateException("For " + clazz + " expected exception of type = " + expectedTypeOfException + ", but was exception of type = " + e.getCause().getClass()); } if (expectedExceptionMessage != null && !expectedExceptionMessage.equals(cause.getMessage())) { throw new IllegalStateException("For " + clazz + " expected exception message = '" + expectedExceptionMessage + "', but was = '" + cause.getMessage() + "'", e.getCause()); } // Everything is okay } else { throw new IllegalStateException("For " + clazz + " no exception was expected", e); } } catch (IllegalArgumentException e) { throw new RuntimeException("Looks like constructor of " + clazz + " is not default", e); } }
java
private void check(Class clazz) { final Constructor<?>[] constructors = clazz.getDeclaredConstructors(); if (constructors.length > 1) { throw new AssertionError(clazz + " has more than one constructor"); } final Constructor<?> constructor = constructors[0]; constructor.setAccessible(true); if (!Modifier.isPrivate(constructor.getModifiers())) { throw new AssertionError("Constructor of " + clazz + " must be private"); } final Class<?>[] parameterTypes = constructor.getParameterTypes(); if (parameterTypes.length > 0) { if (expectedParameters == null) { throw new AssertionError(clazz + " has non-default constructor with some parameters"); } else { if (!Arrays.equals(parameterTypes, expectedParameters)) { throw new AssertionError("Expected constructor with parameters " + getReadableClassesOutput(expectedParameters) + " but found constructor with parameters " + getReadableClassesOutput(parameterTypes)); } else { return; } } } try { constructor.newInstance(); } catch (InstantiationException e) { throw new RuntimeException("Can not instantiate instance of " + clazz, e); } catch (IllegalAccessException e) { // Fixed by setAccessible(true) throw new RuntimeException(e); } catch (InvocationTargetException e) { final Throwable cause = e.getCause(); // It's okay case if we expect some exception from this constructor if (expectedTypeOfException != null || expectedExceptionMessage != null) { if (expectedTypeOfException != null && !expectedTypeOfException.equals(cause.getClass())) { throw new IllegalStateException("For " + clazz + " expected exception of type = " + expectedTypeOfException + ", but was exception of type = " + e.getCause().getClass()); } if (expectedExceptionMessage != null && !expectedExceptionMessage.equals(cause.getMessage())) { throw new IllegalStateException("For " + clazz + " expected exception message = '" + expectedExceptionMessage + "', but was = '" + cause.getMessage() + "'", e.getCause()); } // Everything is okay } else { throw new IllegalStateException("For " + clazz + " no exception was expected", e); } } catch (IllegalArgumentException e) { throw new RuntimeException("Looks like constructor of " + clazz + " is not default", e); } }
[ "private", "void", "check", "(", "Class", "clazz", ")", "{", "final", "Constructor", "<", "?", ">", "[", "]", "constructors", "=", "clazz", ".", "getDeclaredConstructors", "(", ")", ";", "if", "(", "constructors", ".", "length", ">", "1", ")", "{", "throw", "new", "AssertionError", "(", "clazz", "+", "\" has more than one constructor\"", ")", ";", "}", "final", "Constructor", "<", "?", ">", "constructor", "=", "constructors", "[", "0", "]", ";", "constructor", ".", "setAccessible", "(", "true", ")", ";", "if", "(", "!", "Modifier", ".", "isPrivate", "(", "constructor", ".", "getModifiers", "(", ")", ")", ")", "{", "throw", "new", "AssertionError", "(", "\"Constructor of \"", "+", "clazz", "+", "\" must be private\"", ")", ";", "}", "final", "Class", "<", "?", ">", "[", "]", "parameterTypes", "=", "constructor", ".", "getParameterTypes", "(", ")", ";", "if", "(", "parameterTypes", ".", "length", ">", "0", ")", "{", "if", "(", "expectedParameters", "==", "null", ")", "{", "throw", "new", "AssertionError", "(", "clazz", "+", "\" has non-default constructor with some parameters\"", ")", ";", "}", "else", "{", "if", "(", "!", "Arrays", ".", "equals", "(", "parameterTypes", ",", "expectedParameters", ")", ")", "{", "throw", "new", "AssertionError", "(", "\"Expected constructor with parameters \"", "+", "getReadableClassesOutput", "(", "expectedParameters", ")", "+", "\" but found constructor with parameters \"", "+", "getReadableClassesOutput", "(", "parameterTypes", ")", ")", ";", "}", "else", "{", "return", ";", "}", "}", "}", "try", "{", "constructor", ".", "newInstance", "(", ")", ";", "}", "catch", "(", "InstantiationException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "\"Can not instantiate instance of \"", "+", "clazz", ",", "e", ")", ";", "}", "catch", "(", "IllegalAccessException", "e", ")", "{", "// Fixed by setAccessible(true)", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "catch", "(", "InvocationTargetException", "e", ")", "{", "final", "Throwable", "cause", "=", "e", ".", "getCause", "(", ")", ";", "// It's okay case if we expect some exception from this constructor", "if", "(", "expectedTypeOfException", "!=", "null", "||", "expectedExceptionMessage", "!=", "null", ")", "{", "if", "(", "expectedTypeOfException", "!=", "null", "&&", "!", "expectedTypeOfException", ".", "equals", "(", "cause", ".", "getClass", "(", ")", ")", ")", "{", "throw", "new", "IllegalStateException", "(", "\"For \"", "+", "clazz", "+", "\" expected exception of type = \"", "+", "expectedTypeOfException", "+", "\", but was exception of type = \"", "+", "e", ".", "getCause", "(", ")", ".", "getClass", "(", ")", ")", ";", "}", "if", "(", "expectedExceptionMessage", "!=", "null", "&&", "!", "expectedExceptionMessage", ".", "equals", "(", "cause", ".", "getMessage", "(", ")", ")", ")", "{", "throw", "new", "IllegalStateException", "(", "\"For \"", "+", "clazz", "+", "\" expected exception message = '\"", "+", "expectedExceptionMessage", "+", "\"', but was = '\"", "+", "cause", ".", "getMessage", "(", ")", "+", "\"'\"", ",", "e", ".", "getCause", "(", ")", ")", ";", "}", "// Everything is okay", "}", "else", "{", "throw", "new", "IllegalStateException", "(", "\"For \"", "+", "clazz", "+", "\" no exception was expected\"", ",", "e", ")", ";", "}", "}", "catch", "(", "IllegalArgumentException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "\"Looks like constructor of \"", "+", "clazz", "+", "\" is not default\"", ",", "e", ")", ";", "}", "}" ]
Runs the check which will assert that particular class has one private constructor which throws or not throws exception. @param clazz class that needs to be checked.
[ "Runs", "the", "check", "which", "will", "assert", "that", "particular", "class", "has", "one", "private", "constructor", "which", "throws", "or", "not", "throws", "exception", "." ]
5214f94bc4967fad338a75351addef7261ff218a
https://github.com/pushtorefresh/java-private-constructor-checker/blob/5214f94bc4967fad338a75351addef7261ff218a/checker/src/main/java/com/pushtorefresh/private_constructor_checker/PrivateConstructorChecker.java#L173-L230
9,329
jboss/jboss-servlet-api_spec
src/main/java/javax/servlet/ServletSecurityElement.java
ServletSecurityElement.checkMethodNames
private Collection<String> checkMethodNames( Collection<HttpMethodConstraintElement> methodConstraints) { Collection<String> methodNames = new HashSet<String>(); for (HttpMethodConstraintElement methodConstraint : methodConstraints) { String methodName = methodConstraint.getMethodName(); if (!methodNames.add(methodName)) { throw new IllegalArgumentException( "Duplicate HTTP method name: " + methodName); } } return methodNames; }
java
private Collection<String> checkMethodNames( Collection<HttpMethodConstraintElement> methodConstraints) { Collection<String> methodNames = new HashSet<String>(); for (HttpMethodConstraintElement methodConstraint : methodConstraints) { String methodName = methodConstraint.getMethodName(); if (!methodNames.add(methodName)) { throw new IllegalArgumentException( "Duplicate HTTP method name: " + methodName); } } return methodNames; }
[ "private", "Collection", "<", "String", ">", "checkMethodNames", "(", "Collection", "<", "HttpMethodConstraintElement", ">", "methodConstraints", ")", "{", "Collection", "<", "String", ">", "methodNames", "=", "new", "HashSet", "<", "String", ">", "(", ")", ";", "for", "(", "HttpMethodConstraintElement", "methodConstraint", ":", "methodConstraints", ")", "{", "String", "methodName", "=", "methodConstraint", ".", "getMethodName", "(", ")", ";", "if", "(", "!", "methodNames", ".", "add", "(", "methodName", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Duplicate HTTP method name: \"", "+", "methodName", ")", ";", "}", "}", "return", "methodNames", ";", "}" ]
Checks for duplicate method names in methodConstraints. @param methodConstraints @retrun Set of method names @throws IllegalArgumentException if duplicate method names are detected
[ "Checks", "for", "duplicate", "method", "names", "in", "methodConstraints", "." ]
5bc96f2b833c072baff6eb8ae49bc7b5e503e9b2
https://github.com/jboss/jboss-servlet-api_spec/blob/5bc96f2b833c072baff6eb8ae49bc7b5e503e9b2/src/main/java/javax/servlet/ServletSecurityElement.java#L189-L201
9,330
bramp/objectgraph
src/main/java/net/bramp/objectgraph/ObjectGraph.java
ObjectGraph.excludeClasses
public ObjectGraph excludeClasses(Class<?>... classes) { for (Class<?> c : classes) { if (c == null) { throw new NullPointerException("Null class not allowed"); } excludedClasses.add(c); } return this; }
java
public ObjectGraph excludeClasses(Class<?>... classes) { for (Class<?> c : classes) { if (c == null) { throw new NullPointerException("Null class not allowed"); } excludedClasses.add(c); } return this; }
[ "public", "ObjectGraph", "excludeClasses", "(", "Class", "<", "?", ">", "...", "classes", ")", "{", "for", "(", "Class", "<", "?", ">", "c", ":", "classes", ")", "{", "if", "(", "c", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", "\"Null class not allowed\"", ")", ";", "}", "excludedClasses", ".", "add", "(", "c", ")", ";", "}", "return", "this", ";", "}" ]
Exclude any object that extends from these classes. @param classes to exclude. @return this
[ "Exclude", "any", "object", "that", "extends", "from", "these", "classes", "." ]
99be3a76db934f5fb33c0dccd974592cab5761d1
https://github.com/bramp/objectgraph/blob/99be3a76db934f5fb33c0dccd974592cab5761d1/src/main/java/net/bramp/objectgraph/ObjectGraph.java#L102-L110
9,331
bramp/objectgraph
src/main/java/net/bramp/objectgraph/ObjectGraph.java
ObjectGraph.traverse
public void traverse(Object root) { // Reset the state visited.clear(); toVisit.clear(); if (root == null) return; addIfNotVisited(root, root.getClass()); start(); }
java
public void traverse(Object root) { // Reset the state visited.clear(); toVisit.clear(); if (root == null) return; addIfNotVisited(root, root.getClass()); start(); }
[ "public", "void", "traverse", "(", "Object", "root", ")", "{", "// Reset the state", "visited", ".", "clear", "(", ")", ";", "toVisit", ".", "clear", "(", ")", ";", "if", "(", "root", "==", "null", ")", "return", ";", "addIfNotVisited", "(", "root", ",", "root", ".", "getClass", "(", ")", ")", ";", "start", "(", ")", ";", "}" ]
Conducts a breath first search of the object graph. @param root the object to start at.
[ "Conducts", "a", "breath", "first", "search", "of", "the", "object", "graph", "." ]
99be3a76db934f5fb33c0dccd974592cab5761d1
https://github.com/bramp/objectgraph/blob/99be3a76db934f5fb33c0dccd974592cab5761d1/src/main/java/net/bramp/objectgraph/ObjectGraph.java#L117-L126
9,332
bramp/objectgraph
src/main/java/net/bramp/objectgraph/ObjectGraph.java
ObjectGraph.isExcludedClass
private boolean isExcludedClass(Class<?> clazz) { for (Class<?> c : excludedClasses) { if (c.isAssignableFrom(clazz)) { return true; } } return false; }
java
private boolean isExcludedClass(Class<?> clazz) { for (Class<?> c : excludedClasses) { if (c.isAssignableFrom(clazz)) { return true; } } return false; }
[ "private", "boolean", "isExcludedClass", "(", "Class", "<", "?", ">", "clazz", ")", "{", "for", "(", "Class", "<", "?", ">", "c", ":", "excludedClasses", ")", "{", "if", "(", "c", ".", "isAssignableFrom", "(", "clazz", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Is the class on the excluded list. @param clazz @return
[ "Is", "the", "class", "on", "the", "excluded", "list", "." ]
99be3a76db934f5fb33c0dccd974592cab5761d1
https://github.com/bramp/objectgraph/blob/99be3a76db934f5fb33c0dccd974592cab5761d1/src/main/java/net/bramp/objectgraph/ObjectGraph.java#L146-L153
9,333
bramp/objectgraph
src/main/java/net/bramp/objectgraph/ObjectGraph.java
ObjectGraph.addIfNotVisited
private void addIfNotVisited(Object object, Class<?> clazz) { if (object != null && !visited.containsKey(object)) { toVisit.add(object); visited.put(object, clazz); } }
java
private void addIfNotVisited(Object object, Class<?> clazz) { if (object != null && !visited.containsKey(object)) { toVisit.add(object); visited.put(object, clazz); } }
[ "private", "void", "addIfNotVisited", "(", "Object", "object", ",", "Class", "<", "?", ">", "clazz", ")", "{", "if", "(", "object", "!=", "null", "&&", "!", "visited", ".", "containsKey", "(", "object", ")", ")", "{", "toVisit", ".", "add", "(", "object", ")", ";", "visited", ".", "put", "(", "object", ",", "clazz", ")", ";", "}", "}" ]
Add this object to be visited if it has not already been visited, or scheduled to be. @param object The object @param clazz The type of the field
[ "Add", "this", "object", "to", "be", "visited", "if", "it", "has", "not", "already", "been", "visited", "or", "scheduled", "to", "be", "." ]
99be3a76db934f5fb33c0dccd974592cab5761d1
https://github.com/bramp/objectgraph/blob/99be3a76db934f5fb33c0dccd974592cab5761d1/src/main/java/net/bramp/objectgraph/ObjectGraph.java#L161-L166
9,334
bramp/objectgraph
src/main/java/net/bramp/objectgraph/ObjectGraph.java
ObjectGraph.getAllFields
private List<Field> getAllFields(List<Field> fields, Class<?> clazz) { // TODO consider caching the results of this. checkNotNull(fields); checkNotNull(clazz); fields.addAll(Arrays.asList(clazz.getDeclaredFields())); if (clazz.getSuperclass() != null) { getAllFields(fields, clazz.getSuperclass()); } return Collections.unmodifiableList(fields); }
java
private List<Field> getAllFields(List<Field> fields, Class<?> clazz) { // TODO consider caching the results of this. checkNotNull(fields); checkNotNull(clazz); fields.addAll(Arrays.asList(clazz.getDeclaredFields())); if (clazz.getSuperclass() != null) { getAllFields(fields, clazz.getSuperclass()); } return Collections.unmodifiableList(fields); }
[ "private", "List", "<", "Field", ">", "getAllFields", "(", "List", "<", "Field", ">", "fields", ",", "Class", "<", "?", ">", "clazz", ")", "{", "// TODO consider caching the results of this.", "checkNotNull", "(", "fields", ")", ";", "checkNotNull", "(", "clazz", ")", ";", "fields", ".", "addAll", "(", "Arrays", ".", "asList", "(", "clazz", ".", "getDeclaredFields", "(", ")", ")", ")", ";", "if", "(", "clazz", ".", "getSuperclass", "(", ")", "!=", "null", ")", "{", "getAllFields", "(", "fields", ",", "clazz", ".", "getSuperclass", "(", ")", ")", ";", "}", "return", "Collections", ".", "unmodifiableList", "(", "fields", ")", ";", "}" ]
Return all declared and inherited fields for this class. @param fields @param clazz @return
[ "Return", "all", "declared", "and", "inherited", "fields", "for", "this", "class", "." ]
99be3a76db934f5fb33c0dccd974592cab5761d1
https://github.com/bramp/objectgraph/blob/99be3a76db934f5fb33c0dccd974592cab5761d1/src/main/java/net/bramp/objectgraph/ObjectGraph.java#L175-L187
9,335
mojohaus/tidy-maven-plugin
src/main/java/org/codehaus/mojo/tidy/task/FormatIdentifier.java
FormatIdentifier.identifyFormat
Format identifyFormat( String pom ) { for ( String separator : LINE_SEPARATORS ) { if ( pom.contains( separator ) ) { return new Format( separator ); } } throw new IllegalArgumentException( "The pom.xml has no known line separator." ); }
java
Format identifyFormat( String pom ) { for ( String separator : LINE_SEPARATORS ) { if ( pom.contains( separator ) ) { return new Format( separator ); } } throw new IllegalArgumentException( "The pom.xml has no known line separator." ); }
[ "Format", "identifyFormat", "(", "String", "pom", ")", "{", "for", "(", "String", "separator", ":", "LINE_SEPARATORS", ")", "{", "if", "(", "pom", ".", "contains", "(", "separator", ")", ")", "{", "return", "new", "Format", "(", "separator", ")", ";", "}", "}", "throw", "new", "IllegalArgumentException", "(", "\"The pom.xml has no known line separator.\"", ")", ";", "}" ]
Identifies the output format for the given POM. @param pom the POM. @return the output format.
[ "Identifies", "the", "output", "format", "for", "the", "given", "POM", "." ]
191b53ea4a06f9f6f0aa524355560d5d23fe716a
https://github.com/mojohaus/tidy-maven-plugin/blob/191b53ea4a06f9f6f0aa524355560d5d23fe716a/src/main/java/org/codehaus/mojo/tidy/task/FormatIdentifier.java#L40-L51
9,336
luontola/jumi
jumi-core/src/main/java/fi/jumi/core/network/NettyNetworkEndpointAdapter.java
NettyNetworkEndpointAdapter.channelClosed
@Override public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { endpoint.onDisconnected(); super.channelClosed(ctx, e); }
java
@Override public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { endpoint.onDisconnected(); super.channelClosed(ctx, e); }
[ "@", "Override", "public", "void", "channelClosed", "(", "ChannelHandlerContext", "ctx", ",", "ChannelStateEvent", "e", ")", "throws", "Exception", "{", "endpoint", ".", "onDisconnected", "(", ")", ";", "super", ".", "channelClosed", "(", "ctx", ",", "e", ")", ";", "}" ]
of those events comes, even though the channelConnected came. Using just channelClosed appears to be reliable.
[ "of", "those", "events", "comes", "even", "though", "the", "channelConnected", "came", ".", "Using", "just", "channelClosed", "appears", "to", "be", "reliable", "." ]
18815c499b770f51cdb58cc6720dca4f254b2019
https://github.com/luontola/jumi/blob/18815c499b770f51cdb58cc6720dca4f254b2019/jumi-core/src/main/java/fi/jumi/core/network/NettyNetworkEndpointAdapter.java#L37-L41
9,337
TextRazor/textrazor-java
src/com/textrazor/TextRazor.java
TextRazor.analyze
public AnalyzedText analyze(String text) throws NetworkException, AnalysisException { if (null == text) { throw new RuntimeException("text param cannot be null."); } QueryBuilder requestBody = generatePOSTBody(); try { requestBody.addParam("text", text); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Could not url encode form params."); } AnalyzedText response = sendRequest( "", requestBody.build(), ContentType.FORM, "POST", AnalyzedText.class); response.createAnnotationLinks(); return response; }
java
public AnalyzedText analyze(String text) throws NetworkException, AnalysisException { if (null == text) { throw new RuntimeException("text param cannot be null."); } QueryBuilder requestBody = generatePOSTBody(); try { requestBody.addParam("text", text); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Could not url encode form params."); } AnalyzedText response = sendRequest( "", requestBody.build(), ContentType.FORM, "POST", AnalyzedText.class); response.createAnnotationLinks(); return response; }
[ "public", "AnalyzedText", "analyze", "(", "String", "text", ")", "throws", "NetworkException", ",", "AnalysisException", "{", "if", "(", "null", "==", "text", ")", "{", "throw", "new", "RuntimeException", "(", "\"text param cannot be null.\"", ")", ";", "}", "QueryBuilder", "requestBody", "=", "generatePOSTBody", "(", ")", ";", "try", "{", "requestBody", ".", "addParam", "(", "\"text\"", ",", "text", ")", ";", "}", "catch", "(", "UnsupportedEncodingException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "\"Could not url encode form params.\"", ")", ";", "}", "AnalyzedText", "response", "=", "sendRequest", "(", "\"\"", ",", "requestBody", ".", "build", "(", ")", ",", "ContentType", ".", "FORM", ",", "\"POST\"", ",", "AnalyzedText", ".", "class", ")", ";", "response", ".", "createAnnotationLinks", "(", ")", ";", "return", "response", ";", "}" ]
Makes a TextRazor request to analyze a string and returning TextRazor metadata. @param text The content to analyze @return The TextRazor metadata @throws NetworkException @throws AnalysisException
[ "Makes", "a", "TextRazor", "request", "to", "analyze", "a", "string", "and", "returning", "TextRazor", "metadata", "." ]
27b72101f375501e9d21bb6340470b51c2178fda
https://github.com/TextRazor/textrazor-java/blob/27b72101f375501e9d21bb6340470b51c2178fda/src/com/textrazor/TextRazor.java#L86-L110
9,338
TextRazor/textrazor-java
src/com/textrazor/TextRazor.java
TextRazor.addExtractor
public void addExtractor(String extractor) { if (null == this.extractors) { this.extractors = new ArrayList<String>(); } this.extractors.add(extractor); }
java
public void addExtractor(String extractor) { if (null == this.extractors) { this.extractors = new ArrayList<String>(); } this.extractors.add(extractor); }
[ "public", "void", "addExtractor", "(", "String", "extractor", ")", "{", "if", "(", "null", "==", "this", ".", "extractors", ")", "{", "this", ".", "extractors", "=", "new", "ArrayList", "<", "String", ">", "(", ")", ";", "}", "this", ".", "extractors", ".", "add", "(", "extractor", ")", ";", "}" ]
Adds a new "extractor" to the request. @param extractor The new extractor name
[ "Adds", "a", "new", "extractor", "to", "the", "request", "." ]
27b72101f375501e9d21bb6340470b51c2178fda
https://github.com/TextRazor/textrazor-java/blob/27b72101f375501e9d21bb6340470b51c2178fda/src/com/textrazor/TextRazor.java#L253-L259
9,339
sonatype/plexus-cipher
src/main/java/org/sonatype/plexus/components/cipher/DefaultPlexusCipher.java
DefaultPlexusCipher.getServiceTypes
public static String[] getServiceTypes() { Set result = new HashSet(); // All all providers Provider[] providers = Security.getProviders(); for ( int i = 0; i < providers.length; i++ ) { // Get services provided by each provider Set keys = providers[i].keySet(); for ( Iterator it = keys.iterator(); it.hasNext(); ) { String key = (String) it.next(); key = key.split( " " )[0]; if ( key.startsWith( "Alg.Alias." ) ) { // Strip the alias key = key.substring( 10 ); } int ix = key.indexOf( '.' ); result.add( key.substring( 0, ix ) ); } } return (String[]) result.toArray( new String[result.size()] ); }
java
public static String[] getServiceTypes() { Set result = new HashSet(); // All all providers Provider[] providers = Security.getProviders(); for ( int i = 0; i < providers.length; i++ ) { // Get services provided by each provider Set keys = providers[i].keySet(); for ( Iterator it = keys.iterator(); it.hasNext(); ) { String key = (String) it.next(); key = key.split( " " )[0]; if ( key.startsWith( "Alg.Alias." ) ) { // Strip the alias key = key.substring( 10 ); } int ix = key.indexOf( '.' ); result.add( key.substring( 0, ix ) ); } } return (String[]) result.toArray( new String[result.size()] ); }
[ "public", "static", "String", "[", "]", "getServiceTypes", "(", ")", "{", "Set", "result", "=", "new", "HashSet", "(", ")", ";", "// All all providers", "Provider", "[", "]", "providers", "=", "Security", ".", "getProviders", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "providers", ".", "length", ";", "i", "++", ")", "{", "// Get services provided by each provider", "Set", "keys", "=", "providers", "[", "i", "]", ".", "keySet", "(", ")", ";", "for", "(", "Iterator", "it", "=", "keys", ".", "iterator", "(", ")", ";", "it", ".", "hasNext", "(", ")", ";", ")", "{", "String", "key", "=", "(", "String", ")", "it", ".", "next", "(", ")", ";", "key", "=", "key", ".", "split", "(", "\" \"", ")", "[", "0", "]", ";", "if", "(", "key", ".", "startsWith", "(", "\"Alg.Alias.\"", ")", ")", "{", "// Strip the alias", "key", "=", "key", ".", "substring", "(", "10", ")", ";", "}", "int", "ix", "=", "key", ".", "indexOf", "(", "'", "'", ")", ";", "result", ".", "add", "(", "key", ".", "substring", "(", "0", ",", "ix", ")", ")", ";", "}", "}", "return", "(", "String", "[", "]", ")", "result", ".", "toArray", "(", "new", "String", "[", "result", ".", "size", "(", ")", "]", ")", ";", "}" ]
Exploratory part. This method returns all available services types
[ "Exploratory", "part", ".", "This", "method", "returns", "all", "available", "services", "types" ]
0cff29e6b2ee2a3dbd72d289d7f2b7922d000778
https://github.com/sonatype/plexus-cipher/blob/0cff29e6b2ee2a3dbd72d289d7f2b7922d000778/src/main/java/org/sonatype/plexus/components/cipher/DefaultPlexusCipher.java#L137-L162
9,340
mojohaus/tidy-maven-plugin
src/main/java/org/codehaus/mojo/tidy/TidyMojo.java
TidyMojo.tidy
protected String tidy( String pom ) throws MojoExecutionException { try { return POM_TIDY.tidy( pom ); } catch ( XMLStreamException e ) { throw new MojoExecutionException( e.getMessage(), e ); } }
java
protected String tidy( String pom ) throws MojoExecutionException { try { return POM_TIDY.tidy( pom ); } catch ( XMLStreamException e ) { throw new MojoExecutionException( e.getMessage(), e ); } }
[ "protected", "String", "tidy", "(", "String", "pom", ")", "throws", "MojoExecutionException", "{", "try", "{", "return", "POM_TIDY", ".", "tidy", "(", "pom", ")", ";", "}", "catch", "(", "XMLStreamException", "e", ")", "{", "throw", "new", "MojoExecutionException", "(", "e", ".", "getMessage", "(", ")", ",", "e", ")", ";", "}", "}" ]
Tidy the given POM.
[ "Tidy", "the", "given", "POM", "." ]
191b53ea4a06f9f6f0aa524355560d5d23fe716a
https://github.com/mojohaus/tidy-maven-plugin/blob/191b53ea4a06f9f6f0aa524355560d5d23fe716a/src/main/java/org/codehaus/mojo/tidy/TidyMojo.java#L108-L119
9,341
zackpollard/JavaTelegramBot-API
menus/src/main/java/pro/zackpollard/telegrambot/api/menu/InlineMenuRowBuilder.java
InlineMenuRowBuilder.removeLast
public InlineMenuRowBuilder removeLast() { List<InlineMenuButton> buttons = buttons(); if (buttons.size() != 0) buttons.remove(buttons.size() - 1); return this; }
java
public InlineMenuRowBuilder removeLast() { List<InlineMenuButton> buttons = buttons(); if (buttons.size() != 0) buttons.remove(buttons.size() - 1); return this; }
[ "public", "InlineMenuRowBuilder", "removeLast", "(", ")", "{", "List", "<", "InlineMenuButton", ">", "buttons", "=", "buttons", "(", ")", ";", "if", "(", "buttons", ".", "size", "(", ")", "!=", "0", ")", "buttons", ".", "remove", "(", "buttons", ".", "size", "(", ")", "-", "1", ")", ";", "return", "this", ";", "}" ]
Remove the last button in the stack @return this
[ "Remove", "the", "last", "button", "in", "the", "stack" ]
9d100f351824042ca5fc0ea735d1fa376a13e81d
https://github.com/zackpollard/JavaTelegramBot-API/blob/9d100f351824042ca5fc0ea735d1fa376a13e81d/menus/src/main/java/pro/zackpollard/telegrambot/api/menu/InlineMenuRowBuilder.java#L136-L143
9,342
zackpollard/JavaTelegramBot-API
conversations/src/main/java/pro/zackpollard/telegrambot/api/conversations/Conversation.java
Conversation.begin
public Conversation begin() { if (!virgin) { throw new IllegalStateException("You can only start a virgin conversation!"); } Extensions.get(context.getBot(), ConversationRegistry.class).registerConversation(this); if (!silent) { SendableMessage response = currentPrompt.promptMessage(context); if (response != null) { sendMessage(response); } } return this; }
java
public Conversation begin() { if (!virgin) { throw new IllegalStateException("You can only start a virgin conversation!"); } Extensions.get(context.getBot(), ConversationRegistry.class).registerConversation(this); if (!silent) { SendableMessage response = currentPrompt.promptMessage(context); if (response != null) { sendMessage(response); } } return this; }
[ "public", "Conversation", "begin", "(", ")", "{", "if", "(", "!", "virgin", ")", "{", "throw", "new", "IllegalStateException", "(", "\"You can only start a virgin conversation!\"", ")", ";", "}", "Extensions", ".", "get", "(", "context", ".", "getBot", "(", ")", ",", "ConversationRegistry", ".", "class", ")", ".", "registerConversation", "(", "this", ")", ";", "if", "(", "!", "silent", ")", "{", "SendableMessage", "response", "=", "currentPrompt", ".", "promptMessage", "(", "context", ")", ";", "if", "(", "response", "!=", "null", ")", "{", "sendMessage", "(", "response", ")", ";", "}", "}", "return", "this", ";", "}" ]
Initiates the conversation with the first prompt, registers the conversation in the registry. @return The current conversation
[ "Initiates", "the", "conversation", "with", "the", "first", "prompt", "registers", "the", "conversation", "in", "the", "registry", "." ]
9d100f351824042ca5fc0ea735d1fa376a13e81d
https://github.com/zackpollard/JavaTelegramBot-API/blob/9d100f351824042ca5fc0ea735d1fa376a13e81d/conversations/src/main/java/pro/zackpollard/telegrambot/api/conversations/Conversation.java#L148-L164
9,343
zackpollard/JavaTelegramBot-API
conversations/src/main/java/pro/zackpollard/telegrambot/api/conversations/Conversation.java
Conversation.end
public void end() { if (endCallback != null) { endCallback.accept(this, context); } if (currentPrompt != null) { currentPrompt.conversationEnded(context); currentPrompt = null; } Extensions.get(context.getBot(), ConversationRegistry.class).removeConversation(this); virgin = false; }
java
public void end() { if (endCallback != null) { endCallback.accept(this, context); } if (currentPrompt != null) { currentPrompt.conversationEnded(context); currentPrompt = null; } Extensions.get(context.getBot(), ConversationRegistry.class).removeConversation(this); virgin = false; }
[ "public", "void", "end", "(", ")", "{", "if", "(", "endCallback", "!=", "null", ")", "{", "endCallback", ".", "accept", "(", "this", ",", "context", ")", ";", "}", "if", "(", "currentPrompt", "!=", "null", ")", "{", "currentPrompt", ".", "conversationEnded", "(", "context", ")", ";", "currentPrompt", "=", "null", ";", "}", "Extensions", ".", "get", "(", "context", ".", "getBot", "(", ")", ",", "ConversationRegistry", ".", "class", ")", ".", "removeConversation", "(", "this", ")", ";", "virgin", "=", "false", ";", "}" ]
Calls the conversation end method of the current prompt, and removes conversation from registry. @see ConversationPrompt#conversationEnded(ConversationContext)
[ "Calls", "the", "conversation", "end", "method", "of", "the", "current", "prompt", "and", "removes", "conversation", "from", "registry", "." ]
9d100f351824042ca5fc0ea735d1fa376a13e81d
https://github.com/zackpollard/JavaTelegramBot-API/blob/9d100f351824042ca5fc0ea735d1fa376a13e81d/conversations/src/main/java/pro/zackpollard/telegrambot/api/conversations/Conversation.java#L224-L236
9,344
zackpollard/JavaTelegramBot-API
core/src/main/java/pro/zackpollard/telegrambot/api/TelegramBot.java
TelegramBot.login
public static TelegramBot login(String authToken) { try { HttpRequestWithBody request = Unirest.post(API_URL + "bot" + authToken + "/getMe"); HttpResponse<String> response = request.asString(); JSONObject jsonResponse = Utils.processResponse(response); if (jsonResponse != null && Utils.checkResponseStatus(jsonResponse)) { JSONObject result = jsonResponse.getJSONObject("result"); return new TelegramBot(authToken, result.getInt("id"), result.getString("first_name"), result.getString("username")); } } catch (UnirestException e) { e.printStackTrace(); } return null; }
java
public static TelegramBot login(String authToken) { try { HttpRequestWithBody request = Unirest.post(API_URL + "bot" + authToken + "/getMe"); HttpResponse<String> response = request.asString(); JSONObject jsonResponse = Utils.processResponse(response); if (jsonResponse != null && Utils.checkResponseStatus(jsonResponse)) { JSONObject result = jsonResponse.getJSONObject("result"); return new TelegramBot(authToken, result.getInt("id"), result.getString("first_name"), result.getString("username")); } } catch (UnirestException e) { e.printStackTrace(); } return null; }
[ "public", "static", "TelegramBot", "login", "(", "String", "authToken", ")", "{", "try", "{", "HttpRequestWithBody", "request", "=", "Unirest", ".", "post", "(", "API_URL", "+", "\"bot\"", "+", "authToken", "+", "\"/getMe\"", ")", ";", "HttpResponse", "<", "String", ">", "response", "=", "request", ".", "asString", "(", ")", ";", "JSONObject", "jsonResponse", "=", "Utils", ".", "processResponse", "(", "response", ")", ";", "if", "(", "jsonResponse", "!=", "null", "&&", "Utils", ".", "checkResponseStatus", "(", "jsonResponse", ")", ")", "{", "JSONObject", "result", "=", "jsonResponse", ".", "getJSONObject", "(", "\"result\"", ")", ";", "return", "new", "TelegramBot", "(", "authToken", ",", "result", ".", "getInt", "(", "\"id\"", ")", ",", "result", ".", "getString", "(", "\"first_name\"", ")", ",", "result", ".", "getString", "(", "\"username\"", ")", ")", ";", "}", "}", "catch", "(", "UnirestException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "return", "null", ";", "}" ]
Use this method to get a new TelegramBot instance with the selected auth token @param authToken The bots auth token @return A new TelegramBot instance or null if something failed
[ "Use", "this", "method", "to", "get", "a", "new", "TelegramBot", "instance", "with", "the", "selected", "auth", "token" ]
9d100f351824042ca5fc0ea735d1fa376a13e81d
https://github.com/zackpollard/JavaTelegramBot-API/blob/9d100f351824042ca5fc0ea735d1fa376a13e81d/core/src/main/java/pro/zackpollard/telegrambot/api/TelegramBot.java#L90-L109
9,345
zackpollard/JavaTelegramBot-API
core/src/main/java/pro/zackpollard/telegrambot/api/TelegramBot.java
TelegramBot.getChat
public Chat getChat(String chatID) { try { MultipartBody request = Unirest.post(getBotAPIUrl() + "getChat") .field("chat_id", chatID, "application/json; charset=utf8;"); HttpResponse<String> response = request.asString(); JSONObject jsonResponse = Utils.processResponse(response); if (jsonResponse != null && Utils.checkResponseStatus(jsonResponse)) { JSONObject result = jsonResponse.getJSONObject("result"); return ChatImpl.createChat(result, this); } } catch (UnirestException e) { e.printStackTrace(); } return null; }
java
public Chat getChat(String chatID) { try { MultipartBody request = Unirest.post(getBotAPIUrl() + "getChat") .field("chat_id", chatID, "application/json; charset=utf8;"); HttpResponse<String> response = request.asString(); JSONObject jsonResponse = Utils.processResponse(response); if (jsonResponse != null && Utils.checkResponseStatus(jsonResponse)) { JSONObject result = jsonResponse.getJSONObject("result"); return ChatImpl.createChat(result, this); } } catch (UnirestException e) { e.printStackTrace(); } return null; }
[ "public", "Chat", "getChat", "(", "String", "chatID", ")", "{", "try", "{", "MultipartBody", "request", "=", "Unirest", ".", "post", "(", "getBotAPIUrl", "(", ")", "+", "\"getChat\"", ")", ".", "field", "(", "\"chat_id\"", ",", "chatID", ",", "\"application/json; charset=utf8;\"", ")", ";", "HttpResponse", "<", "String", ">", "response", "=", "request", ".", "asString", "(", ")", ";", "JSONObject", "jsonResponse", "=", "Utils", ".", "processResponse", "(", "response", ")", ";", "if", "(", "jsonResponse", "!=", "null", "&&", "Utils", ".", "checkResponseStatus", "(", "jsonResponse", ")", ")", "{", "JSONObject", "result", "=", "jsonResponse", ".", "getJSONObject", "(", "\"result\"", ")", ";", "return", "ChatImpl", ".", "createChat", "(", "result", ",", "this", ")", ";", "}", "}", "catch", "(", "UnirestException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "return", "null", ";", "}" ]
A method used to get a Chat object via the chats ID @param chatID The Chat ID of the chat you want a Chat object of @return A Chat object or null if the chat does not exist or you don't have permission to get this chat
[ "A", "method", "used", "to", "get", "a", "Chat", "object", "via", "the", "chats", "ID" ]
9d100f351824042ca5fc0ea735d1fa376a13e81d
https://github.com/zackpollard/JavaTelegramBot-API/blob/9d100f351824042ca5fc0ea735d1fa376a13e81d/core/src/main/java/pro/zackpollard/telegrambot/api/TelegramBot.java#L130-L150
9,346
zackpollard/JavaTelegramBot-API
core/src/main/java/pro/zackpollard/telegrambot/api/TelegramBot.java
TelegramBot.editMessageCaption
public Message editMessageCaption(Message oldMessage, String caption, InlineReplyMarkup inlineReplyMarkup) { return this.editMessageCaption(oldMessage.getChat().getId(), oldMessage.getMessageId(), caption, inlineReplyMarkup); }
java
public Message editMessageCaption(Message oldMessage, String caption, InlineReplyMarkup inlineReplyMarkup) { return this.editMessageCaption(oldMessage.getChat().getId(), oldMessage.getMessageId(), caption, inlineReplyMarkup); }
[ "public", "Message", "editMessageCaption", "(", "Message", "oldMessage", ",", "String", "caption", ",", "InlineReplyMarkup", "inlineReplyMarkup", ")", "{", "return", "this", ".", "editMessageCaption", "(", "oldMessage", ".", "getChat", "(", ")", ".", "getId", "(", ")", ",", "oldMessage", ".", "getMessageId", "(", ")", ",", "caption", ",", "inlineReplyMarkup", ")", ";", "}" ]
This allows you to edit the caption of any captionable message you have sent previously @param oldMessage The Message object that represents the message you want to edit @param caption The new caption you want to display @param inlineReplyMarkup Any InlineReplyMarkup object you want to edit into the message @return A new Message object representing the edited message
[ "This", "allows", "you", "to", "edit", "the", "caption", "of", "any", "captionable", "message", "you", "have", "sent", "previously" ]
9d100f351824042ca5fc0ea735d1fa376a13e81d
https://github.com/zackpollard/JavaTelegramBot-API/blob/9d100f351824042ca5fc0ea735d1fa376a13e81d/core/src/main/java/pro/zackpollard/telegrambot/api/TelegramBot.java#L759-L762
9,347
zackpollard/JavaTelegramBot-API
core/src/main/java/pro/zackpollard/telegrambot/api/TelegramBot.java
TelegramBot.answerInlineQuery
public boolean answerInlineQuery(String inlineQueryId, InlineQueryResponse inlineQueryResponse) { if (inlineQueryId != null && inlineQueryResponse != null) { HttpResponse<String> response; JSONObject jsonResponse; try { MultipartBody requests = Unirest.post(getBotAPIUrl() + "answerInlineQuery") .field("inline_query_id", inlineQueryId) .field("results", GSON.toJson(inlineQueryResponse.getResults())) .field("cache_time", inlineQueryResponse.getCacheTime()) .field("is_personal", inlineQueryResponse.isPersonal()) .field("next_offset", inlineQueryResponse.getNextOffset()) .field("switch_pm_text", inlineQueryResponse.getSwitchPmText()) .field("switch_pm_parameter", inlineQueryResponse.getSwitchPmParameter()); response = requests.asString(); jsonResponse = Utils.processResponse(response); if (jsonResponse != null) { if (jsonResponse.getBoolean("result")) return true; } } catch (UnirestException e) { e.printStackTrace(); } } return false; }
java
public boolean answerInlineQuery(String inlineQueryId, InlineQueryResponse inlineQueryResponse) { if (inlineQueryId != null && inlineQueryResponse != null) { HttpResponse<String> response; JSONObject jsonResponse; try { MultipartBody requests = Unirest.post(getBotAPIUrl() + "answerInlineQuery") .field("inline_query_id", inlineQueryId) .field("results", GSON.toJson(inlineQueryResponse.getResults())) .field("cache_time", inlineQueryResponse.getCacheTime()) .field("is_personal", inlineQueryResponse.isPersonal()) .field("next_offset", inlineQueryResponse.getNextOffset()) .field("switch_pm_text", inlineQueryResponse.getSwitchPmText()) .field("switch_pm_parameter", inlineQueryResponse.getSwitchPmParameter()); response = requests.asString(); jsonResponse = Utils.processResponse(response); if (jsonResponse != null) { if (jsonResponse.getBoolean("result")) return true; } } catch (UnirestException e) { e.printStackTrace(); } } return false; }
[ "public", "boolean", "answerInlineQuery", "(", "String", "inlineQueryId", ",", "InlineQueryResponse", "inlineQueryResponse", ")", "{", "if", "(", "inlineQueryId", "!=", "null", "&&", "inlineQueryResponse", "!=", "null", ")", "{", "HttpResponse", "<", "String", ">", "response", ";", "JSONObject", "jsonResponse", ";", "try", "{", "MultipartBody", "requests", "=", "Unirest", ".", "post", "(", "getBotAPIUrl", "(", ")", "+", "\"answerInlineQuery\"", ")", ".", "field", "(", "\"inline_query_id\"", ",", "inlineQueryId", ")", ".", "field", "(", "\"results\"", ",", "GSON", ".", "toJson", "(", "inlineQueryResponse", ".", "getResults", "(", ")", ")", ")", ".", "field", "(", "\"cache_time\"", ",", "inlineQueryResponse", ".", "getCacheTime", "(", ")", ")", ".", "field", "(", "\"is_personal\"", ",", "inlineQueryResponse", ".", "isPersonal", "(", ")", ")", ".", "field", "(", "\"next_offset\"", ",", "inlineQueryResponse", ".", "getNextOffset", "(", ")", ")", ".", "field", "(", "\"switch_pm_text\"", ",", "inlineQueryResponse", ".", "getSwitchPmText", "(", ")", ")", ".", "field", "(", "\"switch_pm_parameter\"", ",", "inlineQueryResponse", ".", "getSwitchPmParameter", "(", ")", ")", ";", "response", "=", "requests", ".", "asString", "(", ")", ";", "jsonResponse", "=", "Utils", ".", "processResponse", "(", "response", ")", ";", "if", "(", "jsonResponse", "!=", "null", ")", "{", "if", "(", "jsonResponse", ".", "getBoolean", "(", "\"result\"", ")", ")", "return", "true", ";", "}", "}", "catch", "(", "UnirestException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "}", "return", "false", ";", "}" ]
This allows you to respond to an inline query with an InlineQueryResponse object @param inlineQueryId The ID of the inline query you are responding to @param inlineQueryResponse The InlineQueryResponse object that you want to send to the user @return True if the response was sent successfully, otherwise False
[ "This", "allows", "you", "to", "respond", "to", "an", "inline", "query", "with", "an", "InlineQueryResponse", "object" ]
9d100f351824042ca5fc0ea735d1fa376a13e81d
https://github.com/zackpollard/JavaTelegramBot-API/blob/9d100f351824042ca5fc0ea735d1fa376a13e81d/core/src/main/java/pro/zackpollard/telegrambot/api/TelegramBot.java#L935-L965
9,348
zackpollard/JavaTelegramBot-API
core/src/main/java/pro/zackpollard/telegrambot/api/TelegramBot.java
TelegramBot.kickChatMember
public boolean kickChatMember(String chatId, int userId) { HttpResponse<String> response; JSONObject jsonResponse; try { MultipartBody request = Unirest.post(getBotAPIUrl() + "kickChatMember") .field("chat_id", chatId, "application/json; charset=utf8;") .field("user_id", userId); response = request.asString(); jsonResponse = Utils.processResponse(response); if(jsonResponse != null) { if(jsonResponse.getBoolean("result")) return true; } } catch (UnirestException e) { e.printStackTrace(); } return false; }
java
public boolean kickChatMember(String chatId, int userId) { HttpResponse<String> response; JSONObject jsonResponse; try { MultipartBody request = Unirest.post(getBotAPIUrl() + "kickChatMember") .field("chat_id", chatId, "application/json; charset=utf8;") .field("user_id", userId); response = request.asString(); jsonResponse = Utils.processResponse(response); if(jsonResponse != null) { if(jsonResponse.getBoolean("result")) return true; } } catch (UnirestException e) { e.printStackTrace(); } return false; }
[ "public", "boolean", "kickChatMember", "(", "String", "chatId", ",", "int", "userId", ")", "{", "HttpResponse", "<", "String", ">", "response", ";", "JSONObject", "jsonResponse", ";", "try", "{", "MultipartBody", "request", "=", "Unirest", ".", "post", "(", "getBotAPIUrl", "(", ")", "+", "\"kickChatMember\"", ")", ".", "field", "(", "\"chat_id\"", ",", "chatId", ",", "\"application/json; charset=utf8;\"", ")", ".", "field", "(", "\"user_id\"", ",", "userId", ")", ";", "response", "=", "request", ".", "asString", "(", ")", ";", "jsonResponse", "=", "Utils", ".", "processResponse", "(", "response", ")", ";", "if", "(", "jsonResponse", "!=", "null", ")", "{", "if", "(", "jsonResponse", ".", "getBoolean", "(", "\"result\"", ")", ")", "return", "true", ";", "}", "}", "catch", "(", "UnirestException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "return", "false", ";", "}" ]
Use this method to kick a user from a group or a supergroup. In the case of supergroups, the user will not be able to return to the group on their own using invite links, etc., unless unbanned first. The bot must be an administrator in the group for this to work @param chatId The ID of the chat that you want to kick the user from @param userId The ID of the user that you want to kick from the chat @return True if the user was kicked successfully, otherwise False
[ "Use", "this", "method", "to", "kick", "a", "user", "from", "a", "group", "or", "a", "supergroup", ".", "In", "the", "case", "of", "supergroups", "the", "user", "will", "not", "be", "able", "to", "return", "to", "the", "group", "on", "their", "own", "using", "invite", "links", "etc", ".", "unless", "unbanned", "first", ".", "The", "bot", "must", "be", "an", "administrator", "in", "the", "group", "for", "this", "to", "work" ]
9d100f351824042ca5fc0ea735d1fa376a13e81d
https://github.com/zackpollard/JavaTelegramBot-API/blob/9d100f351824042ca5fc0ea735d1fa376a13e81d/core/src/main/java/pro/zackpollard/telegrambot/api/TelegramBot.java#L1036-L1058
9,349
zackpollard/JavaTelegramBot-API
core/src/main/java/pro/zackpollard/telegrambot/api/TelegramBot.java
TelegramBot.startUpdates
public boolean startUpdates(boolean getPreviousUpdates) { if(updateManager == null) updateManager = new RequestUpdatesManager(this, getPreviousUpdates); if(!updateManager.isRunning()) { updateManager.startUpdates(); return true; } return false; }
java
public boolean startUpdates(boolean getPreviousUpdates) { if(updateManager == null) updateManager = new RequestUpdatesManager(this, getPreviousUpdates); if(!updateManager.isRunning()) { updateManager.startUpdates(); return true; } return false; }
[ "public", "boolean", "startUpdates", "(", "boolean", "getPreviousUpdates", ")", "{", "if", "(", "updateManager", "==", "null", ")", "updateManager", "=", "new", "RequestUpdatesManager", "(", "this", ",", "getPreviousUpdates", ")", ";", "if", "(", "!", "updateManager", ".", "isRunning", "(", ")", ")", "{", "updateManager", ".", "startUpdates", "(", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
Use this method to start the update thread which will begin retrieving messages from the API and firing the relevant events for you to process the data @param getPreviousUpdates Whether you want to retrieve any updates that haven't been processed before, but were created prior to calling the startUpdates method @return True if the updater was started, otherwise False
[ "Use", "this", "method", "to", "start", "the", "update", "thread", "which", "will", "begin", "retrieving", "messages", "from", "the", "API", "and", "firing", "the", "relevant", "events", "for", "you", "to", "process", "the", "data" ]
9d100f351824042ca5fc0ea735d1fa376a13e81d
https://github.com/zackpollard/JavaTelegramBot-API/blob/9d100f351824042ca5fc0ea735d1fa376a13e81d/core/src/main/java/pro/zackpollard/telegrambot/api/TelegramBot.java#L1166-L1177
9,350
zackpollard/JavaTelegramBot-API
conversations/src/main/java/pro/zackpollard/telegrambot/api/conversations/prompt/NumericPrompt.java
NumericPrompt.parseNumber
protected Number parseNumber(String text) { if (INTEGER_PATTERN.matcher(text).matches()) { return Integer.parseInt(text); } if (DOUBLE_PATTERN.matcher(text).matches()) { return Double.parseDouble(text); } if (FLOAT_PATTERN.matcher(text).matches()) { return Float.parseFloat(text); } return null; }
java
protected Number parseNumber(String text) { if (INTEGER_PATTERN.matcher(text).matches()) { return Integer.parseInt(text); } if (DOUBLE_PATTERN.matcher(text).matches()) { return Double.parseDouble(text); } if (FLOAT_PATTERN.matcher(text).matches()) { return Float.parseFloat(text); } return null; }
[ "protected", "Number", "parseNumber", "(", "String", "text", ")", "{", "if", "(", "INTEGER_PATTERN", ".", "matcher", "(", "text", ")", ".", "matches", "(", ")", ")", "{", "return", "Integer", ".", "parseInt", "(", "text", ")", ";", "}", "if", "(", "DOUBLE_PATTERN", ".", "matcher", "(", "text", ")", ".", "matches", "(", ")", ")", "{", "return", "Double", ".", "parseDouble", "(", "text", ")", ";", "}", "if", "(", "FLOAT_PATTERN", ".", "matcher", "(", "text", ")", ".", "matches", "(", ")", ")", "{", "return", "Float", ".", "parseFloat", "(", "text", ")", ";", "}", "return", "null", ";", "}" ]
Parses a number that matches the text, null if no matches @param text Text to be parsed as a number @return Number parsed, null if no match @see NumericPrompt#INTEGER_PATTERN @see NumericPrompt#DOUBLE_PATTERN @see NumericPrompt#FLOAT_PATTERN
[ "Parses", "a", "number", "that", "matches", "the", "text", "null", "if", "no", "matches" ]
9d100f351824042ca5fc0ea735d1fa376a13e81d
https://github.com/zackpollard/JavaTelegramBot-API/blob/9d100f351824042ca5fc0ea735d1fa376a13e81d/conversations/src/main/java/pro/zackpollard/telegrambot/api/conversations/prompt/NumericPrompt.java#L57-L71
9,351
zackpollard/JavaTelegramBot-API
conversations/src/main/java/pro/zackpollard/telegrambot/api/conversations/prompt/IgnoringPrompt.java
IgnoringPrompt.create
public static <T extends Content> IgnoringPrompt<T> create(ContentType type, SendableMessage promptMessage) { return new IgnoringPrompt<>(type, promptMessage); }
java
public static <T extends Content> IgnoringPrompt<T> create(ContentType type, SendableMessage promptMessage) { return new IgnoringPrompt<>(type, promptMessage); }
[ "public", "static", "<", "T", "extends", "Content", ">", "IgnoringPrompt", "<", "T", ">", "create", "(", "ContentType", "type", ",", "SendableMessage", "promptMessage", ")", "{", "return", "new", "IgnoringPrompt", "<>", "(", "type", ",", "promptMessage", ")", ";", "}" ]
Creates new prompt @param type The enum representation of T to accept @param promptMessage The message to send before accepting input @param <T> Accepting content type @return New ignoring prompt
[ "Creates", "new", "prompt" ]
9d100f351824042ca5fc0ea735d1fa376a13e81d
https://github.com/zackpollard/JavaTelegramBot-API/blob/9d100f351824042ca5fc0ea735d1fa376a13e81d/conversations/src/main/java/pro/zackpollard/telegrambot/api/conversations/prompt/IgnoringPrompt.java#L31-L33
9,352
zackpollard/JavaTelegramBot-API
menus/src/main/java/pro/zackpollard/telegrambot/api/menu/button/impl/UserInputInlineMenuButton.java
UserInputInlineMenuButton.handlePress
@Override public void handlePress(CallbackQuery query) { executeCallback(); if (textCallback != null && inputGiven) { inputGiven = false; Conversation.builder(query.getBotInstance()) .forWhom(owner.getBaseMessage().getChat()) .silent(true) .prompts().last(new TextPrompt() { @Override public boolean process(ConversationContext context, TextContent input) { textCallback.accept(UserInputInlineMenuButton.this, input.getContent()); inputGiven = true; return false; } @Override public SendableMessage promptMessage(ConversationContext context) { return null; } }).build().begin(); } }
java
@Override public void handlePress(CallbackQuery query) { executeCallback(); if (textCallback != null && inputGiven) { inputGiven = false; Conversation.builder(query.getBotInstance()) .forWhom(owner.getBaseMessage().getChat()) .silent(true) .prompts().last(new TextPrompt() { @Override public boolean process(ConversationContext context, TextContent input) { textCallback.accept(UserInputInlineMenuButton.this, input.getContent()); inputGiven = true; return false; } @Override public SendableMessage promptMessage(ConversationContext context) { return null; } }).build().begin(); } }
[ "@", "Override", "public", "void", "handlePress", "(", "CallbackQuery", "query", ")", "{", "executeCallback", "(", ")", ";", "if", "(", "textCallback", "!=", "null", "&&", "inputGiven", ")", "{", "inputGiven", "=", "false", ";", "Conversation", ".", "builder", "(", "query", ".", "getBotInstance", "(", ")", ")", ".", "forWhom", "(", "owner", ".", "getBaseMessage", "(", ")", ".", "getChat", "(", ")", ")", ".", "silent", "(", "true", ")", ".", "prompts", "(", ")", ".", "last", "(", "new", "TextPrompt", "(", ")", "{", "@", "Override", "public", "boolean", "process", "(", "ConversationContext", "context", ",", "TextContent", "input", ")", "{", "textCallback", ".", "accept", "(", "UserInputInlineMenuButton", ".", "this", ",", "input", ".", "getContent", "(", ")", ")", ";", "inputGiven", "=", "true", ";", "return", "false", ";", "}", "@", "Override", "public", "SendableMessage", "promptMessage", "(", "ConversationContext", "context", ")", "{", "return", "null", ";", "}", "}", ")", ".", "build", "(", ")", ".", "begin", "(", ")", ";", "}", "}" ]
Initiates a conversation with the chat awaiting text input On input executes callback @param query unused @see Conversation @see TextPrompt
[ "Initiates", "a", "conversation", "with", "the", "chat", "awaiting", "text", "input", "On", "input", "executes", "callback" ]
9d100f351824042ca5fc0ea735d1fa376a13e81d
https://github.com/zackpollard/JavaTelegramBot-API/blob/9d100f351824042ca5fc0ea735d1fa376a13e81d/menus/src/main/java/pro/zackpollard/telegrambot/api/menu/button/impl/UserInputInlineMenuButton.java#L70-L94
9,353
zackpollard/JavaTelegramBot-API
menus/src/main/java/pro/zackpollard/telegrambot/api/menu/button/impl/BackButton.java
BackButton.handlePress
@Override public void handlePress(CallbackQuery query) { InlineMenu lastMenu = owner.getLastMenu(); if (lastMenu != null) { executeCallback(); owner.unregister(); lastMenu.start(); } }
java
@Override public void handlePress(CallbackQuery query) { InlineMenu lastMenu = owner.getLastMenu(); if (lastMenu != null) { executeCallback(); owner.unregister(); lastMenu.start(); } }
[ "@", "Override", "public", "void", "handlePress", "(", "CallbackQuery", "query", ")", "{", "InlineMenu", "lastMenu", "=", "owner", ".", "getLastMenu", "(", ")", ";", "if", "(", "lastMenu", "!=", "null", ")", "{", "executeCallback", "(", ")", ";", "owner", ".", "unregister", "(", ")", ";", "lastMenu", ".", "start", "(", ")", ";", "}", "}" ]
If there is a last menu, execute callback, unregister the current menu, and start the parent. @param query Query to process, unused. @see InlineMenu#unregister() @see InlineMenu#start()
[ "If", "there", "is", "a", "last", "menu", "execute", "callback", "unregister", "the", "current", "menu", "and", "start", "the", "parent", "." ]
9d100f351824042ca5fc0ea735d1fa376a13e81d
https://github.com/zackpollard/JavaTelegramBot-API/blob/9d100f351824042ca5fc0ea735d1fa376a13e81d/menus/src/main/java/pro/zackpollard/telegrambot/api/menu/button/impl/BackButton.java#L66-L75
9,354
zackpollard/JavaTelegramBot-API
core/src/main/java/pro/zackpollard/telegrambot/api/chat/message/send/SendableTextMessage.java
SendableTextMessage.html
public static SendableTextMessageBuilder html(String text) { return builder().message(text).parseMode(ParseMode.HTML); }
java
public static SendableTextMessageBuilder html(String text) { return builder().message(text).parseMode(ParseMode.HTML); }
[ "public", "static", "SendableTextMessageBuilder", "html", "(", "String", "text", ")", "{", "return", "builder", "(", ")", ".", "message", "(", "text", ")", ".", "parseMode", "(", "ParseMode", ".", "HTML", ")", ";", "}" ]
This builder will be created with the text you provide already added with HTML formatting enabled. @param text The text you would like the builder to be created with @return A SendableTextMessageBuilder object with the text provided already added to it in HTML format. Used to construct the SendableTextMessage object
[ "This", "builder", "will", "be", "created", "with", "the", "text", "you", "provide", "already", "added", "with", "HTML", "formatting", "enabled", "." ]
9d100f351824042ca5fc0ea735d1fa376a13e81d
https://github.com/zackpollard/JavaTelegramBot-API/blob/9d100f351824042ca5fc0ea735d1fa376a13e81d/core/src/main/java/pro/zackpollard/telegrambot/api/chat/message/send/SendableTextMessage.java#L57-L59
9,355
zackpollard/JavaTelegramBot-API
conversations/src/main/java/pro/zackpollard/telegrambot/api/conversations/ConversationHistory.java
ConversationHistory.messageAt
public Message messageAt(ConversationPrompt prompt, Conversation conversation) { return messageAt(conversation.getPrompts().indexOf(prompt)); }
java
public Message messageAt(ConversationPrompt prompt, Conversation conversation) { return messageAt(conversation.getPrompts().indexOf(prompt)); }
[ "public", "Message", "messageAt", "(", "ConversationPrompt", "prompt", ",", "Conversation", "conversation", ")", "{", "return", "messageAt", "(", "conversation", ".", "getPrompts", "(", ")", ".", "indexOf", "(", "prompt", ")", ")", ";", "}" ]
Gets message sent at specified prompt @param prompt Prompt identifier @param conversation Conversation prompt is used in @return message sent at specified prompt @throws IndexOutOfBoundsException if there are no messages from that prompt
[ "Gets", "message", "sent", "at", "specified", "prompt" ]
9d100f351824042ca5fc0ea735d1fa376a13e81d
https://github.com/zackpollard/JavaTelegramBot-API/blob/9d100f351824042ca5fc0ea735d1fa376a13e81d/conversations/src/main/java/pro/zackpollard/telegrambot/api/conversations/ConversationHistory.java#L49-L51
9,356
zackpollard/JavaTelegramBot-API
menus/src/main/java/pro/zackpollard/telegrambot/api/menu/button/AbstractInlineMenuButton.java
AbstractInlineMenuButton.keyboardBuilder
protected InlineKeyboardButton.InlineKeyboardButtonBuilder keyboardBuilder() { return InlineKeyboardButton.builder() .text(text) .callbackData("im." + owner.getInternalId() + "." + row + "." + owner.rowAt(row).indexOf(this)); }
java
protected InlineKeyboardButton.InlineKeyboardButtonBuilder keyboardBuilder() { return InlineKeyboardButton.builder() .text(text) .callbackData("im." + owner.getInternalId() + "." + row + "." + owner.rowAt(row).indexOf(this)); }
[ "protected", "InlineKeyboardButton", ".", "InlineKeyboardButtonBuilder", "keyboardBuilder", "(", ")", "{", "return", "InlineKeyboardButton", ".", "builder", "(", ")", ".", "text", "(", "text", ")", ".", "callbackData", "(", "\"im.\"", "+", "owner", ".", "getInternalId", "(", ")", "+", "\".\"", "+", "row", "+", "\".\"", "+", "owner", ".", "rowAt", "(", "row", ")", ".", "indexOf", "(", "this", ")", ")", ";", "}" ]
Sets the text of the button and the callback data to the following. im.x.y.z Where x is the internal id of the owning menu, y is the row index, z is the button index. @return Premade button builder
[ "Sets", "the", "text", "of", "the", "button", "and", "the", "callback", "data", "to", "the", "following", "." ]
9d100f351824042ca5fc0ea735d1fa376a13e81d
https://github.com/zackpollard/JavaTelegramBot-API/blob/9d100f351824042ca5fc0ea735d1fa376a13e81d/menus/src/main/java/pro/zackpollard/telegrambot/api/menu/button/AbstractInlineMenuButton.java#L100-L104
9,357
zackpollard/JavaTelegramBot-API
menus/src/main/java/pro/zackpollard/telegrambot/api/menu/AbstractInlineMenuBuilder.java
AbstractInlineMenuBuilder.buildMenu
protected InlineMenu buildMenu(Message base) { InlineMenu menu = new InlineMenu(base); rows.forEach((row) -> row.buttons.forEach((button) -> button.assignMenu(menu))); menu.userPredicate = userPredicate; menu.rows = rows; return menu; }
java
protected InlineMenu buildMenu(Message base) { InlineMenu menu = new InlineMenu(base); rows.forEach((row) -> row.buttons.forEach((button) -> button.assignMenu(menu))); menu.userPredicate = userPredicate; menu.rows = rows; return menu; }
[ "protected", "InlineMenu", "buildMenu", "(", "Message", "base", ")", "{", "InlineMenu", "menu", "=", "new", "InlineMenu", "(", "base", ")", ";", "rows", ".", "forEach", "(", "(", "row", ")", "-", ">", "row", ".", "buttons", ".", "forEach", "(", "(", "button", ")", "-", ">", "button", ".", "assignMenu", "(", "menu", ")", ")", ")", ";", "menu", ".", "userPredicate", "=", "userPredicate", ";", "menu", ".", "rows", "=", "rows", ";", "return", "menu", ";", "}" ]
Build a menu from message base. Adds &amp; Registers all buttons. Applies user predicate. Applies rows. @param base Message @return built menu
[ "Build", "a", "menu", "from", "message", "base", ".", "Adds", "&amp", ";", "Registers", "all", "buttons", ".", "Applies", "user", "predicate", ".", "Applies", "rows", "." ]
9d100f351824042ca5fc0ea735d1fa376a13e81d
https://github.com/zackpollard/JavaTelegramBot-API/blob/9d100f351824042ca5fc0ea735d1fa376a13e81d/menus/src/main/java/pro/zackpollard/telegrambot/api/menu/AbstractInlineMenuBuilder.java#L52-L58
9,358
zackpollard/JavaTelegramBot-API
menus/src/main/java/pro/zackpollard/telegrambot/api/menu/AbstractInlineMenuBuilder.java
AbstractInlineMenuBuilder.allowedUser
public T allowedUser(User allowedUser) { this.userPredicate = (user) -> user.getId() == allowedUser.getId(); return instance(); }
java
public T allowedUser(User allowedUser) { this.userPredicate = (user) -> user.getId() == allowedUser.getId(); return instance(); }
[ "public", "T", "allowedUser", "(", "User", "allowedUser", ")", "{", "this", ".", "userPredicate", "=", "(", "user", ")", "-", ">", "user", ".", "getId", "(", ")", "==", "allowedUser", ".", "getId", "(", ")", ";", "return", "instance", "(", ")", ";", "}" ]
Allow a single user to use this menu @param allowedUser allowed user @return this
[ "Allow", "a", "single", "user", "to", "use", "this", "menu" ]
9d100f351824042ca5fc0ea735d1fa376a13e81d
https://github.com/zackpollard/JavaTelegramBot-API/blob/9d100f351824042ca5fc0ea735d1fa376a13e81d/menus/src/main/java/pro/zackpollard/telegrambot/api/menu/AbstractInlineMenuBuilder.java#L102-L105
9,359
zackpollard/JavaTelegramBot-API
core/src/main/java/pro/zackpollard/telegrambot/api/utils/Utils.java
Utils.generateRandomString
public static String generateRandomString(int length) { char[] chars = "abcdefghijklmnopqrstuvwxyz1234567890".toCharArray(); StringBuilder sb = new StringBuilder(); Random random = new Random(); for (int i = 0; i < 20; i++) { char c = chars[random.nextInt(chars.length)]; sb.append(c); } return sb.toString(); }
java
public static String generateRandomString(int length) { char[] chars = "abcdefghijklmnopqrstuvwxyz1234567890".toCharArray(); StringBuilder sb = new StringBuilder(); Random random = new Random(); for (int i = 0; i < 20; i++) { char c = chars[random.nextInt(chars.length)]; sb.append(c); } return sb.toString(); }
[ "public", "static", "String", "generateRandomString", "(", "int", "length", ")", "{", "char", "[", "]", "chars", "=", "\"abcdefghijklmnopqrstuvwxyz1234567890\"", ".", "toCharArray", "(", ")", ";", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "Random", "random", "=", "new", "Random", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "20", ";", "i", "++", ")", "{", "char", "c", "=", "chars", "[", "random", ".", "nextInt", "(", "chars", ".", "length", ")", "]", ";", "sb", ".", "append", "(", "c", ")", ";", "}", "return", "sb", ".", "toString", "(", ")", ";", "}" ]
Generates a random alphanumeric String of the length specified @param length The required length of the String @return A random alphanumeric String
[ "Generates", "a", "random", "alphanumeric", "String", "of", "the", "length", "specified" ]
9d100f351824042ca5fc0ea735d1fa376a13e81d
https://github.com/zackpollard/JavaTelegramBot-API/blob/9d100f351824042ca5fc0ea735d1fa376a13e81d/core/src/main/java/pro/zackpollard/telegrambot/api/utils/Utils.java#L33-L44
9,360
zackpollard/JavaTelegramBot-API
core/src/main/java/pro/zackpollard/telegrambot/api/utils/Utils.java
Utils.processResponse
public static JSONObject processResponse(HttpResponse<String> response) { if (response != null) { if (response.getStatus() == 200) { try { return new JSONObject(response.getBody()); } catch (JSONException e) { System.err.println("The API didn't return a JSON response. The actual response was " + response.getBody()); } } else { JSONObject jsonResponse = null; try { jsonResponse = new JSONObject(response.getBody()); } catch (JSONException e) { } if (jsonResponse != null) { System.err.println("The API returned the following error: " + jsonResponse.getString("description")); } else { System.err.println("The API returned error code " + response.getStatus()); } } } return null; }
java
public static JSONObject processResponse(HttpResponse<String> response) { if (response != null) { if (response.getStatus() == 200) { try { return new JSONObject(response.getBody()); } catch (JSONException e) { System.err.println("The API didn't return a JSON response. The actual response was " + response.getBody()); } } else { JSONObject jsonResponse = null; try { jsonResponse = new JSONObject(response.getBody()); } catch (JSONException e) { } if (jsonResponse != null) { System.err.println("The API returned the following error: " + jsonResponse.getString("description")); } else { System.err.println("The API returned error code " + response.getStatus()); } } } return null; }
[ "public", "static", "JSONObject", "processResponse", "(", "HttpResponse", "<", "String", ">", "response", ")", "{", "if", "(", "response", "!=", "null", ")", "{", "if", "(", "response", ".", "getStatus", "(", ")", "==", "200", ")", "{", "try", "{", "return", "new", "JSONObject", "(", "response", ".", "getBody", "(", ")", ")", ";", "}", "catch", "(", "JSONException", "e", ")", "{", "System", ".", "err", ".", "println", "(", "\"The API didn't return a JSON response. The actual response was \"", "+", "response", ".", "getBody", "(", ")", ")", ";", "}", "}", "else", "{", "JSONObject", "jsonResponse", "=", "null", ";", "try", "{", "jsonResponse", "=", "new", "JSONObject", "(", "response", ".", "getBody", "(", ")", ")", ";", "}", "catch", "(", "JSONException", "e", ")", "{", "}", "if", "(", "jsonResponse", "!=", "null", ")", "{", "System", ".", "err", ".", "println", "(", "\"The API returned the following error: \"", "+", "jsonResponse", ".", "getString", "(", "\"description\"", ")", ")", ";", "}", "else", "{", "System", ".", "err", ".", "println", "(", "\"The API returned error code \"", "+", "response", ".", "getStatus", "(", ")", ")", ";", "}", "}", "}", "return", "null", ";", "}" ]
This does some generic processing on HttpResponse objects returned by the Telegram Bot API @param response The HttpResponse object returned by Unirest from the Telegram Bot API call @return A JSONObject containing the processed response or null if something was wrong with the response
[ "This", "does", "some", "generic", "processing", "on", "HttpResponse", "objects", "returned", "by", "the", "Telegram", "Bot", "API" ]
9d100f351824042ca5fc0ea735d1fa376a13e81d
https://github.com/zackpollard/JavaTelegramBot-API/blob/9d100f351824042ca5fc0ea735d1fa376a13e81d/core/src/main/java/pro/zackpollard/telegrambot/api/utils/Utils.java#L53-L87
9,361
zackpollard/JavaTelegramBot-API
core/src/main/java/pro/zackpollard/telegrambot/api/utils/Utils.java
Utils.processReplyContent
public static void processReplyContent(MultipartBody multipartBody, ReplyingOptions replyingOptions) { if (replyingOptions.getReplyTo() != 0) multipartBody.field("reply_to_message_id", String.valueOf(replyingOptions.getReplyTo()), "application/json; charset=utf8;"); if (replyingOptions.getReplyMarkup() != null) { switch (replyingOptions.getReplyMarkup().getType()) { case FORCE_REPLY: multipartBody.field("reply_markup", TelegramBot.GSON.toJson(replyingOptions.getReplyMarkup(), ForceReply.class), "application/json; charset=utf8;"); break; case KEYBOARD_HIDE: multipartBody.field("reply_markup", TelegramBot.GSON.toJson(replyingOptions.getReplyMarkup(), ReplyKeyboardHide.class), "application/json; charset=utf8;"); break; case KEYBOARD_REMOVE: multipartBody.field("reply_markup", TelegramBot.GSON.toJson(replyingOptions.getReplyMarkup(), ReplyKeyboardRemove.class), "application/json; charset=utf8;"); break; case KEYBOARD_MARKUP: multipartBody.field("reply_markup", TelegramBot.GSON.toJson(replyingOptions.getReplyMarkup(), ReplyKeyboardMarkup.class), "application/json; charset=utf8;"); break; case INLINE_KEYBOARD_MARKUP: multipartBody.field("reply_markup", TelegramBot.GSON.toJson(replyingOptions.getReplyMarkup(), InlineKeyboardMarkup.class), "application/json; charset=utf8;"); break; } } }
java
public static void processReplyContent(MultipartBody multipartBody, ReplyingOptions replyingOptions) { if (replyingOptions.getReplyTo() != 0) multipartBody.field("reply_to_message_id", String.valueOf(replyingOptions.getReplyTo()), "application/json; charset=utf8;"); if (replyingOptions.getReplyMarkup() != null) { switch (replyingOptions.getReplyMarkup().getType()) { case FORCE_REPLY: multipartBody.field("reply_markup", TelegramBot.GSON.toJson(replyingOptions.getReplyMarkup(), ForceReply.class), "application/json; charset=utf8;"); break; case KEYBOARD_HIDE: multipartBody.field("reply_markup", TelegramBot.GSON.toJson(replyingOptions.getReplyMarkup(), ReplyKeyboardHide.class), "application/json; charset=utf8;"); break; case KEYBOARD_REMOVE: multipartBody.field("reply_markup", TelegramBot.GSON.toJson(replyingOptions.getReplyMarkup(), ReplyKeyboardRemove.class), "application/json; charset=utf8;"); break; case KEYBOARD_MARKUP: multipartBody.field("reply_markup", TelegramBot.GSON.toJson(replyingOptions.getReplyMarkup(), ReplyKeyboardMarkup.class), "application/json; charset=utf8;"); break; case INLINE_KEYBOARD_MARKUP: multipartBody.field("reply_markup", TelegramBot.GSON.toJson(replyingOptions.getReplyMarkup(), InlineKeyboardMarkup.class), "application/json; charset=utf8;"); break; } } }
[ "public", "static", "void", "processReplyContent", "(", "MultipartBody", "multipartBody", ",", "ReplyingOptions", "replyingOptions", ")", "{", "if", "(", "replyingOptions", ".", "getReplyTo", "(", ")", "!=", "0", ")", "multipartBody", ".", "field", "(", "\"reply_to_message_id\"", ",", "String", ".", "valueOf", "(", "replyingOptions", ".", "getReplyTo", "(", ")", ")", ",", "\"application/json; charset=utf8;\"", ")", ";", "if", "(", "replyingOptions", ".", "getReplyMarkup", "(", ")", "!=", "null", ")", "{", "switch", "(", "replyingOptions", ".", "getReplyMarkup", "(", ")", ".", "getType", "(", ")", ")", "{", "case", "FORCE_REPLY", ":", "multipartBody", ".", "field", "(", "\"reply_markup\"", ",", "TelegramBot", ".", "GSON", ".", "toJson", "(", "replyingOptions", ".", "getReplyMarkup", "(", ")", ",", "ForceReply", ".", "class", ")", ",", "\"application/json; charset=utf8;\"", ")", ";", "break", ";", "case", "KEYBOARD_HIDE", ":", "multipartBody", ".", "field", "(", "\"reply_markup\"", ",", "TelegramBot", ".", "GSON", ".", "toJson", "(", "replyingOptions", ".", "getReplyMarkup", "(", ")", ",", "ReplyKeyboardHide", ".", "class", ")", ",", "\"application/json; charset=utf8;\"", ")", ";", "break", ";", "case", "KEYBOARD_REMOVE", ":", "multipartBody", ".", "field", "(", "\"reply_markup\"", ",", "TelegramBot", ".", "GSON", ".", "toJson", "(", "replyingOptions", ".", "getReplyMarkup", "(", ")", ",", "ReplyKeyboardRemove", ".", "class", ")", ",", "\"application/json; charset=utf8;\"", ")", ";", "break", ";", "case", "KEYBOARD_MARKUP", ":", "multipartBody", ".", "field", "(", "\"reply_markup\"", ",", "TelegramBot", ".", "GSON", ".", "toJson", "(", "replyingOptions", ".", "getReplyMarkup", "(", ")", ",", "ReplyKeyboardMarkup", ".", "class", ")", ",", "\"application/json; charset=utf8;\"", ")", ";", "break", ";", "case", "INLINE_KEYBOARD_MARKUP", ":", "multipartBody", ".", "field", "(", "\"reply_markup\"", ",", "TelegramBot", ".", "GSON", ".", "toJson", "(", "replyingOptions", ".", "getReplyMarkup", "(", ")", ",", "InlineKeyboardMarkup", ".", "class", ")", ",", "\"application/json; charset=utf8;\"", ")", ";", "break", ";", "}", "}", "}" ]
This does generic processing of ReplyingOptions objects when sending a request to the API @param multipartBody The MultipartBody that the ReplyingOptions content should be appended to @param replyingOptions The ReplyingOptions that were used in this request
[ "This", "does", "generic", "processing", "of", "ReplyingOptions", "objects", "when", "sending", "a", "request", "to", "the", "API" ]
9d100f351824042ca5fc0ea735d1fa376a13e81d
https://github.com/zackpollard/JavaTelegramBot-API/blob/9d100f351824042ca5fc0ea735d1fa376a13e81d/core/src/main/java/pro/zackpollard/telegrambot/api/utils/Utils.java#L95-L120
9,362
zackpollard/JavaTelegramBot-API
core/src/main/java/pro/zackpollard/telegrambot/api/utils/Utils.java
Utils.processInputFileField
public static void processInputFileField(MultipartBody request, String fieldName, InputFile inputFile) { String fileId = inputFile.getFileID(); if (fileId != null) { request.field(fieldName, fileId, false); } else if (inputFile.getInputStream() != null) { request.field(fieldName, new InputStreamBody(inputFile.getInputStream(), inputFile.getFileName()), true); } else { // assume file is not null (this is existing behaviour as of 1.5.1) request.field(fieldName, new FileContainer(inputFile), true); } }
java
public static void processInputFileField(MultipartBody request, String fieldName, InputFile inputFile) { String fileId = inputFile.getFileID(); if (fileId != null) { request.field(fieldName, fileId, false); } else if (inputFile.getInputStream() != null) { request.field(fieldName, new InputStreamBody(inputFile.getInputStream(), inputFile.getFileName()), true); } else { // assume file is not null (this is existing behaviour as of 1.5.1) request.field(fieldName, new FileContainer(inputFile), true); } }
[ "public", "static", "void", "processInputFileField", "(", "MultipartBody", "request", ",", "String", "fieldName", ",", "InputFile", "inputFile", ")", "{", "String", "fileId", "=", "inputFile", ".", "getFileID", "(", ")", ";", "if", "(", "fileId", "!=", "null", ")", "{", "request", ".", "field", "(", "fieldName", ",", "fileId", ",", "false", ")", ";", "}", "else", "if", "(", "inputFile", ".", "getInputStream", "(", ")", "!=", "null", ")", "{", "request", ".", "field", "(", "fieldName", ",", "new", "InputStreamBody", "(", "inputFile", ".", "getInputStream", "(", ")", ",", "inputFile", ".", "getFileName", "(", ")", ")", ",", "true", ")", ";", "}", "else", "{", "// assume file is not null (this is existing behaviour as of 1.5.1)", "request", ".", "field", "(", "fieldName", ",", "new", "FileContainer", "(", "inputFile", ")", ",", "true", ")", ";", "}", "}" ]
Adds an input file to a request, with the given field name. @param request The request to be added to. @param fieldName The name of the field. @param inputFile The input file.
[ "Adds", "an", "input", "file", "to", "a", "request", "with", "the", "given", "field", "name", "." ]
9d100f351824042ca5fc0ea735d1fa376a13e81d
https://github.com/zackpollard/JavaTelegramBot-API/blob/9d100f351824042ca5fc0ea735d1fa376a13e81d/core/src/main/java/pro/zackpollard/telegrambot/api/utils/Utils.java#L166-L175
9,363
zackpollard/JavaTelegramBot-API
menus/src/main/java/pro/zackpollard/telegrambot/api/menu/InlineMenu.java
InlineMenu.builder
public static InlineMenuBuilder builder(TelegramBot bot, Chat forWhom) { return new InlineMenuBuilder(bot).forWhom(forWhom); }
java
public static InlineMenuBuilder builder(TelegramBot bot, Chat forWhom) { return new InlineMenuBuilder(bot).forWhom(forWhom); }
[ "public", "static", "InlineMenuBuilder", "builder", "(", "TelegramBot", "bot", ",", "Chat", "forWhom", ")", "{", "return", "new", "InlineMenuBuilder", "(", "bot", ")", ".", "forWhom", "(", "forWhom", ")", ";", "}" ]
Creates new builder, initializes with the required Chat field @param bot The bot that will be used to send the message for this inline menu @param forWhom The chat the inline menu will be sent to @return new inline menu builder initialized with the forWhom field
[ "Creates", "new", "builder", "initializes", "with", "the", "required", "Chat", "field" ]
9d100f351824042ca5fc0ea735d1fa376a13e81d
https://github.com/zackpollard/JavaTelegramBot-API/blob/9d100f351824042ca5fc0ea735d1fa376a13e81d/menus/src/main/java/pro/zackpollard/telegrambot/api/menu/InlineMenu.java#L59-L61
9,364
zackpollard/JavaTelegramBot-API
menus/src/main/java/pro/zackpollard/telegrambot/api/menu/InlineMenu.java
InlineMenu.toKeyboard
public InlineKeyboardMarkup toKeyboard() { InlineKeyboardMarkup.InlineKeyboardMarkupBuilder builder = InlineKeyboardMarkup.builder(); if (rows.isEmpty()) { return null; } rows.stream().map(InlineMenuRow::toButtons).forEach(builder::addRow); return builder.build(); }
java
public InlineKeyboardMarkup toKeyboard() { InlineKeyboardMarkup.InlineKeyboardMarkupBuilder builder = InlineKeyboardMarkup.builder(); if (rows.isEmpty()) { return null; } rows.stream().map(InlineMenuRow::toButtons).forEach(builder::addRow); return builder.build(); }
[ "public", "InlineKeyboardMarkup", "toKeyboard", "(", ")", "{", "InlineKeyboardMarkup", ".", "InlineKeyboardMarkupBuilder", "builder", "=", "InlineKeyboardMarkup", ".", "builder", "(", ")", ";", "if", "(", "rows", ".", "isEmpty", "(", ")", ")", "{", "return", "null", ";", "}", "rows", ".", "stream", "(", ")", ".", "map", "(", "InlineMenuRow", "::", "toButtons", ")", ".", "forEach", "(", "builder", "::", "addRow", ")", ";", "return", "builder", ".", "build", "(", ")", ";", "}" ]
Converts rows to the inline keyboard markup used by the Telegram API @return keyboard markup
[ "Converts", "rows", "to", "the", "inline", "keyboard", "markup", "used", "by", "the", "Telegram", "API" ]
9d100f351824042ca5fc0ea735d1fa376a13e81d
https://github.com/zackpollard/JavaTelegramBot-API/blob/9d100f351824042ca5fc0ea735d1fa376a13e81d/menus/src/main/java/pro/zackpollard/telegrambot/api/menu/InlineMenu.java#L130-L140
9,365
zackpollard/JavaTelegramBot-API
menus/src/main/java/pro/zackpollard/telegrambot/api/menu/InlineMenu.java
InlineMenu.handle
public boolean handle(CallbackQuery query, int row, int button) { if (!validateCaller(InlineMenuRegistry.class)) { throw new UnsupportedOperationException("Invalid caller! Caller must implement InlineMenuRegistry"); } return (userPredicate == null || userPredicate.test(query.getFrom())) && row < rows.size() && rowAt(row).handle(query, button); }
java
public boolean handle(CallbackQuery query, int row, int button) { if (!validateCaller(InlineMenuRegistry.class)) { throw new UnsupportedOperationException("Invalid caller! Caller must implement InlineMenuRegistry"); } return (userPredicate == null || userPredicate.test(query.getFrom())) && row < rows.size() && rowAt(row).handle(query, button); }
[ "public", "boolean", "handle", "(", "CallbackQuery", "query", ",", "int", "row", ",", "int", "button", ")", "{", "if", "(", "!", "validateCaller", "(", "InlineMenuRegistry", ".", "class", ")", ")", "{", "throw", "new", "UnsupportedOperationException", "(", "\"Invalid caller! Caller must implement InlineMenuRegistry\"", ")", ";", "}", "return", "(", "userPredicate", "==", "null", "||", "userPredicate", ".", "test", "(", "query", ".", "getFrom", "(", ")", ")", ")", "&&", "row", "<", "rows", ".", "size", "(", ")", "&&", "rowAt", "(", "row", ")", ".", "handle", "(", "query", ",", "button", ")", ";", "}" ]
Handle an inline query sent. Caller dependent, throws exception if called from a class which doesn't implement InlineMenuRegistry @param query The callback query @param row The button's row @param button The button's column @return Whether the menu handled the request, if not it was due to a user predicate or invalid row or invalid button @see InlineMenuRegistry @see InlineMenuRow#handle(CallbackQuery, int)
[ "Handle", "an", "inline", "query", "sent", ".", "Caller", "dependent", "throws", "exception", "if", "called", "from", "a", "class", "which", "doesn", "t", "implement", "InlineMenuRegistry" ]
9d100f351824042ca5fc0ea735d1fa376a13e81d
https://github.com/zackpollard/JavaTelegramBot-API/blob/9d100f351824042ca5fc0ea735d1fa376a13e81d/menus/src/main/java/pro/zackpollard/telegrambot/api/menu/InlineMenu.java#L154-L161
9,366
zackpollard/JavaTelegramBot-API
menus/src/main/java/pro/zackpollard/telegrambot/api/menu/InlineMenu.java
InlineMenu.setMessageText
public void setMessageText(SendableTextMessage.SendableTextMessageBuilder messageBuilder) { SendableTextMessage message = messageBuilder.build(); baseMessage.getBotInstance().editMessageText(baseMessage, message.getMessage(), message.getParseMode(), message.isDisableWebPagePreview(), toKeyboard()); }
java
public void setMessageText(SendableTextMessage.SendableTextMessageBuilder messageBuilder) { SendableTextMessage message = messageBuilder.build(); baseMessage.getBotInstance().editMessageText(baseMessage, message.getMessage(), message.getParseMode(), message.isDisableWebPagePreview(), toKeyboard()); }
[ "public", "void", "setMessageText", "(", "SendableTextMessage", ".", "SendableTextMessageBuilder", "messageBuilder", ")", "{", "SendableTextMessage", "message", "=", "messageBuilder", ".", "build", "(", ")", ";", "baseMessage", ".", "getBotInstance", "(", ")", ".", "editMessageText", "(", "baseMessage", ",", "message", ".", "getMessage", "(", ")", ",", "message", ".", "getParseMode", "(", ")", ",", "message", ".", "isDisableWebPagePreview", "(", ")", ",", "toKeyboard", "(", ")", ")", ";", "}" ]
Set the text of the current message, updates keyboard @param messageBuilder New Message text @see InlineMenu#apply()
[ "Set", "the", "text", "of", "the", "current", "message", "updates", "keyboard" ]
9d100f351824042ca5fc0ea735d1fa376a13e81d
https://github.com/zackpollard/JavaTelegramBot-API/blob/9d100f351824042ca5fc0ea735d1fa376a13e81d/menus/src/main/java/pro/zackpollard/telegrambot/api/menu/InlineMenu.java#L175-L179
9,367
zackpollard/JavaTelegramBot-API
menus/src/main/java/pro/zackpollard/telegrambot/api/menu/InlineMenuRow.java
InlineMenuRow.toButtons
public List<InlineKeyboardButton> toButtons() { return buttons.stream() .map(InlineMenuButton::toKeyboardButton) .collect(Collectors.toList()); }
java
public List<InlineKeyboardButton> toButtons() { return buttons.stream() .map(InlineMenuButton::toKeyboardButton) .collect(Collectors.toList()); }
[ "public", "List", "<", "InlineKeyboardButton", ">", "toButtons", "(", ")", "{", "return", "buttons", ".", "stream", "(", ")", ".", "map", "(", "InlineMenuButton", "::", "toKeyboardButton", ")", ".", "collect", "(", "Collectors", ".", "toList", "(", ")", ")", ";", "}" ]
Returns row as List&lt;InlineKeyboardButtons&gt; @return list of keyboard buttons @see InlineMenuButton#toKeyboardButton()
[ "Returns", "row", "as", "List&lt", ";", "InlineKeyboardButtons&gt", ";" ]
9d100f351824042ca5fc0ea735d1fa376a13e81d
https://github.com/zackpollard/JavaTelegramBot-API/blob/9d100f351824042ca5fc0ea735d1fa376a13e81d/menus/src/main/java/pro/zackpollard/telegrambot/api/menu/InlineMenuRow.java#L70-L74
9,368
zackpollard/JavaTelegramBot-API
menus/src/main/java/pro/zackpollard/telegrambot/api/menu/InlineMenuRow.java
InlineMenuRow.handle
public boolean handle(CallbackQuery query, int button) { if (button < 0 || button > buttons.size()) { return false; } buttonAt(button).handlePress(query); return true; }
java
public boolean handle(CallbackQuery query, int button) { if (button < 0 || button > buttons.size()) { return false; } buttonAt(button).handlePress(query); return true; }
[ "public", "boolean", "handle", "(", "CallbackQuery", "query", ",", "int", "button", ")", "{", "if", "(", "button", "<", "0", "||", "button", ">", "buttons", ".", "size", "(", ")", ")", "{", "return", "false", ";", "}", "buttonAt", "(", "button", ")", ".", "handlePress", "(", "query", ")", ";", "return", "true", ";", "}" ]
Handle callback query @param query query to be processed @param button button index @return false if the button was out of bounds and therefore wasn't processed
[ "Handle", "callback", "query" ]
9d100f351824042ca5fc0ea735d1fa376a13e81d
https://github.com/zackpollard/JavaTelegramBot-API/blob/9d100f351824042ca5fc0ea735d1fa376a13e81d/menus/src/main/java/pro/zackpollard/telegrambot/api/menu/InlineMenuRow.java#L82-L89
9,369
zackpollard/JavaTelegramBot-API
core/src/main/java/pro/zackpollard/telegrambot/api/event/chat/MigrateToChatEvent.java
MigrateToChatEvent.getChat
@Override public SuperGroupChat getChat() { return (SuperGroupChat) getMessage().getBotInstance().getChat(((MigrateToChatIDContent) getMessage().getContent()).getContent()); }
java
@Override public SuperGroupChat getChat() { return (SuperGroupChat) getMessage().getBotInstance().getChat(((MigrateToChatIDContent) getMessage().getContent()).getContent()); }
[ "@", "Override", "public", "SuperGroupChat", "getChat", "(", ")", "{", "return", "(", "SuperGroupChat", ")", "getMessage", "(", ")", ".", "getBotInstance", "(", ")", ".", "getChat", "(", "(", "(", "MigrateToChatIDContent", ")", "getMessage", "(", ")", ".", "getContent", "(", ")", ")", ".", "getContent", "(", ")", ")", ";", "}" ]
Gets the Chat that was migrated to that triggered this Event @return The Chat that was migrated to that triggred this Event
[ "Gets", "the", "Chat", "that", "was", "migrated", "to", "that", "triggered", "this", "Event" ]
9d100f351824042ca5fc0ea735d1fa376a13e81d
https://github.com/zackpollard/JavaTelegramBot-API/blob/9d100f351824042ca5fc0ea735d1fa376a13e81d/core/src/main/java/pro/zackpollard/telegrambot/api/event/chat/MigrateToChatEvent.java#L22-L26
9,370
timewalker74/ffmq
core/src/main/java/net/timewalker/ffmq4/common/message/MessageType.java
MessageType.createInstance
public static AbstractMessage createInstance( byte type ) { switch (type) { case EMPTY: return new EmptyMessageImpl(); case BYTES: return new BytesMessageImpl(); case MAP: return new MapMessageImpl(); case OBJECT: return new ObjectMessageImpl(); case STREAM: return new StreamMessageImpl(); case TEXT: return new TextMessageImpl(); default: throw new IllegalArgumentException("Unsupported message type : "+type); } }
java
public static AbstractMessage createInstance( byte type ) { switch (type) { case EMPTY: return new EmptyMessageImpl(); case BYTES: return new BytesMessageImpl(); case MAP: return new MapMessageImpl(); case OBJECT: return new ObjectMessageImpl(); case STREAM: return new StreamMessageImpl(); case TEXT: return new TextMessageImpl(); default: throw new IllegalArgumentException("Unsupported message type : "+type); } }
[ "public", "static", "AbstractMessage", "createInstance", "(", "byte", "type", ")", "{", "switch", "(", "type", ")", "{", "case", "EMPTY", ":", "return", "new", "EmptyMessageImpl", "(", ")", ";", "case", "BYTES", ":", "return", "new", "BytesMessageImpl", "(", ")", ";", "case", "MAP", ":", "return", "new", "MapMessageImpl", "(", ")", ";", "case", "OBJECT", ":", "return", "new", "ObjectMessageImpl", "(", ")", ";", "case", "STREAM", ":", "return", "new", "StreamMessageImpl", "(", ")", ";", "case", "TEXT", ":", "return", "new", "TextMessageImpl", "(", ")", ";", "default", ":", "throw", "new", "IllegalArgumentException", "(", "\"Unsupported message type : \"", "+", "type", ")", ";", "}", "}" ]
Create a message instance of the given type
[ "Create", "a", "message", "instance", "of", "the", "given", "type" ]
638773ee29a4a5f9c6119ed74ad14ac9c46382b3
https://github.com/timewalker74/ffmq/blob/638773ee29a4a5f9c6119ed74ad14ac9c46382b3/core/src/main/java/net/timewalker/ffmq4/common/message/MessageType.java#L38-L52
9,371
timewalker74/ffmq
core/src/main/java/net/timewalker/ffmq4/common/session/AbstractSession.java
AbstractSession.wakeUpConsumers
public final void wakeUpConsumers() throws JMSException { synchronized (consumersMap) { Iterator<AbstractMessageConsumer> allConsumers = consumersMap.values().iterator(); while (allConsumers.hasNext()) { AbstractMessageConsumer consumer = allConsumers.next(); consumer.wakeUp(); } } }
java
public final void wakeUpConsumers() throws JMSException { synchronized (consumersMap) { Iterator<AbstractMessageConsumer> allConsumers = consumersMap.values().iterator(); while (allConsumers.hasNext()) { AbstractMessageConsumer consumer = allConsumers.next(); consumer.wakeUp(); } } }
[ "public", "final", "void", "wakeUpConsumers", "(", ")", "throws", "JMSException", "{", "synchronized", "(", "consumersMap", ")", "{", "Iterator", "<", "AbstractMessageConsumer", ">", "allConsumers", "=", "consumersMap", ".", "values", "(", ")", ".", "iterator", "(", ")", ";", "while", "(", "allConsumers", ".", "hasNext", "(", ")", ")", "{", "AbstractMessageConsumer", "consumer", "=", "allConsumers", ".", "next", "(", ")", ";", "consumer", ".", "wakeUp", "(", ")", ";", "}", "}", "}" ]
Wake up all children consumers
[ "Wake", "up", "all", "children", "consumers" ]
638773ee29a4a5f9c6119ed74ad14ac9c46382b3
https://github.com/timewalker74/ffmq/blob/638773ee29a4a5f9c6119ed74ad14ac9c46382b3/core/src/main/java/net/timewalker/ffmq4/common/session/AbstractSession.java#L189-L200
9,372
timewalker74/ffmq
core/src/main/java/net/timewalker/ffmq4/common/session/AbstractSession.java
AbstractSession.registerConsumer
protected final void registerConsumer( AbstractMessageConsumer consumer ) { if (consumersMap.put(consumer.getId(),consumer) != null) throw new IllegalArgumentException("Consumer "+consumer.getId()+" already exists"); }
java
protected final void registerConsumer( AbstractMessageConsumer consumer ) { if (consumersMap.put(consumer.getId(),consumer) != null) throw new IllegalArgumentException("Consumer "+consumer.getId()+" already exists"); }
[ "protected", "final", "void", "registerConsumer", "(", "AbstractMessageConsumer", "consumer", ")", "{", "if", "(", "consumersMap", ".", "put", "(", "consumer", ".", "getId", "(", ")", ",", "consumer", ")", "!=", "null", ")", "throw", "new", "IllegalArgumentException", "(", "\"Consumer \"", "+", "consumer", ".", "getId", "(", ")", "+", "\" already exists\"", ")", ";", "}" ]
Register a consumer
[ "Register", "a", "consumer" ]
638773ee29a4a5f9c6119ed74ad14ac9c46382b3
https://github.com/timewalker74/ffmq/blob/638773ee29a4a5f9c6119ed74ad14ac9c46382b3/core/src/main/java/net/timewalker/ffmq4/common/session/AbstractSession.java#L221-L225
9,373
timewalker74/ffmq
core/src/main/java/net/timewalker/ffmq4/common/session/AbstractSession.java
AbstractSession.registerProducer
protected final void registerProducer( AbstractMessageProducer producer ) { if (producersMap.put(producer.getId(),producer) != null) throw new IllegalArgumentException("Producer "+producer.getId()+" already exists"); }
java
protected final void registerProducer( AbstractMessageProducer producer ) { if (producersMap.put(producer.getId(),producer) != null) throw new IllegalArgumentException("Producer "+producer.getId()+" already exists"); }
[ "protected", "final", "void", "registerProducer", "(", "AbstractMessageProducer", "producer", ")", "{", "if", "(", "producersMap", ".", "put", "(", "producer", ".", "getId", "(", ")", ",", "producer", ")", "!=", "null", ")", "throw", "new", "IllegalArgumentException", "(", "\"Producer \"", "+", "producer", ".", "getId", "(", ")", "+", "\" already exists\"", ")", ";", "}" ]
Register a producer
[ "Register", "a", "producer" ]
638773ee29a4a5f9c6119ed74ad14ac9c46382b3
https://github.com/timewalker74/ffmq/blob/638773ee29a4a5f9c6119ed74ad14ac9c46382b3/core/src/main/java/net/timewalker/ffmq4/common/session/AbstractSession.java#L230-L234
9,374
timewalker74/ffmq
core/src/main/java/net/timewalker/ffmq4/common/session/AbstractSession.java
AbstractSession.registerBrowser
protected final void registerBrowser( AbstractQueueBrowser browser ) { if (browsersMap.put(browser.getId(),browser) != null) throw new IllegalArgumentException("Browser "+browser.getId()+" already exists"); }
java
protected final void registerBrowser( AbstractQueueBrowser browser ) { if (browsersMap.put(browser.getId(),browser) != null) throw new IllegalArgumentException("Browser "+browser.getId()+" already exists"); }
[ "protected", "final", "void", "registerBrowser", "(", "AbstractQueueBrowser", "browser", ")", "{", "if", "(", "browsersMap", ".", "put", "(", "browser", ".", "getId", "(", ")", ",", "browser", ")", "!=", "null", ")", "throw", "new", "IllegalArgumentException", "(", "\"Browser \"", "+", "browser", ".", "getId", "(", ")", "+", "\" already exists\"", ")", ";", "}" ]
Register a browser
[ "Register", "a", "browser" ]
638773ee29a4a5f9c6119ed74ad14ac9c46382b3
https://github.com/timewalker74/ffmq/blob/638773ee29a4a5f9c6119ed74ad14ac9c46382b3/core/src/main/java/net/timewalker/ffmq4/common/session/AbstractSession.java#L239-L243
9,375
timewalker74/ffmq
core/src/main/java/net/timewalker/ffmq4/common/session/AbstractSession.java
AbstractSession.unregisterConsumer
protected final void unregisterConsumer( AbstractMessageConsumer consumerToRemove ) { if (consumersMap.remove(consumerToRemove.getId()) == null) log.warn("Unknown consumer : "+consumerToRemove); }
java
protected final void unregisterConsumer( AbstractMessageConsumer consumerToRemove ) { if (consumersMap.remove(consumerToRemove.getId()) == null) log.warn("Unknown consumer : "+consumerToRemove); }
[ "protected", "final", "void", "unregisterConsumer", "(", "AbstractMessageConsumer", "consumerToRemove", ")", "{", "if", "(", "consumersMap", ".", "remove", "(", "consumerToRemove", ".", "getId", "(", ")", ")", "==", "null", ")", "log", ".", "warn", "(", "\"Unknown consumer : \"", "+", "consumerToRemove", ")", ";", "}" ]
Unregister a consumer
[ "Unregister", "a", "consumer" ]
638773ee29a4a5f9c6119ed74ad14ac9c46382b3
https://github.com/timewalker74/ffmq/blob/638773ee29a4a5f9c6119ed74ad14ac9c46382b3/core/src/main/java/net/timewalker/ffmq4/common/session/AbstractSession.java#L248-L252
9,376
timewalker74/ffmq
core/src/main/java/net/timewalker/ffmq4/common/session/AbstractSession.java
AbstractSession.unregisterProducer
protected final void unregisterProducer( AbstractMessageProducer producerToRemove ) { if (producersMap.remove(producerToRemove.getId()) == null) log.warn("Unknown producer : "+producerToRemove); }
java
protected final void unregisterProducer( AbstractMessageProducer producerToRemove ) { if (producersMap.remove(producerToRemove.getId()) == null) log.warn("Unknown producer : "+producerToRemove); }
[ "protected", "final", "void", "unregisterProducer", "(", "AbstractMessageProducer", "producerToRemove", ")", "{", "if", "(", "producersMap", ".", "remove", "(", "producerToRemove", ".", "getId", "(", ")", ")", "==", "null", ")", "log", ".", "warn", "(", "\"Unknown producer : \"", "+", "producerToRemove", ")", ";", "}" ]
Unregister a producer
[ "Unregister", "a", "producer" ]
638773ee29a4a5f9c6119ed74ad14ac9c46382b3
https://github.com/timewalker74/ffmq/blob/638773ee29a4a5f9c6119ed74ad14ac9c46382b3/core/src/main/java/net/timewalker/ffmq4/common/session/AbstractSession.java#L257-L261
9,377
timewalker74/ffmq
core/src/main/java/net/timewalker/ffmq4/common/session/AbstractSession.java
AbstractSession.unregisterBrowser
protected final void unregisterBrowser( AbstractQueueBrowser browserToRemove ) { if (browsersMap.remove(browserToRemove.getId()) == null) log.warn("Unknown browser : "+browserToRemove); }
java
protected final void unregisterBrowser( AbstractQueueBrowser browserToRemove ) { if (browsersMap.remove(browserToRemove.getId()) == null) log.warn("Unknown browser : "+browserToRemove); }
[ "protected", "final", "void", "unregisterBrowser", "(", "AbstractQueueBrowser", "browserToRemove", ")", "{", "if", "(", "browsersMap", ".", "remove", "(", "browserToRemove", ".", "getId", "(", ")", ")", "==", "null", ")", "log", ".", "warn", "(", "\"Unknown browser : \"", "+", "browserToRemove", ")", ";", "}" ]
Unregister a browser
[ "Unregister", "a", "browser" ]
638773ee29a4a5f9c6119ed74ad14ac9c46382b3
https://github.com/timewalker74/ffmq/blob/638773ee29a4a5f9c6119ed74ad14ac9c46382b3/core/src/main/java/net/timewalker/ffmq4/common/session/AbstractSession.java#L266-L270
9,378
timewalker74/ffmq
core/src/main/java/net/timewalker/ffmq4/common/session/AbstractSession.java
AbstractSession.closeRemainingBrowsers
private void closeRemainingBrowsers() { List<AbstractQueueBrowser> browsersToClose = new ArrayList<>(browsersMap.size()); synchronized (browsersMap) { browsersToClose.addAll(browsersMap.values()); } for (int n = 0 ; n < browsersToClose.size() ; n++) { QueueBrowser browser = browsersToClose.get(n); log.debug("Auto-closing unclosed browser : "+browser); try { browser.close(); } catch (Exception e) { log.error("Could not close browser "+browser,e); } } }
java
private void closeRemainingBrowsers() { List<AbstractQueueBrowser> browsersToClose = new ArrayList<>(browsersMap.size()); synchronized (browsersMap) { browsersToClose.addAll(browsersMap.values()); } for (int n = 0 ; n < browsersToClose.size() ; n++) { QueueBrowser browser = browsersToClose.get(n); log.debug("Auto-closing unclosed browser : "+browser); try { browser.close(); } catch (Exception e) { log.error("Could not close browser "+browser,e); } } }
[ "private", "void", "closeRemainingBrowsers", "(", ")", "{", "List", "<", "AbstractQueueBrowser", ">", "browsersToClose", "=", "new", "ArrayList", "<>", "(", "browsersMap", ".", "size", "(", ")", ")", ";", "synchronized", "(", "browsersMap", ")", "{", "browsersToClose", ".", "addAll", "(", "browsersMap", ".", "values", "(", ")", ")", ";", "}", "for", "(", "int", "n", "=", "0", ";", "n", "<", "browsersToClose", ".", "size", "(", ")", ";", "n", "++", ")", "{", "QueueBrowser", "browser", "=", "browsersToClose", ".", "get", "(", "n", ")", ";", "log", ".", "debug", "(", "\"Auto-closing unclosed browser : \"", "+", "browser", ")", ";", "try", "{", "browser", ".", "close", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "log", ".", "error", "(", "\"Could not close browser \"", "+", "browser", ",", "e", ")", ";", "}", "}", "}" ]
Close remaining browsers
[ "Close", "remaining", "browsers" ]
638773ee29a4a5f9c6119ed74ad14ac9c46382b3
https://github.com/timewalker74/ffmq/blob/638773ee29a4a5f9c6119ed74ad14ac9c46382b3/core/src/main/java/net/timewalker/ffmq4/common/session/AbstractSession.java#L325-L345
9,379
timewalker74/ffmq
core/src/main/java/net/timewalker/ffmq4/utils/JNDITools.java
JNDITools.getContext
public static Context getContext( String jdniInitialContextFactoryName , String providerURL , Hashtable<String,Object> extraEnv ) throws NamingException { Hashtable<String,Object> env = new Hashtable<>(); env.put(Context.INITIAL_CONTEXT_FACTORY, jdniInitialContextFactoryName); env.put(Context.PROVIDER_URL, providerURL); if (extraEnv != null) env.putAll(extraEnv); return createJndiContext(env); }
java
public static Context getContext( String jdniInitialContextFactoryName , String providerURL , Hashtable<String,Object> extraEnv ) throws NamingException { Hashtable<String,Object> env = new Hashtable<>(); env.put(Context.INITIAL_CONTEXT_FACTORY, jdniInitialContextFactoryName); env.put(Context.PROVIDER_URL, providerURL); if (extraEnv != null) env.putAll(extraEnv); return createJndiContext(env); }
[ "public", "static", "Context", "getContext", "(", "String", "jdniInitialContextFactoryName", ",", "String", "providerURL", ",", "Hashtable", "<", "String", ",", "Object", ">", "extraEnv", ")", "throws", "NamingException", "{", "Hashtable", "<", "String", ",", "Object", ">", "env", "=", "new", "Hashtable", "<>", "(", ")", ";", "env", ".", "put", "(", "Context", ".", "INITIAL_CONTEXT_FACTORY", ",", "jdniInitialContextFactoryName", ")", ";", "env", ".", "put", "(", "Context", ".", "PROVIDER_URL", ",", "providerURL", ")", ";", "if", "(", "extraEnv", "!=", "null", ")", "env", ".", "putAll", "(", "extraEnv", ")", ";", "return", "createJndiContext", "(", "env", ")", ";", "}" ]
Create a JNDI context for the current provider @param jdniInitialContextFactoryName @param providerURL @param extraEnv @return a JNDI context @throws NamingException
[ "Create", "a", "JNDI", "context", "for", "the", "current", "provider" ]
638773ee29a4a5f9c6119ed74ad14ac9c46382b3
https://github.com/timewalker74/ffmq/blob/638773ee29a4a5f9c6119ed74ad14ac9c46382b3/core/src/main/java/net/timewalker/ffmq4/utils/JNDITools.java#L52-L60
9,380
Domo42/saga-lib
saga-lib/src/main/java/com/codebullets/sagalib/processing/SagaEnvironment.java
SagaEnvironment.create
public static SagaEnvironment create( final TimeoutManager timeoutManager, final StateStorage storage, final Provider<CurrentExecutionContext> contextProvider, final Set<SagaModule> modules, final Set<SagaLifetimeInterceptor> interceptors, final InstanceResolver sagaInstanceResolver, final ModuleCoordinatorFactory coordinatorFactory) { return new SagaEnvironment(timeoutManager, storage, contextProvider, modules, interceptors, sagaInstanceResolver, coordinatorFactory); }
java
public static SagaEnvironment create( final TimeoutManager timeoutManager, final StateStorage storage, final Provider<CurrentExecutionContext> contextProvider, final Set<SagaModule> modules, final Set<SagaLifetimeInterceptor> interceptors, final InstanceResolver sagaInstanceResolver, final ModuleCoordinatorFactory coordinatorFactory) { return new SagaEnvironment(timeoutManager, storage, contextProvider, modules, interceptors, sagaInstanceResolver, coordinatorFactory); }
[ "public", "static", "SagaEnvironment", "create", "(", "final", "TimeoutManager", "timeoutManager", ",", "final", "StateStorage", "storage", ",", "final", "Provider", "<", "CurrentExecutionContext", ">", "contextProvider", ",", "final", "Set", "<", "SagaModule", ">", "modules", ",", "final", "Set", "<", "SagaLifetimeInterceptor", ">", "interceptors", ",", "final", "InstanceResolver", "sagaInstanceResolver", ",", "final", "ModuleCoordinatorFactory", "coordinatorFactory", ")", "{", "return", "new", "SagaEnvironment", "(", "timeoutManager", ",", "storage", ",", "contextProvider", ",", "modules", ",", "interceptors", ",", "sagaInstanceResolver", ",", "coordinatorFactory", ")", ";", "}" ]
Creates a new SagaEnvironment instance.
[ "Creates", "a", "new", "SagaEnvironment", "instance", "." ]
c8f232e2a51fcb6a3fe0082cfbf105c1e6bf90ef
https://github.com/Domo42/saga-lib/blob/c8f232e2a51fcb6a3fe0082cfbf105c1e6bf90ef/saga-lib/src/main/java/com/codebullets/sagalib/processing/SagaEnvironment.java#L116-L125
9,381
timewalker74/ffmq
core/src/main/java/net/timewalker/ffmq4/local/TransactionSet.java
TransactionSet.removeUpdatesForQueue
public synchronized void removeUpdatesForQueue( String queueName ) { Iterator<TransactionItem> entries = items.iterator(); while (entries.hasNext()) { TransactionItem item = entries.next(); if (item.getDestination().getName().equals(queueName)) entries.remove(); } }
java
public synchronized void removeUpdatesForQueue( String queueName ) { Iterator<TransactionItem> entries = items.iterator(); while (entries.hasNext()) { TransactionItem item = entries.next(); if (item.getDestination().getName().equals(queueName)) entries.remove(); } }
[ "public", "synchronized", "void", "removeUpdatesForQueue", "(", "String", "queueName", ")", "{", "Iterator", "<", "TransactionItem", ">", "entries", "=", "items", ".", "iterator", "(", ")", ";", "while", "(", "entries", ".", "hasNext", "(", ")", ")", "{", "TransactionItem", "item", "=", "entries", ".", "next", "(", ")", ";", "if", "(", "item", ".", "getDestination", "(", ")", ".", "getName", "(", ")", ".", "equals", "(", "queueName", ")", ")", "entries", ".", "remove", "(", ")", ";", "}", "}" ]
Remove all pending updates for the given queue @param queueName the queue name
[ "Remove", "all", "pending", "updates", "for", "the", "given", "queue" ]
638773ee29a4a5f9c6119ed74ad14ac9c46382b3
https://github.com/timewalker74/ffmq/blob/638773ee29a4a5f9c6119ed74ad14ac9c46382b3/core/src/main/java/net/timewalker/ffmq4/local/TransactionSet.java#L78-L87
9,382
timewalker74/ffmq
core/src/main/java/net/timewalker/ffmq4/local/TransactionSet.java
TransactionSet.clear
public synchronized TransactionItem[] clear( List<String> deliveredMessageIDs ) throws FFMQException { int len = deliveredMessageIDs.size(); TransactionItem[] itemsSnapshot = new TransactionItem[len]; for(int n=0;n<len;n++) { String deliveredMessageID = deliveredMessageIDs.get(len-n-1); boolean found = false; Iterator<TransactionItem> entries = items.iterator(); while (entries.hasNext()) { TransactionItem item = entries.next(); if (item.getMessageId().equals(deliveredMessageID)) { found = true; itemsSnapshot[n] = item; // Store in snapshot entries.remove(); break; } } if (!found) throw new FFMQException("Message does not belong to transaction : "+deliveredMessageID,"INTERNAL_ERROR"); } return itemsSnapshot; }
java
public synchronized TransactionItem[] clear( List<String> deliveredMessageIDs ) throws FFMQException { int len = deliveredMessageIDs.size(); TransactionItem[] itemsSnapshot = new TransactionItem[len]; for(int n=0;n<len;n++) { String deliveredMessageID = deliveredMessageIDs.get(len-n-1); boolean found = false; Iterator<TransactionItem> entries = items.iterator(); while (entries.hasNext()) { TransactionItem item = entries.next(); if (item.getMessageId().equals(deliveredMessageID)) { found = true; itemsSnapshot[n] = item; // Store in snapshot entries.remove(); break; } } if (!found) throw new FFMQException("Message does not belong to transaction : "+deliveredMessageID,"INTERNAL_ERROR"); } return itemsSnapshot; }
[ "public", "synchronized", "TransactionItem", "[", "]", "clear", "(", "List", "<", "String", ">", "deliveredMessageIDs", ")", "throws", "FFMQException", "{", "int", "len", "=", "deliveredMessageIDs", ".", "size", "(", ")", ";", "TransactionItem", "[", "]", "itemsSnapshot", "=", "new", "TransactionItem", "[", "len", "]", ";", "for", "(", "int", "n", "=", "0", ";", "n", "<", "len", ";", "n", "++", ")", "{", "String", "deliveredMessageID", "=", "deliveredMessageIDs", ".", "get", "(", "len", "-", "n", "-", "1", ")", ";", "boolean", "found", "=", "false", ";", "Iterator", "<", "TransactionItem", ">", "entries", "=", "items", ".", "iterator", "(", ")", ";", "while", "(", "entries", ".", "hasNext", "(", ")", ")", "{", "TransactionItem", "item", "=", "entries", ".", "next", "(", ")", ";", "if", "(", "item", ".", "getMessageId", "(", ")", ".", "equals", "(", "deliveredMessageID", ")", ")", "{", "found", "=", "true", ";", "itemsSnapshot", "[", "n", "]", "=", "item", ";", "// Store in snapshot", "entries", ".", "remove", "(", ")", ";", "break", ";", "}", "}", "if", "(", "!", "found", ")", "throw", "new", "FFMQException", "(", "\"Message does not belong to transaction : \"", "+", "deliveredMessageID", ",", "\"INTERNAL_ERROR\"", ")", ";", "}", "return", "itemsSnapshot", ";", "}" ]
Clear items by IDs from the transaction set and return a snapshot of the items
[ "Clear", "items", "by", "IDs", "from", "the", "transaction", "set", "and", "return", "a", "snapshot", "of", "the", "items" ]
638773ee29a4a5f9c6119ed74ad14ac9c46382b3
https://github.com/timewalker74/ffmq/blob/638773ee29a4a5f9c6119ed74ad14ac9c46382b3/core/src/main/java/net/timewalker/ffmq4/local/TransactionSet.java#L101-L127
9,383
timewalker74/ffmq
core/src/main/java/net/timewalker/ffmq4/local/TransactionSet.java
TransactionSet.clear
public synchronized TransactionItem[] clear() { // Create snapshot TransactionItem[] itemsSnapshot = items.toArray(new TransactionItem[items.size()]); // Clear items.clear(); return itemsSnapshot; }
java
public synchronized TransactionItem[] clear() { // Create snapshot TransactionItem[] itemsSnapshot = items.toArray(new TransactionItem[items.size()]); // Clear items.clear(); return itemsSnapshot; }
[ "public", "synchronized", "TransactionItem", "[", "]", "clear", "(", ")", "{", "// Create snapshot", "TransactionItem", "[", "]", "itemsSnapshot", "=", "items", ".", "toArray", "(", "new", "TransactionItem", "[", "items", ".", "size", "(", ")", "]", ")", ";", "// Clear", "items", ".", "clear", "(", ")", ";", "return", "itemsSnapshot", ";", "}" ]
Clear the set and return a snapshot of its content
[ "Clear", "the", "set", "and", "return", "a", "snapshot", "of", "its", "content" ]
638773ee29a4a5f9c6119ed74ad14ac9c46382b3
https://github.com/timewalker74/ffmq/blob/638773ee29a4a5f9c6119ed74ad14ac9c46382b3/core/src/main/java/net/timewalker/ffmq4/local/TransactionSet.java#L132-L141
9,384
timewalker74/ffmq
server/src/main/java/net/timewalker/ffmq4/spring/FFMQServerBean.java
FFMQServerBean.start
public void start() throws JMSException { if (server == null) { checkProperties(); log.info("Starting FFMQServerBean ..."); Settings settings = loadConfig(); server = new FFMQServer(engineName,settings); server.start(); } }
java
public void start() throws JMSException { if (server == null) { checkProperties(); log.info("Starting FFMQServerBean ..."); Settings settings = loadConfig(); server = new FFMQServer(engineName,settings); server.start(); } }
[ "public", "void", "start", "(", ")", "throws", "JMSException", "{", "if", "(", "server", "==", "null", ")", "{", "checkProperties", "(", ")", ";", "log", ".", "info", "(", "\"Starting FFMQServerBean ...\"", ")", ";", "Settings", "settings", "=", "loadConfig", "(", ")", ";", "server", "=", "new", "FFMQServer", "(", "engineName", ",", "settings", ")", ";", "server", ".", "start", "(", ")", ";", "}", "}" ]
Starts the server bean @throws JMSException on startup error
[ "Starts", "the", "server", "bean" ]
638773ee29a4a5f9c6119ed74ad14ac9c46382b3
https://github.com/timewalker74/ffmq/blob/638773ee29a4a5f9c6119ed74ad14ac9c46382b3/server/src/main/java/net/timewalker/ffmq4/spring/FFMQServerBean.java#L133-L143
9,385
Domo42/saga-lib
saga-lib/src/main/java/com/codebullets/sagalib/processing/SagaInstanceFactory.java
SagaInstanceFactory.createNew
public SagaInstanceInfo createNew(final SagaType type) { Saga newSaga = startNewSaga(type.getSagaClass()); return SagaInstanceInfo.define(newSaga, true); }
java
public SagaInstanceInfo createNew(final SagaType type) { Saga newSaga = startNewSaga(type.getSagaClass()); return SagaInstanceInfo.define(newSaga, true); }
[ "public", "SagaInstanceInfo", "createNew", "(", "final", "SagaType", "type", ")", "{", "Saga", "newSaga", "=", "startNewSaga", "(", "type", ".", "getSagaClass", "(", ")", ")", ";", "return", "SagaInstanceInfo", ".", "define", "(", "newSaga", ",", "true", ")", ";", "}" ]
Creates and initializes a new saga instance based on the provided type information.
[ "Creates", "and", "initializes", "a", "new", "saga", "instance", "based", "on", "the", "provided", "type", "information", "." ]
c8f232e2a51fcb6a3fe0082cfbf105c1e6bf90ef
https://github.com/Domo42/saga-lib/blob/c8f232e2a51fcb6a3fe0082cfbf105c1e6bf90ef/saga-lib/src/main/java/com/codebullets/sagalib/processing/SagaInstanceFactory.java#L47-L50
9,386
Domo42/saga-lib
saga-lib/src/main/java/com/codebullets/sagalib/processing/SagaInstanceFactory.java
SagaInstanceFactory.startNewSaga
private Saga startNewSaga(final Class<? extends Saga> sagaToStart) { Saga createdSaga = null; try { createdSaga = createNewSagaInstance(sagaToStart); createdSaga.createNewState(); SagaState newState = createdSaga.state(); newState.setSagaId(UUID.randomUUID().toString()); newState.setType(sagaToStart.getName()); } catch (Exception ex) { LOG.error("Unable to create new instance of saga type {}.", sagaToStart, ex); } return createdSaga; }
java
private Saga startNewSaga(final Class<? extends Saga> sagaToStart) { Saga createdSaga = null; try { createdSaga = createNewSagaInstance(sagaToStart); createdSaga.createNewState(); SagaState newState = createdSaga.state(); newState.setSagaId(UUID.randomUUID().toString()); newState.setType(sagaToStart.getName()); } catch (Exception ex) { LOG.error("Unable to create new instance of saga type {}.", sagaToStart, ex); } return createdSaga; }
[ "private", "Saga", "startNewSaga", "(", "final", "Class", "<", "?", "extends", "Saga", ">", "sagaToStart", ")", "{", "Saga", "createdSaga", "=", "null", ";", "try", "{", "createdSaga", "=", "createNewSagaInstance", "(", "sagaToStart", ")", ";", "createdSaga", ".", "createNewState", "(", ")", ";", "SagaState", "newState", "=", "createdSaga", ".", "state", "(", ")", ";", "newState", ".", "setSagaId", "(", "UUID", ".", "randomUUID", "(", ")", ".", "toString", "(", ")", ")", ";", "newState", ".", "setType", "(", "sagaToStart", ".", "getName", "(", ")", ")", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "LOG", ".", "error", "(", "\"Unable to create new instance of saga type {}.\"", ",", "sagaToStart", ",", "ex", ")", ";", "}", "return", "createdSaga", ";", "}" ]
Starts a new saga by creating an instance and attaching a new saga state.
[ "Starts", "a", "new", "saga", "by", "creating", "an", "instance", "and", "attaching", "a", "new", "saga", "state", "." ]
c8f232e2a51fcb6a3fe0082cfbf105c1e6bf90ef
https://github.com/Domo42/saga-lib/blob/c8f232e2a51fcb6a3fe0082cfbf105c1e6bf90ef/saga-lib/src/main/java/com/codebullets/sagalib/processing/SagaInstanceFactory.java#L55-L70
9,387
Domo42/saga-lib
saga-lib/src/main/java/com/codebullets/sagalib/processing/SagaInstanceFactory.java
SagaInstanceFactory.continueExisting
public Saga continueExisting(final Class<? extends Saga> sagaType, final SagaState state) throws ExecutionException { // do not catch exception as in create new // if there is an exception during creation, although we want to continue // something is terribly wrong -> it has worked at least once before. Saga saga = createNewSagaInstance(sagaType); saga.setState(state); return saga; }
java
public Saga continueExisting(final Class<? extends Saga> sagaType, final SagaState state) throws ExecutionException { // do not catch exception as in create new // if there is an exception during creation, although we want to continue // something is terribly wrong -> it has worked at least once before. Saga saga = createNewSagaInstance(sagaType); saga.setState(state); return saga; }
[ "public", "Saga", "continueExisting", "(", "final", "Class", "<", "?", "extends", "Saga", ">", "sagaType", ",", "final", "SagaState", "state", ")", "throws", "ExecutionException", "{", "// do not catch exception as in create new", "// if there is an exception during creation, although we want to continue", "// something is terribly wrong -> it has worked at least once before.", "Saga", "saga", "=", "createNewSagaInstance", "(", "sagaType", ")", ";", "saga", ".", "setState", "(", "state", ")", ";", "return", "saga", ";", "}" ]
Creates a new saga instance attaching an existing saga state. @throws ExecutionException Is thrown in case no provider can be found to create an instance. The actual cause can be inspected by {@link ExecutionException#getCause()}.
[ "Creates", "a", "new", "saga", "instance", "attaching", "an", "existing", "saga", "state", "." ]
c8f232e2a51fcb6a3fe0082cfbf105c1e6bf90ef
https://github.com/Domo42/saga-lib/blob/c8f232e2a51fcb6a3fe0082cfbf105c1e6bf90ef/saga-lib/src/main/java/com/codebullets/sagalib/processing/SagaInstanceFactory.java#L77-L84
9,388
Domo42/saga-lib
saga-lib/src/main/java/com/codebullets/sagalib/processing/SagaInstanceFactory.java
SagaInstanceFactory.continueExisting
public Saga continueExisting(final String sagaTypeName, final SagaState state) throws ExecutionException { return continueSaga(sagaTypeName, state); }
java
public Saga continueExisting(final String sagaTypeName, final SagaState state) throws ExecutionException { return continueSaga(sagaTypeName, state); }
[ "public", "Saga", "continueExisting", "(", "final", "String", "sagaTypeName", ",", "final", "SagaState", "state", ")", "throws", "ExecutionException", "{", "return", "continueSaga", "(", "sagaTypeName", ",", "state", ")", ";", "}" ]
Create a new saga instance based on fully qualified name and the existing saga state. @throws ExecutionException Is thrown in case no provider can be found to create an instance. The actual cause can be inspected by {@link ExecutionException#getCause()}.
[ "Create", "a", "new", "saga", "instance", "based", "on", "fully", "qualified", "name", "and", "the", "existing", "saga", "state", "." ]
c8f232e2a51fcb6a3fe0082cfbf105c1e6bf90ef
https://github.com/Domo42/saga-lib/blob/c8f232e2a51fcb6a3fe0082cfbf105c1e6bf90ef/saga-lib/src/main/java/com/codebullets/sagalib/processing/SagaInstanceFactory.java#L91-L93
9,389
timewalker74/ffmq
core/src/main/java/net/timewalker/ffmq4/utils/id/UUIDProvider.java
UUIDProvider.getUUID
public String getUUID() { StringBuilder uuid = new StringBuilder(36); int i = (int)System.currentTimeMillis(); int j = seed.nextInt(); hexFormat(i,uuid); uuid.append(fixedPart); hexFormat(j,uuid); return uuid.toString(); }
java
public String getUUID() { StringBuilder uuid = new StringBuilder(36); int i = (int)System.currentTimeMillis(); int j = seed.nextInt(); hexFormat(i,uuid); uuid.append(fixedPart); hexFormat(j,uuid); return uuid.toString(); }
[ "public", "String", "getUUID", "(", ")", "{", "StringBuilder", "uuid", "=", "new", "StringBuilder", "(", "36", ")", ";", "int", "i", "=", "(", "int", ")", "System", ".", "currentTimeMillis", "(", ")", ";", "int", "j", "=", "seed", ".", "nextInt", "(", ")", ";", "hexFormat", "(", "i", ",", "uuid", ")", ";", "uuid", ".", "append", "(", "fixedPart", ")", ";", "hexFormat", "(", "j", ",", "uuid", ")", ";", "return", "uuid", ".", "toString", "(", ")", ";", "}" ]
Generate a new UUID
[ "Generate", "a", "new", "UUID" ]
638773ee29a4a5f9c6119ed74ad14ac9c46382b3
https://github.com/timewalker74/ffmq/blob/638773ee29a4a5f9c6119ed74ad14ac9c46382b3/core/src/main/java/net/timewalker/ffmq4/utils/id/UUIDProvider.java#L100-L109
9,390
Domo42/saga-lib
saga-lib/src/main/java/com/codebullets/sagalib/AbstractSaga.java
AbstractSaga.requestTimeout
protected TimeoutId requestTimeout(final long delay, final TimeUnit unit) { return requestTimeout(delay, unit, null, null); }
java
protected TimeoutId requestTimeout(final long delay, final TimeUnit unit) { return requestTimeout(delay, unit, null, null); }
[ "protected", "TimeoutId", "requestTimeout", "(", "final", "long", "delay", ",", "final", "TimeUnit", "unit", ")", "{", "return", "requestTimeout", "(", "delay", ",", "unit", ",", "null", ",", "null", ")", ";", "}" ]
Requests a timeout event to be sent back to this saga.
[ "Requests", "a", "timeout", "event", "to", "be", "sent", "back", "to", "this", "saga", "." ]
c8f232e2a51fcb6a3fe0082cfbf105c1e6bf90ef
https://github.com/Domo42/saga-lib/blob/c8f232e2a51fcb6a3fe0082cfbf105c1e6bf90ef/saga-lib/src/main/java/com/codebullets/sagalib/AbstractSaga.java#L86-L88
9,391
Domo42/saga-lib
saga-lib/src/main/java/com/codebullets/sagalib/AbstractSaga.java
AbstractSaga.requestTimeout
protected TimeoutId requestTimeout(final long delay, final TimeUnit unit, @Nullable final String name) { return requestTimeout(delay, unit, name, null); }
java
protected TimeoutId requestTimeout(final long delay, final TimeUnit unit, @Nullable final String name) { return requestTimeout(delay, unit, name, null); }
[ "protected", "TimeoutId", "requestTimeout", "(", "final", "long", "delay", ",", "final", "TimeUnit", "unit", ",", "@", "Nullable", "final", "String", "name", ")", "{", "return", "requestTimeout", "(", "delay", ",", "unit", ",", "name", ",", "null", ")", ";", "}" ]
Requests a timeout event with a specific name to this saga. The name can be used to distinguish the timeout if multiple ones have been requested by the saga.
[ "Requests", "a", "timeout", "event", "with", "a", "specific", "name", "to", "this", "saga", ".", "The", "name", "can", "be", "used", "to", "distinguish", "the", "timeout", "if", "multiple", "ones", "have", "been", "requested", "by", "the", "saga", "." ]
c8f232e2a51fcb6a3fe0082cfbf105c1e6bf90ef
https://github.com/Domo42/saga-lib/blob/c8f232e2a51fcb6a3fe0082cfbf105c1e6bf90ef/saga-lib/src/main/java/com/codebullets/sagalib/AbstractSaga.java#L94-L96
9,392
Domo42/saga-lib
saga-lib/src/main/java/com/codebullets/sagalib/AbstractSaga.java
AbstractSaga.requestTimeout
protected TimeoutId requestTimeout(final long delay, final TimeUnit unit, @Nullable final Object data) { return requestTimeout(delay, unit, null, data); }
java
protected TimeoutId requestTimeout(final long delay, final TimeUnit unit, @Nullable final Object data) { return requestTimeout(delay, unit, null, data); }
[ "protected", "TimeoutId", "requestTimeout", "(", "final", "long", "delay", ",", "final", "TimeUnit", "unit", ",", "@", "Nullable", "final", "Object", "data", ")", "{", "return", "requestTimeout", "(", "delay", ",", "unit", ",", "null", ",", "data", ")", ";", "}" ]
Requests a timeout event attaching specific timeout data. This data is returned with the timeout message received.
[ "Requests", "a", "timeout", "event", "attaching", "specific", "timeout", "data", ".", "This", "data", "is", "returned", "with", "the", "timeout", "message", "received", "." ]
c8f232e2a51fcb6a3fe0082cfbf105c1e6bf90ef
https://github.com/Domo42/saga-lib/blob/c8f232e2a51fcb6a3fe0082cfbf105c1e6bf90ef/saga-lib/src/main/java/com/codebullets/sagalib/AbstractSaga.java#L102-L104
9,393
Domo42/saga-lib
saga-lib/src/main/java/com/codebullets/sagalib/AbstractSaga.java
AbstractSaga.requestTimeout
protected TimeoutId requestTimeout(final long delay, final TimeUnit unit, @Nullable final String name, @Nullable final Object data) { return timeoutManager.requestTimeout(context(), state().getSagaId(), delay, unit, name, data); }
java
protected TimeoutId requestTimeout(final long delay, final TimeUnit unit, @Nullable final String name, @Nullable final Object data) { return timeoutManager.requestTimeout(context(), state().getSagaId(), delay, unit, name, data); }
[ "protected", "TimeoutId", "requestTimeout", "(", "final", "long", "delay", ",", "final", "TimeUnit", "unit", ",", "@", "Nullable", "final", "String", "name", ",", "@", "Nullable", "final", "Object", "data", ")", "{", "return", "timeoutManager", ".", "requestTimeout", "(", "context", "(", ")", ",", "state", "(", ")", ".", "getSagaId", "(", ")", ",", "delay", ",", "unit", ",", "name", ",", "data", ")", ";", "}" ]
Requests a timeout event with a specific name and attached data.
[ "Requests", "a", "timeout", "event", "with", "a", "specific", "name", "and", "attached", "data", "." ]
c8f232e2a51fcb6a3fe0082cfbf105c1e6bf90ef
https://github.com/Domo42/saga-lib/blob/c8f232e2a51fcb6a3fe0082cfbf105c1e6bf90ef/saga-lib/src/main/java/com/codebullets/sagalib/AbstractSaga.java#L109-L111
9,394
timewalker74/ffmq
server/src/main/java/net/timewalker/ffmq4/listeners/ClientProcessor.java
ClientProcessor.process
protected AbstractResponsePacket process( AbstractQueryPacket query ) throws JMSException { switch (query.getType()) { case PacketType.Q_GET : return processGet((GetQuery)query); case PacketType.Q_PUT : return processPut((PutQuery)query); case PacketType.Q_COMMIT : return processCommit((CommitQuery)query); case PacketType.Q_ACKNOWLEDGE : return processAcknowledge((AcknowledgeQuery)query); case PacketType.Q_ROLLBACK : return processRollback((RollbackQuery)query); case PacketType.Q_RECOVER : return processRecover((RecoverQuery)query); case PacketType.Q_CREATE_SESSION : return processCreateSession((CreateSessionQuery)query); case PacketType.Q_CLOSE_SESSION : return processCloseSession((CloseSessionQuery)query); case PacketType.Q_CREATE_CONSUMER: return processCreateConsumer((CreateConsumerQuery)query); case PacketType.Q_CREATE_DURABLE_SUBSCRIBER : return processCreateDurableSubscriber((CreateDurableSubscriberQuery)query); case PacketType.Q_CREATE_BROWSER : return processCreateBrowser((CreateBrowserQuery)query); case PacketType.Q_CREATE_BROWSER_ENUM : return processQueueBrowserGetEnumeration((QueueBrowserGetEnumerationQuery)query); case PacketType.Q_BROWSER_ENUM_FETCH : return processQueueBrowserFetchElement((QueueBrowserFetchElementQuery)query); case PacketType.Q_CLOSE_CONSUMER : return processCloseConsumer((CloseConsumerQuery)query); case PacketType.Q_CLOSE_BROWSER : return processCloseBrowser((CloseBrowserQuery)query); case PacketType.Q_CLOSE_BROWSER_ENUM : return processCloseBrowserEnumeration((CloseBrowserEnumerationQuery)query); case PacketType.Q_CREATE_TEMP_QUEUE : return processCreateTemporaryQueue((CreateTemporaryQueueQuery)query); case PacketType.Q_CREATE_TEMP_TOPIC : return processCreateTemporaryTopic((CreateTemporaryTopicQuery)query); case PacketType.Q_DELETE_TEMP_QUEUE : return processDeleteTemporaryQueue((DeleteTemporaryQueueQuery)query); case PacketType.Q_DELETE_TEMP_TOPIC : return processDeleteTemporaryTopic((DeleteTemporaryTopicQuery)query); case PacketType.Q_OPEN_CONNECTION : return processOpenConnection((OpenConnectionQuery)query); case PacketType.Q_START_CONNECTION : return processStartConnection(); case PacketType.Q_STOP_CONNECTION : return processStopConnection(); case PacketType.Q_SET_CLIENT_ID : return processSetClientID((SetClientIDQuery)query); case PacketType.Q_UNSUBSCRIBE : return processUnsubscribe((UnsubscribeQuery)query); case PacketType.Q_PREFETCH : return processPrefetch((PrefetchQuery)query); case PacketType.Q_PING : return processPing(); case PacketType.Q_ROLLBACK_MESSAGE : return processRollbackMessage((RollbackMessageQuery)query); default: throw new javax.jms.IllegalStateException("Unkown query type id : "+query.getType()); } }
java
protected AbstractResponsePacket process( AbstractQueryPacket query ) throws JMSException { switch (query.getType()) { case PacketType.Q_GET : return processGet((GetQuery)query); case PacketType.Q_PUT : return processPut((PutQuery)query); case PacketType.Q_COMMIT : return processCommit((CommitQuery)query); case PacketType.Q_ACKNOWLEDGE : return processAcknowledge((AcknowledgeQuery)query); case PacketType.Q_ROLLBACK : return processRollback((RollbackQuery)query); case PacketType.Q_RECOVER : return processRecover((RecoverQuery)query); case PacketType.Q_CREATE_SESSION : return processCreateSession((CreateSessionQuery)query); case PacketType.Q_CLOSE_SESSION : return processCloseSession((CloseSessionQuery)query); case PacketType.Q_CREATE_CONSUMER: return processCreateConsumer((CreateConsumerQuery)query); case PacketType.Q_CREATE_DURABLE_SUBSCRIBER : return processCreateDurableSubscriber((CreateDurableSubscriberQuery)query); case PacketType.Q_CREATE_BROWSER : return processCreateBrowser((CreateBrowserQuery)query); case PacketType.Q_CREATE_BROWSER_ENUM : return processQueueBrowserGetEnumeration((QueueBrowserGetEnumerationQuery)query); case PacketType.Q_BROWSER_ENUM_FETCH : return processQueueBrowserFetchElement((QueueBrowserFetchElementQuery)query); case PacketType.Q_CLOSE_CONSUMER : return processCloseConsumer((CloseConsumerQuery)query); case PacketType.Q_CLOSE_BROWSER : return processCloseBrowser((CloseBrowserQuery)query); case PacketType.Q_CLOSE_BROWSER_ENUM : return processCloseBrowserEnumeration((CloseBrowserEnumerationQuery)query); case PacketType.Q_CREATE_TEMP_QUEUE : return processCreateTemporaryQueue((CreateTemporaryQueueQuery)query); case PacketType.Q_CREATE_TEMP_TOPIC : return processCreateTemporaryTopic((CreateTemporaryTopicQuery)query); case PacketType.Q_DELETE_TEMP_QUEUE : return processDeleteTemporaryQueue((DeleteTemporaryQueueQuery)query); case PacketType.Q_DELETE_TEMP_TOPIC : return processDeleteTemporaryTopic((DeleteTemporaryTopicQuery)query); case PacketType.Q_OPEN_CONNECTION : return processOpenConnection((OpenConnectionQuery)query); case PacketType.Q_START_CONNECTION : return processStartConnection(); case PacketType.Q_STOP_CONNECTION : return processStopConnection(); case PacketType.Q_SET_CLIENT_ID : return processSetClientID((SetClientIDQuery)query); case PacketType.Q_UNSUBSCRIBE : return processUnsubscribe((UnsubscribeQuery)query); case PacketType.Q_PREFETCH : return processPrefetch((PrefetchQuery)query); case PacketType.Q_PING : return processPing(); case PacketType.Q_ROLLBACK_MESSAGE : return processRollbackMessage((RollbackMessageQuery)query); default: throw new javax.jms.IllegalStateException("Unkown query type id : "+query.getType()); } }
[ "protected", "AbstractResponsePacket", "process", "(", "AbstractQueryPacket", "query", ")", "throws", "JMSException", "{", "switch", "(", "query", ".", "getType", "(", ")", ")", "{", "case", "PacketType", ".", "Q_GET", ":", "return", "processGet", "(", "(", "GetQuery", ")", "query", ")", ";", "case", "PacketType", ".", "Q_PUT", ":", "return", "processPut", "(", "(", "PutQuery", ")", "query", ")", ";", "case", "PacketType", ".", "Q_COMMIT", ":", "return", "processCommit", "(", "(", "CommitQuery", ")", "query", ")", ";", "case", "PacketType", ".", "Q_ACKNOWLEDGE", ":", "return", "processAcknowledge", "(", "(", "AcknowledgeQuery", ")", "query", ")", ";", "case", "PacketType", ".", "Q_ROLLBACK", ":", "return", "processRollback", "(", "(", "RollbackQuery", ")", "query", ")", ";", "case", "PacketType", ".", "Q_RECOVER", ":", "return", "processRecover", "(", "(", "RecoverQuery", ")", "query", ")", ";", "case", "PacketType", ".", "Q_CREATE_SESSION", ":", "return", "processCreateSession", "(", "(", "CreateSessionQuery", ")", "query", ")", ";", "case", "PacketType", ".", "Q_CLOSE_SESSION", ":", "return", "processCloseSession", "(", "(", "CloseSessionQuery", ")", "query", ")", ";", "case", "PacketType", ".", "Q_CREATE_CONSUMER", ":", "return", "processCreateConsumer", "(", "(", "CreateConsumerQuery", ")", "query", ")", ";", "case", "PacketType", ".", "Q_CREATE_DURABLE_SUBSCRIBER", ":", "return", "processCreateDurableSubscriber", "(", "(", "CreateDurableSubscriberQuery", ")", "query", ")", ";", "case", "PacketType", ".", "Q_CREATE_BROWSER", ":", "return", "processCreateBrowser", "(", "(", "CreateBrowserQuery", ")", "query", ")", ";", "case", "PacketType", ".", "Q_CREATE_BROWSER_ENUM", ":", "return", "processQueueBrowserGetEnumeration", "(", "(", "QueueBrowserGetEnumerationQuery", ")", "query", ")", ";", "case", "PacketType", ".", "Q_BROWSER_ENUM_FETCH", ":", "return", "processQueueBrowserFetchElement", "(", "(", "QueueBrowserFetchElementQuery", ")", "query", ")", ";", "case", "PacketType", ".", "Q_CLOSE_CONSUMER", ":", "return", "processCloseConsumer", "(", "(", "CloseConsumerQuery", ")", "query", ")", ";", "case", "PacketType", ".", "Q_CLOSE_BROWSER", ":", "return", "processCloseBrowser", "(", "(", "CloseBrowserQuery", ")", "query", ")", ";", "case", "PacketType", ".", "Q_CLOSE_BROWSER_ENUM", ":", "return", "processCloseBrowserEnumeration", "(", "(", "CloseBrowserEnumerationQuery", ")", "query", ")", ";", "case", "PacketType", ".", "Q_CREATE_TEMP_QUEUE", ":", "return", "processCreateTemporaryQueue", "(", "(", "CreateTemporaryQueueQuery", ")", "query", ")", ";", "case", "PacketType", ".", "Q_CREATE_TEMP_TOPIC", ":", "return", "processCreateTemporaryTopic", "(", "(", "CreateTemporaryTopicQuery", ")", "query", ")", ";", "case", "PacketType", ".", "Q_DELETE_TEMP_QUEUE", ":", "return", "processDeleteTemporaryQueue", "(", "(", "DeleteTemporaryQueueQuery", ")", "query", ")", ";", "case", "PacketType", ".", "Q_DELETE_TEMP_TOPIC", ":", "return", "processDeleteTemporaryTopic", "(", "(", "DeleteTemporaryTopicQuery", ")", "query", ")", ";", "case", "PacketType", ".", "Q_OPEN_CONNECTION", ":", "return", "processOpenConnection", "(", "(", "OpenConnectionQuery", ")", "query", ")", ";", "case", "PacketType", ".", "Q_START_CONNECTION", ":", "return", "processStartConnection", "(", ")", ";", "case", "PacketType", ".", "Q_STOP_CONNECTION", ":", "return", "processStopConnection", "(", ")", ";", "case", "PacketType", ".", "Q_SET_CLIENT_ID", ":", "return", "processSetClientID", "(", "(", "SetClientIDQuery", ")", "query", ")", ";", "case", "PacketType", ".", "Q_UNSUBSCRIBE", ":", "return", "processUnsubscribe", "(", "(", "UnsubscribeQuery", ")", "query", ")", ";", "case", "PacketType", ".", "Q_PREFETCH", ":", "return", "processPrefetch", "(", "(", "PrefetchQuery", ")", "query", ")", ";", "case", "PacketType", ".", "Q_PING", ":", "return", "processPing", "(", ")", ";", "case", "PacketType", ".", "Q_ROLLBACK_MESSAGE", ":", "return", "processRollbackMessage", "(", "(", "RollbackMessageQuery", ")", "query", ")", ";", "default", ":", "throw", "new", "javax", ".", "jms", ".", "IllegalStateException", "(", "\"Unkown query type id : \"", "+", "query", ".", "getType", "(", ")", ")", ";", "}", "}" ]
Process an incoming packet
[ "Process", "an", "incoming", "packet" ]
638773ee29a4a5f9c6119ed74ad14ac9c46382b3
https://github.com/timewalker74/ffmq/blob/638773ee29a4a5f9c6119ed74ad14ac9c46382b3/server/src/main/java/net/timewalker/ffmq4/listeners/ClientProcessor.java#L363-L399
9,395
timewalker74/ffmq
core/src/main/java/net/timewalker/ffmq4/jndi/FFMQInitialContextFactory.java
FFMQInitialContextFactory.preLoad
@SuppressWarnings("unchecked") protected void preLoad(FFMQJNDIContext context) throws NamingException { context.bind(FFMQConstants.JNDI_CONNECTION_FACTORY_NAME, new FFMQConnectionFactory((Hashtable<String, Object>) context.getEnvironment())); context.bind(FFMQConstants.JNDI_QUEUE_CONNECTION_FACTORY_NAME, new FFMQQueueConnectionFactory((Hashtable<String, Object>) context.getEnvironment())); context.bind(FFMQConstants.JNDI_TOPIC_CONNECTION_FACTORY_NAME, new FFMQTopicConnectionFactory((Hashtable<String, Object>) context.getEnvironment())); }
java
@SuppressWarnings("unchecked") protected void preLoad(FFMQJNDIContext context) throws NamingException { context.bind(FFMQConstants.JNDI_CONNECTION_FACTORY_NAME, new FFMQConnectionFactory((Hashtable<String, Object>) context.getEnvironment())); context.bind(FFMQConstants.JNDI_QUEUE_CONNECTION_FACTORY_NAME, new FFMQQueueConnectionFactory((Hashtable<String, Object>) context.getEnvironment())); context.bind(FFMQConstants.JNDI_TOPIC_CONNECTION_FACTORY_NAME, new FFMQTopicConnectionFactory((Hashtable<String, Object>) context.getEnvironment())); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "protected", "void", "preLoad", "(", "FFMQJNDIContext", "context", ")", "throws", "NamingException", "{", "context", ".", "bind", "(", "FFMQConstants", ".", "JNDI_CONNECTION_FACTORY_NAME", ",", "new", "FFMQConnectionFactory", "(", "(", "Hashtable", "<", "String", ",", "Object", ">", ")", "context", ".", "getEnvironment", "(", ")", ")", ")", ";", "context", ".", "bind", "(", "FFMQConstants", ".", "JNDI_QUEUE_CONNECTION_FACTORY_NAME", ",", "new", "FFMQQueueConnectionFactory", "(", "(", "Hashtable", "<", "String", ",", "Object", ">", ")", "context", ".", "getEnvironment", "(", ")", ")", ")", ";", "context", ".", "bind", "(", "FFMQConstants", ".", "JNDI_TOPIC_CONNECTION_FACTORY_NAME", ",", "new", "FFMQTopicConnectionFactory", "(", "(", "Hashtable", "<", "String", ",", "Object", ">", ")", "context", ".", "getEnvironment", "(", ")", ")", ")", ";", "}" ]
Preload the context with factories
[ "Preload", "the", "context", "with", "factories" ]
638773ee29a4a5f9c6119ed74ad14ac9c46382b3
https://github.com/timewalker74/ffmq/blob/638773ee29a4a5f9c6119ed74ad14ac9c46382b3/core/src/main/java/net/timewalker/ffmq4/jndi/FFMQInitialContextFactory.java#L58-L64
9,396
Domo42/saga-lib
saga-lib/src/main/java/com/codebullets/sagalib/Headers.java
Headers.copyFromStream
public static Map<HeaderName<?>, Object> copyFromStream(@Nullable final Stream<Map.Entry<HeaderName<?>, Object>> stream) { Map<HeaderName<?>, Object> headerMap; if (stream == null) { headerMap = new HashMap<>(); } else { headerMap = stream.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); } return headerMap; }
java
public static Map<HeaderName<?>, Object> copyFromStream(@Nullable final Stream<Map.Entry<HeaderName<?>, Object>> stream) { Map<HeaderName<?>, Object> headerMap; if (stream == null) { headerMap = new HashMap<>(); } else { headerMap = stream.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); } return headerMap; }
[ "public", "static", "Map", "<", "HeaderName", "<", "?", ">", ",", "Object", ">", "copyFromStream", "(", "@", "Nullable", "final", "Stream", "<", "Map", ".", "Entry", "<", "HeaderName", "<", "?", ">", ",", "Object", ">", ">", "stream", ")", "{", "Map", "<", "HeaderName", "<", "?", ">", ",", "Object", ">", "headerMap", ";", "if", "(", "stream", "==", "null", ")", "{", "headerMap", "=", "new", "HashMap", "<>", "(", ")", ";", "}", "else", "{", "headerMap", "=", "stream", ".", "collect", "(", "Collectors", ".", "toMap", "(", "Map", ".", "Entry", "::", "getKey", ",", "Map", ".", "Entry", "::", "getValue", ")", ")", ";", "}", "return", "headerMap", ";", "}" ]
Creates a new map, by picking all header entries from the provided stream.
[ "Creates", "a", "new", "map", "by", "picking", "all", "header", "entries", "from", "the", "provided", "stream", "." ]
c8f232e2a51fcb6a3fe0082cfbf105c1e6bf90ef
https://github.com/Domo42/saga-lib/blob/c8f232e2a51fcb6a3fe0082cfbf105c1e6bf90ef/saga-lib/src/main/java/com/codebullets/sagalib/Headers.java#L35-L45
9,397
Domo42/saga-lib
saga-lib/src/main/java/com/codebullets/sagalib/processing/TypesForMessageMapper.java
TypesForMessageMapper.setPreferredOrder
public void setPreferredOrder(final Collection<Class<? extends Saga>> preferredOrder) { checkNotNull(preferredOrder, "Preferred order list may not be null. Empty is allowed."); cacheLoader.setPreferredOrder(preferredOrder); sagasForMessageType.invalidateAll(); }
java
public void setPreferredOrder(final Collection<Class<? extends Saga>> preferredOrder) { checkNotNull(preferredOrder, "Preferred order list may not be null. Empty is allowed."); cacheLoader.setPreferredOrder(preferredOrder); sagasForMessageType.invalidateAll(); }
[ "public", "void", "setPreferredOrder", "(", "final", "Collection", "<", "Class", "<", "?", "extends", "Saga", ">", ">", "preferredOrder", ")", "{", "checkNotNull", "(", "preferredOrder", ",", "\"Preferred order list may not be null. Empty is allowed.\"", ")", ";", "cacheLoader", ".", "setPreferredOrder", "(", "preferredOrder", ")", ";", "sagasForMessageType", ".", "invalidateAll", "(", ")", ";", "}" ]
Sets the handlers that should be executed first.
[ "Sets", "the", "handlers", "that", "should", "be", "executed", "first", "." ]
c8f232e2a51fcb6a3fe0082cfbf105c1e6bf90ef
https://github.com/Domo42/saga-lib/blob/c8f232e2a51fcb6a3fe0082cfbf105c1e6bf90ef/saga-lib/src/main/java/com/codebullets/sagalib/processing/TypesForMessageMapper.java#L60-L65
9,398
Domo42/saga-lib
saga-lib/src/main/java/com/codebullets/sagalib/processing/TypesForMessageMapper.java
TypesForMessageMapper.initializeMessageMappings
private Multimap<Class, SagaType> initializeMessageMappings(final Map<Class<? extends Saga>, SagaHandlersMap> handlersMap) { Multimap<Class, SagaType> scannedTypes = LinkedListMultimap.create(); for (Map.Entry<Class<? extends Saga>, SagaHandlersMap> entry : handlersMap.entrySet()) { Class<? extends Saga> sagaClass = entry.getKey(); Collection<MessageHandler> sagaHandlers = entry.getValue().messageHandlers(); for (MessageHandler handler : sagaHandlers) { // remember all message types where a completely new saga needs to be started. if (handler.getStartsSaga()) { scannedTypes.put(handler.getMessageType(), SagaType.startsNewSaga(sagaClass)); } else { scannedTypes.put(handler.getMessageType(), SagaType.continueSaga(sagaClass)); } } } return scannedTypes; }
java
private Multimap<Class, SagaType> initializeMessageMappings(final Map<Class<? extends Saga>, SagaHandlersMap> handlersMap) { Multimap<Class, SagaType> scannedTypes = LinkedListMultimap.create(); for (Map.Entry<Class<? extends Saga>, SagaHandlersMap> entry : handlersMap.entrySet()) { Class<? extends Saga> sagaClass = entry.getKey(); Collection<MessageHandler> sagaHandlers = entry.getValue().messageHandlers(); for (MessageHandler handler : sagaHandlers) { // remember all message types where a completely new saga needs to be started. if (handler.getStartsSaga()) { scannedTypes.put(handler.getMessageType(), SagaType.startsNewSaga(sagaClass)); } else { scannedTypes.put(handler.getMessageType(), SagaType.continueSaga(sagaClass)); } } } return scannedTypes; }
[ "private", "Multimap", "<", "Class", ",", "SagaType", ">", "initializeMessageMappings", "(", "final", "Map", "<", "Class", "<", "?", "extends", "Saga", ">", ",", "SagaHandlersMap", ">", "handlersMap", ")", "{", "Multimap", "<", "Class", ",", "SagaType", ">", "scannedTypes", "=", "LinkedListMultimap", ".", "create", "(", ")", ";", "for", "(", "Map", ".", "Entry", "<", "Class", "<", "?", "extends", "Saga", ">", ",", "SagaHandlersMap", ">", "entry", ":", "handlersMap", ".", "entrySet", "(", ")", ")", "{", "Class", "<", "?", "extends", "Saga", ">", "sagaClass", "=", "entry", ".", "getKey", "(", ")", ";", "Collection", "<", "MessageHandler", ">", "sagaHandlers", "=", "entry", ".", "getValue", "(", ")", ".", "messageHandlers", "(", ")", ";", "for", "(", "MessageHandler", "handler", ":", "sagaHandlers", ")", "{", "// remember all message types where a completely new saga needs to be started.", "if", "(", "handler", ".", "getStartsSaga", "(", ")", ")", "{", "scannedTypes", ".", "put", "(", "handler", ".", "getMessageType", "(", ")", ",", "SagaType", ".", "startsNewSaga", "(", "sagaClass", ")", ")", ";", "}", "else", "{", "scannedTypes", ".", "put", "(", "handler", ".", "getMessageType", "(", ")", ",", "SagaType", ".", "continueSaga", "(", "sagaClass", ")", ")", ";", "}", "}", "}", "return", "scannedTypes", ";", "}" ]
Populate internal map to translate between incoming message event type and saga type.
[ "Populate", "internal", "map", "to", "translate", "between", "incoming", "message", "event", "type", "and", "saga", "type", "." ]
c8f232e2a51fcb6a3fe0082cfbf105c1e6bf90ef
https://github.com/Domo42/saga-lib/blob/c8f232e2a51fcb6a3fe0082cfbf105c1e6bf90ef/saga-lib/src/main/java/com/codebullets/sagalib/processing/TypesForMessageMapper.java#L77-L96
9,399
timewalker74/ffmq
core/src/main/java/net/timewalker/ffmq4/management/destination/definition/TopicDefinition.java
TopicDefinition.supportDeliveryMode
public boolean supportDeliveryMode( int deliveryMode ) { switch (deliveryMode) { case DeliveryMode.PERSISTENT : return initialBlockCount > 0; case DeliveryMode.NON_PERSISTENT : return maxNonPersistentMessages > 0; default : throw new IllegalArgumentException("Invalid delivery mode : "+deliveryMode); } }
java
public boolean supportDeliveryMode( int deliveryMode ) { switch (deliveryMode) { case DeliveryMode.PERSISTENT : return initialBlockCount > 0; case DeliveryMode.NON_PERSISTENT : return maxNonPersistentMessages > 0; default : throw new IllegalArgumentException("Invalid delivery mode : "+deliveryMode); } }
[ "public", "boolean", "supportDeliveryMode", "(", "int", "deliveryMode", ")", "{", "switch", "(", "deliveryMode", ")", "{", "case", "DeliveryMode", ".", "PERSISTENT", ":", "return", "initialBlockCount", ">", "0", ";", "case", "DeliveryMode", ".", "NON_PERSISTENT", ":", "return", "maxNonPersistentMessages", ">", "0", ";", "default", ":", "throw", "new", "IllegalArgumentException", "(", "\"Invalid delivery mode : \"", "+", "deliveryMode", ")", ";", "}", "}" ]
Test if this topic definition supports the given delivery mode @param deliveryMode a delivery mode @return true if the mode is supported
[ "Test", "if", "this", "topic", "definition", "supports", "the", "given", "delivery", "mode" ]
638773ee29a4a5f9c6119ed74ad14ac9c46382b3
https://github.com/timewalker74/ffmq/blob/638773ee29a4a5f9c6119ed74ad14ac9c46382b3/core/src/main/java/net/timewalker/ffmq4/management/destination/definition/TopicDefinition.java#L160-L169