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
27,100
igniterealtime/Smack
smack-core/src/main/java/org/jivesoftware/smack/util/PacketParserUtils.java
PacketParserUtils.parseStreamError
public static StreamError parseStreamError(XmlPullParser parser, XmlEnvironment outerXmlEnvironment) throws XmlPullParserException, IOException, SmackParsingException { final int initialDepth = parser.getDepth(); List<ExtensionElement> extensions = new ArrayList<>(); Map<String, String> descriptiveTexts = null; StreamError.Condition condition = null; String conditionText = null; XmlEnvironment streamErrorXmlEnvironment = XmlEnvironment.from(parser, outerXmlEnvironment); outerloop: while (true) { int eventType = parser.next(); switch (eventType) { case XmlPullParser.START_TAG: String name = parser.getName(); String namespace = parser.getNamespace(); switch (namespace) { case StreamError.NAMESPACE: switch (name) { case "text": descriptiveTexts = parseDescriptiveTexts(parser, descriptiveTexts); break; default: // If it's not a text element, that is qualified by the StreamError.NAMESPACE, // then it has to be the stream error code condition = StreamError.Condition.fromString(name); if (!parser.isEmptyElementTag()) { conditionText = parser.nextText(); } break; } break; default: PacketParserUtils.addExtensionElement(extensions, parser, name, namespace, streamErrorXmlEnvironment); break; } break; case XmlPullParser.END_TAG: if (parser.getDepth() == initialDepth) { break outerloop; } break; } } return new StreamError(condition, conditionText, descriptiveTexts, extensions); }
java
public static StreamError parseStreamError(XmlPullParser parser, XmlEnvironment outerXmlEnvironment) throws XmlPullParserException, IOException, SmackParsingException { final int initialDepth = parser.getDepth(); List<ExtensionElement> extensions = new ArrayList<>(); Map<String, String> descriptiveTexts = null; StreamError.Condition condition = null; String conditionText = null; XmlEnvironment streamErrorXmlEnvironment = XmlEnvironment.from(parser, outerXmlEnvironment); outerloop: while (true) { int eventType = parser.next(); switch (eventType) { case XmlPullParser.START_TAG: String name = parser.getName(); String namespace = parser.getNamespace(); switch (namespace) { case StreamError.NAMESPACE: switch (name) { case "text": descriptiveTexts = parseDescriptiveTexts(parser, descriptiveTexts); break; default: // If it's not a text element, that is qualified by the StreamError.NAMESPACE, // then it has to be the stream error code condition = StreamError.Condition.fromString(name); if (!parser.isEmptyElementTag()) { conditionText = parser.nextText(); } break; } break; default: PacketParserUtils.addExtensionElement(extensions, parser, name, namespace, streamErrorXmlEnvironment); break; } break; case XmlPullParser.END_TAG: if (parser.getDepth() == initialDepth) { break outerloop; } break; } } return new StreamError(condition, conditionText, descriptiveTexts, extensions); }
[ "public", "static", "StreamError", "parseStreamError", "(", "XmlPullParser", "parser", ",", "XmlEnvironment", "outerXmlEnvironment", ")", "throws", "XmlPullParserException", ",", "IOException", ",", "SmackParsingException", "{", "final", "int", "initialDepth", "=", "parser", ".", "getDepth", "(", ")", ";", "List", "<", "ExtensionElement", ">", "extensions", "=", "new", "ArrayList", "<>", "(", ")", ";", "Map", "<", "String", ",", "String", ">", "descriptiveTexts", "=", "null", ";", "StreamError", ".", "Condition", "condition", "=", "null", ";", "String", "conditionText", "=", "null", ";", "XmlEnvironment", "streamErrorXmlEnvironment", "=", "XmlEnvironment", ".", "from", "(", "parser", ",", "outerXmlEnvironment", ")", ";", "outerloop", ":", "while", "(", "true", ")", "{", "int", "eventType", "=", "parser", ".", "next", "(", ")", ";", "switch", "(", "eventType", ")", "{", "case", "XmlPullParser", ".", "START_TAG", ":", "String", "name", "=", "parser", ".", "getName", "(", ")", ";", "String", "namespace", "=", "parser", ".", "getNamespace", "(", ")", ";", "switch", "(", "namespace", ")", "{", "case", "StreamError", ".", "NAMESPACE", ":", "switch", "(", "name", ")", "{", "case", "\"text\"", ":", "descriptiveTexts", "=", "parseDescriptiveTexts", "(", "parser", ",", "descriptiveTexts", ")", ";", "break", ";", "default", ":", "// If it's not a text element, that is qualified by the StreamError.NAMESPACE,", "// then it has to be the stream error code", "condition", "=", "StreamError", ".", "Condition", ".", "fromString", "(", "name", ")", ";", "if", "(", "!", "parser", ".", "isEmptyElementTag", "(", ")", ")", "{", "conditionText", "=", "parser", ".", "nextText", "(", ")", ";", "}", "break", ";", "}", "break", ";", "default", ":", "PacketParserUtils", ".", "addExtensionElement", "(", "extensions", ",", "parser", ",", "name", ",", "namespace", ",", "streamErrorXmlEnvironment", ")", ";", "break", ";", "}", "break", ";", "case", "XmlPullParser", ".", "END_TAG", ":", "if", "(", "parser", ".", "getDepth", "(", ")", "==", "initialDepth", ")", "{", "break", "outerloop", ";", "}", "break", ";", "}", "}", "return", "new", "StreamError", "(", "condition", ",", "conditionText", ",", "descriptiveTexts", ",", "extensions", ")", ";", "}" ]
Parses stream error packets. @param parser the XML parser. @param outerXmlEnvironment the outer XML environment (optional). @return an stream error packet. @throws IOException @throws XmlPullParserException @throws SmackParsingException
[ "Parses", "stream", "error", "packets", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-core/src/main/java/org/jivesoftware/smack/util/PacketParserUtils.java#L821-L863
27,101
igniterealtime/Smack
smack-core/src/main/java/org/jivesoftware/smack/util/PacketParserUtils.java
PacketParserUtils.parseError
public static StanzaError.Builder parseError(XmlPullParser parser, XmlEnvironment outerXmlEnvironment) throws XmlPullParserException, IOException, SmackParsingException { final int initialDepth = parser.getDepth(); Map<String, String> descriptiveTexts = null; XmlEnvironment stanzaErrorXmlEnvironment = XmlEnvironment.from(parser, outerXmlEnvironment); List<ExtensionElement> extensions = new ArrayList<>(); StanzaError.Builder builder = StanzaError.getBuilder(); // Parse the error header builder.setType(StanzaError.Type.fromString(parser.getAttributeValue("", "type"))); builder.setErrorGenerator(parser.getAttributeValue("", "by")); outerloop: while (true) { int eventType = parser.next(); switch (eventType) { case XmlPullParser.START_TAG: String name = parser.getName(); String namespace = parser.getNamespace(); switch (namespace) { case StanzaError.ERROR_CONDITION_AND_TEXT_NAMESPACE: switch (name) { case Stanza.TEXT: descriptiveTexts = parseDescriptiveTexts(parser, descriptiveTexts); break; default: builder.setCondition(StanzaError.Condition.fromString(name)); if (!parser.isEmptyElementTag()) { builder.setConditionText(parser.nextText()); } break; } break; default: PacketParserUtils.addExtensionElement(extensions, parser, name, namespace, stanzaErrorXmlEnvironment); } break; case XmlPullParser.END_TAG: if (parser.getDepth() == initialDepth) { break outerloop; } } } builder.setExtensions(extensions).setDescriptiveTexts(descriptiveTexts); return builder; }
java
public static StanzaError.Builder parseError(XmlPullParser parser, XmlEnvironment outerXmlEnvironment) throws XmlPullParserException, IOException, SmackParsingException { final int initialDepth = parser.getDepth(); Map<String, String> descriptiveTexts = null; XmlEnvironment stanzaErrorXmlEnvironment = XmlEnvironment.from(parser, outerXmlEnvironment); List<ExtensionElement> extensions = new ArrayList<>(); StanzaError.Builder builder = StanzaError.getBuilder(); // Parse the error header builder.setType(StanzaError.Type.fromString(parser.getAttributeValue("", "type"))); builder.setErrorGenerator(parser.getAttributeValue("", "by")); outerloop: while (true) { int eventType = parser.next(); switch (eventType) { case XmlPullParser.START_TAG: String name = parser.getName(); String namespace = parser.getNamespace(); switch (namespace) { case StanzaError.ERROR_CONDITION_AND_TEXT_NAMESPACE: switch (name) { case Stanza.TEXT: descriptiveTexts = parseDescriptiveTexts(parser, descriptiveTexts); break; default: builder.setCondition(StanzaError.Condition.fromString(name)); if (!parser.isEmptyElementTag()) { builder.setConditionText(parser.nextText()); } break; } break; default: PacketParserUtils.addExtensionElement(extensions, parser, name, namespace, stanzaErrorXmlEnvironment); } break; case XmlPullParser.END_TAG: if (parser.getDepth() == initialDepth) { break outerloop; } } } builder.setExtensions(extensions).setDescriptiveTexts(descriptiveTexts); return builder; }
[ "public", "static", "StanzaError", ".", "Builder", "parseError", "(", "XmlPullParser", "parser", ",", "XmlEnvironment", "outerXmlEnvironment", ")", "throws", "XmlPullParserException", ",", "IOException", ",", "SmackParsingException", "{", "final", "int", "initialDepth", "=", "parser", ".", "getDepth", "(", ")", ";", "Map", "<", "String", ",", "String", ">", "descriptiveTexts", "=", "null", ";", "XmlEnvironment", "stanzaErrorXmlEnvironment", "=", "XmlEnvironment", ".", "from", "(", "parser", ",", "outerXmlEnvironment", ")", ";", "List", "<", "ExtensionElement", ">", "extensions", "=", "new", "ArrayList", "<>", "(", ")", ";", "StanzaError", ".", "Builder", "builder", "=", "StanzaError", ".", "getBuilder", "(", ")", ";", "// Parse the error header", "builder", ".", "setType", "(", "StanzaError", ".", "Type", ".", "fromString", "(", "parser", ".", "getAttributeValue", "(", "\"\"", ",", "\"type\"", ")", ")", ")", ";", "builder", ".", "setErrorGenerator", "(", "parser", ".", "getAttributeValue", "(", "\"\"", ",", "\"by\"", ")", ")", ";", "outerloop", ":", "while", "(", "true", ")", "{", "int", "eventType", "=", "parser", ".", "next", "(", ")", ";", "switch", "(", "eventType", ")", "{", "case", "XmlPullParser", ".", "START_TAG", ":", "String", "name", "=", "parser", ".", "getName", "(", ")", ";", "String", "namespace", "=", "parser", ".", "getNamespace", "(", ")", ";", "switch", "(", "namespace", ")", "{", "case", "StanzaError", ".", "ERROR_CONDITION_AND_TEXT_NAMESPACE", ":", "switch", "(", "name", ")", "{", "case", "Stanza", ".", "TEXT", ":", "descriptiveTexts", "=", "parseDescriptiveTexts", "(", "parser", ",", "descriptiveTexts", ")", ";", "break", ";", "default", ":", "builder", ".", "setCondition", "(", "StanzaError", ".", "Condition", ".", "fromString", "(", "name", ")", ")", ";", "if", "(", "!", "parser", ".", "isEmptyElementTag", "(", ")", ")", "{", "builder", ".", "setConditionText", "(", "parser", ".", "nextText", "(", ")", ")", ";", "}", "break", ";", "}", "break", ";", "default", ":", "PacketParserUtils", ".", "addExtensionElement", "(", "extensions", ",", "parser", ",", "name", ",", "namespace", ",", "stanzaErrorXmlEnvironment", ")", ";", "}", "break", ";", "case", "XmlPullParser", ".", "END_TAG", ":", "if", "(", "parser", ".", "getDepth", "(", ")", "==", "initialDepth", ")", "{", "break", "outerloop", ";", "}", "}", "}", "builder", ".", "setExtensions", "(", "extensions", ")", ".", "setDescriptiveTexts", "(", "descriptiveTexts", ")", ";", "return", "builder", ";", "}" ]
Parses error sub-packets. @param parser the XML parser. @param outerXmlEnvironment the outer XML environment (optional). @return an error sub-packet. @throws IOException @throws XmlPullParserException @throws SmackParsingException
[ "Parses", "error", "sub", "-", "packets", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-core/src/main/java/org/jivesoftware/smack/util/PacketParserUtils.java#L879-L922
27,102
igniterealtime/Smack
smack-core/src/main/java/org/jivesoftware/smack/util/PacketParserUtils.java
PacketParserUtils.parseExtensionElement
public static ExtensionElement parseExtensionElement(String elementName, String namespace, XmlPullParser parser, XmlEnvironment outerXmlEnvironment) throws XmlPullParserException, IOException, SmackParsingException { ParserUtils.assertAtStartTag(parser); // See if a provider is registered to handle the extension. ExtensionElementProvider<ExtensionElement> provider = ProviderManager.getExtensionProvider(elementName, namespace); if (provider != null) { return provider.parse(parser, outerXmlEnvironment); } // No providers registered, so use a default extension. return StandardExtensionElementProvider.INSTANCE.parse(parser, outerXmlEnvironment); }
java
public static ExtensionElement parseExtensionElement(String elementName, String namespace, XmlPullParser parser, XmlEnvironment outerXmlEnvironment) throws XmlPullParserException, IOException, SmackParsingException { ParserUtils.assertAtStartTag(parser); // See if a provider is registered to handle the extension. ExtensionElementProvider<ExtensionElement> provider = ProviderManager.getExtensionProvider(elementName, namespace); if (provider != null) { return provider.parse(parser, outerXmlEnvironment); } // No providers registered, so use a default extension. return StandardExtensionElementProvider.INSTANCE.parse(parser, outerXmlEnvironment); }
[ "public", "static", "ExtensionElement", "parseExtensionElement", "(", "String", "elementName", ",", "String", "namespace", ",", "XmlPullParser", "parser", ",", "XmlEnvironment", "outerXmlEnvironment", ")", "throws", "XmlPullParserException", ",", "IOException", ",", "SmackParsingException", "{", "ParserUtils", ".", "assertAtStartTag", "(", "parser", ")", ";", "// See if a provider is registered to handle the extension.", "ExtensionElementProvider", "<", "ExtensionElement", ">", "provider", "=", "ProviderManager", ".", "getExtensionProvider", "(", "elementName", ",", "namespace", ")", ";", "if", "(", "provider", "!=", "null", ")", "{", "return", "provider", ".", "parse", "(", "parser", ",", "outerXmlEnvironment", ")", ";", "}", "// No providers registered, so use a default extension.", "return", "StandardExtensionElementProvider", ".", "INSTANCE", ".", "parse", "(", "parser", ",", "outerXmlEnvironment", ")", ";", "}" ]
Parses an extension element. @param elementName the XML element name of the extension element. @param namespace the XML namespace of the stanza extension. @param parser the XML parser, positioned at the starting element of the extension. @param outerXmlEnvironment the outer XML environment (optional). @return an extension element. @throws XmlPullParserException @throws IOException @throws SmackParsingException
[ "Parses", "an", "extension", "element", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-core/src/main/java/org/jivesoftware/smack/util/PacketParserUtils.java#L937-L948
27,103
igniterealtime/Smack
smack-legacy/src/main/java/org/jivesoftware/smackx/xevent/MessageEventManager.java
MessageEventManager.fireMessageEventRequestListeners
private void fireMessageEventRequestListeners( Jid from, String packetID, String methodName) { try { Method method = MessageEventRequestListener.class.getDeclaredMethod( methodName, new Class<?>[] { Jid.class, String.class, MessageEventManager.class }); for (MessageEventRequestListener listener : messageEventRequestListeners) { method.invoke(listener, new Object[] { from, packetID, this }); } } catch (Exception e) { LOGGER.log(Level.SEVERE, "Error while invoking MessageEventRequestListener's " + methodName, e); } }
java
private void fireMessageEventRequestListeners( Jid from, String packetID, String methodName) { try { Method method = MessageEventRequestListener.class.getDeclaredMethod( methodName, new Class<?>[] { Jid.class, String.class, MessageEventManager.class }); for (MessageEventRequestListener listener : messageEventRequestListeners) { method.invoke(listener, new Object[] { from, packetID, this }); } } catch (Exception e) { LOGGER.log(Level.SEVERE, "Error while invoking MessageEventRequestListener's " + methodName, e); } }
[ "private", "void", "fireMessageEventRequestListeners", "(", "Jid", "from", ",", "String", "packetID", ",", "String", "methodName", ")", "{", "try", "{", "Method", "method", "=", "MessageEventRequestListener", ".", "class", ".", "getDeclaredMethod", "(", "methodName", ",", "new", "Class", "<", "?", ">", "[", "]", "{", "Jid", ".", "class", ",", "String", ".", "class", ",", "MessageEventManager", ".", "class", "}", ")", ";", "for", "(", "MessageEventRequestListener", "listener", ":", "messageEventRequestListeners", ")", "{", "method", ".", "invoke", "(", "listener", ",", "new", "Object", "[", "]", "{", "from", ",", "packetID", ",", "this", "}", ")", ";", "}", "}", "catch", "(", "Exception", "e", ")", "{", "LOGGER", ".", "log", "(", "Level", ".", "SEVERE", ",", "\"Error while invoking MessageEventRequestListener's \"", "+", "methodName", ",", "e", ")", ";", "}", "}" ]
Fires message event request listeners.
[ "Fires", "message", "event", "request", "listeners", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-legacy/src/main/java/org/jivesoftware/smackx/xevent/MessageEventManager.java#L170-L185
27,104
igniterealtime/Smack
smack-legacy/src/main/java/org/jivesoftware/smackx/xevent/MessageEventManager.java
MessageEventManager.fireMessageEventNotificationListeners
private void fireMessageEventNotificationListeners( Jid from, String packetID, String methodName) { try { Method method = MessageEventNotificationListener.class.getDeclaredMethod( methodName, new Class<?>[] { Jid.class, String.class }); for (MessageEventNotificationListener listener : messageEventNotificationListeners) { method.invoke(listener, new Object[] { from, packetID }); } } catch (Exception e) { LOGGER.log(Level.SEVERE, "Error while invoking MessageEventNotificationListener's " + methodName, e); } }
java
private void fireMessageEventNotificationListeners( Jid from, String packetID, String methodName) { try { Method method = MessageEventNotificationListener.class.getDeclaredMethod( methodName, new Class<?>[] { Jid.class, String.class }); for (MessageEventNotificationListener listener : messageEventNotificationListeners) { method.invoke(listener, new Object[] { from, packetID }); } } catch (Exception e) { LOGGER.log(Level.SEVERE, "Error while invoking MessageEventNotificationListener's " + methodName, e); } }
[ "private", "void", "fireMessageEventNotificationListeners", "(", "Jid", "from", ",", "String", "packetID", ",", "String", "methodName", ")", "{", "try", "{", "Method", "method", "=", "MessageEventNotificationListener", ".", "class", ".", "getDeclaredMethod", "(", "methodName", ",", "new", "Class", "<", "?", ">", "[", "]", "{", "Jid", ".", "class", ",", "String", ".", "class", "}", ")", ";", "for", "(", "MessageEventNotificationListener", "listener", ":", "messageEventNotificationListeners", ")", "{", "method", ".", "invoke", "(", "listener", ",", "new", "Object", "[", "]", "{", "from", ",", "packetID", "}", ")", ";", "}", "}", "catch", "(", "Exception", "e", ")", "{", "LOGGER", ".", "log", "(", "Level", ".", "SEVERE", ",", "\"Error while invoking MessageEventNotificationListener's \"", "+", "methodName", ",", "e", ")", ";", "}", "}" ]
Fires message event notification listeners.
[ "Fires", "message", "event", "notification", "listeners", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-legacy/src/main/java/org/jivesoftware/smackx/xevent/MessageEventManager.java#L190-L205
27,105
igniterealtime/Smack
smack-legacy/src/main/java/org/jivesoftware/smackx/xevent/MessageEventManager.java
MessageEventManager.sendDeliveredNotification
public void sendDeliveredNotification(Jid to, String packetID) throws NotConnectedException, InterruptedException { // Create the message to send Message msg = new Message(to); // Create a MessageEvent Package and add it to the message MessageEvent messageEvent = new MessageEvent(); messageEvent.setDelivered(true); messageEvent.setStanzaId(packetID); msg.addExtension(messageEvent); // Send the packet connection().sendStanza(msg); }
java
public void sendDeliveredNotification(Jid to, String packetID) throws NotConnectedException, InterruptedException { // Create the message to send Message msg = new Message(to); // Create a MessageEvent Package and add it to the message MessageEvent messageEvent = new MessageEvent(); messageEvent.setDelivered(true); messageEvent.setStanzaId(packetID); msg.addExtension(messageEvent); // Send the packet connection().sendStanza(msg); }
[ "public", "void", "sendDeliveredNotification", "(", "Jid", "to", ",", "String", "packetID", ")", "throws", "NotConnectedException", ",", "InterruptedException", "{", "// Create the message to send", "Message", "msg", "=", "new", "Message", "(", "to", ")", ";", "// Create a MessageEvent Package and add it to the message", "MessageEvent", "messageEvent", "=", "new", "MessageEvent", "(", ")", ";", "messageEvent", ".", "setDelivered", "(", "true", ")", ";", "messageEvent", ".", "setStanzaId", "(", "packetID", ")", ";", "msg", ".", "addExtension", "(", "messageEvent", ")", ";", "// Send the packet", "connection", "(", ")", ".", "sendStanza", "(", "msg", ")", ";", "}" ]
Sends the notification that the message was delivered to the sender of the original message. @param to the recipient of the notification. @param packetID the id of the message to send. @throws NotConnectedException @throws InterruptedException
[ "Sends", "the", "notification", "that", "the", "message", "was", "delivered", "to", "the", "sender", "of", "the", "original", "message", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-legacy/src/main/java/org/jivesoftware/smackx/xevent/MessageEventManager.java#L215-L225
27,106
igniterealtime/Smack
smack-legacy/src/main/java/org/jivesoftware/smackx/xevent/MessageEventManager.java
MessageEventManager.sendDisplayedNotification
public void sendDisplayedNotification(Jid to, String packetID) throws NotConnectedException, InterruptedException { // Create the message to send Message msg = new Message(to); // Create a MessageEvent Package and add it to the message MessageEvent messageEvent = new MessageEvent(); messageEvent.setDisplayed(true); messageEvent.setStanzaId(packetID); msg.addExtension(messageEvent); // Send the packet connection().sendStanza(msg); }
java
public void sendDisplayedNotification(Jid to, String packetID) throws NotConnectedException, InterruptedException { // Create the message to send Message msg = new Message(to); // Create a MessageEvent Package and add it to the message MessageEvent messageEvent = new MessageEvent(); messageEvent.setDisplayed(true); messageEvent.setStanzaId(packetID); msg.addExtension(messageEvent); // Send the packet connection().sendStanza(msg); }
[ "public", "void", "sendDisplayedNotification", "(", "Jid", "to", ",", "String", "packetID", ")", "throws", "NotConnectedException", ",", "InterruptedException", "{", "// Create the message to send", "Message", "msg", "=", "new", "Message", "(", "to", ")", ";", "// Create a MessageEvent Package and add it to the message", "MessageEvent", "messageEvent", "=", "new", "MessageEvent", "(", ")", ";", "messageEvent", ".", "setDisplayed", "(", "true", ")", ";", "messageEvent", ".", "setStanzaId", "(", "packetID", ")", ";", "msg", ".", "addExtension", "(", "messageEvent", ")", ";", "// Send the packet", "connection", "(", ")", ".", "sendStanza", "(", "msg", ")", ";", "}" ]
Sends the notification that the message was displayed to the sender of the original message. @param to the recipient of the notification. @param packetID the id of the message to send. @throws NotConnectedException @throws InterruptedException
[ "Sends", "the", "notification", "that", "the", "message", "was", "displayed", "to", "the", "sender", "of", "the", "original", "message", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-legacy/src/main/java/org/jivesoftware/smackx/xevent/MessageEventManager.java#L235-L245
27,107
igniterealtime/Smack
smack-legacy/src/main/java/org/jivesoftware/smackx/xevent/MessageEventManager.java
MessageEventManager.sendComposingNotification
public void sendComposingNotification(Jid to, String packetID) throws NotConnectedException, InterruptedException { // Create the message to send Message msg = new Message(to); // Create a MessageEvent Package and add it to the message MessageEvent messageEvent = new MessageEvent(); messageEvent.setComposing(true); messageEvent.setStanzaId(packetID); msg.addExtension(messageEvent); // Send the packet connection().sendStanza(msg); }
java
public void sendComposingNotification(Jid to, String packetID) throws NotConnectedException, InterruptedException { // Create the message to send Message msg = new Message(to); // Create a MessageEvent Package and add it to the message MessageEvent messageEvent = new MessageEvent(); messageEvent.setComposing(true); messageEvent.setStanzaId(packetID); msg.addExtension(messageEvent); // Send the packet connection().sendStanza(msg); }
[ "public", "void", "sendComposingNotification", "(", "Jid", "to", ",", "String", "packetID", ")", "throws", "NotConnectedException", ",", "InterruptedException", "{", "// Create the message to send", "Message", "msg", "=", "new", "Message", "(", "to", ")", ";", "// Create a MessageEvent Package and add it to the message", "MessageEvent", "messageEvent", "=", "new", "MessageEvent", "(", ")", ";", "messageEvent", ".", "setComposing", "(", "true", ")", ";", "messageEvent", ".", "setStanzaId", "(", "packetID", ")", ";", "msg", ".", "addExtension", "(", "messageEvent", ")", ";", "// Send the packet", "connection", "(", ")", ".", "sendStanza", "(", "msg", ")", ";", "}" ]
Sends the notification that the receiver of the message is composing a reply. @param to the recipient of the notification. @param packetID the id of the message to send. @throws NotConnectedException @throws InterruptedException
[ "Sends", "the", "notification", "that", "the", "receiver", "of", "the", "message", "is", "composing", "a", "reply", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-legacy/src/main/java/org/jivesoftware/smackx/xevent/MessageEventManager.java#L255-L265
27,108
igniterealtime/Smack
smack-legacy/src/main/java/org/jivesoftware/smackx/xevent/MessageEventManager.java
MessageEventManager.sendCancelledNotification
public void sendCancelledNotification(Jid to, String packetID) throws NotConnectedException, InterruptedException { // Create the message to send Message msg = new Message(to); // Create a MessageEvent Package and add it to the message MessageEvent messageEvent = new MessageEvent(); messageEvent.setCancelled(true); messageEvent.setStanzaId(packetID); msg.addExtension(messageEvent); // Send the packet connection().sendStanza(msg); }
java
public void sendCancelledNotification(Jid to, String packetID) throws NotConnectedException, InterruptedException { // Create the message to send Message msg = new Message(to); // Create a MessageEvent Package and add it to the message MessageEvent messageEvent = new MessageEvent(); messageEvent.setCancelled(true); messageEvent.setStanzaId(packetID); msg.addExtension(messageEvent); // Send the packet connection().sendStanza(msg); }
[ "public", "void", "sendCancelledNotification", "(", "Jid", "to", ",", "String", "packetID", ")", "throws", "NotConnectedException", ",", "InterruptedException", "{", "// Create the message to send", "Message", "msg", "=", "new", "Message", "(", "to", ")", ";", "// Create a MessageEvent Package and add it to the message", "MessageEvent", "messageEvent", "=", "new", "MessageEvent", "(", ")", ";", "messageEvent", ".", "setCancelled", "(", "true", ")", ";", "messageEvent", ".", "setStanzaId", "(", "packetID", ")", ";", "msg", ".", "addExtension", "(", "messageEvent", ")", ";", "// Send the packet", "connection", "(", ")", ".", "sendStanza", "(", "msg", ")", ";", "}" ]
Sends the notification that the receiver of the message has cancelled composing a reply. @param to the recipient of the notification. @param packetID the id of the message to send. @throws NotConnectedException @throws InterruptedException
[ "Sends", "the", "notification", "that", "the", "receiver", "of", "the", "message", "has", "cancelled", "composing", "a", "reply", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-legacy/src/main/java/org/jivesoftware/smackx/xevent/MessageEventManager.java#L275-L285
27,109
igniterealtime/Smack
smack-extensions/src/main/java/org/jivesoftware/smackx/filetransfer/StreamNegotiator.java
StreamNegotiator.createInitiationAccept
protected static StreamInitiation createInitiationAccept( StreamInitiation streamInitiationOffer, String[] namespaces) { StreamInitiation response = new StreamInitiation(); response.setTo(streamInitiationOffer.getFrom()); response.setFrom(streamInitiationOffer.getTo()); response.setType(IQ.Type.result); response.setStanzaId(streamInitiationOffer.getStanzaId()); DataForm form = new DataForm(DataForm.Type.submit); FormField field = new FormField( FileTransferNegotiator.STREAM_DATA_FIELD_NAME); for (String namespace : namespaces) { field.addValue(namespace); } form.addField(field); response.setFeatureNegotiationForm(form); return response; }
java
protected static StreamInitiation createInitiationAccept( StreamInitiation streamInitiationOffer, String[] namespaces) { StreamInitiation response = new StreamInitiation(); response.setTo(streamInitiationOffer.getFrom()); response.setFrom(streamInitiationOffer.getTo()); response.setType(IQ.Type.result); response.setStanzaId(streamInitiationOffer.getStanzaId()); DataForm form = new DataForm(DataForm.Type.submit); FormField field = new FormField( FileTransferNegotiator.STREAM_DATA_FIELD_NAME); for (String namespace : namespaces) { field.addValue(namespace); } form.addField(field); response.setFeatureNegotiationForm(form); return response; }
[ "protected", "static", "StreamInitiation", "createInitiationAccept", "(", "StreamInitiation", "streamInitiationOffer", ",", "String", "[", "]", "namespaces", ")", "{", "StreamInitiation", "response", "=", "new", "StreamInitiation", "(", ")", ";", "response", ".", "setTo", "(", "streamInitiationOffer", ".", "getFrom", "(", ")", ")", ";", "response", ".", "setFrom", "(", "streamInitiationOffer", ".", "getTo", "(", ")", ")", ";", "response", ".", "setType", "(", "IQ", ".", "Type", ".", "result", ")", ";", "response", ".", "setStanzaId", "(", "streamInitiationOffer", ".", "getStanzaId", "(", ")", ")", ";", "DataForm", "form", "=", "new", "DataForm", "(", "DataForm", ".", "Type", ".", "submit", ")", ";", "FormField", "field", "=", "new", "FormField", "(", "FileTransferNegotiator", ".", "STREAM_DATA_FIELD_NAME", ")", ";", "for", "(", "String", "namespace", ":", "namespaces", ")", "{", "field", ".", "addValue", "(", "namespace", ")", ";", "}", "form", ".", "addField", "(", "field", ")", ";", "response", ".", "setFeatureNegotiationForm", "(", "form", ")", ";", "return", "response", ";", "}" ]
Creates the initiation acceptance stanza to forward to the stream initiator. @param streamInitiationOffer The offer from the stream initiator to connect for a stream. @param namespaces The namespace that relates to the accepted means of transfer. @return The response to be forwarded to the initiator.
[ "Creates", "the", "initiation", "acceptance", "stanza", "to", "forward", "to", "the", "stream", "initiator", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/filetransfer/StreamNegotiator.java#L75-L93
27,110
igniterealtime/Smack
smack-extensions/src/main/java/org/jivesoftware/smackx/iqregister/AccountManager.java
AccountManager.getInstance
public static synchronized AccountManager getInstance(XMPPConnection connection) { AccountManager accountManager = INSTANCES.get(connection); if (accountManager == null) { accountManager = new AccountManager(connection); INSTANCES.put(connection, accountManager); } return accountManager; }
java
public static synchronized AccountManager getInstance(XMPPConnection connection) { AccountManager accountManager = INSTANCES.get(connection); if (accountManager == null) { accountManager = new AccountManager(connection); INSTANCES.put(connection, accountManager); } return accountManager; }
[ "public", "static", "synchronized", "AccountManager", "getInstance", "(", "XMPPConnection", "connection", ")", "{", "AccountManager", "accountManager", "=", "INSTANCES", ".", "get", "(", "connection", ")", ";", "if", "(", "accountManager", "==", "null", ")", "{", "accountManager", "=", "new", "AccountManager", "(", "connection", ")", ";", "INSTANCES", ".", "put", "(", "connection", ",", "accountManager", ")", ";", "}", "return", "accountManager", ";", "}" ]
Returns the AccountManager instance associated with a given XMPPConnection. @param connection the connection used to look for the proper ServiceDiscoveryManager. @return the AccountManager associated with a given XMPPConnection.
[ "Returns", "the", "AccountManager", "instance", "associated", "with", "a", "given", "XMPPConnection", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/iqregister/AccountManager.java#L59-L66
27,111
igniterealtime/Smack
smack-extensions/src/main/java/org/jivesoftware/smackx/iqregister/AccountManager.java
AccountManager.supportsAccountCreation
public boolean supportsAccountCreation() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { // TODO: Replace this body with isSupported() and possible deprecate this method. // Check if we already know that the server supports creating new accounts if (accountCreationSupported) { return true; } // No information is known yet (e.g. no stream feature was received from the server // indicating that it supports creating new accounts) so send an IQ packet as a way // to discover if this feature is supported if (info == null) { getRegistrationInfo(); accountCreationSupported = info.getType() != IQ.Type.error; } return accountCreationSupported; }
java
public boolean supportsAccountCreation() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { // TODO: Replace this body with isSupported() and possible deprecate this method. // Check if we already know that the server supports creating new accounts if (accountCreationSupported) { return true; } // No information is known yet (e.g. no stream feature was received from the server // indicating that it supports creating new accounts) so send an IQ packet as a way // to discover if this feature is supported if (info == null) { getRegistrationInfo(); accountCreationSupported = info.getType() != IQ.Type.error; } return accountCreationSupported; }
[ "public", "boolean", "supportsAccountCreation", "(", ")", "throws", "NoResponseException", ",", "XMPPErrorException", ",", "NotConnectedException", ",", "InterruptedException", "{", "// TODO: Replace this body with isSupported() and possible deprecate this method.", "// Check if we already know that the server supports creating new accounts", "if", "(", "accountCreationSupported", ")", "{", "return", "true", ";", "}", "// No information is known yet (e.g. no stream feature was received from the server", "// indicating that it supports creating new accounts) so send an IQ packet as a way", "// to discover if this feature is supported", "if", "(", "info", "==", "null", ")", "{", "getRegistrationInfo", "(", ")", ";", "accountCreationSupported", "=", "info", ".", "getType", "(", ")", "!=", "IQ", ".", "Type", ".", "error", ";", "}", "return", "accountCreationSupported", ";", "}" ]
Returns true if the server supports creating new accounts. Many servers require that you not be currently authenticated when creating new accounts, so the safest behavior is to only create new accounts before having logged in to a server. @return true if the server support creating new accounts. @throws XMPPErrorException @throws NoResponseException @throws NotConnectedException @throws InterruptedException
[ "Returns", "true", "if", "the", "server", "supports", "creating", "new", "accounts", ".", "Many", "servers", "require", "that", "you", "not", "be", "currently", "authenticated", "when", "creating", "new", "accounts", "so", "the", "safest", "behavior", "is", "to", "only", "create", "new", "accounts", "before", "having", "logged", "in", "to", "a", "server", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/iqregister/AccountManager.java#L139-L154
27,112
igniterealtime/Smack
smack-extensions/src/main/java/org/jivesoftware/smackx/iqregister/AccountManager.java
AccountManager.createAccount
public void createAccount(Localpart username, String password) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { // Create a map for all the required attributes, but give them blank values. Map<String, String> attributes = new HashMap<>(); for (String attributeName : getAccountAttributes()) { attributes.put(attributeName, ""); } createAccount(username, password, attributes); }
java
public void createAccount(Localpart username, String password) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { // Create a map for all the required attributes, but give them blank values. Map<String, String> attributes = new HashMap<>(); for (String attributeName : getAccountAttributes()) { attributes.put(attributeName, ""); } createAccount(username, password, attributes); }
[ "public", "void", "createAccount", "(", "Localpart", "username", ",", "String", "password", ")", "throws", "NoResponseException", ",", "XMPPErrorException", ",", "NotConnectedException", ",", "InterruptedException", "{", "// Create a map for all the required attributes, but give them blank values.", "Map", "<", "String", ",", "String", ">", "attributes", "=", "new", "HashMap", "<>", "(", ")", ";", "for", "(", "String", "attributeName", ":", "getAccountAttributes", "(", ")", ")", "{", "attributes", ".", "put", "(", "attributeName", ",", "\"\"", ")", ";", "}", "createAccount", "(", "username", ",", "password", ",", "attributes", ")", ";", "}" ]
Creates a new account using the specified username and password. The server may require a number of extra account attributes such as an email address and phone number. In that case, Smack will attempt to automatically set all required attributes with blank values, which may or may not be accepted by the server. Therefore, it's recommended to check the required account attributes and to let the end-user populate them with real values instead. @param username the username. @param password the password. @throws XMPPErrorException @throws NoResponseException @throws NotConnectedException @throws InterruptedException
[ "Creates", "a", "new", "account", "using", "the", "specified", "username", "and", "password", ".", "The", "server", "may", "require", "a", "number", "of", "extra", "account", "attributes", "such", "as", "an", "email", "address", "and", "phone", "number", ".", "In", "that", "case", "Smack", "will", "attempt", "to", "automatically", "set", "all", "required", "attributes", "with", "blank", "values", "which", "may", "or", "may", "not", "be", "accepted", "by", "the", "server", ".", "Therefore", "it", "s", "recommended", "to", "check", "the", "required", "account", "attributes", "and", "to", "let", "the", "end", "-", "user", "populate", "them", "with", "real", "values", "instead", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/iqregister/AccountManager.java#L248-L255
27,113
igniterealtime/Smack
smack-extensions/src/main/java/org/jivesoftware/smackx/iqregister/AccountManager.java
AccountManager.changePassword
public void changePassword(String newPassword) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { if (!connection().isSecureConnection() && !allowSensitiveOperationOverInsecureConnection) { throw new IllegalStateException("Changing password over insecure connection."); } Map<String, String> map = new HashMap<>(); map.put("username", connection().getUser().getLocalpart().toString()); map.put("password",newPassword); Registration reg = new Registration(map); reg.setType(IQ.Type.set); reg.setTo(connection().getXMPPServiceDomain()); createStanzaCollectorAndSend(reg).nextResultOrThrow(); }
java
public void changePassword(String newPassword) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { if (!connection().isSecureConnection() && !allowSensitiveOperationOverInsecureConnection) { throw new IllegalStateException("Changing password over insecure connection."); } Map<String, String> map = new HashMap<>(); map.put("username", connection().getUser().getLocalpart().toString()); map.put("password",newPassword); Registration reg = new Registration(map); reg.setType(IQ.Type.set); reg.setTo(connection().getXMPPServiceDomain()); createStanzaCollectorAndSend(reg).nextResultOrThrow(); }
[ "public", "void", "changePassword", "(", "String", "newPassword", ")", "throws", "NoResponseException", ",", "XMPPErrorException", ",", "NotConnectedException", ",", "InterruptedException", "{", "if", "(", "!", "connection", "(", ")", ".", "isSecureConnection", "(", ")", "&&", "!", "allowSensitiveOperationOverInsecureConnection", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Changing password over insecure connection.\"", ")", ";", "}", "Map", "<", "String", ",", "String", ">", "map", "=", "new", "HashMap", "<>", "(", ")", ";", "map", ".", "put", "(", "\"username\"", ",", "connection", "(", ")", ".", "getUser", "(", ")", ".", "getLocalpart", "(", ")", ".", "toString", "(", ")", ")", ";", "map", ".", "put", "(", "\"password\"", ",", "newPassword", ")", ";", "Registration", "reg", "=", "new", "Registration", "(", "map", ")", ";", "reg", ".", "setType", "(", "IQ", ".", "Type", ".", "set", ")", ";", "reg", ".", "setTo", "(", "connection", "(", ")", ".", "getXMPPServiceDomain", "(", ")", ")", ";", "createStanzaCollectorAndSend", "(", "reg", ")", ".", "nextResultOrThrow", "(", ")", ";", "}" ]
Changes the password of the currently logged-in account. This operation can only be performed after a successful login operation has been completed. Not all servers support changing passwords; an XMPPException will be thrown when that is the case. @param newPassword new password. @throws IllegalStateException if not currently logged-in to the server. @throws XMPPErrorException if an error occurs when changing the password. @throws NoResponseException if there was no response from the server. @throws NotConnectedException @throws InterruptedException
[ "Changes", "the", "password", "of", "the", "currently", "logged", "-", "in", "account", ".", "This", "operation", "can", "only", "be", "performed", "after", "a", "successful", "login", "operation", "has", "been", "completed", ".", "Not", "all", "servers", "support", "changing", "passwords", ";", "an", "XMPPException", "will", "be", "thrown", "when", "that", "is", "the", "case", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/iqregister/AccountManager.java#L304-L315
27,114
igniterealtime/Smack
smack-extensions/src/main/java/org/jivesoftware/smackx/iqregister/AccountManager.java
AccountManager.deleteAccount
public void deleteAccount() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { Map<String, String> attributes = new HashMap<>(); // To delete an account, we add a single attribute, "remove", that is blank. attributes.put("remove", ""); Registration reg = new Registration(attributes); reg.setType(IQ.Type.set); reg.setTo(connection().getXMPPServiceDomain()); createStanzaCollectorAndSend(reg).nextResultOrThrow(); }
java
public void deleteAccount() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { Map<String, String> attributes = new HashMap<>(); // To delete an account, we add a single attribute, "remove", that is blank. attributes.put("remove", ""); Registration reg = new Registration(attributes); reg.setType(IQ.Type.set); reg.setTo(connection().getXMPPServiceDomain()); createStanzaCollectorAndSend(reg).nextResultOrThrow(); }
[ "public", "void", "deleteAccount", "(", ")", "throws", "NoResponseException", ",", "XMPPErrorException", ",", "NotConnectedException", ",", "InterruptedException", "{", "Map", "<", "String", ",", "String", ">", "attributes", "=", "new", "HashMap", "<>", "(", ")", ";", "// To delete an account, we add a single attribute, \"remove\", that is blank.", "attributes", ".", "put", "(", "\"remove\"", ",", "\"\"", ")", ";", "Registration", "reg", "=", "new", "Registration", "(", "attributes", ")", ";", "reg", ".", "setType", "(", "IQ", ".", "Type", ".", "set", ")", ";", "reg", ".", "setTo", "(", "connection", "(", ")", ".", "getXMPPServiceDomain", "(", ")", ")", ";", "createStanzaCollectorAndSend", "(", "reg", ")", ".", "nextResultOrThrow", "(", ")", ";", "}" ]
Deletes the currently logged-in account from the server. This operation can only be performed after a successful login operation has been completed. Not all servers support deleting accounts; an XMPPException will be thrown when that is the case. @throws IllegalStateException if not currently logged-in to the server. @throws XMPPErrorException if an error occurs when deleting the account. @throws NoResponseException if there was no response from the server. @throws NotConnectedException @throws InterruptedException
[ "Deletes", "the", "currently", "logged", "-", "in", "account", "from", "the", "server", ".", "This", "operation", "can", "only", "be", "performed", "after", "a", "successful", "login", "operation", "has", "been", "completed", ".", "Not", "all", "servers", "support", "deleting", "accounts", ";", "an", "XMPPException", "will", "be", "thrown", "when", "that", "is", "the", "case", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/iqregister/AccountManager.java#L328-L336
27,115
igniterealtime/Smack
smack-extensions/src/main/java/org/jivesoftware/smackx/ping/PingManager.java
PingManager.maybeSchedulePingServerTask
private synchronized void maybeSchedulePingServerTask(int delta) { maybeStopPingServerTask(); if (pingInterval > 0) { int nextPingIn = pingInterval - delta; LOGGER.fine("Scheduling ServerPingTask in " + nextPingIn + " seconds (pingInterval=" + pingInterval + ", delta=" + delta + ")"); nextAutomaticPing = schedule(pingServerRunnable, nextPingIn, TimeUnit.SECONDS); } }
java
private synchronized void maybeSchedulePingServerTask(int delta) { maybeStopPingServerTask(); if (pingInterval > 0) { int nextPingIn = pingInterval - delta; LOGGER.fine("Scheduling ServerPingTask in " + nextPingIn + " seconds (pingInterval=" + pingInterval + ", delta=" + delta + ")"); nextAutomaticPing = schedule(pingServerRunnable, nextPingIn, TimeUnit.SECONDS); } }
[ "private", "synchronized", "void", "maybeSchedulePingServerTask", "(", "int", "delta", ")", "{", "maybeStopPingServerTask", "(", ")", ";", "if", "(", "pingInterval", ">", "0", ")", "{", "int", "nextPingIn", "=", "pingInterval", "-", "delta", ";", "LOGGER", ".", "fine", "(", "\"Scheduling ServerPingTask in \"", "+", "nextPingIn", "+", "\" seconds (pingInterval=\"", "+", "pingInterval", "+", "\", delta=\"", "+", "delta", "+", "\")\"", ")", ";", "nextAutomaticPing", "=", "schedule", "(", "pingServerRunnable", ",", "nextPingIn", ",", "TimeUnit", ".", "SECONDS", ")", ";", "}", "}" ]
Cancels any existing periodic ping task if there is one and schedules a new ping task if pingInterval is greater then zero. @param delta the delta to the last received stanza in seconds
[ "Cancels", "any", "existing", "periodic", "ping", "task", "if", "there", "is", "one", "and", "schedules", "a", "new", "ping", "task", "if", "pingInterval", "is", "greater", "then", "zero", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/ping/PingManager.java#L386-L394
27,116
igniterealtime/Smack
smack-extensions/src/main/java/org/jivesoftware/smackx/caps/EntityCapsManager.java
EntityCapsManager.addDiscoverInfoByNode
static void addDiscoverInfoByNode(String nodeVer, DiscoverInfo info) { CAPS_CACHE.put(nodeVer, info); if (persistentCache != null) persistentCache.addDiscoverInfoByNodePersistent(nodeVer, info); }
java
static void addDiscoverInfoByNode(String nodeVer, DiscoverInfo info) { CAPS_CACHE.put(nodeVer, info); if (persistentCache != null) persistentCache.addDiscoverInfoByNodePersistent(nodeVer, info); }
[ "static", "void", "addDiscoverInfoByNode", "(", "String", "nodeVer", ",", "DiscoverInfo", "info", ")", "{", "CAPS_CACHE", ".", "put", "(", "nodeVer", ",", "info", ")", ";", "if", "(", "persistentCache", "!=", "null", ")", "persistentCache", ".", "addDiscoverInfoByNodePersistent", "(", "nodeVer", ",", "info", ")", ";", "}" ]
Add DiscoverInfo to the database. @param nodeVer The node and verification String (e.g. "http://psi-im.org#q07IKJEyjvHSyhy//CH0CxmKi8w="). @param info DiscoverInfo for the specified node.
[ "Add", "DiscoverInfo", "to", "the", "database", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/caps/EntityCapsManager.java#L183-L188
27,117
igniterealtime/Smack
smack-extensions/src/main/java/org/jivesoftware/smackx/caps/EntityCapsManager.java
EntityCapsManager.getDiscoveryInfoByNodeVer
public static DiscoverInfo getDiscoveryInfoByNodeVer(String nodeVer) { DiscoverInfo info = CAPS_CACHE.lookup(nodeVer); // If it was not in CAPS_CACHE, try to retrieve the information from persistentCache if (info == null && persistentCache != null) { info = persistentCache.lookup(nodeVer); // Promote the information to CAPS_CACHE if one was found if (info != null) { CAPS_CACHE.put(nodeVer, info); } } // If we were able to retrieve information from one of the caches, copy it before returning if (info != null) info = new DiscoverInfo(info); return info; }
java
public static DiscoverInfo getDiscoveryInfoByNodeVer(String nodeVer) { DiscoverInfo info = CAPS_CACHE.lookup(nodeVer); // If it was not in CAPS_CACHE, try to retrieve the information from persistentCache if (info == null && persistentCache != null) { info = persistentCache.lookup(nodeVer); // Promote the information to CAPS_CACHE if one was found if (info != null) { CAPS_CACHE.put(nodeVer, info); } } // If we were able to retrieve information from one of the caches, copy it before returning if (info != null) info = new DiscoverInfo(info); return info; }
[ "public", "static", "DiscoverInfo", "getDiscoveryInfoByNodeVer", "(", "String", "nodeVer", ")", "{", "DiscoverInfo", "info", "=", "CAPS_CACHE", ".", "lookup", "(", "nodeVer", ")", ";", "// If it was not in CAPS_CACHE, try to retrieve the information from persistentCache", "if", "(", "info", "==", "null", "&&", "persistentCache", "!=", "null", ")", "{", "info", "=", "persistentCache", ".", "lookup", "(", "nodeVer", ")", ";", "// Promote the information to CAPS_CACHE if one was found", "if", "(", "info", "!=", "null", ")", "{", "CAPS_CACHE", ".", "put", "(", "nodeVer", ",", "info", ")", ";", "}", "}", "// If we were able to retrieve information from one of the caches, copy it before returning", "if", "(", "info", "!=", "null", ")", "info", "=", "new", "DiscoverInfo", "(", "info", ")", ";", "return", "info", ";", "}" ]
Retrieve DiscoverInfo for a specific node. @param nodeVer The node name (e.g. "http://psi-im.org#q07IKJEyjvHSyhy//CH0CxmKi8w="). @return The corresponding DiscoverInfo or null if none is known.
[ "Retrieve", "DiscoverInfo", "for", "a", "specific", "node", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/caps/EntityCapsManager.java#L236-L253
27,118
igniterealtime/Smack
smack-extensions/src/main/java/org/jivesoftware/smackx/caps/EntityCapsManager.java
EntityCapsManager.areEntityCapsSupported
public boolean areEntityCapsSupported(Jid jid) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { return sdm.supportsFeature(jid, NAMESPACE); }
java
public boolean areEntityCapsSupported(Jid jid) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { return sdm.supportsFeature(jid, NAMESPACE); }
[ "public", "boolean", "areEntityCapsSupported", "(", "Jid", "jid", ")", "throws", "NoResponseException", ",", "XMPPErrorException", ",", "NotConnectedException", ",", "InterruptedException", "{", "return", "sdm", ".", "supportsFeature", "(", "jid", ",", "NAMESPACE", ")", ";", "}" ]
Returns true if Entity Caps are supported by a given JID. @param jid @return true if the entity supports Entity Capabilities. @throws XMPPErrorException @throws NoResponseException @throws NotConnectedException @throws InterruptedException
[ "Returns", "true", "if", "Entity", "Caps", "are", "supported", "by", "a", "given", "JID", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/caps/EntityCapsManager.java#L493-L495
27,119
igniterealtime/Smack
smack-extensions/src/main/java/org/jivesoftware/smackx/caps/EntityCapsManager.java
EntityCapsManager.updateLocalEntityCaps
private void updateLocalEntityCaps() { XMPPConnection connection = connection(); DiscoverInfo discoverInfo = new DiscoverInfo(); discoverInfo.setType(IQ.Type.result); sdm.addDiscoverInfoTo(discoverInfo); // getLocalNodeVer() will return a result only after currentCapsVersion is set. Therefore // set it first and then call getLocalNodeVer() currentCapsVersion = generateVerificationString(discoverInfo); final String localNodeVer = getLocalNodeVer(); discoverInfo.setNode(localNodeVer); addDiscoverInfoByNode(localNodeVer, discoverInfo); if (lastLocalCapsVersions.size() > 10) { CapsVersionAndHash oldCapsVersion = lastLocalCapsVersions.poll(); sdm.removeNodeInformationProvider(entityNode + '#' + oldCapsVersion.version); } lastLocalCapsVersions.add(currentCapsVersion); if (connection != null) JID_TO_NODEVER_CACHE.put(connection.getUser(), new NodeVerHash(entityNode, currentCapsVersion)); final List<Identity> identities = new LinkedList<>(ServiceDiscoveryManager.getInstanceFor(connection).getIdentities()); sdm.setNodeInformationProvider(localNodeVer, new AbstractNodeInformationProvider() { List<String> features = sdm.getFeatures(); List<ExtensionElement> packetExtensions = sdm.getExtendedInfoAsList(); @Override public List<String> getNodeFeatures() { return features; } @Override public List<Identity> getNodeIdentities() { return identities; } @Override public List<ExtensionElement> getNodePacketExtensions() { return packetExtensions; } }); // Re-send the last sent presence, and let the stanza interceptor // add a <c/> node to it. // See http://xmpp.org/extensions/xep-0115.html#advertise // We only send a presence packet if there was already one send // to respect ConnectionConfiguration.isSendPresence() if (connection != null && connection.isAuthenticated() && presenceSend != null) { try { connection.sendStanza(presenceSend.cloneWithNewId()); } catch (InterruptedException | NotConnectedException e) { LOGGER.log(Level.WARNING, "Could could not update presence with caps info", e); } } }
java
private void updateLocalEntityCaps() { XMPPConnection connection = connection(); DiscoverInfo discoverInfo = new DiscoverInfo(); discoverInfo.setType(IQ.Type.result); sdm.addDiscoverInfoTo(discoverInfo); // getLocalNodeVer() will return a result only after currentCapsVersion is set. Therefore // set it first and then call getLocalNodeVer() currentCapsVersion = generateVerificationString(discoverInfo); final String localNodeVer = getLocalNodeVer(); discoverInfo.setNode(localNodeVer); addDiscoverInfoByNode(localNodeVer, discoverInfo); if (lastLocalCapsVersions.size() > 10) { CapsVersionAndHash oldCapsVersion = lastLocalCapsVersions.poll(); sdm.removeNodeInformationProvider(entityNode + '#' + oldCapsVersion.version); } lastLocalCapsVersions.add(currentCapsVersion); if (connection != null) JID_TO_NODEVER_CACHE.put(connection.getUser(), new NodeVerHash(entityNode, currentCapsVersion)); final List<Identity> identities = new LinkedList<>(ServiceDiscoveryManager.getInstanceFor(connection).getIdentities()); sdm.setNodeInformationProvider(localNodeVer, new AbstractNodeInformationProvider() { List<String> features = sdm.getFeatures(); List<ExtensionElement> packetExtensions = sdm.getExtendedInfoAsList(); @Override public List<String> getNodeFeatures() { return features; } @Override public List<Identity> getNodeIdentities() { return identities; } @Override public List<ExtensionElement> getNodePacketExtensions() { return packetExtensions; } }); // Re-send the last sent presence, and let the stanza interceptor // add a <c/> node to it. // See http://xmpp.org/extensions/xep-0115.html#advertise // We only send a presence packet if there was already one send // to respect ConnectionConfiguration.isSendPresence() if (connection != null && connection.isAuthenticated() && presenceSend != null) { try { connection.sendStanza(presenceSend.cloneWithNewId()); } catch (InterruptedException | NotConnectedException e) { LOGGER.log(Level.WARNING, "Could could not update presence with caps info", e); } } }
[ "private", "void", "updateLocalEntityCaps", "(", ")", "{", "XMPPConnection", "connection", "=", "connection", "(", ")", ";", "DiscoverInfo", "discoverInfo", "=", "new", "DiscoverInfo", "(", ")", ";", "discoverInfo", ".", "setType", "(", "IQ", ".", "Type", ".", "result", ")", ";", "sdm", ".", "addDiscoverInfoTo", "(", "discoverInfo", ")", ";", "// getLocalNodeVer() will return a result only after currentCapsVersion is set. Therefore", "// set it first and then call getLocalNodeVer()", "currentCapsVersion", "=", "generateVerificationString", "(", "discoverInfo", ")", ";", "final", "String", "localNodeVer", "=", "getLocalNodeVer", "(", ")", ";", "discoverInfo", ".", "setNode", "(", "localNodeVer", ")", ";", "addDiscoverInfoByNode", "(", "localNodeVer", ",", "discoverInfo", ")", ";", "if", "(", "lastLocalCapsVersions", ".", "size", "(", ")", ">", "10", ")", "{", "CapsVersionAndHash", "oldCapsVersion", "=", "lastLocalCapsVersions", ".", "poll", "(", ")", ";", "sdm", ".", "removeNodeInformationProvider", "(", "entityNode", "+", "'", "'", "+", "oldCapsVersion", ".", "version", ")", ";", "}", "lastLocalCapsVersions", ".", "add", "(", "currentCapsVersion", ")", ";", "if", "(", "connection", "!=", "null", ")", "JID_TO_NODEVER_CACHE", ".", "put", "(", "connection", ".", "getUser", "(", ")", ",", "new", "NodeVerHash", "(", "entityNode", ",", "currentCapsVersion", ")", ")", ";", "final", "List", "<", "Identity", ">", "identities", "=", "new", "LinkedList", "<>", "(", "ServiceDiscoveryManager", ".", "getInstanceFor", "(", "connection", ")", ".", "getIdentities", "(", ")", ")", ";", "sdm", ".", "setNodeInformationProvider", "(", "localNodeVer", ",", "new", "AbstractNodeInformationProvider", "(", ")", "{", "List", "<", "String", ">", "features", "=", "sdm", ".", "getFeatures", "(", ")", ";", "List", "<", "ExtensionElement", ">", "packetExtensions", "=", "sdm", ".", "getExtendedInfoAsList", "(", ")", ";", "@", "Override", "public", "List", "<", "String", ">", "getNodeFeatures", "(", ")", "{", "return", "features", ";", "}", "@", "Override", "public", "List", "<", "Identity", ">", "getNodeIdentities", "(", ")", "{", "return", "identities", ";", "}", "@", "Override", "public", "List", "<", "ExtensionElement", ">", "getNodePacketExtensions", "(", ")", "{", "return", "packetExtensions", ";", "}", "}", ")", ";", "// Re-send the last sent presence, and let the stanza interceptor", "// add a <c/> node to it.", "// See http://xmpp.org/extensions/xep-0115.html#advertise", "// We only send a presence packet if there was already one send", "// to respect ConnectionConfiguration.isSendPresence()", "if", "(", "connection", "!=", "null", "&&", "connection", ".", "isAuthenticated", "(", ")", "&&", "presenceSend", "!=", "null", ")", "{", "try", "{", "connection", ".", "sendStanza", "(", "presenceSend", ".", "cloneWithNewId", "(", ")", ")", ";", "}", "catch", "(", "InterruptedException", "|", "NotConnectedException", "e", ")", "{", "LOGGER", ".", "log", "(", "Level", ".", "WARNING", ",", "\"Could could not update presence with caps info\"", ",", "e", ")", ";", "}", "}", "}" ]
Updates the local user Entity Caps information with the data provided If we are connected and there was already a presence send, another presence is send to inform others about your new Entity Caps node string.
[ "Updates", "the", "local", "user", "Entity", "Caps", "information", "with", "the", "data", "provided" ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/caps/EntityCapsManager.java#L517-L570
27,120
igniterealtime/Smack
smack-extensions/src/main/java/org/jivesoftware/smackx/caps/EntityCapsManager.java
EntityCapsManager.verifyDiscoverInfoVersion
public static boolean verifyDiscoverInfoVersion(String ver, String hash, DiscoverInfo info) { // step 3.3 check for duplicate identities if (info.containsDuplicateIdentities()) return false; // step 3.4 check for duplicate features if (info.containsDuplicateFeatures()) return false; // step 3.5 check for well-formed packet extensions if (verifyPacketExtensions(info)) return false; String calculatedVer = generateVerificationString(info, hash).version; if (!ver.equals(calculatedVer)) return false; return true; }
java
public static boolean verifyDiscoverInfoVersion(String ver, String hash, DiscoverInfo info) { // step 3.3 check for duplicate identities if (info.containsDuplicateIdentities()) return false; // step 3.4 check for duplicate features if (info.containsDuplicateFeatures()) return false; // step 3.5 check for well-formed packet extensions if (verifyPacketExtensions(info)) return false; String calculatedVer = generateVerificationString(info, hash).version; if (!ver.equals(calculatedVer)) return false; return true; }
[ "public", "static", "boolean", "verifyDiscoverInfoVersion", "(", "String", "ver", ",", "String", "hash", ",", "DiscoverInfo", "info", ")", "{", "// step 3.3 check for duplicate identities", "if", "(", "info", ".", "containsDuplicateIdentities", "(", ")", ")", "return", "false", ";", "// step 3.4 check for duplicate features", "if", "(", "info", ".", "containsDuplicateFeatures", "(", ")", ")", "return", "false", ";", "// step 3.5 check for well-formed packet extensions", "if", "(", "verifyPacketExtensions", "(", "info", ")", ")", "return", "false", ";", "String", "calculatedVer", "=", "generateVerificationString", "(", "info", ",", "hash", ")", ".", "version", ";", "if", "(", "!", "ver", ".", "equals", "(", "calculatedVer", ")", ")", "return", "false", ";", "return", "true", ";", "}" ]
Verify DiscoverInfo and Caps Node as defined in XEP-0115 5.4 Processing Method. @see <a href="http://xmpp.org/extensions/xep-0115.html#ver-proc">XEP-0115 5.4 Processing Method</a> @param ver @param hash @param info @return true if it's valid and should be cache, false if not
[ "Verify", "DiscoverInfo", "and", "Caps", "Node", "as", "defined", "in", "XEP", "-", "0115", "5", ".", "4", "Processing", "Method", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/caps/EntityCapsManager.java#L584-L603
27,121
igniterealtime/Smack
smack-omemo/src/main/java/org/jivesoftware/smackx/omemo/util/OmemoKeyUtil.java
OmemoKeyUtil.preKeyPublicKeysForBundle
public HashMap<Integer, byte[]> preKeyPublicKeysForBundle(TreeMap<Integer, T_PreKey> preKeyHashMap) { HashMap<Integer, byte[]> out = new HashMap<>(); for (Map.Entry<Integer, T_PreKey> e : preKeyHashMap.entrySet()) { out.put(e.getKey(), preKeyForBundle(e.getValue())); } return out; }
java
public HashMap<Integer, byte[]> preKeyPublicKeysForBundle(TreeMap<Integer, T_PreKey> preKeyHashMap) { HashMap<Integer, byte[]> out = new HashMap<>(); for (Map.Entry<Integer, T_PreKey> e : preKeyHashMap.entrySet()) { out.put(e.getKey(), preKeyForBundle(e.getValue())); } return out; }
[ "public", "HashMap", "<", "Integer", ",", "byte", "[", "]", ">", "preKeyPublicKeysForBundle", "(", "TreeMap", "<", "Integer", ",", "T_PreKey", ">", "preKeyHashMap", ")", "{", "HashMap", "<", "Integer", ",", "byte", "[", "]", ">", "out", "=", "new", "HashMap", "<>", "(", ")", ";", "for", "(", "Map", ".", "Entry", "<", "Integer", ",", "T_PreKey", ">", "e", ":", "preKeyHashMap", ".", "entrySet", "(", ")", ")", "{", "out", ".", "put", "(", "e", ".", "getKey", "(", ")", ",", "preKeyForBundle", "(", "e", ".", "getValue", "(", ")", ")", ")", ";", "}", "return", "out", ";", "}" ]
Prepare a whole bunche of preKeys for transport. @param preKeyHashMap HashMap of preKeys @return HashMap of byte arrays but with the same keyIds as key
[ "Prepare", "a", "whole", "bunche", "of", "preKeys", "for", "transport", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-omemo/src/main/java/org/jivesoftware/smackx/omemo/util/OmemoKeyUtil.java#L328-L334
27,122
igniterealtime/Smack
smack-omemo/src/main/java/org/jivesoftware/smackx/omemo/util/OmemoKeyUtil.java
OmemoKeyUtil.addInBounds
public static int addInBounds(int value, int added) { int avail = Integer.MAX_VALUE - value; if (avail < added) { return added - avail; } else { return value + added; } }
java
public static int addInBounds(int value, int added) { int avail = Integer.MAX_VALUE - value; if (avail < added) { return added - avail; } else { return value + added; } }
[ "public", "static", "int", "addInBounds", "(", "int", "value", ",", "int", "added", ")", "{", "int", "avail", "=", "Integer", ".", "MAX_VALUE", "-", "value", ";", "if", "(", "avail", "<", "added", ")", "{", "return", "added", "-", "avail", ";", "}", "else", "{", "return", "value", "+", "added", ";", "}", "}" ]
Add integers modulo MAX_VALUE. @param value base integer @param added value that is added to the base value @return (value plus added) modulo Integer.MAX_VALUE
[ "Add", "integers", "modulo", "MAX_VALUE", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-omemo/src/main/java/org/jivesoftware/smackx/omemo/util/OmemoKeyUtil.java#L383-L390
27,123
igniterealtime/Smack
smack-extensions/src/main/java/org/jivesoftware/smackx/disco/packet/DiscoverItems.java
DiscoverItems.addItems
public void addItems(Collection<Item> itemsToAdd) { if (itemsToAdd == null) return; for (Item i : itemsToAdd) { addItem(i); } }
java
public void addItems(Collection<Item> itemsToAdd) { if (itemsToAdd == null) return; for (Item i : itemsToAdd) { addItem(i); } }
[ "public", "void", "addItems", "(", "Collection", "<", "Item", ">", "itemsToAdd", ")", "{", "if", "(", "itemsToAdd", "==", "null", ")", "return", ";", "for", "(", "Item", "i", ":", "itemsToAdd", ")", "{", "addItem", "(", "i", ")", ";", "}", "}" ]
Adds a collection of items to the discovered information. Does nothing if itemsToAdd is null @param itemsToAdd
[ "Adds", "a", "collection", "of", "items", "to", "the", "discovered", "information", ".", "Does", "nothing", "if", "itemsToAdd", "is", "null" ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/disco/packet/DiscoverItems.java#L64-L69
27,124
igniterealtime/Smack
smack-im/src/main/java/org/jivesoftware/smack/chat/Chat.java
Chat.sendMessage
public void sendMessage(Message message) throws NotConnectedException, InterruptedException { // Force the recipient, message type, and thread ID since the user elected // to send the message through this chat object. message.setTo(participant); message.setType(Message.Type.chat); message.setThread(threadID); chatManager.sendMessage(this, message); }
java
public void sendMessage(Message message) throws NotConnectedException, InterruptedException { // Force the recipient, message type, and thread ID since the user elected // to send the message through this chat object. message.setTo(participant); message.setType(Message.Type.chat); message.setThread(threadID); chatManager.sendMessage(this, message); }
[ "public", "void", "sendMessage", "(", "Message", "message", ")", "throws", "NotConnectedException", ",", "InterruptedException", "{", "// Force the recipient, message type, and thread ID since the user elected", "// to send the message through this chat object.", "message", ".", "setTo", "(", "participant", ")", ";", "message", ".", "setType", "(", "Message", ".", "Type", ".", "chat", ")", ";", "message", ".", "setThread", "(", "threadID", ")", ";", "chatManager", ".", "sendMessage", "(", "this", ",", "message", ")", ";", "}" ]
Sends a message to the other chat participant. The thread ID, recipient, and message type of the message will automatically set to those of this chat. @param message the message to send. @throws NotConnectedException @throws InterruptedException
[ "Sends", "a", "message", "to", "the", "other", "chat", "participant", ".", "The", "thread", "ID", "recipient", "and", "message", "type", "of", "the", "message", "will", "automatically", "set", "to", "those", "of", "this", "chat", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-im/src/main/java/org/jivesoftware/smack/chat/Chat.java#L114-L121
27,125
igniterealtime/Smack
smack-experimental/src/main/java/org/jivesoftware/smackx/carbons/CarbonManager.java
CarbonManager.getInstanceFor
public static synchronized CarbonManager getInstanceFor(XMPPConnection connection) { CarbonManager carbonManager = INSTANCES.get(connection); if (carbonManager == null) { carbonManager = new CarbonManager(connection); INSTANCES.put(connection, carbonManager); } return carbonManager; }
java
public static synchronized CarbonManager getInstanceFor(XMPPConnection connection) { CarbonManager carbonManager = INSTANCES.get(connection); if (carbonManager == null) { carbonManager = new CarbonManager(connection); INSTANCES.put(connection, carbonManager); } return carbonManager; }
[ "public", "static", "synchronized", "CarbonManager", "getInstanceFor", "(", "XMPPConnection", "connection", ")", "{", "CarbonManager", "carbonManager", "=", "INSTANCES", ".", "get", "(", "connection", ")", ";", "if", "(", "carbonManager", "==", "null", ")", "{", "carbonManager", "=", "new", "CarbonManager", "(", "connection", ")", ";", "INSTANCES", ".", "put", "(", "connection", ",", "carbonManager", ")", ";", "}", "return", "carbonManager", ";", "}" ]
Obtain the CarbonManager responsible for a connection. @param connection the connection object. @return a CarbonManager instance
[ "Obtain", "the", "CarbonManager", "responsible", "for", "a", "connection", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-experimental/src/main/java/org/jivesoftware/smackx/carbons/CarbonManager.java#L179-L188
27,126
igniterealtime/Smack
smack-experimental/src/main/java/org/jivesoftware/smackx/carbons/CarbonManager.java
CarbonManager.setCarbonsEnabled
public synchronized void setCarbonsEnabled(final boolean new_state) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { if (enabled_state == new_state) return; IQ setIQ = carbonsEnabledIQ(new_state); connection().createStanzaCollectorAndSend(setIQ).nextResultOrThrow(); enabled_state = new_state; }
java
public synchronized void setCarbonsEnabled(final boolean new_state) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { if (enabled_state == new_state) return; IQ setIQ = carbonsEnabledIQ(new_state); connection().createStanzaCollectorAndSend(setIQ).nextResultOrThrow(); enabled_state = new_state; }
[ "public", "synchronized", "void", "setCarbonsEnabled", "(", "final", "boolean", "new_state", ")", "throws", "NoResponseException", ",", "XMPPErrorException", ",", "NotConnectedException", ",", "InterruptedException", "{", "if", "(", "enabled_state", "==", "new_state", ")", "return", ";", "IQ", "setIQ", "=", "carbonsEnabledIQ", "(", "new_state", ")", ";", "connection", "(", ")", ".", "createStanzaCollectorAndSend", "(", "setIQ", ")", ".", "nextResultOrThrow", "(", ")", ";", "enabled_state", "=", "new_state", ";", "}" ]
Notify server to change the carbons state. This method blocks some time until the server replies to the IQ and returns true on success. You should first check for support using isSupportedByServer(). @param new_state whether carbons should be enabled or disabled @throws XMPPErrorException @throws NoResponseException @throws NotConnectedException @throws InterruptedException
[ "Notify", "server", "to", "change", "the", "carbons", "state", ".", "This", "method", "blocks", "some", "time", "until", "the", "server", "replies", "to", "the", "IQ", "and", "returns", "true", "on", "success", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-experimental/src/main/java/org/jivesoftware/smackx/carbons/CarbonManager.java#L311-L320
27,127
igniterealtime/Smack
smack-extensions/src/main/java/org/jivesoftware/smackx/amp/AMPManager.java
AMPManager.isServiceEnabled
public static boolean isServiceEnabled(XMPPConnection connection) { connection.getXMPPServiceDomain(); return ServiceDiscoveryManager.getInstanceFor(connection).includesFeature(AMPExtension.NAMESPACE); }
java
public static boolean isServiceEnabled(XMPPConnection connection) { connection.getXMPPServiceDomain(); return ServiceDiscoveryManager.getInstanceFor(connection).includesFeature(AMPExtension.NAMESPACE); }
[ "public", "static", "boolean", "isServiceEnabled", "(", "XMPPConnection", "connection", ")", "{", "connection", ".", "getXMPPServiceDomain", "(", ")", ";", "return", "ServiceDiscoveryManager", ".", "getInstanceFor", "(", "connection", ")", ".", "includesFeature", "(", "AMPExtension", ".", "NAMESPACE", ")", ";", "}" ]
Returns true if the AMP support is enabled for the given connection. @param connection the connection to look for AMP support @return a boolean indicating if the AMP support is enabled for the given connection
[ "Returns", "true", "if", "the", "AMP", "support", "is", "enabled", "for", "the", "given", "connection", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/amp/AMPManager.java#L78-L81
27,128
igniterealtime/Smack
smack-extensions/src/main/java/org/jivesoftware/smackx/amp/AMPManager.java
AMPManager.isActionSupported
public static boolean isActionSupported(XMPPConnection connection, AMPExtension.Action action) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { String featureName = AMPExtension.NAMESPACE + "?action=" + action.toString(); return isFeatureSupportedByServer(connection, featureName); }
java
public static boolean isActionSupported(XMPPConnection connection, AMPExtension.Action action) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { String featureName = AMPExtension.NAMESPACE + "?action=" + action.toString(); return isFeatureSupportedByServer(connection, featureName); }
[ "public", "static", "boolean", "isActionSupported", "(", "XMPPConnection", "connection", ",", "AMPExtension", ".", "Action", "action", ")", "throws", "NoResponseException", ",", "XMPPErrorException", ",", "NotConnectedException", ",", "InterruptedException", "{", "String", "featureName", "=", "AMPExtension", ".", "NAMESPACE", "+", "\"?action=\"", "+", "action", ".", "toString", "(", ")", ";", "return", "isFeatureSupportedByServer", "(", "connection", ",", "featureName", ")", ";", "}" ]
Check if server supports specified action. @param connection active xmpp connection @param action action to check @return true if this action is supported. @throws XMPPErrorException @throws NoResponseException @throws NotConnectedException @throws InterruptedException
[ "Check", "if", "server", "supports", "specified", "action", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/amp/AMPManager.java#L93-L96
27,129
igniterealtime/Smack
smack-extensions/src/main/java/org/jivesoftware/smackx/amp/AMPManager.java
AMPManager.isConditionSupported
public static boolean isConditionSupported(XMPPConnection connection, String conditionName) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { String featureName = AMPExtension.NAMESPACE + "?condition=" + conditionName; return isFeatureSupportedByServer(connection, featureName); }
java
public static boolean isConditionSupported(XMPPConnection connection, String conditionName) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { String featureName = AMPExtension.NAMESPACE + "?condition=" + conditionName; return isFeatureSupportedByServer(connection, featureName); }
[ "public", "static", "boolean", "isConditionSupported", "(", "XMPPConnection", "connection", ",", "String", "conditionName", ")", "throws", "NoResponseException", ",", "XMPPErrorException", ",", "NotConnectedException", ",", "InterruptedException", "{", "String", "featureName", "=", "AMPExtension", ".", "NAMESPACE", "+", "\"?condition=\"", "+", "conditionName", ";", "return", "isFeatureSupportedByServer", "(", "connection", ",", "featureName", ")", ";", "}" ]
Check if server supports specified condition. @param connection active xmpp connection @param conditionName name of condition to check @return true if this condition is supported. @throws XMPPErrorException @throws NoResponseException @throws NotConnectedException @throws InterruptedException @see AMPDeliverCondition @see AMPExpireAtCondition @see AMPMatchResourceCondition
[ "Check", "if", "server", "supports", "specified", "condition", "." ]
870756997faec1e1bfabfac0cd6c2395b04da873
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/amp/AMPManager.java#L111-L114
27,130
spotify/scio
scio-examples/src/main/java/org/apache/beam/examples/subprocess/kernel/SubProcessKernel.java
SubProcessKernel.getTotalCommandBytes
private int getTotalCommandBytes(SubProcessCommandLineArgs commands) { int size = 0; for (SubProcessCommandLineArgs.Command c : commands.getParameters()) { size += c.value.length(); } return size; }
java
private int getTotalCommandBytes(SubProcessCommandLineArgs commands) { int size = 0; for (SubProcessCommandLineArgs.Command c : commands.getParameters()) { size += c.value.length(); } return size; }
[ "private", "int", "getTotalCommandBytes", "(", "SubProcessCommandLineArgs", "commands", ")", "{", "int", "size", "=", "0", ";", "for", "(", "SubProcessCommandLineArgs", ".", "Command", "c", ":", "commands", ".", "getParameters", "(", ")", ")", "{", "size", "+=", "c", ".", "value", ".", "length", "(", ")", ";", "}", "return", "size", ";", "}" ]
Add up the total bytes used by the process. @param commands @return
[ "Add", "up", "the", "total", "bytes", "used", "by", "the", "process", "." ]
ed9a44428251b0c6834aad231b463d8eda418471
https://github.com/spotify/scio/blob/ed9a44428251b0c6834aad231b463d8eda418471/scio-examples/src/main/java/org/apache/beam/examples/subprocess/kernel/SubProcessKernel.java#L137-L143
27,131
spotify/scio
scio-examples/src/main/java/org/apache/beam/examples/subprocess/kernel/SubProcessKernel.java
SubProcessKernel.collectProcessResultsBytes
private byte[] collectProcessResultsBytes(Process process, ProcessBuilder builder, SubProcessIOFiles outPutFiles) throws Exception { Byte[] results; try { LOG.debug(String.format("Executing process %s", createLogEntryFromInputs(builder.command()))); // If process exit value is not 0 then subprocess failed, record logs if (process.exitValue() != 0) { outPutFiles.copyOutPutFilesToBucket(configuration, FileUtils.toStringParams(builder)); String log = createLogEntryForProcessFailure(process, builder.command(), outPutFiles); throw new Exception(log); } // If no return file then either something went wrong or the binary is setup incorrectly for // the ret file either way throw error if (!Files.exists(outPutFiles.resultFile)) { String log = createLogEntryForProcessFailure(process, builder.command(), outPutFiles); outPutFiles.copyOutPutFilesToBucket(configuration, FileUtils.toStringParams(builder)); throw new Exception(log); } // Everything looks healthy return bytes return Files.readAllBytes(outPutFiles.resultFile); } catch (Exception ex) { String log = String.format("Unexpected error runnng process. %s error message was %s", createLogEntryFromInputs(builder.command()), ex.getMessage()); throw new Exception(log); } }
java
private byte[] collectProcessResultsBytes(Process process, ProcessBuilder builder, SubProcessIOFiles outPutFiles) throws Exception { Byte[] results; try { LOG.debug(String.format("Executing process %s", createLogEntryFromInputs(builder.command()))); // If process exit value is not 0 then subprocess failed, record logs if (process.exitValue() != 0) { outPutFiles.copyOutPutFilesToBucket(configuration, FileUtils.toStringParams(builder)); String log = createLogEntryForProcessFailure(process, builder.command(), outPutFiles); throw new Exception(log); } // If no return file then either something went wrong or the binary is setup incorrectly for // the ret file either way throw error if (!Files.exists(outPutFiles.resultFile)) { String log = createLogEntryForProcessFailure(process, builder.command(), outPutFiles); outPutFiles.copyOutPutFilesToBucket(configuration, FileUtils.toStringParams(builder)); throw new Exception(log); } // Everything looks healthy return bytes return Files.readAllBytes(outPutFiles.resultFile); } catch (Exception ex) { String log = String.format("Unexpected error runnng process. %s error message was %s", createLogEntryFromInputs(builder.command()), ex.getMessage()); throw new Exception(log); } }
[ "private", "byte", "[", "]", "collectProcessResultsBytes", "(", "Process", "process", ",", "ProcessBuilder", "builder", ",", "SubProcessIOFiles", "outPutFiles", ")", "throws", "Exception", "{", "Byte", "[", "]", "results", ";", "try", "{", "LOG", ".", "debug", "(", "String", ".", "format", "(", "\"Executing process %s\"", ",", "createLogEntryFromInputs", "(", "builder", ".", "command", "(", ")", ")", ")", ")", ";", "// If process exit value is not 0 then subprocess failed, record logs", "if", "(", "process", ".", "exitValue", "(", ")", "!=", "0", ")", "{", "outPutFiles", ".", "copyOutPutFilesToBucket", "(", "configuration", ",", "FileUtils", ".", "toStringParams", "(", "builder", ")", ")", ";", "String", "log", "=", "createLogEntryForProcessFailure", "(", "process", ",", "builder", ".", "command", "(", ")", ",", "outPutFiles", ")", ";", "throw", "new", "Exception", "(", "log", ")", ";", "}", "// If no return file then either something went wrong or the binary is setup incorrectly for", "// the ret file either way throw error", "if", "(", "!", "Files", ".", "exists", "(", "outPutFiles", ".", "resultFile", ")", ")", "{", "String", "log", "=", "createLogEntryForProcessFailure", "(", "process", ",", "builder", ".", "command", "(", ")", ",", "outPutFiles", ")", ";", "outPutFiles", ".", "copyOutPutFilesToBucket", "(", "configuration", ",", "FileUtils", ".", "toStringParams", "(", "builder", ")", ")", ";", "throw", "new", "Exception", "(", "log", ")", ";", "}", "// Everything looks healthy return bytes", "return", "Files", ".", "readAllBytes", "(", "outPutFiles", ".", "resultFile", ")", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "String", "log", "=", "String", ".", "format", "(", "\"Unexpected error runnng process. %s error message was %s\"", ",", "createLogEntryFromInputs", "(", "builder", ".", "command", "(", ")", ")", ",", "ex", ".", "getMessage", "(", ")", ")", ";", "throw", "new", "Exception", "(", "log", ")", ";", "}", "}" ]
Used when the reault file contains binary data. @param process @param builder @param outPutFiles @return Binary results @throws Exception if process has non 0 value or no logs found then throw exception
[ "Used", "when", "the", "reault", "file", "contains", "binary", "data", "." ]
ed9a44428251b0c6834aad231b463d8eda418471
https://github.com/spotify/scio/blob/ed9a44428251b0c6834aad231b463d8eda418471/scio-examples/src/main/java/org/apache/beam/examples/subprocess/kernel/SubProcessKernel.java#L226-L258
27,132
spotify/scio
scio-examples/src/main/java/org/apache/beam/examples/subprocess/kernel/SubProcessKernel.java
SubProcessKernel.appendExecutablePath
private ProcessBuilder appendExecutablePath(ProcessBuilder builder) { String executable = builder.command().get(0); if (executable == null) { throw new IllegalArgumentException( "No executable provided to the Process Builder... we will do... nothing... "); } builder.command().set(0, FileUtils.getFileResourceId(configuration.getWorkerPath(), executable).toString()); return builder; }
java
private ProcessBuilder appendExecutablePath(ProcessBuilder builder) { String executable = builder.command().get(0); if (executable == null) { throw new IllegalArgumentException( "No executable provided to the Process Builder... we will do... nothing... "); } builder.command().set(0, FileUtils.getFileResourceId(configuration.getWorkerPath(), executable).toString()); return builder; }
[ "private", "ProcessBuilder", "appendExecutablePath", "(", "ProcessBuilder", "builder", ")", "{", "String", "executable", "=", "builder", ".", "command", "(", ")", ".", "get", "(", "0", ")", ";", "if", "(", "executable", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"No executable provided to the Process Builder... we will do... nothing... \"", ")", ";", "}", "builder", ".", "command", "(", ")", ".", "set", "(", "0", ",", "FileUtils", ".", "getFileResourceId", "(", "configuration", ".", "getWorkerPath", "(", ")", ",", "executable", ")", ".", "toString", "(", ")", ")", ";", "return", "builder", ";", "}" ]
Pass the Path of the binary to the SubProcess in Command position 0
[ "Pass", "the", "Path", "of", "the", "binary", "to", "the", "SubProcess", "in", "Command", "position", "0" ]
ed9a44428251b0c6834aad231b463d8eda418471
https://github.com/spotify/scio/blob/ed9a44428251b0c6834aad231b463d8eda418471/scio-examples/src/main/java/org/apache/beam/examples/subprocess/kernel/SubProcessKernel.java#L301-L310
27,133
spotify/scio
scio-examples/src/main/java/org/apache/beam/examples/complete/game/GameStats.java
GameStats.configureSessionWindowWrite
protected static Map<String, WriteWindowedToBigQuery.FieldInfo<Double>> configureSessionWindowWrite() { Map<String, WriteWindowedToBigQuery.FieldInfo<Double>> tableConfigure = new HashMap<>(); tableConfigure.put( "window_start", new WriteWindowedToBigQuery.FieldInfo<>( "STRING", (c, w) -> { IntervalWindow window = (IntervalWindow) w; return GameConstants.DATE_TIME_FORMATTER.print(window.start()); })); tableConfigure.put( "mean_duration", new WriteWindowedToBigQuery.FieldInfo<>("FLOAT", (c, w) -> c.element())); return tableConfigure; }
java
protected static Map<String, WriteWindowedToBigQuery.FieldInfo<Double>> configureSessionWindowWrite() { Map<String, WriteWindowedToBigQuery.FieldInfo<Double>> tableConfigure = new HashMap<>(); tableConfigure.put( "window_start", new WriteWindowedToBigQuery.FieldInfo<>( "STRING", (c, w) -> { IntervalWindow window = (IntervalWindow) w; return GameConstants.DATE_TIME_FORMATTER.print(window.start()); })); tableConfigure.put( "mean_duration", new WriteWindowedToBigQuery.FieldInfo<>("FLOAT", (c, w) -> c.element())); return tableConfigure; }
[ "protected", "static", "Map", "<", "String", ",", "WriteWindowedToBigQuery", ".", "FieldInfo", "<", "Double", ">", ">", "configureSessionWindowWrite", "(", ")", "{", "Map", "<", "String", ",", "WriteWindowedToBigQuery", ".", "FieldInfo", "<", "Double", ">", ">", "tableConfigure", "=", "new", "HashMap", "<>", "(", ")", ";", "tableConfigure", ".", "put", "(", "\"window_start\"", ",", "new", "WriteWindowedToBigQuery", ".", "FieldInfo", "<>", "(", "\"STRING\"", ",", "(", "c", ",", "w", ")", "->", "{", "IntervalWindow", "window", "=", "(", "IntervalWindow", ")", "w", ";", "return", "GameConstants", ".", "DATE_TIME_FORMATTER", ".", "print", "(", "window", ".", "start", "(", ")", ")", ";", "}", ")", ")", ";", "tableConfigure", ".", "put", "(", "\"mean_duration\"", ",", "new", "WriteWindowedToBigQuery", ".", "FieldInfo", "<>", "(", "\"FLOAT\"", ",", "(", "c", ",", "w", ")", "->", "c", ".", "element", "(", ")", ")", ")", ";", "return", "tableConfigure", ";", "}" ]
Create a map of information that describes how to write pipeline output to BigQuery. This map is used to write information about mean user session time.
[ "Create", "a", "map", "of", "information", "that", "describes", "how", "to", "write", "pipeline", "output", "to", "BigQuery", ".", "This", "map", "is", "used", "to", "write", "information", "about", "mean", "user", "session", "time", "." ]
ed9a44428251b0c6834aad231b463d8eda418471
https://github.com/spotify/scio/blob/ed9a44428251b0c6834aad231b463d8eda418471/scio-examples/src/main/java/org/apache/beam/examples/complete/game/GameStats.java#L212-L227
27,134
spotify/scio
scio-examples/src/main/java/org/apache/beam/examples/subprocess/utils/FileUtils.java
FileUtils.createDirectoriesOnWorker
public static void createDirectoriesOnWorker(SubProcessConfiguration configuration) throws IOException { try { Path path = Paths.get(configuration.getWorkerPath()); if (!path.toFile().exists()) { Files.createDirectories(path); LOG.info(String.format("Created Folder %s ", path.toFile())); } } catch (FileAlreadyExistsException ex) { LOG.warn(String.format( " Tried to create folder %s which already existsed, this should not happen!", configuration.getWorkerPath()), ex); } }
java
public static void createDirectoriesOnWorker(SubProcessConfiguration configuration) throws IOException { try { Path path = Paths.get(configuration.getWorkerPath()); if (!path.toFile().exists()) { Files.createDirectories(path); LOG.info(String.format("Created Folder %s ", path.toFile())); } } catch (FileAlreadyExistsException ex) { LOG.warn(String.format( " Tried to create folder %s which already existsed, this should not happen!", configuration.getWorkerPath()), ex); } }
[ "public", "static", "void", "createDirectoriesOnWorker", "(", "SubProcessConfiguration", "configuration", ")", "throws", "IOException", "{", "try", "{", "Path", "path", "=", "Paths", ".", "get", "(", "configuration", ".", "getWorkerPath", "(", ")", ")", ";", "if", "(", "!", "path", ".", "toFile", "(", ")", ".", "exists", "(", ")", ")", "{", "Files", ".", "createDirectories", "(", "path", ")", ";", "LOG", ".", "info", "(", "String", ".", "format", "(", "\"Created Folder %s \"", ",", "path", ".", "toFile", "(", ")", ")", ")", ";", "}", "}", "catch", "(", "FileAlreadyExistsException", "ex", ")", "{", "LOG", ".", "warn", "(", "String", ".", "format", "(", "\" Tried to create folder %s which already existsed, this should not happen!\"", ",", "configuration", ".", "getWorkerPath", "(", ")", ")", ",", "ex", ")", ";", "}", "}" ]
Create directories needed based on configuration. @param configuration @throws IOException
[ "Create", "directories", "needed", "based", "on", "configuration", "." ]
ed9a44428251b0c6834aad231b463d8eda418471
https://github.com/spotify/scio/blob/ed9a44428251b0c6834aad231b463d8eda418471/scio-examples/src/main/java/org/apache/beam/examples/subprocess/utils/FileUtils.java#L134-L150
27,135
spotify/scio
scio-examples/src/main/java/org/apache/beam/examples/complete/game/injector/InjectorUtils.java
InjectorUtils.getClient
public static Pubsub getClient(final HttpTransport httpTransport, final JsonFactory jsonFactory) throws IOException { checkNotNull(httpTransport); checkNotNull(jsonFactory); GoogleCredential credential = GoogleCredential.getApplicationDefault(httpTransport, jsonFactory); if (credential.createScopedRequired()) { credential = credential.createScoped(PubsubScopes.all()); } if (credential.getClientAuthentication() != null) { System.out.println("\n***Warning! You are not using service account credentials to " + "authenticate.\nYou need to use service account credentials for this example," + "\nsince user-level credentials do not have enough pubsub quota,\nand so you will run " + "out of PubSub quota very quickly.\nSee " + "https://developers.google.com/identity/protocols/application-default-credentials."); System.exit(1); } HttpRequestInitializer initializer = new RetryHttpInitializerWrapper(credential); return new Pubsub.Builder(httpTransport, jsonFactory, initializer) .setApplicationName(APP_NAME) .build(); }
java
public static Pubsub getClient(final HttpTransport httpTransport, final JsonFactory jsonFactory) throws IOException { checkNotNull(httpTransport); checkNotNull(jsonFactory); GoogleCredential credential = GoogleCredential.getApplicationDefault(httpTransport, jsonFactory); if (credential.createScopedRequired()) { credential = credential.createScoped(PubsubScopes.all()); } if (credential.getClientAuthentication() != null) { System.out.println("\n***Warning! You are not using service account credentials to " + "authenticate.\nYou need to use service account credentials for this example," + "\nsince user-level credentials do not have enough pubsub quota,\nand so you will run " + "out of PubSub quota very quickly.\nSee " + "https://developers.google.com/identity/protocols/application-default-credentials."); System.exit(1); } HttpRequestInitializer initializer = new RetryHttpInitializerWrapper(credential); return new Pubsub.Builder(httpTransport, jsonFactory, initializer) .setApplicationName(APP_NAME) .build(); }
[ "public", "static", "Pubsub", "getClient", "(", "final", "HttpTransport", "httpTransport", ",", "final", "JsonFactory", "jsonFactory", ")", "throws", "IOException", "{", "checkNotNull", "(", "httpTransport", ")", ";", "checkNotNull", "(", "jsonFactory", ")", ";", "GoogleCredential", "credential", "=", "GoogleCredential", ".", "getApplicationDefault", "(", "httpTransport", ",", "jsonFactory", ")", ";", "if", "(", "credential", ".", "createScopedRequired", "(", ")", ")", "{", "credential", "=", "credential", ".", "createScoped", "(", "PubsubScopes", ".", "all", "(", ")", ")", ";", "}", "if", "(", "credential", ".", "getClientAuthentication", "(", ")", "!=", "null", ")", "{", "System", ".", "out", ".", "println", "(", "\"\\n***Warning! You are not using service account credentials to \"", "+", "\"authenticate.\\nYou need to use service account credentials for this example,\"", "+", "\"\\nsince user-level credentials do not have enough pubsub quota,\\nand so you will run \"", "+", "\"out of PubSub quota very quickly.\\nSee \"", "+", "\"https://developers.google.com/identity/protocols/application-default-credentials.\"", ")", ";", "System", ".", "exit", "(", "1", ")", ";", "}", "HttpRequestInitializer", "initializer", "=", "new", "RetryHttpInitializerWrapper", "(", "credential", ")", ";", "return", "new", "Pubsub", ".", "Builder", "(", "httpTransport", ",", "jsonFactory", ",", "initializer", ")", ".", "setApplicationName", "(", "APP_NAME", ")", ".", "build", "(", ")", ";", "}" ]
Builds a new Pubsub client and returns it.
[ "Builds", "a", "new", "Pubsub", "client", "and", "returns", "it", "." ]
ed9a44428251b0c6834aad231b463d8eda418471
https://github.com/spotify/scio/blob/ed9a44428251b0c6834aad231b463d8eda418471/scio-examples/src/main/java/org/apache/beam/examples/complete/game/injector/InjectorUtils.java#L41-L64
27,136
spotify/scio
scio-examples/src/main/java/org/apache/beam/examples/complete/game/injector/InjectorUtils.java
InjectorUtils.createTopic
public static void createTopic(Pubsub client, String fullTopicName) throws IOException { System.out.println("fullTopicName " + fullTopicName); try { client.projects().topics().get(fullTopicName).execute(); } catch (GoogleJsonResponseException e) { if (e.getStatusCode() == HttpStatusCodes.STATUS_CODE_NOT_FOUND) { Topic topic = client.projects().topics() .create(fullTopicName, new Topic()) .execute(); System.out.printf("Topic %s was created.%n", topic.getName()); } } }
java
public static void createTopic(Pubsub client, String fullTopicName) throws IOException { System.out.println("fullTopicName " + fullTopicName); try { client.projects().topics().get(fullTopicName).execute(); } catch (GoogleJsonResponseException e) { if (e.getStatusCode() == HttpStatusCodes.STATUS_CODE_NOT_FOUND) { Topic topic = client.projects().topics() .create(fullTopicName, new Topic()) .execute(); System.out.printf("Topic %s was created.%n", topic.getName()); } } }
[ "public", "static", "void", "createTopic", "(", "Pubsub", "client", ",", "String", "fullTopicName", ")", "throws", "IOException", "{", "System", ".", "out", ".", "println", "(", "\"fullTopicName \"", "+", "fullTopicName", ")", ";", "try", "{", "client", ".", "projects", "(", ")", ".", "topics", "(", ")", ".", "get", "(", "fullTopicName", ")", ".", "execute", "(", ")", ";", "}", "catch", "(", "GoogleJsonResponseException", "e", ")", "{", "if", "(", "e", ".", "getStatusCode", "(", ")", "==", "HttpStatusCodes", ".", "STATUS_CODE_NOT_FOUND", ")", "{", "Topic", "topic", "=", "client", ".", "projects", "(", ")", ".", "topics", "(", ")", ".", "create", "(", "fullTopicName", ",", "new", "Topic", "(", ")", ")", ".", "execute", "(", ")", ";", "System", ".", "out", ".", "printf", "(", "\"Topic %s was created.%n\"", ",", "topic", ".", "getName", "(", ")", ")", ";", "}", "}", "}" ]
Create a topic if it doesn't exist.
[ "Create", "a", "topic", "if", "it", "doesn", "t", "exist", "." ]
ed9a44428251b0c6834aad231b463d8eda418471
https://github.com/spotify/scio/blob/ed9a44428251b0c6834aad231b463d8eda418471/scio-examples/src/main/java/org/apache/beam/examples/complete/game/injector/InjectorUtils.java#L87-L100
27,137
spotify/scio
scio-examples/src/main/java/org/apache/beam/examples/complete/game/StatefulTeamScore.java
StatefulTeamScore.configureCompleteWindowedTableWrite
private static Map<String, FieldInfo<KV<String, Integer>>> configureCompleteWindowedTableWrite() { Map<String, WriteWindowedToBigQuery.FieldInfo<KV<String, Integer>>> tableConfigure = new HashMap<>(); tableConfigure.put( "team", new WriteWindowedToBigQuery.FieldInfo<>("STRING", (c, w) -> c.element().getKey())); tableConfigure.put( "total_score", new WriteWindowedToBigQuery.FieldInfo<>("INTEGER", (c, w) -> c.element().getValue())); tableConfigure.put( "processing_time", new WriteWindowedToBigQuery.FieldInfo<>( "STRING", (c, w) -> GameConstants.DATE_TIME_FORMATTER.print(Instant.now()))); return tableConfigure; }
java
private static Map<String, FieldInfo<KV<String, Integer>>> configureCompleteWindowedTableWrite() { Map<String, WriteWindowedToBigQuery.FieldInfo<KV<String, Integer>>> tableConfigure = new HashMap<>(); tableConfigure.put( "team", new WriteWindowedToBigQuery.FieldInfo<>("STRING", (c, w) -> c.element().getKey())); tableConfigure.put( "total_score", new WriteWindowedToBigQuery.FieldInfo<>("INTEGER", (c, w) -> c.element().getValue())); tableConfigure.put( "processing_time", new WriteWindowedToBigQuery.FieldInfo<>( "STRING", (c, w) -> GameConstants.DATE_TIME_FORMATTER.print(Instant.now()))); return tableConfigure; }
[ "private", "static", "Map", "<", "String", ",", "FieldInfo", "<", "KV", "<", "String", ",", "Integer", ">", ">", ">", "configureCompleteWindowedTableWrite", "(", ")", "{", "Map", "<", "String", ",", "WriteWindowedToBigQuery", ".", "FieldInfo", "<", "KV", "<", "String", ",", "Integer", ">", ">", ">", "tableConfigure", "=", "new", "HashMap", "<>", "(", ")", ";", "tableConfigure", ".", "put", "(", "\"team\"", ",", "new", "WriteWindowedToBigQuery", ".", "FieldInfo", "<>", "(", "\"STRING\"", ",", "(", "c", ",", "w", ")", "->", "c", ".", "element", "(", ")", ".", "getKey", "(", ")", ")", ")", ";", "tableConfigure", ".", "put", "(", "\"total_score\"", ",", "new", "WriteWindowedToBigQuery", ".", "FieldInfo", "<>", "(", "\"INTEGER\"", ",", "(", "c", ",", "w", ")", "->", "c", ".", "element", "(", ")", ".", "getValue", "(", ")", ")", ")", ";", "tableConfigure", ".", "put", "(", "\"processing_time\"", ",", "new", "WriteWindowedToBigQuery", ".", "FieldInfo", "<>", "(", "\"STRING\"", ",", "(", "c", ",", "w", ")", "->", "GameConstants", ".", "DATE_TIME_FORMATTER", ".", "print", "(", "Instant", ".", "now", "(", ")", ")", ")", ")", ";", "return", "tableConfigure", ";", "}" ]
Create a map of information that describes how to write pipeline output to BigQuery. This map is used to write team score sums.
[ "Create", "a", "map", "of", "information", "that", "describes", "how", "to", "write", "pipeline", "output", "to", "BigQuery", ".", "This", "map", "is", "used", "to", "write", "team", "score", "sums", "." ]
ed9a44428251b0c6834aad231b463d8eda418471
https://github.com/spotify/scio/blob/ed9a44428251b0c6834aad231b463d8eda418471/scio-examples/src/main/java/org/apache/beam/examples/complete/game/StatefulTeamScore.java#L97-L111
27,138
spotify/scio
scio-core/src/main/java/com/spotify/scio/util/RemoteFileUtil.java
RemoteFileUtil.delete
public void delete(URI src) { Path dst = null; try { dst = paths.get(src); } catch (ExecutionException e) { throw new RuntimeException(e); } try { Files.deleteIfExists(dst); paths.invalidate(src); } catch (IOException e) { String msg = String.format("Failed to delete %s -> %s", src, dst); LOG.error(msg, e); } }
java
public void delete(URI src) { Path dst = null; try { dst = paths.get(src); } catch (ExecutionException e) { throw new RuntimeException(e); } try { Files.deleteIfExists(dst); paths.invalidate(src); } catch (IOException e) { String msg = String.format("Failed to delete %s -> %s", src, dst); LOG.error(msg, e); } }
[ "public", "void", "delete", "(", "URI", "src", ")", "{", "Path", "dst", "=", "null", ";", "try", "{", "dst", "=", "paths", ".", "get", "(", "src", ")", ";", "}", "catch", "(", "ExecutionException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "try", "{", "Files", ".", "deleteIfExists", "(", "dst", ")", ";", "paths", ".", "invalidate", "(", "src", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "String", "msg", "=", "String", ".", "format", "(", "\"Failed to delete %s -> %s\"", ",", "src", ",", "dst", ")", ";", "LOG", ".", "error", "(", "msg", ",", "e", ")", ";", "}", "}" ]
Delete a single downloaded local file.
[ "Delete", "a", "single", "downloaded", "local", "file", "." ]
ed9a44428251b0c6834aad231b463d8eda418471
https://github.com/spotify/scio/blob/ed9a44428251b0c6834aad231b463d8eda418471/scio-core/src/main/java/com/spotify/scio/util/RemoteFileUtil.java#L117-L131
27,139
spotify/scio
scio-core/src/main/java/com/spotify/scio/util/RemoteFileUtil.java
RemoteFileUtil.delete
public void delete(List<URI> srcs) { for (URI src : srcs) { delete(src); } paths.invalidateAll(srcs); }
java
public void delete(List<URI> srcs) { for (URI src : srcs) { delete(src); } paths.invalidateAll(srcs); }
[ "public", "void", "delete", "(", "List", "<", "URI", ">", "srcs", ")", "{", "for", "(", "URI", "src", ":", "srcs", ")", "{", "delete", "(", "src", ")", ";", "}", "paths", ".", "invalidateAll", "(", "srcs", ")", ";", "}" ]
Delete a batch of downloaded local files.
[ "Delete", "a", "batch", "of", "downloaded", "local", "files", "." ]
ed9a44428251b0c6834aad231b463d8eda418471
https://github.com/spotify/scio/blob/ed9a44428251b0c6834aad231b463d8eda418471/scio-core/src/main/java/com/spotify/scio/util/RemoteFileUtil.java#L136-L141
27,140
spotify/scio
scio-core/src/main/java/com/spotify/scio/util/RemoteFileUtil.java
RemoteFileUtil.copyToLocal
private static void copyToLocal(Metadata src, Path dst) throws IOException { FileChannel dstCh = FileChannel.open( dst, StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW); ReadableByteChannel srcCh = FileSystems.open(src.resourceId()); long srcSize = src.sizeBytes(); long copied = 0; do { copied += dstCh.transferFrom(srcCh, copied, srcSize - copied); } while (copied < srcSize); dstCh.close(); srcCh.close(); Preconditions.checkState(copied == srcSize); }
java
private static void copyToLocal(Metadata src, Path dst) throws IOException { FileChannel dstCh = FileChannel.open( dst, StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW); ReadableByteChannel srcCh = FileSystems.open(src.resourceId()); long srcSize = src.sizeBytes(); long copied = 0; do { copied += dstCh.transferFrom(srcCh, copied, srcSize - copied); } while (copied < srcSize); dstCh.close(); srcCh.close(); Preconditions.checkState(copied == srcSize); }
[ "private", "static", "void", "copyToLocal", "(", "Metadata", "src", ",", "Path", "dst", ")", "throws", "IOException", "{", "FileChannel", "dstCh", "=", "FileChannel", ".", "open", "(", "dst", ",", "StandardOpenOption", ".", "WRITE", ",", "StandardOpenOption", ".", "CREATE_NEW", ")", ";", "ReadableByteChannel", "srcCh", "=", "FileSystems", ".", "open", "(", "src", ".", "resourceId", "(", ")", ")", ";", "long", "srcSize", "=", "src", ".", "sizeBytes", "(", ")", ";", "long", "copied", "=", "0", ";", "do", "{", "copied", "+=", "dstCh", ".", "transferFrom", "(", "srcCh", ",", "copied", ",", "srcSize", "-", "copied", ")", ";", "}", "while", "(", "copied", "<", "srcSize", ")", ";", "dstCh", ".", "close", "(", ")", ";", "srcCh", ".", "close", "(", ")", ";", "Preconditions", ".", "checkState", "(", "copied", "==", "srcSize", ")", ";", "}" ]
Copy a single file from remote source to local destination
[ "Copy", "a", "single", "file", "from", "remote", "source", "to", "local", "destination" ]
ed9a44428251b0c6834aad231b463d8eda418471
https://github.com/spotify/scio/blob/ed9a44428251b0c6834aad231b463d8eda418471/scio-core/src/main/java/com/spotify/scio/util/RemoteFileUtil.java#L219-L231
27,141
spotify/scio
scio-core/src/main/java/com/spotify/scio/util/RemoteFileUtil.java
RemoteFileUtil.copyToRemote
private static void copyToRemote(Path src, URI dst) throws IOException { ResourceId dstId = FileSystems.matchNewResource(dst.toString(), false); WritableByteChannel dstCh = FileSystems.create(dstId, MimeTypes.BINARY); FileChannel srcCh = FileChannel.open(src, StandardOpenOption.READ); long srcSize = srcCh.size(); long copied = 0; do { copied += srcCh.transferTo(copied, srcSize - copied, dstCh); } while (copied < srcSize); dstCh.close(); srcCh.close(); Preconditions.checkState(copied == srcSize); }
java
private static void copyToRemote(Path src, URI dst) throws IOException { ResourceId dstId = FileSystems.matchNewResource(dst.toString(), false); WritableByteChannel dstCh = FileSystems.create(dstId, MimeTypes.BINARY); FileChannel srcCh = FileChannel.open(src, StandardOpenOption.READ); long srcSize = srcCh.size(); long copied = 0; do { copied += srcCh.transferTo(copied, srcSize - copied, dstCh); } while (copied < srcSize); dstCh.close(); srcCh.close(); Preconditions.checkState(copied == srcSize); }
[ "private", "static", "void", "copyToRemote", "(", "Path", "src", ",", "URI", "dst", ")", "throws", "IOException", "{", "ResourceId", "dstId", "=", "FileSystems", ".", "matchNewResource", "(", "dst", ".", "toString", "(", ")", ",", "false", ")", ";", "WritableByteChannel", "dstCh", "=", "FileSystems", ".", "create", "(", "dstId", ",", "MimeTypes", ".", "BINARY", ")", ";", "FileChannel", "srcCh", "=", "FileChannel", ".", "open", "(", "src", ",", "StandardOpenOption", ".", "READ", ")", ";", "long", "srcSize", "=", "srcCh", ".", "size", "(", ")", ";", "long", "copied", "=", "0", ";", "do", "{", "copied", "+=", "srcCh", ".", "transferTo", "(", "copied", ",", "srcSize", "-", "copied", ",", "dstCh", ")", ";", "}", "while", "(", "copied", "<", "srcSize", ")", ";", "dstCh", ".", "close", "(", ")", ";", "srcCh", ".", "close", "(", ")", ";", "Preconditions", ".", "checkState", "(", "copied", "==", "srcSize", ")", ";", "}" ]
Copy a single file from local source to remote destination
[ "Copy", "a", "single", "file", "from", "local", "source", "to", "remote", "destination" ]
ed9a44428251b0c6834aad231b463d8eda418471
https://github.com/spotify/scio/blob/ed9a44428251b0c6834aad231b463d8eda418471/scio-core/src/main/java/com/spotify/scio/util/RemoteFileUtil.java#L234-L246
27,142
spotify/scio
scio-examples/src/main/java/org/apache/beam/examples/cookbook/JoinExamples.java
JoinExamples.joinEvents
static PCollection<String> joinEvents(PCollection<TableRow> eventsTable, PCollection<TableRow> countryCodes) throws Exception { final TupleTag<String> eventInfoTag = new TupleTag<>(); final TupleTag<String> countryInfoTag = new TupleTag<>(); // transform both input collections to tuple collections, where the keys are country // codes in both cases. PCollection<KV<String, String>> eventInfo = eventsTable.apply( ParDo.of(new ExtractEventDataFn())); PCollection<KV<String, String>> countryInfo = countryCodes.apply( ParDo.of(new ExtractCountryInfoFn())); // country code 'key' -> CGBKR (<event info>, <country name>) PCollection<KV<String, CoGbkResult>> kvpCollection = KeyedPCollectionTuple.of(eventInfoTag, eventInfo) .and(countryInfoTag, countryInfo) .apply(CoGroupByKey.create()); // Process the CoGbkResult elements generated by the CoGroupByKey transform. // country code 'key' -> string of <event info>, <country name> PCollection<KV<String, String>> finalResultCollection = kvpCollection.apply("Process", ParDo.of( new DoFn<KV<String, CoGbkResult>, KV<String, String>>() { @ProcessElement public void processElement(ProcessContext c) { KV<String, CoGbkResult> e = c.element(); String countryCode = e.getKey(); String countryName = "none"; countryName = e.getValue().getOnly(countryInfoTag); for (String eventInfo : c.element().getValue().getAll(eventInfoTag)) { // Generate a string that combines information from both collection values c.output(KV.of(countryCode, "Country name: " + countryName + ", Event info: " + eventInfo)); } } })); // write to GCS PCollection<String> formattedResults = finalResultCollection .apply("Format", ParDo.of(new DoFn<KV<String, String>, String>() { @ProcessElement public void processElement(ProcessContext c) { String outputstring = "Country code: " + c.element().getKey() + ", " + c.element().getValue(); c.output(outputstring); } })); return formattedResults; }
java
static PCollection<String> joinEvents(PCollection<TableRow> eventsTable, PCollection<TableRow> countryCodes) throws Exception { final TupleTag<String> eventInfoTag = new TupleTag<>(); final TupleTag<String> countryInfoTag = new TupleTag<>(); // transform both input collections to tuple collections, where the keys are country // codes in both cases. PCollection<KV<String, String>> eventInfo = eventsTable.apply( ParDo.of(new ExtractEventDataFn())); PCollection<KV<String, String>> countryInfo = countryCodes.apply( ParDo.of(new ExtractCountryInfoFn())); // country code 'key' -> CGBKR (<event info>, <country name>) PCollection<KV<String, CoGbkResult>> kvpCollection = KeyedPCollectionTuple.of(eventInfoTag, eventInfo) .and(countryInfoTag, countryInfo) .apply(CoGroupByKey.create()); // Process the CoGbkResult elements generated by the CoGroupByKey transform. // country code 'key' -> string of <event info>, <country name> PCollection<KV<String, String>> finalResultCollection = kvpCollection.apply("Process", ParDo.of( new DoFn<KV<String, CoGbkResult>, KV<String, String>>() { @ProcessElement public void processElement(ProcessContext c) { KV<String, CoGbkResult> e = c.element(); String countryCode = e.getKey(); String countryName = "none"; countryName = e.getValue().getOnly(countryInfoTag); for (String eventInfo : c.element().getValue().getAll(eventInfoTag)) { // Generate a string that combines information from both collection values c.output(KV.of(countryCode, "Country name: " + countryName + ", Event info: " + eventInfo)); } } })); // write to GCS PCollection<String> formattedResults = finalResultCollection .apply("Format", ParDo.of(new DoFn<KV<String, String>, String>() { @ProcessElement public void processElement(ProcessContext c) { String outputstring = "Country code: " + c.element().getKey() + ", " + c.element().getValue(); c.output(outputstring); } })); return formattedResults; }
[ "static", "PCollection", "<", "String", ">", "joinEvents", "(", "PCollection", "<", "TableRow", ">", "eventsTable", ",", "PCollection", "<", "TableRow", ">", "countryCodes", ")", "throws", "Exception", "{", "final", "TupleTag", "<", "String", ">", "eventInfoTag", "=", "new", "TupleTag", "<>", "(", ")", ";", "final", "TupleTag", "<", "String", ">", "countryInfoTag", "=", "new", "TupleTag", "<>", "(", ")", ";", "// transform both input collections to tuple collections, where the keys are country", "// codes in both cases.", "PCollection", "<", "KV", "<", "String", ",", "String", ">", ">", "eventInfo", "=", "eventsTable", ".", "apply", "(", "ParDo", ".", "of", "(", "new", "ExtractEventDataFn", "(", ")", ")", ")", ";", "PCollection", "<", "KV", "<", "String", ",", "String", ">", ">", "countryInfo", "=", "countryCodes", ".", "apply", "(", "ParDo", ".", "of", "(", "new", "ExtractCountryInfoFn", "(", ")", ")", ")", ";", "// country code 'key' -> CGBKR (<event info>, <country name>)", "PCollection", "<", "KV", "<", "String", ",", "CoGbkResult", ">", ">", "kvpCollection", "=", "KeyedPCollectionTuple", ".", "of", "(", "eventInfoTag", ",", "eventInfo", ")", ".", "and", "(", "countryInfoTag", ",", "countryInfo", ")", ".", "apply", "(", "CoGroupByKey", ".", "create", "(", ")", ")", ";", "// Process the CoGbkResult elements generated by the CoGroupByKey transform.", "// country code 'key' -> string of <event info>, <country name>", "PCollection", "<", "KV", "<", "String", ",", "String", ">", ">", "finalResultCollection", "=", "kvpCollection", ".", "apply", "(", "\"Process\"", ",", "ParDo", ".", "of", "(", "new", "DoFn", "<", "KV", "<", "String", ",", "CoGbkResult", ">", ",", "KV", "<", "String", ",", "String", ">", ">", "(", ")", "{", "@", "ProcessElement", "public", "void", "processElement", "(", "ProcessContext", "c", ")", "{", "KV", "<", "String", ",", "CoGbkResult", ">", "e", "=", "c", ".", "element", "(", ")", ";", "String", "countryCode", "=", "e", ".", "getKey", "(", ")", ";", "String", "countryName", "=", "\"none\"", ";", "countryName", "=", "e", ".", "getValue", "(", ")", ".", "getOnly", "(", "countryInfoTag", ")", ";", "for", "(", "String", "eventInfo", ":", "c", ".", "element", "(", ")", ".", "getValue", "(", ")", ".", "getAll", "(", "eventInfoTag", ")", ")", "{", "// Generate a string that combines information from both collection values", "c", ".", "output", "(", "KV", ".", "of", "(", "countryCode", ",", "\"Country name: \"", "+", "countryName", "+", "\", Event info: \"", "+", "eventInfo", ")", ")", ";", "}", "}", "}", ")", ")", ";", "// write to GCS", "PCollection", "<", "String", ">", "formattedResults", "=", "finalResultCollection", ".", "apply", "(", "\"Format\"", ",", "ParDo", ".", "of", "(", "new", "DoFn", "<", "KV", "<", "String", ",", "String", ">", ",", "String", ">", "(", ")", "{", "@", "ProcessElement", "public", "void", "processElement", "(", "ProcessContext", "c", ")", "{", "String", "outputstring", "=", "\"Country code: \"", "+", "c", ".", "element", "(", ")", ".", "getKey", "(", ")", "+", "\", \"", "+", "c", ".", "element", "(", ")", ".", "getValue", "(", ")", ";", "c", ".", "output", "(", "outputstring", ")", ";", "}", "}", ")", ")", ";", "return", "formattedResults", ";", "}" ]
Join two collections, using country code as the key.
[ "Join", "two", "collections", "using", "country", "code", "as", "the", "key", "." ]
ed9a44428251b0c6834aad231b463d8eda418471
https://github.com/spotify/scio/blob/ed9a44428251b0c6834aad231b463d8eda418471/scio-examples/src/main/java/org/apache/beam/examples/cookbook/JoinExamples.java#L68-L117
27,143
spotify/scio
scio-examples/src/main/java/org/apache/beam/examples/complete/game/LeaderBoard.java
LeaderBoard.configureWindowedTableWrite
protected static Map<String, WriteWindowedToBigQuery.FieldInfo<KV<String, Integer>>> configureWindowedTableWrite() { Map<String, WriteWindowedToBigQuery.FieldInfo<KV<String, Integer>>> tableConfigure = new HashMap<>(); tableConfigure.put( "team", new WriteWindowedToBigQuery.FieldInfo<>("STRING", (c, w) -> c.element().getKey())); tableConfigure.put( "total_score", new WriteWindowedToBigQuery.FieldInfo<>("INTEGER", (c, w) -> c.element().getValue())); tableConfigure.put( "window_start", new WriteWindowedToBigQuery.FieldInfo<>( "STRING", (c, w) -> { IntervalWindow window = (IntervalWindow) w; return GameConstants.DATE_TIME_FORMATTER.print(window.start()); })); tableConfigure.put( "processing_time", new WriteWindowedToBigQuery.FieldInfo<>( "STRING", (c, w) -> GameConstants.DATE_TIME_FORMATTER.print(Instant.now()))); tableConfigure.put( "timing", new WriteWindowedToBigQuery.FieldInfo<>( "STRING", (c, w) -> c.pane().getTiming().toString())); return tableConfigure; }
java
protected static Map<String, WriteWindowedToBigQuery.FieldInfo<KV<String, Integer>>> configureWindowedTableWrite() { Map<String, WriteWindowedToBigQuery.FieldInfo<KV<String, Integer>>> tableConfigure = new HashMap<>(); tableConfigure.put( "team", new WriteWindowedToBigQuery.FieldInfo<>("STRING", (c, w) -> c.element().getKey())); tableConfigure.put( "total_score", new WriteWindowedToBigQuery.FieldInfo<>("INTEGER", (c, w) -> c.element().getValue())); tableConfigure.put( "window_start", new WriteWindowedToBigQuery.FieldInfo<>( "STRING", (c, w) -> { IntervalWindow window = (IntervalWindow) w; return GameConstants.DATE_TIME_FORMATTER.print(window.start()); })); tableConfigure.put( "processing_time", new WriteWindowedToBigQuery.FieldInfo<>( "STRING", (c, w) -> GameConstants.DATE_TIME_FORMATTER.print(Instant.now()))); tableConfigure.put( "timing", new WriteWindowedToBigQuery.FieldInfo<>( "STRING", (c, w) -> c.pane().getTiming().toString())); return tableConfigure; }
[ "protected", "static", "Map", "<", "String", ",", "WriteWindowedToBigQuery", ".", "FieldInfo", "<", "KV", "<", "String", ",", "Integer", ">", ">", ">", "configureWindowedTableWrite", "(", ")", "{", "Map", "<", "String", ",", "WriteWindowedToBigQuery", ".", "FieldInfo", "<", "KV", "<", "String", ",", "Integer", ">", ">", ">", "tableConfigure", "=", "new", "HashMap", "<>", "(", ")", ";", "tableConfigure", ".", "put", "(", "\"team\"", ",", "new", "WriteWindowedToBigQuery", ".", "FieldInfo", "<>", "(", "\"STRING\"", ",", "(", "c", ",", "w", ")", "->", "c", ".", "element", "(", ")", ".", "getKey", "(", ")", ")", ")", ";", "tableConfigure", ".", "put", "(", "\"total_score\"", ",", "new", "WriteWindowedToBigQuery", ".", "FieldInfo", "<>", "(", "\"INTEGER\"", ",", "(", "c", ",", "w", ")", "->", "c", ".", "element", "(", ")", ".", "getValue", "(", ")", ")", ")", ";", "tableConfigure", ".", "put", "(", "\"window_start\"", ",", "new", "WriteWindowedToBigQuery", ".", "FieldInfo", "<>", "(", "\"STRING\"", ",", "(", "c", ",", "w", ")", "->", "{", "IntervalWindow", "window", "=", "(", "IntervalWindow", ")", "w", ";", "return", "GameConstants", ".", "DATE_TIME_FORMATTER", ".", "print", "(", "window", ".", "start", "(", ")", ")", ";", "}", ")", ")", ";", "tableConfigure", ".", "put", "(", "\"processing_time\"", ",", "new", "WriteWindowedToBigQuery", ".", "FieldInfo", "<>", "(", "\"STRING\"", ",", "(", "c", ",", "w", ")", "->", "GameConstants", ".", "DATE_TIME_FORMATTER", ".", "print", "(", "Instant", ".", "now", "(", ")", ")", ")", ")", ";", "tableConfigure", ".", "put", "(", "\"timing\"", ",", "new", "WriteWindowedToBigQuery", ".", "FieldInfo", "<>", "(", "\"STRING\"", ",", "(", "c", ",", "w", ")", "->", "c", ".", "pane", "(", ")", ".", "getTiming", "(", ")", ".", "toString", "(", ")", ")", ")", ";", "return", "tableConfigure", ";", "}" ]
Create a map of information that describes how to write pipeline output to BigQuery. This map is used to write team score sums and includes event timing information.
[ "Create", "a", "map", "of", "information", "that", "describes", "how", "to", "write", "pipeline", "output", "to", "BigQuery", ".", "This", "map", "is", "used", "to", "write", "team", "score", "sums", "and", "includes", "event", "timing", "information", "." ]
ed9a44428251b0c6834aad231b463d8eda418471
https://github.com/spotify/scio/blob/ed9a44428251b0c6834aad231b463d8eda418471/scio-examples/src/main/java/org/apache/beam/examples/complete/game/LeaderBoard.java#L131-L158
27,144
spotify/scio
scio-examples/src/main/java/org/apache/beam/examples/complete/game/LeaderBoard.java
LeaderBoard.configureGlobalWindowBigQueryWrite
protected static Map<String, WriteToBigQuery.FieldInfo<KV<String, Integer>>> configureGlobalWindowBigQueryWrite() { Map<String, WriteToBigQuery.FieldInfo<KV<String, Integer>>> tableConfigure = configureBigQueryWrite(); tableConfigure.put( "processing_time", new WriteToBigQuery.FieldInfo<>( "STRING", (c, w) -> GameConstants.DATE_TIME_FORMATTER.print(Instant.now()))); return tableConfigure; }
java
protected static Map<String, WriteToBigQuery.FieldInfo<KV<String, Integer>>> configureGlobalWindowBigQueryWrite() { Map<String, WriteToBigQuery.FieldInfo<KV<String, Integer>>> tableConfigure = configureBigQueryWrite(); tableConfigure.put( "processing_time", new WriteToBigQuery.FieldInfo<>( "STRING", (c, w) -> GameConstants.DATE_TIME_FORMATTER.print(Instant.now()))); return tableConfigure; }
[ "protected", "static", "Map", "<", "String", ",", "WriteToBigQuery", ".", "FieldInfo", "<", "KV", "<", "String", ",", "Integer", ">", ">", ">", "configureGlobalWindowBigQueryWrite", "(", ")", "{", "Map", "<", "String", ",", "WriteToBigQuery", ".", "FieldInfo", "<", "KV", "<", "String", ",", "Integer", ">", ">", ">", "tableConfigure", "=", "configureBigQueryWrite", "(", ")", ";", "tableConfigure", ".", "put", "(", "\"processing_time\"", ",", "new", "WriteToBigQuery", ".", "FieldInfo", "<>", "(", "\"STRING\"", ",", "(", "c", ",", "w", ")", "->", "GameConstants", ".", "DATE_TIME_FORMATTER", ".", "print", "(", "Instant", ".", "now", "(", ")", ")", ")", ")", ";", "return", "tableConfigure", ";", "}" ]
Create a map of information that describes how to write pipeline output to BigQuery. This map is used to write user score sums.
[ "Create", "a", "map", "of", "information", "that", "describes", "how", "to", "write", "pipeline", "output", "to", "BigQuery", ".", "This", "map", "is", "used", "to", "write", "user", "score", "sums", "." ]
ed9a44428251b0c6834aad231b463d8eda418471
https://github.com/spotify/scio/blob/ed9a44428251b0c6834aad231b463d8eda418471/scio-examples/src/main/java/org/apache/beam/examples/complete/game/LeaderBoard.java#L181-L191
27,145
spotify/scio
scio-examples/src/main/java/org/apache/beam/examples/snippets/Snippets.java
Snippets.formatCoGbkResults
public static String formatCoGbkResults( String name, Iterable<String> emails, Iterable<String> phones) { List<String> emailsList = new ArrayList<>(); for (String elem : emails) { emailsList.add("'" + elem + "'"); } Collections.sort(emailsList); String emailsStr = "[" + String.join(", ", emailsList) + "]"; List<String> phonesList = new ArrayList<>(); for (String elem : phones) { phonesList.add("'" + elem + "'"); } Collections.sort(phonesList); String phonesStr = "[" + String.join(", ", phonesList) + "]"; return name + "; " + emailsStr + "; " + phonesStr; }
java
public static String formatCoGbkResults( String name, Iterable<String> emails, Iterable<String> phones) { List<String> emailsList = new ArrayList<>(); for (String elem : emails) { emailsList.add("'" + elem + "'"); } Collections.sort(emailsList); String emailsStr = "[" + String.join(", ", emailsList) + "]"; List<String> phonesList = new ArrayList<>(); for (String elem : phones) { phonesList.add("'" + elem + "'"); } Collections.sort(phonesList); String phonesStr = "[" + String.join(", ", phonesList) + "]"; return name + "; " + emailsStr + "; " + phonesStr; }
[ "public", "static", "String", "formatCoGbkResults", "(", "String", "name", ",", "Iterable", "<", "String", ">", "emails", ",", "Iterable", "<", "String", ">", "phones", ")", "{", "List", "<", "String", ">", "emailsList", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "String", "elem", ":", "emails", ")", "{", "emailsList", ".", "add", "(", "\"'\"", "+", "elem", "+", "\"'\"", ")", ";", "}", "Collections", ".", "sort", "(", "emailsList", ")", ";", "String", "emailsStr", "=", "\"[\"", "+", "String", ".", "join", "(", "\", \"", ",", "emailsList", ")", "+", "\"]\"", ";", "List", "<", "String", ">", "phonesList", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "String", "elem", ":", "phones", ")", "{", "phonesList", ".", "add", "(", "\"'\"", "+", "elem", "+", "\"'\"", ")", ";", "}", "Collections", ".", "sort", "(", "phonesList", ")", ";", "String", "phonesStr", "=", "\"[\"", "+", "String", ".", "join", "(", "\", \"", ",", "phonesList", ")", "+", "\"]\"", ";", "return", "name", "+", "\"; \"", "+", "emailsStr", "+", "\"; \"", "+", "phonesStr", ";", "}" ]
Helper function to format results in coGroupByKeyTuple.
[ "Helper", "function", "to", "format", "results", "in", "coGroupByKeyTuple", "." ]
ed9a44428251b0c6834aad231b463d8eda418471
https://github.com/spotify/scio/blob/ed9a44428251b0c6834aad231b463d8eda418471/scio-examples/src/main/java/org/apache/beam/examples/snippets/Snippets.java#L365-L383
27,146
spotify/scio
scio-examples/src/main/java/org/apache/beam/examples/snippets/Snippets.java
Snippets.coGroupByKeyTuple
public static PCollection<String> coGroupByKeyTuple( TupleTag<String> emailsTag, TupleTag<String> phonesTag, PCollection<KV<String, String>> emails, PCollection<KV<String, String>> phones) { // [START CoGroupByKeyTuple] PCollection<KV<String, CoGbkResult>> results = KeyedPCollectionTuple .of(emailsTag, emails) .and(phonesTag, phones) .apply(CoGroupByKey.create()); PCollection<String> contactLines = results.apply(ParDo.of( new DoFn<KV<String, CoGbkResult>, String>() { @ProcessElement public void processElement(ProcessContext c) { KV<String, CoGbkResult> e = c.element(); String name = e.getKey(); Iterable<String> emailsIter = e.getValue().getAll(emailsTag); Iterable<String> phonesIter = e.getValue().getAll(phonesTag); String formattedResult = Snippets.formatCoGbkResults(name, emailsIter, phonesIter); c.output(formattedResult); } } )); // [END CoGroupByKeyTuple] return contactLines; }
java
public static PCollection<String> coGroupByKeyTuple( TupleTag<String> emailsTag, TupleTag<String> phonesTag, PCollection<KV<String, String>> emails, PCollection<KV<String, String>> phones) { // [START CoGroupByKeyTuple] PCollection<KV<String, CoGbkResult>> results = KeyedPCollectionTuple .of(emailsTag, emails) .and(phonesTag, phones) .apply(CoGroupByKey.create()); PCollection<String> contactLines = results.apply(ParDo.of( new DoFn<KV<String, CoGbkResult>, String>() { @ProcessElement public void processElement(ProcessContext c) { KV<String, CoGbkResult> e = c.element(); String name = e.getKey(); Iterable<String> emailsIter = e.getValue().getAll(emailsTag); Iterable<String> phonesIter = e.getValue().getAll(phonesTag); String formattedResult = Snippets.formatCoGbkResults(name, emailsIter, phonesIter); c.output(formattedResult); } } )); // [END CoGroupByKeyTuple] return contactLines; }
[ "public", "static", "PCollection", "<", "String", ">", "coGroupByKeyTuple", "(", "TupleTag", "<", "String", ">", "emailsTag", ",", "TupleTag", "<", "String", ">", "phonesTag", ",", "PCollection", "<", "KV", "<", "String", ",", "String", ">", ">", "emails", ",", "PCollection", "<", "KV", "<", "String", ",", "String", ">", ">", "phones", ")", "{", "// [START CoGroupByKeyTuple]", "PCollection", "<", "KV", "<", "String", ",", "CoGbkResult", ">", ">", "results", "=", "KeyedPCollectionTuple", ".", "of", "(", "emailsTag", ",", "emails", ")", ".", "and", "(", "phonesTag", ",", "phones", ")", ".", "apply", "(", "CoGroupByKey", ".", "create", "(", ")", ")", ";", "PCollection", "<", "String", ">", "contactLines", "=", "results", ".", "apply", "(", "ParDo", ".", "of", "(", "new", "DoFn", "<", "KV", "<", "String", ",", "CoGbkResult", ">", ",", "String", ">", "(", ")", "{", "@", "ProcessElement", "public", "void", "processElement", "(", "ProcessContext", "c", ")", "{", "KV", "<", "String", ",", "CoGbkResult", ">", "e", "=", "c", ".", "element", "(", ")", ";", "String", "name", "=", "e", ".", "getKey", "(", ")", ";", "Iterable", "<", "String", ">", "emailsIter", "=", "e", ".", "getValue", "(", ")", ".", "getAll", "(", "emailsTag", ")", ";", "Iterable", "<", "String", ">", "phonesIter", "=", "e", ".", "getValue", "(", ")", ".", "getAll", "(", "phonesTag", ")", ";", "String", "formattedResult", "=", "Snippets", ".", "formatCoGbkResults", "(", "name", ",", "emailsIter", ",", "phonesIter", ")", ";", "c", ".", "output", "(", "formattedResult", ")", ";", "}", "}", ")", ")", ";", "// [END CoGroupByKeyTuple]", "return", "contactLines", ";", "}" ]
Using a CoGroupByKey transform.
[ "Using", "a", "CoGroupByKey", "transform", "." ]
ed9a44428251b0c6834aad231b463d8eda418471
https://github.com/spotify/scio/blob/ed9a44428251b0c6834aad231b463d8eda418471/scio-examples/src/main/java/org/apache/beam/examples/snippets/Snippets.java#L386-L414
27,147
spotify/scio
scio-bigtable/src/main/java/com/spotify/scio/bigtable/BigtableUtil.java
BigtableUtil.getClusterSizes
public static Map<String, Integer> getClusterSizes( final String projectId, final String instanceId ) throws IOException, GeneralSecurityException { try (BigtableClusterUtilities clusterUtil = BigtableClusterUtilities .forInstance(projectId, instanceId)) { return Collections.unmodifiableMap( clusterUtil.getClusters().getClustersList().stream() .collect(Collectors.toMap( cn -> cn.getName().substring(cn.getName().indexOf("/clusters/") + 10), Cluster::getServeNodes))); } }
java
public static Map<String, Integer> getClusterSizes( final String projectId, final String instanceId ) throws IOException, GeneralSecurityException { try (BigtableClusterUtilities clusterUtil = BigtableClusterUtilities .forInstance(projectId, instanceId)) { return Collections.unmodifiableMap( clusterUtil.getClusters().getClustersList().stream() .collect(Collectors.toMap( cn -> cn.getName().substring(cn.getName().indexOf("/clusters/") + 10), Cluster::getServeNodes))); } }
[ "public", "static", "Map", "<", "String", ",", "Integer", ">", "getClusterSizes", "(", "final", "String", "projectId", ",", "final", "String", "instanceId", ")", "throws", "IOException", ",", "GeneralSecurityException", "{", "try", "(", "BigtableClusterUtilities", "clusterUtil", "=", "BigtableClusterUtilities", ".", "forInstance", "(", "projectId", ",", "instanceId", ")", ")", "{", "return", "Collections", ".", "unmodifiableMap", "(", "clusterUtil", ".", "getClusters", "(", ")", ".", "getClustersList", "(", ")", ".", "stream", "(", ")", ".", "collect", "(", "Collectors", ".", "toMap", "(", "cn", "->", "cn", ".", "getName", "(", ")", ".", "substring", "(", "cn", ".", "getName", "(", ")", ".", "indexOf", "(", "\"/clusters/\"", ")", "+", "10", ")", ",", "Cluster", "::", "getServeNodes", ")", ")", ")", ";", "}", "}" ]
Get size of all clusters for specified Bigtable instance. @param projectId GCP projectId @param instanceId Bigtable instanceId @return map of clusterId to its number of nodes @throws IOException If setting up channel pool fails @throws GeneralSecurityException If security-related exceptions occurs
[ "Get", "size", "of", "all", "clusters", "for", "specified", "Bigtable", "instance", "." ]
ed9a44428251b0c6834aad231b463d8eda418471
https://github.com/spotify/scio/blob/ed9a44428251b0c6834aad231b463d8eda418471/scio-bigtable/src/main/java/com/spotify/scio/bigtable/BigtableUtil.java#L121-L133
27,148
spotify/scio
scio-examples/src/main/java/org/apache/beam/examples/common/ExampleUtils.java
ExampleUtils.setupBigQueryTable
public void setupBigQueryTable() throws IOException { ExampleBigQueryTableOptions bigQueryTableOptions = options.as(ExampleBigQueryTableOptions.class); if (bigQueryTableOptions.getBigQueryDataset() != null && bigQueryTableOptions.getBigQueryTable() != null && bigQueryTableOptions.getBigQuerySchema() != null) { pendingMessages.add("******************Set Up Big Query Table*******************"); setupBigQueryTable(bigQueryTableOptions.getProject(), bigQueryTableOptions.getBigQueryDataset(), bigQueryTableOptions.getBigQueryTable(), bigQueryTableOptions.getBigQuerySchema()); pendingMessages.add("The BigQuery table has been set up for this example: " + bigQueryTableOptions.getProject() + ":" + bigQueryTableOptions.getBigQueryDataset() + "." + bigQueryTableOptions.getBigQueryTable()); } }
java
public void setupBigQueryTable() throws IOException { ExampleBigQueryTableOptions bigQueryTableOptions = options.as(ExampleBigQueryTableOptions.class); if (bigQueryTableOptions.getBigQueryDataset() != null && bigQueryTableOptions.getBigQueryTable() != null && bigQueryTableOptions.getBigQuerySchema() != null) { pendingMessages.add("******************Set Up Big Query Table*******************"); setupBigQueryTable(bigQueryTableOptions.getProject(), bigQueryTableOptions.getBigQueryDataset(), bigQueryTableOptions.getBigQueryTable(), bigQueryTableOptions.getBigQuerySchema()); pendingMessages.add("The BigQuery table has been set up for this example: " + bigQueryTableOptions.getProject() + ":" + bigQueryTableOptions.getBigQueryDataset() + "." + bigQueryTableOptions.getBigQueryTable()); } }
[ "public", "void", "setupBigQueryTable", "(", ")", "throws", "IOException", "{", "ExampleBigQueryTableOptions", "bigQueryTableOptions", "=", "options", ".", "as", "(", "ExampleBigQueryTableOptions", ".", "class", ")", ";", "if", "(", "bigQueryTableOptions", ".", "getBigQueryDataset", "(", ")", "!=", "null", "&&", "bigQueryTableOptions", ".", "getBigQueryTable", "(", ")", "!=", "null", "&&", "bigQueryTableOptions", ".", "getBigQuerySchema", "(", ")", "!=", "null", ")", "{", "pendingMessages", ".", "add", "(", "\"******************Set Up Big Query Table*******************\"", ")", ";", "setupBigQueryTable", "(", "bigQueryTableOptions", ".", "getProject", "(", ")", ",", "bigQueryTableOptions", ".", "getBigQueryDataset", "(", ")", ",", "bigQueryTableOptions", ".", "getBigQueryTable", "(", ")", ",", "bigQueryTableOptions", ".", "getBigQuerySchema", "(", ")", ")", ";", "pendingMessages", ".", "add", "(", "\"The BigQuery table has been set up for this example: \"", "+", "bigQueryTableOptions", ".", "getProject", "(", ")", "+", "\":\"", "+", "bigQueryTableOptions", ".", "getBigQueryDataset", "(", ")", "+", "\".\"", "+", "bigQueryTableOptions", ".", "getBigQueryTable", "(", ")", ")", ";", "}", "}" ]
Sets up the BigQuery table with the given schema. <p>If the table already exists, the schema has to match the given one. Otherwise, the example will throw a RuntimeException. If the table doesn't exist, a new table with the given schema will be created. @throws IOException if there is a problem setting up the BigQuery table
[ "Sets", "up", "the", "BigQuery", "table", "with", "the", "given", "schema", "." ]
ed9a44428251b0c6834aad231b463d8eda418471
https://github.com/spotify/scio/blob/ed9a44428251b0c6834aad231b463d8eda418471/scio-examples/src/main/java/org/apache/beam/examples/common/ExampleUtils.java#L153-L169
27,149
spotify/scio
scio-examples/src/main/java/org/apache/beam/examples/common/ExampleUtils.java
ExampleUtils.tearDown
private void tearDown() { pendingMessages.add("*************************Tear Down*************************"); ExamplePubsubTopicAndSubscriptionOptions pubsubOptions = options.as(ExamplePubsubTopicAndSubscriptionOptions.class); if (!pubsubOptions.getPubsubTopic().isEmpty()) { try { deletePubsubTopic(pubsubOptions.getPubsubTopic()); pendingMessages.add("The Pub/Sub topic has been deleted: " + pubsubOptions.getPubsubTopic()); } catch (IOException e) { pendingMessages.add("Failed to delete the Pub/Sub topic : " + pubsubOptions.getPubsubTopic()); } if (!pubsubOptions.getPubsubSubscription().isEmpty()) { try { deletePubsubSubscription(pubsubOptions.getPubsubSubscription()); pendingMessages.add("The Pub/Sub subscription has been deleted: " + pubsubOptions.getPubsubSubscription()); } catch (IOException e) { pendingMessages.add("Failed to delete the Pub/Sub subscription : " + pubsubOptions.getPubsubSubscription()); } } } ExampleBigQueryTableOptions bigQueryTableOptions = options.as(ExampleBigQueryTableOptions.class); if (bigQueryTableOptions.getBigQueryDataset() != null && bigQueryTableOptions.getBigQueryTable() != null && bigQueryTableOptions.getBigQuerySchema() != null) { pendingMessages.add("The BigQuery table might contain the example's output, " + "and it is not deleted automatically: " + bigQueryTableOptions.getProject() + ":" + bigQueryTableOptions.getBigQueryDataset() + "." + bigQueryTableOptions.getBigQueryTable()); pendingMessages.add("Please go to the Developers Console to delete it manually." + " Otherwise, you may be charged for its usage."); } }
java
private void tearDown() { pendingMessages.add("*************************Tear Down*************************"); ExamplePubsubTopicAndSubscriptionOptions pubsubOptions = options.as(ExamplePubsubTopicAndSubscriptionOptions.class); if (!pubsubOptions.getPubsubTopic().isEmpty()) { try { deletePubsubTopic(pubsubOptions.getPubsubTopic()); pendingMessages.add("The Pub/Sub topic has been deleted: " + pubsubOptions.getPubsubTopic()); } catch (IOException e) { pendingMessages.add("Failed to delete the Pub/Sub topic : " + pubsubOptions.getPubsubTopic()); } if (!pubsubOptions.getPubsubSubscription().isEmpty()) { try { deletePubsubSubscription(pubsubOptions.getPubsubSubscription()); pendingMessages.add("The Pub/Sub subscription has been deleted: " + pubsubOptions.getPubsubSubscription()); } catch (IOException e) { pendingMessages.add("Failed to delete the Pub/Sub subscription : " + pubsubOptions.getPubsubSubscription()); } } } ExampleBigQueryTableOptions bigQueryTableOptions = options.as(ExampleBigQueryTableOptions.class); if (bigQueryTableOptions.getBigQueryDataset() != null && bigQueryTableOptions.getBigQueryTable() != null && bigQueryTableOptions.getBigQuerySchema() != null) { pendingMessages.add("The BigQuery table might contain the example's output, " + "and it is not deleted automatically: " + bigQueryTableOptions.getProject() + ":" + bigQueryTableOptions.getBigQueryDataset() + "." + bigQueryTableOptions.getBigQueryTable()); pendingMessages.add("Please go to the Developers Console to delete it manually." + " Otherwise, you may be charged for its usage."); } }
[ "private", "void", "tearDown", "(", ")", "{", "pendingMessages", ".", "add", "(", "\"*************************Tear Down*************************\"", ")", ";", "ExamplePubsubTopicAndSubscriptionOptions", "pubsubOptions", "=", "options", ".", "as", "(", "ExamplePubsubTopicAndSubscriptionOptions", ".", "class", ")", ";", "if", "(", "!", "pubsubOptions", ".", "getPubsubTopic", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "try", "{", "deletePubsubTopic", "(", "pubsubOptions", ".", "getPubsubTopic", "(", ")", ")", ";", "pendingMessages", ".", "add", "(", "\"The Pub/Sub topic has been deleted: \"", "+", "pubsubOptions", ".", "getPubsubTopic", "(", ")", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "pendingMessages", ".", "add", "(", "\"Failed to delete the Pub/Sub topic : \"", "+", "pubsubOptions", ".", "getPubsubTopic", "(", ")", ")", ";", "}", "if", "(", "!", "pubsubOptions", ".", "getPubsubSubscription", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "try", "{", "deletePubsubSubscription", "(", "pubsubOptions", ".", "getPubsubSubscription", "(", ")", ")", ";", "pendingMessages", ".", "add", "(", "\"The Pub/Sub subscription has been deleted: \"", "+", "pubsubOptions", ".", "getPubsubSubscription", "(", ")", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "pendingMessages", ".", "add", "(", "\"Failed to delete the Pub/Sub subscription : \"", "+", "pubsubOptions", ".", "getPubsubSubscription", "(", ")", ")", ";", "}", "}", "}", "ExampleBigQueryTableOptions", "bigQueryTableOptions", "=", "options", ".", "as", "(", "ExampleBigQueryTableOptions", ".", "class", ")", ";", "if", "(", "bigQueryTableOptions", ".", "getBigQueryDataset", "(", ")", "!=", "null", "&&", "bigQueryTableOptions", ".", "getBigQueryTable", "(", ")", "!=", "null", "&&", "bigQueryTableOptions", ".", "getBigQuerySchema", "(", ")", "!=", "null", ")", "{", "pendingMessages", ".", "add", "(", "\"The BigQuery table might contain the example's output, \"", "+", "\"and it is not deleted automatically: \"", "+", "bigQueryTableOptions", ".", "getProject", "(", ")", "+", "\":\"", "+", "bigQueryTableOptions", ".", "getBigQueryDataset", "(", ")", "+", "\".\"", "+", "bigQueryTableOptions", ".", "getBigQueryTable", "(", ")", ")", ";", "pendingMessages", ".", "add", "(", "\"Please go to the Developers Console to delete it manually.\"", "+", "\" Otherwise, you may be charged for its usage.\"", ")", ";", "}", "}" ]
Tears down external resources that can be deleted upon the example's completion.
[ "Tears", "down", "external", "resources", "that", "can", "be", "deleted", "upon", "the", "example", "s", "completion", "." ]
ed9a44428251b0c6834aad231b463d8eda418471
https://github.com/spotify/scio/blob/ed9a44428251b0c6834aad231b463d8eda418471/scio-examples/src/main/java/org/apache/beam/examples/common/ExampleUtils.java#L174-L212
27,150
spotify/scio
scio-examples/src/main/java/org/apache/beam/examples/common/ExampleUtils.java
ExampleUtils.waitToFinish
public void waitToFinish(PipelineResult result) { pipelinesToCancel.add(result); if (!options.as(ExampleOptions.class).getKeepJobsRunning()) { addShutdownHook(pipelinesToCancel); } try { result.waitUntilFinish(); } catch (UnsupportedOperationException e) { // Do nothing if the given PipelineResult doesn't support waitUntilFinish(), // such as EvaluationResults returned by DirectRunner. tearDown(); printPendingMessages(); } catch (Exception e) { throw new RuntimeException("Failed to wait the pipeline until finish: " + result); } }
java
public void waitToFinish(PipelineResult result) { pipelinesToCancel.add(result); if (!options.as(ExampleOptions.class).getKeepJobsRunning()) { addShutdownHook(pipelinesToCancel); } try { result.waitUntilFinish(); } catch (UnsupportedOperationException e) { // Do nothing if the given PipelineResult doesn't support waitUntilFinish(), // such as EvaluationResults returned by DirectRunner. tearDown(); printPendingMessages(); } catch (Exception e) { throw new RuntimeException("Failed to wait the pipeline until finish: " + result); } }
[ "public", "void", "waitToFinish", "(", "PipelineResult", "result", ")", "{", "pipelinesToCancel", ".", "add", "(", "result", ")", ";", "if", "(", "!", "options", ".", "as", "(", "ExampleOptions", ".", "class", ")", ".", "getKeepJobsRunning", "(", ")", ")", "{", "addShutdownHook", "(", "pipelinesToCancel", ")", ";", "}", "try", "{", "result", ".", "waitUntilFinish", "(", ")", ";", "}", "catch", "(", "UnsupportedOperationException", "e", ")", "{", "// Do nothing if the given PipelineResult doesn't support waitUntilFinish(),", "// such as EvaluationResults returned by DirectRunner.", "tearDown", "(", ")", ";", "printPendingMessages", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "RuntimeException", "(", "\"Failed to wait the pipeline until finish: \"", "+", "result", ")", ";", "}", "}" ]
Waits for the pipeline to finish and cancels it before the program exists.
[ "Waits", "for", "the", "pipeline", "to", "finish", "and", "cancels", "it", "before", "the", "program", "exists", "." ]
ed9a44428251b0c6834aad231b463d8eda418471
https://github.com/spotify/scio/blob/ed9a44428251b0c6834aad231b463d8eda418471/scio-examples/src/main/java/org/apache/beam/examples/common/ExampleUtils.java#L331-L346
27,151
spotify/scio
scio-examples/src/main/java/org/apache/beam/examples/complete/StreamingWordExtract.java
StreamingWordExtract.main
public static void main(String[] args) throws IOException { StreamingWordExtractOptions options = PipelineOptionsFactory.fromArgs(args) .withValidation() .as(StreamingWordExtractOptions.class); options.setStreaming(true); options.setBigQuerySchema(StringToRowConverter.getSchema()); ExampleUtils exampleUtils = new ExampleUtils(options); exampleUtils.setup(); Pipeline pipeline = Pipeline.create(options); String tableSpec = new StringBuilder() .append(options.getProject()).append(":") .append(options.getBigQueryDataset()).append(".") .append(options.getBigQueryTable()) .toString(); pipeline .apply("ReadLines", TextIO.read().from(options.getInputFile())) .apply(ParDo.of(new ExtractWords())) .apply(ParDo.of(new Uppercase())) .apply(ParDo.of(new StringToRowConverter())) .apply(BigQueryIO.writeTableRows().to(tableSpec) .withSchema(StringToRowConverter.getSchema())); PipelineResult result = pipeline.run(); // ExampleUtils will try to cancel the pipeline before the program exists. exampleUtils.waitToFinish(result); }
java
public static void main(String[] args) throws IOException { StreamingWordExtractOptions options = PipelineOptionsFactory.fromArgs(args) .withValidation() .as(StreamingWordExtractOptions.class); options.setStreaming(true); options.setBigQuerySchema(StringToRowConverter.getSchema()); ExampleUtils exampleUtils = new ExampleUtils(options); exampleUtils.setup(); Pipeline pipeline = Pipeline.create(options); String tableSpec = new StringBuilder() .append(options.getProject()).append(":") .append(options.getBigQueryDataset()).append(".") .append(options.getBigQueryTable()) .toString(); pipeline .apply("ReadLines", TextIO.read().from(options.getInputFile())) .apply(ParDo.of(new ExtractWords())) .apply(ParDo.of(new Uppercase())) .apply(ParDo.of(new StringToRowConverter())) .apply(BigQueryIO.writeTableRows().to(tableSpec) .withSchema(StringToRowConverter.getSchema())); PipelineResult result = pipeline.run(); // ExampleUtils will try to cancel the pipeline before the program exists. exampleUtils.waitToFinish(result); }
[ "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "throws", "IOException", "{", "StreamingWordExtractOptions", "options", "=", "PipelineOptionsFactory", ".", "fromArgs", "(", "args", ")", ".", "withValidation", "(", ")", ".", "as", "(", "StreamingWordExtractOptions", ".", "class", ")", ";", "options", ".", "setStreaming", "(", "true", ")", ";", "options", ".", "setBigQuerySchema", "(", "StringToRowConverter", ".", "getSchema", "(", ")", ")", ";", "ExampleUtils", "exampleUtils", "=", "new", "ExampleUtils", "(", "options", ")", ";", "exampleUtils", ".", "setup", "(", ")", ";", "Pipeline", "pipeline", "=", "Pipeline", ".", "create", "(", "options", ")", ";", "String", "tableSpec", "=", "new", "StringBuilder", "(", ")", ".", "append", "(", "options", ".", "getProject", "(", ")", ")", ".", "append", "(", "\":\"", ")", ".", "append", "(", "options", ".", "getBigQueryDataset", "(", ")", ")", ".", "append", "(", "\".\"", ")", ".", "append", "(", "options", ".", "getBigQueryTable", "(", ")", ")", ".", "toString", "(", ")", ";", "pipeline", ".", "apply", "(", "\"ReadLines\"", ",", "TextIO", ".", "read", "(", ")", ".", "from", "(", "options", ".", "getInputFile", "(", ")", ")", ")", ".", "apply", "(", "ParDo", ".", "of", "(", "new", "ExtractWords", "(", ")", ")", ")", ".", "apply", "(", "ParDo", ".", "of", "(", "new", "Uppercase", "(", ")", ")", ")", ".", "apply", "(", "ParDo", ".", "of", "(", "new", "StringToRowConverter", "(", ")", ")", ")", ".", "apply", "(", "BigQueryIO", ".", "writeTableRows", "(", ")", ".", "to", "(", "tableSpec", ")", ".", "withSchema", "(", "StringToRowConverter", ".", "getSchema", "(", ")", ")", ")", ";", "PipelineResult", "result", "=", "pipeline", ".", "run", "(", ")", ";", "// ExampleUtils will try to cancel the pipeline before the program exists.", "exampleUtils", ".", "waitToFinish", "(", "result", ")", ";", "}" ]
Sets up and starts streaming pipeline. @throws IOException if there is a problem setting up resources
[ "Sets", "up", "and", "starts", "streaming", "pipeline", "." ]
ed9a44428251b0c6834aad231b463d8eda418471
https://github.com/spotify/scio/blob/ed9a44428251b0c6834aad231b463d8eda418471/scio-examples/src/main/java/org/apache/beam/examples/complete/StreamingWordExtract.java#L116-L145
27,152
spotify/scio
scio-examples/src/main/java/org/apache/beam/examples/subprocess/kernel/SubProcessIOFiles.java
SubProcessIOFiles.close
@Override public void close() throws IOException { if (Files.exists(outFile)) { Files.delete(outFile); } if (Files.exists(errFile)) { Files.delete(errFile); } if (Files.exists(resultFile)) { Files.delete(resultFile); } }
java
@Override public void close() throws IOException { if (Files.exists(outFile)) { Files.delete(outFile); } if (Files.exists(errFile)) { Files.delete(errFile); } if (Files.exists(resultFile)) { Files.delete(resultFile); } }
[ "@", "Override", "public", "void", "close", "(", ")", "throws", "IOException", "{", "if", "(", "Files", ".", "exists", "(", "outFile", ")", ")", "{", "Files", ".", "delete", "(", "outFile", ")", ";", "}", "if", "(", "Files", ".", "exists", "(", "errFile", ")", ")", "{", "Files", ".", "delete", "(", "errFile", ")", ";", "}", "if", "(", "Files", ".", "exists", "(", "resultFile", ")", ")", "{", "Files", ".", "delete", "(", "resultFile", ")", ";", "}", "}" ]
Clean up the files that have been created on the local worker file system. Without this expect both performance issues and eventual failure
[ "Clean", "up", "the", "files", "that", "have", "been", "created", "on", "the", "local", "worker", "file", "system", ".", "Without", "this", "expect", "both", "performance", "issues", "and", "eventual", "failure" ]
ed9a44428251b0c6834aad231b463d8eda418471
https://github.com/spotify/scio/blob/ed9a44428251b0c6834aad231b463d8eda418471/scio-examples/src/main/java/org/apache/beam/examples/subprocess/kernel/SubProcessIOFiles.java#L90-L104
27,153
spotify/scio
scio-examples/src/main/java/org/apache/beam/examples/subprocess/kernel/SubProcessIOFiles.java
SubProcessIOFiles.copyOutPutFilesToBucket
public void copyOutPutFilesToBucket(SubProcessConfiguration configuration, String params) { if (Files.exists(outFile) || Files.exists(errFile)) { try { outFileLocation = FileUtils.copyFileFromWorkerToGCS(configuration, outFile); } catch (Exception ex) { LOG.error("Error uploading log file to storage ", ex); } try { errFileLocation = FileUtils.copyFileFromWorkerToGCS(configuration, errFile); } catch (Exception ex) { LOG.error("Error uploading log file to storage ", ex); } LOG.info(String.format("Log Files for process: %s outFile was: %s errFile was: %s", params, outFileLocation, errFileLocation)); } else { LOG.error(String.format("There was no output file or err file for process %s", params)); } }
java
public void copyOutPutFilesToBucket(SubProcessConfiguration configuration, String params) { if (Files.exists(outFile) || Files.exists(errFile)) { try { outFileLocation = FileUtils.copyFileFromWorkerToGCS(configuration, outFile); } catch (Exception ex) { LOG.error("Error uploading log file to storage ", ex); } try { errFileLocation = FileUtils.copyFileFromWorkerToGCS(configuration, errFile); } catch (Exception ex) { LOG.error("Error uploading log file to storage ", ex); } LOG.info(String.format("Log Files for process: %s outFile was: %s errFile was: %s", params, outFileLocation, errFileLocation)); } else { LOG.error(String.format("There was no output file or err file for process %s", params)); } }
[ "public", "void", "copyOutPutFilesToBucket", "(", "SubProcessConfiguration", "configuration", ",", "String", "params", ")", "{", "if", "(", "Files", ".", "exists", "(", "outFile", ")", "||", "Files", ".", "exists", "(", "errFile", ")", ")", "{", "try", "{", "outFileLocation", "=", "FileUtils", ".", "copyFileFromWorkerToGCS", "(", "configuration", ",", "outFile", ")", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "LOG", ".", "error", "(", "\"Error uploading log file to storage \"", ",", "ex", ")", ";", "}", "try", "{", "errFileLocation", "=", "FileUtils", ".", "copyFileFromWorkerToGCS", "(", "configuration", ",", "errFile", ")", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "LOG", ".", "error", "(", "\"Error uploading log file to storage \"", ",", "ex", ")", ";", "}", "LOG", ".", "info", "(", "String", ".", "format", "(", "\"Log Files for process: %s outFile was: %s errFile was: %s\"", ",", "params", ",", "outFileLocation", ",", "errFileLocation", ")", ")", ";", "}", "else", "{", "LOG", ".", "error", "(", "String", ".", "format", "(", "\"There was no output file or err file for process %s\"", ",", "params", ")", ")", ";", "}", "}" ]
Will copy the output files to the GCS path setup via the configuration. @param configuration @param params
[ "Will", "copy", "the", "output", "files", "to", "the", "GCS", "path", "setup", "via", "the", "configuration", "." ]
ed9a44428251b0c6834aad231b463d8eda418471
https://github.com/spotify/scio/blob/ed9a44428251b0c6834aad231b463d8eda418471/scio-examples/src/main/java/org/apache/beam/examples/subprocess/kernel/SubProcessIOFiles.java#L111-L130
27,154
spotify/scio
scio-examples/src/main/java/org/apache/beam/examples/complete/game/utils/WriteToBigQuery.java
WriteToBigQuery.getSchema
protected TableSchema getSchema() { List<TableFieldSchema> fields = new ArrayList<>(); for (Map.Entry<String, FieldInfo<InputT>> entry : fieldInfo.entrySet()) { String key = entry.getKey(); FieldInfo<InputT> fcnInfo = entry.getValue(); String bqType = fcnInfo.getFieldType(); fields.add(new TableFieldSchema().setName(key).setType(bqType)); } return new TableSchema().setFields(fields); }
java
protected TableSchema getSchema() { List<TableFieldSchema> fields = new ArrayList<>(); for (Map.Entry<String, FieldInfo<InputT>> entry : fieldInfo.entrySet()) { String key = entry.getKey(); FieldInfo<InputT> fcnInfo = entry.getValue(); String bqType = fcnInfo.getFieldType(); fields.add(new TableFieldSchema().setName(key).setType(bqType)); } return new TableSchema().setFields(fields); }
[ "protected", "TableSchema", "getSchema", "(", ")", "{", "List", "<", "TableFieldSchema", ">", "fields", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "Map", ".", "Entry", "<", "String", ",", "FieldInfo", "<", "InputT", ">", ">", "entry", ":", "fieldInfo", ".", "entrySet", "(", ")", ")", "{", "String", "key", "=", "entry", ".", "getKey", "(", ")", ";", "FieldInfo", "<", "InputT", ">", "fcnInfo", "=", "entry", ".", "getValue", "(", ")", ";", "String", "bqType", "=", "fcnInfo", ".", "getFieldType", "(", ")", ";", "fields", ".", "add", "(", "new", "TableFieldSchema", "(", ")", ".", "setName", "(", "key", ")", ".", "setType", "(", "bqType", ")", ")", ";", "}", "return", "new", "TableSchema", "(", ")", ".", "setFields", "(", "fields", ")", ";", "}" ]
Build the output table schema.
[ "Build", "the", "output", "table", "schema", "." ]
ed9a44428251b0c6834aad231b463d8eda418471
https://github.com/spotify/scio/blob/ed9a44428251b0c6834aad231b463d8eda418471/scio-examples/src/main/java/org/apache/beam/examples/complete/game/utils/WriteToBigQuery.java#L113-L122
27,155
spotify/scio
scio-examples/src/main/java/org/apache/beam/examples/complete/game/utils/WriteToBigQuery.java
WriteToBigQuery.getTable
static TableReference getTable(String projectId, String datasetId, String tableName) { TableReference table = new TableReference(); table.setDatasetId(datasetId); table.setProjectId(projectId); table.setTableId(tableName); return table; }
java
static TableReference getTable(String projectId, String datasetId, String tableName) { TableReference table = new TableReference(); table.setDatasetId(datasetId); table.setProjectId(projectId); table.setTableId(tableName); return table; }
[ "static", "TableReference", "getTable", "(", "String", "projectId", ",", "String", "datasetId", ",", "String", "tableName", ")", "{", "TableReference", "table", "=", "new", "TableReference", "(", ")", ";", "table", ".", "setDatasetId", "(", "datasetId", ")", ";", "table", ".", "setProjectId", "(", "projectId", ")", ";", "table", ".", "setTableId", "(", "tableName", ")", ";", "return", "table", ";", "}" ]
Utility to construct an output table reference.
[ "Utility", "to", "construct", "an", "output", "table", "reference", "." ]
ed9a44428251b0c6834aad231b463d8eda418471
https://github.com/spotify/scio/blob/ed9a44428251b0c6834aad231b463d8eda418471/scio-examples/src/main/java/org/apache/beam/examples/complete/game/utils/WriteToBigQuery.java#L138-L144
27,156
spotify/scio
scio-core/src/main/java/com/spotify/scio/transforms/AsyncLookupDoFn.java
AsyncLookupDoFn.flush
private void flush(Consumer<Result> outputFn) { Result r = results.poll(); while (r != null) { outputFn.accept(r); resultCount++; r = results.poll(); } }
java
private void flush(Consumer<Result> outputFn) { Result r = results.poll(); while (r != null) { outputFn.accept(r); resultCount++; r = results.poll(); } }
[ "private", "void", "flush", "(", "Consumer", "<", "Result", ">", "outputFn", ")", "{", "Result", "r", "=", "results", ".", "poll", "(", ")", ";", "while", "(", "r", "!=", "null", ")", "{", "outputFn", ".", "accept", "(", "r", ")", ";", "resultCount", "++", ";", "r", "=", "results", ".", "poll", "(", ")", ";", "}", "}" ]
Flush pending errors and results
[ "Flush", "pending", "errors", "and", "results" ]
ed9a44428251b0c6834aad231b463d8eda418471
https://github.com/spotify/scio/blob/ed9a44428251b0c6834aad231b463d8eda418471/scio-core/src/main/java/com/spotify/scio/transforms/AsyncLookupDoFn.java#L193-L200
27,157
spotify/scio
scio-bigquery/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/PatchedBigQueryTableRowIterator.java
PatchedBigQueryTableRowIterator.open
public void open() throws IOException, InterruptedException { if (queryConfig != null) { ref = executeQueryAndWaitForCompletion(); } // Get table schema. schema = getTable(ref).getSchema(); }
java
public void open() throws IOException, InterruptedException { if (queryConfig != null) { ref = executeQueryAndWaitForCompletion(); } // Get table schema. schema = getTable(ref).getSchema(); }
[ "public", "void", "open", "(", ")", "throws", "IOException", ",", "InterruptedException", "{", "if", "(", "queryConfig", "!=", "null", ")", "{", "ref", "=", "executeQueryAndWaitForCompletion", "(", ")", ";", "}", "// Get table schema.", "schema", "=", "getTable", "(", "ref", ")", ".", "getSchema", "(", ")", ";", "}" ]
Opens the table for read. @throws IOException on failure
[ "Opens", "the", "table", "for", "read", "." ]
ed9a44428251b0c6834aad231b463d8eda418471
https://github.com/spotify/scio/blob/ed9a44428251b0c6834aad231b463d8eda418471/scio-bigquery/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/PatchedBigQueryTableRowIterator.java#L138-L144
27,158
spotify/scio
scio-bigquery/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/PatchedBigQueryTableRowIterator.java
PatchedBigQueryTableRowIterator.getTypedCellValue
@Nullable private Object getTypedCellValue(TableFieldSchema fieldSchema, Object v) { if (Data.isNull(v)) { return null; } if (Objects.equals(fieldSchema.getMode(), "REPEATED")) { TableFieldSchema elementSchema = fieldSchema.clone().setMode("REQUIRED"); @SuppressWarnings("unchecked") List<Map<String, Object>> rawCells = (List<Map<String, Object>>) v; ImmutableList.Builder<Object> values = ImmutableList.builder(); for (Map<String, Object> element : rawCells) { values.add(getTypedCellValue(elementSchema, element.get("v"))); } return values.build(); } if (fieldSchema.getType().equals("RECORD")) { @SuppressWarnings("unchecked") Map<String, Object> typedV = (Map<String, Object>) v; return getTypedTableRow(fieldSchema.getFields(), typedV); } if (fieldSchema.getType().equals("FLOAT")) { return Double.parseDouble((String) v); } if (fieldSchema.getType().equals("BOOLEAN")) { return Boolean.parseBoolean((String) v); } if (fieldSchema.getType().equals("TIMESTAMP")) { return formatTimestamp((String) v); } // Returns the original value for: // 1. String, 2. base64 encoded BYTES, 3. DATE, DATETIME, TIME strings. return v; }
java
@Nullable private Object getTypedCellValue(TableFieldSchema fieldSchema, Object v) { if (Data.isNull(v)) { return null; } if (Objects.equals(fieldSchema.getMode(), "REPEATED")) { TableFieldSchema elementSchema = fieldSchema.clone().setMode("REQUIRED"); @SuppressWarnings("unchecked") List<Map<String, Object>> rawCells = (List<Map<String, Object>>) v; ImmutableList.Builder<Object> values = ImmutableList.builder(); for (Map<String, Object> element : rawCells) { values.add(getTypedCellValue(elementSchema, element.get("v"))); } return values.build(); } if (fieldSchema.getType().equals("RECORD")) { @SuppressWarnings("unchecked") Map<String, Object> typedV = (Map<String, Object>) v; return getTypedTableRow(fieldSchema.getFields(), typedV); } if (fieldSchema.getType().equals("FLOAT")) { return Double.parseDouble((String) v); } if (fieldSchema.getType().equals("BOOLEAN")) { return Boolean.parseBoolean((String) v); } if (fieldSchema.getType().equals("TIMESTAMP")) { return formatTimestamp((String) v); } // Returns the original value for: // 1. String, 2. base64 encoded BYTES, 3. DATE, DATETIME, TIME strings. return v; }
[ "@", "Nullable", "private", "Object", "getTypedCellValue", "(", "TableFieldSchema", "fieldSchema", ",", "Object", "v", ")", "{", "if", "(", "Data", ".", "isNull", "(", "v", ")", ")", "{", "return", "null", ";", "}", "if", "(", "Objects", ".", "equals", "(", "fieldSchema", ".", "getMode", "(", ")", ",", "\"REPEATED\"", ")", ")", "{", "TableFieldSchema", "elementSchema", "=", "fieldSchema", ".", "clone", "(", ")", ".", "setMode", "(", "\"REQUIRED\"", ")", ";", "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "List", "<", "Map", "<", "String", ",", "Object", ">", ">", "rawCells", "=", "(", "List", "<", "Map", "<", "String", ",", "Object", ">", ">", ")", "v", ";", "ImmutableList", ".", "Builder", "<", "Object", ">", "values", "=", "ImmutableList", ".", "builder", "(", ")", ";", "for", "(", "Map", "<", "String", ",", "Object", ">", "element", ":", "rawCells", ")", "{", "values", ".", "add", "(", "getTypedCellValue", "(", "elementSchema", ",", "element", ".", "get", "(", "\"v\"", ")", ")", ")", ";", "}", "return", "values", ".", "build", "(", ")", ";", "}", "if", "(", "fieldSchema", ".", "getType", "(", ")", ".", "equals", "(", "\"RECORD\"", ")", ")", "{", "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "Map", "<", "String", ",", "Object", ">", "typedV", "=", "(", "Map", "<", "String", ",", "Object", ">", ")", "v", ";", "return", "getTypedTableRow", "(", "fieldSchema", ".", "getFields", "(", ")", ",", "typedV", ")", ";", "}", "if", "(", "fieldSchema", ".", "getType", "(", ")", ".", "equals", "(", "\"FLOAT\"", ")", ")", "{", "return", "Double", ".", "parseDouble", "(", "(", "String", ")", "v", ")", ";", "}", "if", "(", "fieldSchema", ".", "getType", "(", ")", ".", "equals", "(", "\"BOOLEAN\"", ")", ")", "{", "return", "Boolean", ".", "parseBoolean", "(", "(", "String", ")", "v", ")", ";", "}", "if", "(", "fieldSchema", ".", "getType", "(", ")", ".", "equals", "(", "\"TIMESTAMP\"", ")", ")", "{", "return", "formatTimestamp", "(", "(", "String", ")", "v", ")", ";", "}", "// Returns the original value for:", "// 1. String, 2. base64 encoded BYTES, 3. DATE, DATETIME, TIME strings.", "return", "v", ";", "}" ]
Adjusts a field returned from the BigQuery API to match what we will receive when running BigQuery's export-to-GCS and parallel read, which is the efficient parallel implementation used for batch jobs executed on the Beam Runners that perform initial splitting. <p>The following is the relationship between BigQuery schema and Java types: <ul> <li>Nulls are {@code null}. <li>Repeated fields are {@code List} of objects. <li>Record columns are {@link TableRow} objects. <li>{@code BOOLEAN} columns are JSON booleans, hence Java {@code Boolean} objects. <li>{@code FLOAT} columns are JSON floats, hence Java {@code Double} objects. <li>{@code TIMESTAMP} columns are {@code String} objects that are of the format {@code yyyy-MM-dd HH:mm:ss[.SSSSSS] UTC}, where the {@code .SSSSSS} has no trailing zeros and can be 1 to 6 digits long. <li>Every other atomic type is a {@code String}. </ul> <p>Note that integers are encoded as strings to match BigQuery's exported JSON format. <p>Finally, values are stored in the {@link TableRow} as {"field name": value} pairs and are not accessible through the {@link TableRow#getF} function.
[ "Adjusts", "a", "field", "returned", "from", "the", "BigQuery", "API", "to", "match", "what", "we", "will", "receive", "when", "running", "BigQuery", "s", "export", "-", "to", "-", "GCS", "and", "parallel", "read", "which", "is", "the", "efficient", "parallel", "implementation", "used", "for", "batch", "jobs", "executed", "on", "the", "Beam", "Runners", "that", "perform", "initial", "splitting", "." ]
ed9a44428251b0c6834aad231b463d8eda418471
https://github.com/spotify/scio/blob/ed9a44428251b0c6834aad231b463d8eda418471/scio-bigquery/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/PatchedBigQueryTableRowIterator.java#L214-L251
27,159
spotify/scio
scio-bigquery/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/PatchedBigQueryTableRowIterator.java
PatchedBigQueryTableRowIterator.getTable
private Table getTable(TableReference ref) throws IOException, InterruptedException { Bigquery.Tables.Get get = client.tables().get(ref.getProjectId(), ref.getDatasetId(), ref.getTableId()); return executeWithBackOff( get, String.format( "Error opening BigQuery table %s of dataset %s.", ref.getTableId(), ref.getDatasetId())); }
java
private Table getTable(TableReference ref) throws IOException, InterruptedException { Bigquery.Tables.Get get = client.tables().get(ref.getProjectId(), ref.getDatasetId(), ref.getTableId()); return executeWithBackOff( get, String.format( "Error opening BigQuery table %s of dataset %s.", ref.getTableId(), ref.getDatasetId())); }
[ "private", "Table", "getTable", "(", "TableReference", "ref", ")", "throws", "IOException", ",", "InterruptedException", "{", "Bigquery", ".", "Tables", ".", "Get", "get", "=", "client", ".", "tables", "(", ")", ".", "get", "(", "ref", ".", "getProjectId", "(", ")", ",", "ref", ".", "getDatasetId", "(", ")", ",", "ref", ".", "getTableId", "(", ")", ")", ";", "return", "executeWithBackOff", "(", "get", ",", "String", ".", "format", "(", "\"Error opening BigQuery table %s of dataset %s.\"", ",", "ref", ".", "getTableId", "(", ")", ",", "ref", ".", "getDatasetId", "(", ")", ")", ")", ";", "}" ]
Get the BiqQuery table.
[ "Get", "the", "BiqQuery", "table", "." ]
ed9a44428251b0c6834aad231b463d8eda418471
https://github.com/spotify/scio/blob/ed9a44428251b0c6834aad231b463d8eda418471/scio-bigquery/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/PatchedBigQueryTableRowIterator.java#L328-L338
27,160
spotify/scio
scio-bigquery/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/PatchedBigQueryTableRowIterator.java
PatchedBigQueryTableRowIterator.deleteTable
private void deleteTable(String datasetId, String tableId) throws IOException, InterruptedException { executeWithBackOff( client.tables().delete(projectId, datasetId, tableId), String.format( "Error when trying to delete the temporary table %s in dataset %s of project %s. " + "Manual deletion may be required.", tableId, datasetId, projectId)); }
java
private void deleteTable(String datasetId, String tableId) throws IOException, InterruptedException { executeWithBackOff( client.tables().delete(projectId, datasetId, tableId), String.format( "Error when trying to delete the temporary table %s in dataset %s of project %s. " + "Manual deletion may be required.", tableId, datasetId, projectId)); }
[ "private", "void", "deleteTable", "(", "String", "datasetId", ",", "String", "tableId", ")", "throws", "IOException", ",", "InterruptedException", "{", "executeWithBackOff", "(", "client", ".", "tables", "(", ")", ".", "delete", "(", "projectId", ",", "datasetId", ",", "tableId", ")", ",", "String", ".", "format", "(", "\"Error when trying to delete the temporary table %s in dataset %s of project %s. \"", "+", "\"Manual deletion may be required.\"", ",", "tableId", ",", "datasetId", ",", "projectId", ")", ")", ";", "}" ]
Delete the given table that is available in the given dataset.
[ "Delete", "the", "given", "table", "that", "is", "available", "in", "the", "given", "dataset", "." ]
ed9a44428251b0c6834aad231b463d8eda418471
https://github.com/spotify/scio/blob/ed9a44428251b0c6834aad231b463d8eda418471/scio-bigquery/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/PatchedBigQueryTableRowIterator.java#L360-L368
27,161
spotify/scio
scio-bigquery/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/PatchedBigQueryTableRowIterator.java
PatchedBigQueryTableRowIterator.deleteDataset
private void deleteDataset(String datasetId) throws IOException, InterruptedException { executeWithBackOff( client.datasets().delete(projectId, datasetId), String.format( "Error when trying to delete the temporary dataset %s in project %s. " + "Manual deletion may be required.", datasetId, projectId)); }
java
private void deleteDataset(String datasetId) throws IOException, InterruptedException { executeWithBackOff( client.datasets().delete(projectId, datasetId), String.format( "Error when trying to delete the temporary dataset %s in project %s. " + "Manual deletion may be required.", datasetId, projectId)); }
[ "private", "void", "deleteDataset", "(", "String", "datasetId", ")", "throws", "IOException", ",", "InterruptedException", "{", "executeWithBackOff", "(", "client", ".", "datasets", "(", ")", ".", "delete", "(", "projectId", ",", "datasetId", ")", ",", "String", ".", "format", "(", "\"Error when trying to delete the temporary dataset %s in project %s. \"", "+", "\"Manual deletion may be required.\"", ",", "datasetId", ",", "projectId", ")", ")", ";", "}" ]
Delete the given dataset. This will fail if the given dataset has any tables.
[ "Delete", "the", "given", "dataset", ".", "This", "will", "fail", "if", "the", "given", "dataset", "has", "any", "tables", "." ]
ed9a44428251b0c6834aad231b463d8eda418471
https://github.com/spotify/scio/blob/ed9a44428251b0c6834aad231b463d8eda418471/scio-bigquery/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/PatchedBigQueryTableRowIterator.java#L371-L378
27,162
spotify/scio
scio-bigquery/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/PatchedBigQueryTableRowIterator.java
PatchedBigQueryTableRowIterator.executeWithBackOff
public static <T> T executeWithBackOff(AbstractGoogleClientRequest<T> client, String error) throws IOException, InterruptedException { Sleeper sleeper = Sleeper.DEFAULT; BackOff backOff = BackOffAdapter.toGcpBackOff( FluentBackoff.DEFAULT .withMaxRetries(MAX_RETRIES).withInitialBackoff(INITIAL_BACKOFF_TIME).backoff()); T result = null; while (true) { try { result = client.execute(); break; } catch (IOException e) { LOG.error("{}", error, e); if (!BackOffUtils.next(sleeper, backOff)) { String errorMessage = String.format( "%s Failing to execute job after %d attempts.", error, MAX_RETRIES + 1); LOG.error("{}", errorMessage, e); throw new IOException(errorMessage, e); } } } return result; }
java
public static <T> T executeWithBackOff(AbstractGoogleClientRequest<T> client, String error) throws IOException, InterruptedException { Sleeper sleeper = Sleeper.DEFAULT; BackOff backOff = BackOffAdapter.toGcpBackOff( FluentBackoff.DEFAULT .withMaxRetries(MAX_RETRIES).withInitialBackoff(INITIAL_BACKOFF_TIME).backoff()); T result = null; while (true) { try { result = client.execute(); break; } catch (IOException e) { LOG.error("{}", error, e); if (!BackOffUtils.next(sleeper, backOff)) { String errorMessage = String.format( "%s Failing to execute job after %d attempts.", error, MAX_RETRIES + 1); LOG.error("{}", errorMessage, e); throw new IOException(errorMessage, e); } } } return result; }
[ "public", "static", "<", "T", ">", "T", "executeWithBackOff", "(", "AbstractGoogleClientRequest", "<", "T", ">", "client", ",", "String", "error", ")", "throws", "IOException", ",", "InterruptedException", "{", "Sleeper", "sleeper", "=", "Sleeper", ".", "DEFAULT", ";", "BackOff", "backOff", "=", "BackOffAdapter", ".", "toGcpBackOff", "(", "FluentBackoff", ".", "DEFAULT", ".", "withMaxRetries", "(", "MAX_RETRIES", ")", ".", "withInitialBackoff", "(", "INITIAL_BACKOFF_TIME", ")", ".", "backoff", "(", ")", ")", ";", "T", "result", "=", "null", ";", "while", "(", "true", ")", "{", "try", "{", "result", "=", "client", ".", "execute", "(", ")", ";", "break", ";", "}", "catch", "(", "IOException", "e", ")", "{", "LOG", ".", "error", "(", "\"{}\"", ",", "error", ",", "e", ")", ";", "if", "(", "!", "BackOffUtils", ".", "next", "(", "sleeper", ",", "backOff", ")", ")", "{", "String", "errorMessage", "=", "String", ".", "format", "(", "\"%s Failing to execute job after %d attempts.\"", ",", "error", ",", "MAX_RETRIES", "+", "1", ")", ";", "LOG", ".", "error", "(", "\"{}\"", ",", "errorMessage", ",", "e", ")", ";", "throw", "new", "IOException", "(", "errorMessage", ",", "e", ")", ";", "}", "}", "}", "return", "result", ";", "}" ]
formatter parameter.
[ "formatter", "parameter", "." ]
ed9a44428251b0c6834aad231b463d8eda418471
https://github.com/spotify/scio/blob/ed9a44428251b0c6834aad231b463d8eda418471/scio-bigquery/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/PatchedBigQueryTableRowIterator.java#L460-L484
27,163
spotify/scio
scio-examples/src/main/java/org/apache/beam/examples/complete/game/injector/Injector.java
Injector.randomElement
private static String randomElement(ArrayList<String> list) { int index = random.nextInt(list.size()); return list.get(index); }
java
private static String randomElement(ArrayList<String> list) { int index = random.nextInt(list.size()); return list.get(index); }
[ "private", "static", "String", "randomElement", "(", "ArrayList", "<", "String", ">", "list", ")", "{", "int", "index", "=", "random", ".", "nextInt", "(", "list", ".", "size", "(", ")", ")", ";", "return", "list", ".", "get", "(", "index", ")", ";", "}" ]
Utility to grab a random element from an array of Strings.
[ "Utility", "to", "grab", "a", "random", "element", "from", "an", "array", "of", "Strings", "." ]
ed9a44428251b0c6834aad231b463d8eda418471
https://github.com/spotify/scio/blob/ed9a44428251b0c6834aad231b463d8eda418471/scio-examples/src/main/java/org/apache/beam/examples/complete/game/injector/Injector.java#L217-L220
27,164
spotify/scio
scio-examples/src/main/java/org/apache/beam/examples/complete/game/injector/Injector.java
Injector.randomTeam
private static TeamInfo randomTeam(ArrayList<TeamInfo> list) { int index = random.nextInt(list.size()); TeamInfo team = list.get(index); // If the selected team is expired, remove it and return a new team. long currTime = System.currentTimeMillis(); if ((team.getEndTimeInMillis() < currTime) || team.numMembers() == 0) { System.out.println("\nteam " + team + " is too old; replacing."); System.out.println("start time: " + team.getStartTimeInMillis() + ", end time: " + team.getEndTimeInMillis() + ", current time:" + currTime); removeTeam(index); // Add a new team in its stead. return (addLiveTeam()); } else { return team; } }
java
private static TeamInfo randomTeam(ArrayList<TeamInfo> list) { int index = random.nextInt(list.size()); TeamInfo team = list.get(index); // If the selected team is expired, remove it and return a new team. long currTime = System.currentTimeMillis(); if ((team.getEndTimeInMillis() < currTime) || team.numMembers() == 0) { System.out.println("\nteam " + team + " is too old; replacing."); System.out.println("start time: " + team.getStartTimeInMillis() + ", end time: " + team.getEndTimeInMillis() + ", current time:" + currTime); removeTeam(index); // Add a new team in its stead. return (addLiveTeam()); } else { return team; } }
[ "private", "static", "TeamInfo", "randomTeam", "(", "ArrayList", "<", "TeamInfo", ">", "list", ")", "{", "int", "index", "=", "random", ".", "nextInt", "(", "list", ".", "size", "(", ")", ")", ";", "TeamInfo", "team", "=", "list", ".", "get", "(", "index", ")", ";", "// If the selected team is expired, remove it and return a new team.", "long", "currTime", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "if", "(", "(", "team", ".", "getEndTimeInMillis", "(", ")", "<", "currTime", ")", "||", "team", ".", "numMembers", "(", ")", "==", "0", ")", "{", "System", ".", "out", ".", "println", "(", "\"\\nteam \"", "+", "team", "+", "\" is too old; replacing.\"", ")", ";", "System", ".", "out", ".", "println", "(", "\"start time: \"", "+", "team", ".", "getStartTimeInMillis", "(", ")", "+", "\", end time: \"", "+", "team", ".", "getEndTimeInMillis", "(", ")", "+", "\", current time:\"", "+", "currTime", ")", ";", "removeTeam", "(", "index", ")", ";", "// Add a new team in its stead.", "return", "(", "addLiveTeam", "(", ")", ")", ";", "}", "else", "{", "return", "team", ";", "}", "}" ]
Get and return a random team. If the selected team is too old w.r.t its expiration, remove it, replacing it with a new team.
[ "Get", "and", "return", "a", "random", "team", ".", "If", "the", "selected", "team", "is", "too", "old", "w", ".", "r", ".", "t", "its", "expiration", "remove", "it", "replacing", "it", "with", "a", "new", "team", "." ]
ed9a44428251b0c6834aad231b463d8eda418471
https://github.com/spotify/scio/blob/ed9a44428251b0c6834aad231b463d8eda418471/scio-examples/src/main/java/org/apache/beam/examples/complete/game/injector/Injector.java#L226-L242
27,165
spotify/scio
scio-examples/src/main/java/org/apache/beam/examples/complete/game/injector/Injector.java
Injector.addLiveTeam
private static synchronized TeamInfo addLiveTeam() { String teamName = randomElement(COLORS) + randomElement(ANIMALS); String robot = null; // Decide if we want to add a robot to the team. if (random.nextInt(ROBOT_PROBABILITY) == 0) { robot = "Robot-" + random.nextInt(NUM_ROBOTS); } // Create the new team. TeamInfo newTeam = new TeamInfo(teamName, System.currentTimeMillis(), robot); liveTeams.add(newTeam); System.out.println("[+" + newTeam + "]"); return newTeam; }
java
private static synchronized TeamInfo addLiveTeam() { String teamName = randomElement(COLORS) + randomElement(ANIMALS); String robot = null; // Decide if we want to add a robot to the team. if (random.nextInt(ROBOT_PROBABILITY) == 0) { robot = "Robot-" + random.nextInt(NUM_ROBOTS); } // Create the new team. TeamInfo newTeam = new TeamInfo(teamName, System.currentTimeMillis(), robot); liveTeams.add(newTeam); System.out.println("[+" + newTeam + "]"); return newTeam; }
[ "private", "static", "synchronized", "TeamInfo", "addLiveTeam", "(", ")", "{", "String", "teamName", "=", "randomElement", "(", "COLORS", ")", "+", "randomElement", "(", "ANIMALS", ")", ";", "String", "robot", "=", "null", ";", "// Decide if we want to add a robot to the team.", "if", "(", "random", ".", "nextInt", "(", "ROBOT_PROBABILITY", ")", "==", "0", ")", "{", "robot", "=", "\"Robot-\"", "+", "random", ".", "nextInt", "(", "NUM_ROBOTS", ")", ";", "}", "// Create the new team.", "TeamInfo", "newTeam", "=", "new", "TeamInfo", "(", "teamName", ",", "System", ".", "currentTimeMillis", "(", ")", ",", "robot", ")", ";", "liveTeams", ".", "add", "(", "newTeam", ")", ";", "System", ".", "out", ".", "println", "(", "\"[+\"", "+", "newTeam", "+", "\"]\"", ")", ";", "return", "newTeam", ";", "}" ]
Create and add a team. Possibly add a robot to the team.
[ "Create", "and", "add", "a", "team", ".", "Possibly", "add", "a", "robot", "to", "the", "team", "." ]
ed9a44428251b0c6834aad231b463d8eda418471
https://github.com/spotify/scio/blob/ed9a44428251b0c6834aad231b463d8eda418471/scio-examples/src/main/java/org/apache/beam/examples/complete/game/injector/Injector.java#L247-L259
27,166
spotify/scio
scio-examples/src/main/java/org/apache/beam/examples/complete/game/injector/Injector.java
Injector.removeTeam
private static synchronized void removeTeam(int teamIndex) { TeamInfo removedTeam = liveTeams.remove(teamIndex); System.out.println("[-" + removedTeam + "]"); }
java
private static synchronized void removeTeam(int teamIndex) { TeamInfo removedTeam = liveTeams.remove(teamIndex); System.out.println("[-" + removedTeam + "]"); }
[ "private", "static", "synchronized", "void", "removeTeam", "(", "int", "teamIndex", ")", "{", "TeamInfo", "removedTeam", "=", "liveTeams", ".", "remove", "(", "teamIndex", ")", ";", "System", ".", "out", ".", "println", "(", "\"[-\"", "+", "removedTeam", "+", "\"]\"", ")", ";", "}" ]
Remove a specific team.
[ "Remove", "a", "specific", "team", "." ]
ed9a44428251b0c6834aad231b463d8eda418471
https://github.com/spotify/scio/blob/ed9a44428251b0c6834aad231b463d8eda418471/scio-examples/src/main/java/org/apache/beam/examples/complete/game/injector/Injector.java#L264-L267
27,167
spotify/scio
scio-examples/src/main/java/org/apache/beam/examples/complete/game/injector/Injector.java
Injector.generateEvent
private static String generateEvent(Long currTime, int delayInMillis) { TeamInfo team = randomTeam(liveTeams); String teamName = team.getTeamName(); String user; final int parseErrorRate = 900000; String robot = team.getRobot(); // If the team has an associated robot team member... if (robot != null) { // Then use that robot for the message with some probability. // Set this probability to higher than that used to select any of the 'regular' team // members, so that if there is a robot on the team, it has a higher click rate. if (random.nextInt(team.numMembers() / 2) == 0) { user = robot; } else { user = team.getRandomUser(); } } else { // No robot. user = team.getRandomUser(); } String event = user + "," + teamName + "," + random.nextInt(MAX_SCORE); // Randomly introduce occasional parse errors. if (random.nextInt(parseErrorRate) == 0) { System.out.println("Introducing a parse error."); event = "THIS LINE REPRESENTS CORRUPT DATA AND WILL CAUSE A PARSE ERROR"; } return addTimeInfoToEvent(event, currTime, delayInMillis); }
java
private static String generateEvent(Long currTime, int delayInMillis) { TeamInfo team = randomTeam(liveTeams); String teamName = team.getTeamName(); String user; final int parseErrorRate = 900000; String robot = team.getRobot(); // If the team has an associated robot team member... if (robot != null) { // Then use that robot for the message with some probability. // Set this probability to higher than that used to select any of the 'regular' team // members, so that if there is a robot on the team, it has a higher click rate. if (random.nextInt(team.numMembers() / 2) == 0) { user = robot; } else { user = team.getRandomUser(); } } else { // No robot. user = team.getRandomUser(); } String event = user + "," + teamName + "," + random.nextInt(MAX_SCORE); // Randomly introduce occasional parse errors. if (random.nextInt(parseErrorRate) == 0) { System.out.println("Introducing a parse error."); event = "THIS LINE REPRESENTS CORRUPT DATA AND WILL CAUSE A PARSE ERROR"; } return addTimeInfoToEvent(event, currTime, delayInMillis); }
[ "private", "static", "String", "generateEvent", "(", "Long", "currTime", ",", "int", "delayInMillis", ")", "{", "TeamInfo", "team", "=", "randomTeam", "(", "liveTeams", ")", ";", "String", "teamName", "=", "team", ".", "getTeamName", "(", ")", ";", "String", "user", ";", "final", "int", "parseErrorRate", "=", "900000", ";", "String", "robot", "=", "team", ".", "getRobot", "(", ")", ";", "// If the team has an associated robot team member...", "if", "(", "robot", "!=", "null", ")", "{", "// Then use that robot for the message with some probability.", "// Set this probability to higher than that used to select any of the 'regular' team", "// members, so that if there is a robot on the team, it has a higher click rate.", "if", "(", "random", ".", "nextInt", "(", "team", ".", "numMembers", "(", ")", "/", "2", ")", "==", "0", ")", "{", "user", "=", "robot", ";", "}", "else", "{", "user", "=", "team", ".", "getRandomUser", "(", ")", ";", "}", "}", "else", "{", "// No robot.", "user", "=", "team", ".", "getRandomUser", "(", ")", ";", "}", "String", "event", "=", "user", "+", "\",\"", "+", "teamName", "+", "\",\"", "+", "random", ".", "nextInt", "(", "MAX_SCORE", ")", ";", "// Randomly introduce occasional parse errors.", "if", "(", "random", ".", "nextInt", "(", "parseErrorRate", ")", "==", "0", ")", "{", "System", ".", "out", ".", "println", "(", "\"Introducing a parse error.\"", ")", ";", "event", "=", "\"THIS LINE REPRESENTS CORRUPT DATA AND WILL CAUSE A PARSE ERROR\"", ";", "}", "return", "addTimeInfoToEvent", "(", "event", ",", "currTime", ",", "delayInMillis", ")", ";", "}" ]
Generate a user gaming event.
[ "Generate", "a", "user", "gaming", "event", "." ]
ed9a44428251b0c6834aad231b463d8eda418471
https://github.com/spotify/scio/blob/ed9a44428251b0c6834aad231b463d8eda418471/scio-examples/src/main/java/org/apache/beam/examples/complete/game/injector/Injector.java#L270-L297
27,168
spotify/scio
scio-examples/src/main/java/org/apache/beam/examples/complete/game/injector/Injector.java
Injector.addTimeInfoToEvent
private static String addTimeInfoToEvent(String message, Long currTime, int delayInMillis) { String eventTimeString = Long.toString((currTime - delayInMillis) / 1000 * 1000); // Add a (redundant) 'human-readable' date string to make the data semantics more clear. String dateString = GameConstants.DATE_TIME_FORMATTER.print(currTime); message = message + "," + eventTimeString + "," + dateString; return message; }
java
private static String addTimeInfoToEvent(String message, Long currTime, int delayInMillis) { String eventTimeString = Long.toString((currTime - delayInMillis) / 1000 * 1000); // Add a (redundant) 'human-readable' date string to make the data semantics more clear. String dateString = GameConstants.DATE_TIME_FORMATTER.print(currTime); message = message + "," + eventTimeString + "," + dateString; return message; }
[ "private", "static", "String", "addTimeInfoToEvent", "(", "String", "message", ",", "Long", "currTime", ",", "int", "delayInMillis", ")", "{", "String", "eventTimeString", "=", "Long", ".", "toString", "(", "(", "currTime", "-", "delayInMillis", ")", "/", "1000", "*", "1000", ")", ";", "// Add a (redundant) 'human-readable' date string to make the data semantics more clear.", "String", "dateString", "=", "GameConstants", ".", "DATE_TIME_FORMATTER", ".", "print", "(", "currTime", ")", ";", "message", "=", "message", "+", "\",\"", "+", "eventTimeString", "+", "\",\"", "+", "dateString", ";", "return", "message", ";", "}" ]
Add time info to a generated gaming event.
[ "Add", "time", "info", "to", "a", "generated", "gaming", "event", "." ]
ed9a44428251b0c6834aad231b463d8eda418471
https://github.com/spotify/scio/blob/ed9a44428251b0c6834aad231b463d8eda418471/scio-examples/src/main/java/org/apache/beam/examples/complete/game/injector/Injector.java#L302-L309
27,169
spotify/scio
scio-examples/src/main/java/org/apache/beam/examples/complete/game/injector/Injector.java
Injector.publishData
public static void publishData(int numMessages, int delayInMillis) throws IOException { List<PubsubMessage> pubsubMessages = new ArrayList<>(); for (int i = 0; i < Math.max(1, numMessages); i++) { Long currTime = System.currentTimeMillis(); String message = generateEvent(currTime, delayInMillis); PubsubMessage pubsubMessage = new PubsubMessage() .encodeData(message.getBytes("UTF-8")); pubsubMessage.setAttributes( ImmutableMap.of(GameConstants.TIMESTAMP_ATTRIBUTE, Long.toString((currTime - delayInMillis) / 1000 * 1000))); if (delayInMillis != 0) { System.out.println(pubsubMessage.getAttributes()); System.out.println("late data for: " + message); } pubsubMessages.add(pubsubMessage); } PublishRequest publishRequest = new PublishRequest(); publishRequest.setMessages(pubsubMessages); pubsub.projects().topics().publish(topic, publishRequest).execute(); }
java
public static void publishData(int numMessages, int delayInMillis) throws IOException { List<PubsubMessage> pubsubMessages = new ArrayList<>(); for (int i = 0; i < Math.max(1, numMessages); i++) { Long currTime = System.currentTimeMillis(); String message = generateEvent(currTime, delayInMillis); PubsubMessage pubsubMessage = new PubsubMessage() .encodeData(message.getBytes("UTF-8")); pubsubMessage.setAttributes( ImmutableMap.of(GameConstants.TIMESTAMP_ATTRIBUTE, Long.toString((currTime - delayInMillis) / 1000 * 1000))); if (delayInMillis != 0) { System.out.println(pubsubMessage.getAttributes()); System.out.println("late data for: " + message); } pubsubMessages.add(pubsubMessage); } PublishRequest publishRequest = new PublishRequest(); publishRequest.setMessages(pubsubMessages); pubsub.projects().topics().publish(topic, publishRequest).execute(); }
[ "public", "static", "void", "publishData", "(", "int", "numMessages", ",", "int", "delayInMillis", ")", "throws", "IOException", "{", "List", "<", "PubsubMessage", ">", "pubsubMessages", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "Math", ".", "max", "(", "1", ",", "numMessages", ")", ";", "i", "++", ")", "{", "Long", "currTime", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "String", "message", "=", "generateEvent", "(", "currTime", ",", "delayInMillis", ")", ";", "PubsubMessage", "pubsubMessage", "=", "new", "PubsubMessage", "(", ")", ".", "encodeData", "(", "message", ".", "getBytes", "(", "\"UTF-8\"", ")", ")", ";", "pubsubMessage", ".", "setAttributes", "(", "ImmutableMap", ".", "of", "(", "GameConstants", ".", "TIMESTAMP_ATTRIBUTE", ",", "Long", ".", "toString", "(", "(", "currTime", "-", "delayInMillis", ")", "/", "1000", "*", "1000", ")", ")", ")", ";", "if", "(", "delayInMillis", "!=", "0", ")", "{", "System", ".", "out", ".", "println", "(", "pubsubMessage", ".", "getAttributes", "(", ")", ")", ";", "System", ".", "out", ".", "println", "(", "\"late data for: \"", "+", "message", ")", ";", "}", "pubsubMessages", ".", "add", "(", "pubsubMessage", ")", ";", "}", "PublishRequest", "publishRequest", "=", "new", "PublishRequest", "(", ")", ";", "publishRequest", ".", "setMessages", "(", "pubsubMessages", ")", ";", "pubsub", ".", "projects", "(", ")", ".", "topics", "(", ")", ".", "publish", "(", "topic", ",", "publishRequest", ")", ".", "execute", "(", ")", ";", "}" ]
Publish 'numMessages' arbitrary events from live users with the provided delay, to a PubSub topic.
[ "Publish", "numMessages", "arbitrary", "events", "from", "live", "users", "with", "the", "provided", "delay", "to", "a", "PubSub", "topic", "." ]
ed9a44428251b0c6834aad231b463d8eda418471
https://github.com/spotify/scio/blob/ed9a44428251b0c6834aad231b463d8eda418471/scio-examples/src/main/java/org/apache/beam/examples/complete/game/injector/Injector.java#L315-L337
27,170
spotify/scio
scio-examples/src/main/java/org/apache/beam/examples/complete/game/injector/Injector.java
Injector.publishDataToFile
public static void publishDataToFile(String fileName, int numMessages, int delayInMillis) throws IOException { PrintWriter out = new PrintWriter(new OutputStreamWriter( new BufferedOutputStream(new FileOutputStream(fileName, true)), "UTF-8")); try { for (int i = 0; i < Math.max(1, numMessages); i++) { Long currTime = System.currentTimeMillis(); String message = generateEvent(currTime, delayInMillis); out.println(message); } } catch (Exception e) { System.err.print("Error in writing generated events to file"); e.printStackTrace(); } finally { out.flush(); out.close(); } }
java
public static void publishDataToFile(String fileName, int numMessages, int delayInMillis) throws IOException { PrintWriter out = new PrintWriter(new OutputStreamWriter( new BufferedOutputStream(new FileOutputStream(fileName, true)), "UTF-8")); try { for (int i = 0; i < Math.max(1, numMessages); i++) { Long currTime = System.currentTimeMillis(); String message = generateEvent(currTime, delayInMillis); out.println(message); } } catch (Exception e) { System.err.print("Error in writing generated events to file"); e.printStackTrace(); } finally { out.flush(); out.close(); } }
[ "public", "static", "void", "publishDataToFile", "(", "String", "fileName", ",", "int", "numMessages", ",", "int", "delayInMillis", ")", "throws", "IOException", "{", "PrintWriter", "out", "=", "new", "PrintWriter", "(", "new", "OutputStreamWriter", "(", "new", "BufferedOutputStream", "(", "new", "FileOutputStream", "(", "fileName", ",", "true", ")", ")", ",", "\"UTF-8\"", ")", ")", ";", "try", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "Math", ".", "max", "(", "1", ",", "numMessages", ")", ";", "i", "++", ")", "{", "Long", "currTime", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "String", "message", "=", "generateEvent", "(", "currTime", ",", "delayInMillis", ")", ";", "out", ".", "println", "(", "message", ")", ";", "}", "}", "catch", "(", "Exception", "e", ")", "{", "System", ".", "err", ".", "print", "(", "\"Error in writing generated events to file\"", ")", ";", "e", ".", "printStackTrace", "(", ")", ";", "}", "finally", "{", "out", ".", "flush", "(", ")", ";", "out", ".", "close", "(", ")", ";", "}", "}" ]
Publish generated events to a file.
[ "Publish", "generated", "events", "to", "a", "file", "." ]
ed9a44428251b0c6834aad231b463d8eda418471
https://github.com/spotify/scio/blob/ed9a44428251b0c6834aad231b463d8eda418471/scio-examples/src/main/java/org/apache/beam/examples/complete/game/injector/Injector.java#L342-L360
27,171
spotify/scio
scio-cassandra/cassandra2/src/main/java/org/apache/cassandra/db/DeletionInfo.java
DeletionInfo.isDeleted
public boolean isDeleted(Cell cell) { // We do rely on this test: if topLevel.markedForDeleteAt is MIN_VALUE, we should not // consider the column deleted even if timestamp=MIN_VALUE, otherwise this break QueryFilter.isRelevant if (isLive()) return false; if (cell.timestamp() <= topLevel.markedForDeleteAt) return true; // No matter what the counter cell's timestamp is, a tombstone always takes precedence. See CASSANDRA-7346. if (!topLevel.isLive() && cell instanceof CounterCell) return true; return ranges != null && ranges.isDeleted(cell); }
java
public boolean isDeleted(Cell cell) { // We do rely on this test: if topLevel.markedForDeleteAt is MIN_VALUE, we should not // consider the column deleted even if timestamp=MIN_VALUE, otherwise this break QueryFilter.isRelevant if (isLive()) return false; if (cell.timestamp() <= topLevel.markedForDeleteAt) return true; // No matter what the counter cell's timestamp is, a tombstone always takes precedence. See CASSANDRA-7346. if (!topLevel.isLive() && cell instanceof CounterCell) return true; return ranges != null && ranges.isDeleted(cell); }
[ "public", "boolean", "isDeleted", "(", "Cell", "cell", ")", "{", "// We do rely on this test: if topLevel.markedForDeleteAt is MIN_VALUE, we should not", "// consider the column deleted even if timestamp=MIN_VALUE, otherwise this break QueryFilter.isRelevant", "if", "(", "isLive", "(", ")", ")", "return", "false", ";", "if", "(", "cell", ".", "timestamp", "(", ")", "<=", "topLevel", ".", "markedForDeleteAt", ")", "return", "true", ";", "// No matter what the counter cell's timestamp is, a tombstone always takes precedence. See CASSANDRA-7346.", "if", "(", "!", "topLevel", ".", "isLive", "(", ")", "&&", "cell", "instanceof", "CounterCell", ")", "return", "true", ";", "return", "ranges", "!=", "null", "&&", "ranges", ".", "isDeleted", "(", "cell", ")", ";", "}" ]
Return whether a given cell is deleted by the container having this deletion info. @param cell the cell to check. @return true if the cell is deleted, false otherwise
[ "Return", "whether", "a", "given", "cell", "is", "deleted", "by", "the", "container", "having", "this", "deletion", "info", "." ]
ed9a44428251b0c6834aad231b463d8eda418471
https://github.com/spotify/scio/blob/ed9a44428251b0c6834aad231b463d8eda418471/scio-cassandra/cassandra2/src/main/java/org/apache/cassandra/db/DeletionInfo.java#L131-L146
27,172
spotify/scio
scio-cassandra/cassandra2/src/main/java/org/apache/cassandra/db/DeletionInfo.java
DeletionInfo.diff
public DeletionInfo diff(DeletionInfo superset) { RangeTombstoneList rangeDiff = superset.ranges == null || superset.ranges.isEmpty() ? null : ranges == null ? superset.ranges : ranges.diff(superset.ranges); return topLevel.markedForDeleteAt != superset.topLevel.markedForDeleteAt || rangeDiff != null ? new DeletionInfo(superset.topLevel, rangeDiff) : DeletionInfo.live(); }
java
public DeletionInfo diff(DeletionInfo superset) { RangeTombstoneList rangeDiff = superset.ranges == null || superset.ranges.isEmpty() ? null : ranges == null ? superset.ranges : ranges.diff(superset.ranges); return topLevel.markedForDeleteAt != superset.topLevel.markedForDeleteAt || rangeDiff != null ? new DeletionInfo(superset.topLevel, rangeDiff) : DeletionInfo.live(); }
[ "public", "DeletionInfo", "diff", "(", "DeletionInfo", "superset", ")", "{", "RangeTombstoneList", "rangeDiff", "=", "superset", ".", "ranges", "==", "null", "||", "superset", ".", "ranges", ".", "isEmpty", "(", ")", "?", "null", ":", "ranges", "==", "null", "?", "superset", ".", "ranges", ":", "ranges", ".", "diff", "(", "superset", ".", "ranges", ")", ";", "return", "topLevel", ".", "markedForDeleteAt", "!=", "superset", ".", "topLevel", ".", "markedForDeleteAt", "||", "rangeDiff", "!=", "null", "?", "new", "DeletionInfo", "(", "superset", ".", "topLevel", ",", "rangeDiff", ")", ":", "DeletionInfo", ".", "live", "(", ")", ";", "}" ]
Evaluates difference between this deletion info and superset for read repair @return the difference between the two, or LIVE if no difference
[ "Evaluates", "difference", "between", "this", "deletion", "info", "and", "superset", "for", "read", "repair" ]
ed9a44428251b0c6834aad231b463d8eda418471
https://github.com/spotify/scio/blob/ed9a44428251b0c6834aad231b463d8eda418471/scio-cassandra/cassandra2/src/main/java/org/apache/cassandra/db/DeletionInfo.java#L187-L196
27,173
spotify/scio
scio-cassandra/cassandra2/src/main/java/org/apache/cassandra/db/DeletionInfo.java
DeletionInfo.updateDigest
public void updateDigest(MessageDigest digest) { if (topLevel.markedForDeleteAt != Long.MIN_VALUE) digest.update(ByteBufferUtil.bytes(topLevel.markedForDeleteAt)); if (ranges != null) ranges.updateDigest(digest); }
java
public void updateDigest(MessageDigest digest) { if (topLevel.markedForDeleteAt != Long.MIN_VALUE) digest.update(ByteBufferUtil.bytes(topLevel.markedForDeleteAt)); if (ranges != null) ranges.updateDigest(digest); }
[ "public", "void", "updateDigest", "(", "MessageDigest", "digest", ")", "{", "if", "(", "topLevel", ".", "markedForDeleteAt", "!=", "Long", ".", "MIN_VALUE", ")", "digest", ".", "update", "(", "ByteBufferUtil", ".", "bytes", "(", "topLevel", ".", "markedForDeleteAt", ")", ")", ";", "if", "(", "ranges", "!=", "null", ")", "ranges", ".", "updateDigest", "(", "digest", ")", ";", "}" ]
Digests deletion info. Used to trigger read repair on mismatch.
[ "Digests", "deletion", "info", ".", "Used", "to", "trigger", "read", "repair", "on", "mismatch", "." ]
ed9a44428251b0c6834aad231b463d8eda418471
https://github.com/spotify/scio/blob/ed9a44428251b0c6834aad231b463d8eda418471/scio-cassandra/cassandra2/src/main/java/org/apache/cassandra/db/DeletionInfo.java#L202-L209
27,174
spotify/scio
scio-cassandra/cassandra2/src/main/java/org/apache/cassandra/db/DeletionInfo.java
DeletionInfo.add
public DeletionInfo add(DeletionInfo newInfo) { add(newInfo.topLevel); if (ranges == null) ranges = newInfo.ranges == null ? null : newInfo.ranges.copy(); else if (newInfo.ranges != null) ranges.addAll(newInfo.ranges); return this; }
java
public DeletionInfo add(DeletionInfo newInfo) { add(newInfo.topLevel); if (ranges == null) ranges = newInfo.ranges == null ? null : newInfo.ranges.copy(); else if (newInfo.ranges != null) ranges.addAll(newInfo.ranges); return this; }
[ "public", "DeletionInfo", "add", "(", "DeletionInfo", "newInfo", ")", "{", "add", "(", "newInfo", ".", "topLevel", ")", ";", "if", "(", "ranges", "==", "null", ")", "ranges", "=", "newInfo", ".", "ranges", "==", "null", "?", "null", ":", "newInfo", ".", "ranges", ".", "copy", "(", ")", ";", "else", "if", "(", "newInfo", ".", "ranges", "!=", "null", ")", "ranges", ".", "addAll", "(", "newInfo", ".", "ranges", ")", ";", "return", "this", ";", "}" ]
Combines another DeletionInfo with this one and returns the result. Whichever top-level tombstone has the higher markedForDeleteAt timestamp will be kept, along with its localDeletionTime. The range tombstones will be combined. @return this object.
[ "Combines", "another", "DeletionInfo", "with", "this", "one", "and", "returns", "the", "result", ".", "Whichever", "top", "-", "level", "tombstone", "has", "the", "higher", "markedForDeleteAt", "timestamp", "will", "be", "kept", "along", "with", "its", "localDeletionTime", ".", "The", "range", "tombstones", "will", "be", "combined", "." ]
ed9a44428251b0c6834aad231b463d8eda418471
https://github.com/spotify/scio/blob/ed9a44428251b0c6834aad231b463d8eda418471/scio-cassandra/cassandra2/src/main/java/org/apache/cassandra/db/DeletionInfo.java#L250-L260
27,175
spotify/scio
scio-cassandra/cassandra2/src/main/java/org/apache/cassandra/db/DeletionInfo.java
DeletionInfo.minTimestamp
public long minTimestamp() { return ranges == null ? topLevel.markedForDeleteAt : Math.min(topLevel.markedForDeleteAt, ranges.minMarkedAt()); }
java
public long minTimestamp() { return ranges == null ? topLevel.markedForDeleteAt : Math.min(topLevel.markedForDeleteAt, ranges.minMarkedAt()); }
[ "public", "long", "minTimestamp", "(", ")", "{", "return", "ranges", "==", "null", "?", "topLevel", ".", "markedForDeleteAt", ":", "Math", ".", "min", "(", "topLevel", ".", "markedForDeleteAt", ",", "ranges", ".", "minMarkedAt", "(", ")", ")", ";", "}" ]
Returns the minimum timestamp in any of the range tombstones or the top-level tombstone.
[ "Returns", "the", "minimum", "timestamp", "in", "any", "of", "the", "range", "tombstones", "or", "the", "top", "-", "level", "tombstone", "." ]
ed9a44428251b0c6834aad231b463d8eda418471
https://github.com/spotify/scio/blob/ed9a44428251b0c6834aad231b463d8eda418471/scio-cassandra/cassandra2/src/main/java/org/apache/cassandra/db/DeletionInfo.java#L265-L270
27,176
spotify/scio
scio-cassandra/cassandra2/src/main/java/org/apache/cassandra/db/DeletionInfo.java
DeletionInfo.maxTimestamp
public long maxTimestamp() { return ranges == null ? topLevel.markedForDeleteAt : Math.max(topLevel.markedForDeleteAt, ranges.maxMarkedAt()); }
java
public long maxTimestamp() { return ranges == null ? topLevel.markedForDeleteAt : Math.max(topLevel.markedForDeleteAt, ranges.maxMarkedAt()); }
[ "public", "long", "maxTimestamp", "(", ")", "{", "return", "ranges", "==", "null", "?", "topLevel", ".", "markedForDeleteAt", ":", "Math", ".", "max", "(", "topLevel", ".", "markedForDeleteAt", ",", "ranges", ".", "maxMarkedAt", "(", ")", ")", ";", "}" ]
Returns the maximum timestamp in any of the range tombstones or the top-level tombstone.
[ "Returns", "the", "maximum", "timestamp", "in", "any", "of", "the", "range", "tombstones", "or", "the", "top", "-", "level", "tombstone", "." ]
ed9a44428251b0c6834aad231b463d8eda418471
https://github.com/spotify/scio/blob/ed9a44428251b0c6834aad231b463d8eda418471/scio-cassandra/cassandra2/src/main/java/org/apache/cassandra/db/DeletionInfo.java#L275-L280
27,177
spotify/scio
scio-cassandra/cassandra2/src/main/java/org/apache/cassandra/hadoop/cql3/CqlBulkRecordWriterUtil.java
CqlBulkRecordWriterUtil.newWriter
public static CqlBulkRecordWriter newWriter(Configuration conf, String host, int port, String username, String password, String keyspace, String table, String partitioner, String tableSchema, String insertStatement) throws IOException { Config.setClientMode(true); ConfigHelper.setOutputInitialAddress(conf, host); if (port >= 0) { ConfigHelper.setOutputRpcPort(conf, String.valueOf(port)); } if (username != null && password != null) { ConfigHelper.setOutputKeyspaceUserNameAndPassword(conf, username, password); } ConfigHelper.setOutputKeyspace(conf, keyspace); ConfigHelper.setOutputColumnFamily(conf, table); ConfigHelper.setOutputPartitioner(conf, partitioner); CqlBulkOutputFormat.setTableSchema(conf, table, tableSchema); CqlBulkOutputFormat.setTableInsertStatement(conf, table, insertStatement); conf.set(CqlBulkRecordWriter.OUTPUT_LOCATION, Files.createTempDirectory("scio-cassandra-").toString()); // workaround for Hadoop static initialization if (!System.getProperties().containsKey("hadoop.home.dir") && !System.getenv().containsKey("HADOOP_HOME")) { System.setProperty("hadoop.home.dir", "/"); } return new CqlBulkRecordWriter(conf); }
java
public static CqlBulkRecordWriter newWriter(Configuration conf, String host, int port, String username, String password, String keyspace, String table, String partitioner, String tableSchema, String insertStatement) throws IOException { Config.setClientMode(true); ConfigHelper.setOutputInitialAddress(conf, host); if (port >= 0) { ConfigHelper.setOutputRpcPort(conf, String.valueOf(port)); } if (username != null && password != null) { ConfigHelper.setOutputKeyspaceUserNameAndPassword(conf, username, password); } ConfigHelper.setOutputKeyspace(conf, keyspace); ConfigHelper.setOutputColumnFamily(conf, table); ConfigHelper.setOutputPartitioner(conf, partitioner); CqlBulkOutputFormat.setTableSchema(conf, table, tableSchema); CqlBulkOutputFormat.setTableInsertStatement(conf, table, insertStatement); conf.set(CqlBulkRecordWriter.OUTPUT_LOCATION, Files.createTempDirectory("scio-cassandra-").toString()); // workaround for Hadoop static initialization if (!System.getProperties().containsKey("hadoop.home.dir") && !System.getenv().containsKey("HADOOP_HOME")) { System.setProperty("hadoop.home.dir", "/"); } return new CqlBulkRecordWriter(conf); }
[ "public", "static", "CqlBulkRecordWriter", "newWriter", "(", "Configuration", "conf", ",", "String", "host", ",", "int", "port", ",", "String", "username", ",", "String", "password", ",", "String", "keyspace", ",", "String", "table", ",", "String", "partitioner", ",", "String", "tableSchema", ",", "String", "insertStatement", ")", "throws", "IOException", "{", "Config", ".", "setClientMode", "(", "true", ")", ";", "ConfigHelper", ".", "setOutputInitialAddress", "(", "conf", ",", "host", ")", ";", "if", "(", "port", ">=", "0", ")", "{", "ConfigHelper", ".", "setOutputRpcPort", "(", "conf", ",", "String", ".", "valueOf", "(", "port", ")", ")", ";", "}", "if", "(", "username", "!=", "null", "&&", "password", "!=", "null", ")", "{", "ConfigHelper", ".", "setOutputKeyspaceUserNameAndPassword", "(", "conf", ",", "username", ",", "password", ")", ";", "}", "ConfigHelper", ".", "setOutputKeyspace", "(", "conf", ",", "keyspace", ")", ";", "ConfigHelper", ".", "setOutputColumnFamily", "(", "conf", ",", "table", ")", ";", "ConfigHelper", ".", "setOutputPartitioner", "(", "conf", ",", "partitioner", ")", ";", "CqlBulkOutputFormat", ".", "setTableSchema", "(", "conf", ",", "table", ",", "tableSchema", ")", ";", "CqlBulkOutputFormat", ".", "setTableInsertStatement", "(", "conf", ",", "table", ",", "insertStatement", ")", ";", "conf", ".", "set", "(", "CqlBulkRecordWriter", ".", "OUTPUT_LOCATION", ",", "Files", ".", "createTempDirectory", "(", "\"scio-cassandra-\"", ")", ".", "toString", "(", ")", ")", ";", "// workaround for Hadoop static initialization", "if", "(", "!", "System", ".", "getProperties", "(", ")", ".", "containsKey", "(", "\"hadoop.home.dir\"", ")", "&&", "!", "System", ".", "getenv", "(", ")", ".", "containsKey", "(", "\"HADOOP_HOME\"", ")", ")", "{", "System", ".", "setProperty", "(", "\"hadoop.home.dir\"", ",", "\"/\"", ")", ";", "}", "return", "new", "CqlBulkRecordWriter", "(", "conf", ")", ";", "}" ]
Workaround to expose package private constructor.
[ "Workaround", "to", "expose", "package", "private", "constructor", "." ]
ed9a44428251b0c6834aad231b463d8eda418471
https://github.com/spotify/scio/blob/ed9a44428251b0c6834aad231b463d8eda418471/scio-cassandra/cassandra2/src/main/java/org/apache/cassandra/hadoop/cql3/CqlBulkRecordWriterUtil.java#L29-L62
27,178
spotify/scio
scio-examples/src/main/java/org/apache/beam/examples/complete/game/injector/RetryHttpInitializerWrapper.java
RetryHttpInitializerWrapper.initialize
@Override public final void initialize(final HttpRequest request) { request.setReadTimeout(2 * ONEMINITUES); // 2 minutes read timeout final HttpUnsuccessfulResponseHandler backoffHandler = new HttpBackOffUnsuccessfulResponseHandler( new ExponentialBackOff()) .setSleeper(sleeper); request.setInterceptor(wrappedCredential); request.setUnsuccessfulResponseHandler( (request1, response, supportsRetry) -> { if (wrappedCredential.handleResponse(request1, response, supportsRetry)) { // If credential decides it can handle it, the return code or message indicated // something specific to authentication, and no backoff is desired. return true; } else if (backoffHandler.handleResponse(request1, response, supportsRetry)) { // Otherwise, we defer to the judgement of our internal backoff handler. LOG.info("Retrying " + request1.getUrl().toString()); return true; } else { return false; } }); request.setIOExceptionHandler( new HttpBackOffIOExceptionHandler(new ExponentialBackOff()) .setSleeper(sleeper)); }
java
@Override public final void initialize(final HttpRequest request) { request.setReadTimeout(2 * ONEMINITUES); // 2 minutes read timeout final HttpUnsuccessfulResponseHandler backoffHandler = new HttpBackOffUnsuccessfulResponseHandler( new ExponentialBackOff()) .setSleeper(sleeper); request.setInterceptor(wrappedCredential); request.setUnsuccessfulResponseHandler( (request1, response, supportsRetry) -> { if (wrappedCredential.handleResponse(request1, response, supportsRetry)) { // If credential decides it can handle it, the return code or message indicated // something specific to authentication, and no backoff is desired. return true; } else if (backoffHandler.handleResponse(request1, response, supportsRetry)) { // Otherwise, we defer to the judgement of our internal backoff handler. LOG.info("Retrying " + request1.getUrl().toString()); return true; } else { return false; } }); request.setIOExceptionHandler( new HttpBackOffIOExceptionHandler(new ExponentialBackOff()) .setSleeper(sleeper)); }
[ "@", "Override", "public", "final", "void", "initialize", "(", "final", "HttpRequest", "request", ")", "{", "request", ".", "setReadTimeout", "(", "2", "*", "ONEMINITUES", ")", ";", "// 2 minutes read timeout", "final", "HttpUnsuccessfulResponseHandler", "backoffHandler", "=", "new", "HttpBackOffUnsuccessfulResponseHandler", "(", "new", "ExponentialBackOff", "(", ")", ")", ".", "setSleeper", "(", "sleeper", ")", ";", "request", ".", "setInterceptor", "(", "wrappedCredential", ")", ";", "request", ".", "setUnsuccessfulResponseHandler", "(", "(", "request1", ",", "response", ",", "supportsRetry", ")", "->", "{", "if", "(", "wrappedCredential", ".", "handleResponse", "(", "request1", ",", "response", ",", "supportsRetry", ")", ")", "{", "// If credential decides it can handle it, the return code or message indicated", "// something specific to authentication, and no backoff is desired.", "return", "true", ";", "}", "else", "if", "(", "backoffHandler", ".", "handleResponse", "(", "request1", ",", "response", ",", "supportsRetry", ")", ")", "{", "// Otherwise, we defer to the judgement of our internal backoff handler.", "LOG", ".", "info", "(", "\"Retrying \"", "+", "request1", ".", "getUrl", "(", ")", ".", "toString", "(", ")", ")", ";", "return", "true", ";", "}", "else", "{", "return", "false", ";", "}", "}", ")", ";", "request", ".", "setIOExceptionHandler", "(", "new", "HttpBackOffIOExceptionHandler", "(", "new", "ExponentialBackOff", "(", ")", ")", ".", "setSleeper", "(", "sleeper", ")", ")", ";", "}" ]
Initializes the given request.
[ "Initializes", "the", "given", "request", "." ]
ed9a44428251b0c6834aad231b463d8eda418471
https://github.com/spotify/scio/blob/ed9a44428251b0c6834aad231b463d8eda418471/scio-examples/src/main/java/org/apache/beam/examples/complete/game/injector/RetryHttpInitializerWrapper.java#L89-L114
27,179
line/line-bot-sdk-java
line-bot-api-client/src/main/java/com/linecorp/bot/client/LineMessagingClientBuilder.java
LineMessagingClientBuilder.okHttpClientBuilder
public LineMessagingClientBuilder okHttpClientBuilder( @NonNull final OkHttpClient.Builder okHttpClientBuilder, final boolean addAuthenticationHeader) { this.okHttpClientBuilder = okHttpClientBuilder; this.addAuthenticationHeader = addAuthenticationHeader; return this; }
java
public LineMessagingClientBuilder okHttpClientBuilder( @NonNull final OkHttpClient.Builder okHttpClientBuilder, final boolean addAuthenticationHeader) { this.okHttpClientBuilder = okHttpClientBuilder; this.addAuthenticationHeader = addAuthenticationHeader; return this; }
[ "public", "LineMessagingClientBuilder", "okHttpClientBuilder", "(", "@", "NonNull", "final", "OkHttpClient", ".", "Builder", "okHttpClientBuilder", ",", "final", "boolean", "addAuthenticationHeader", ")", "{", "this", ".", "okHttpClientBuilder", "=", "okHttpClientBuilder", ";", "this", ".", "addAuthenticationHeader", "=", "addAuthenticationHeader", ";", "return", "this", ";", "}" ]
Set customized OkHttpClient.Builder. <p>In case of you need your own customized {@link OkHttpClient}, this builder allows specify {@link OkHttpClient.Builder} instance. <p>To use this method, please add dependency to 'com.squareup.retrofit2:retrofit'. @param addAuthenticationHeader If true, all default okhttp interceptors ignored. You should insert authentication headers yourself.
[ "Set", "customized", "OkHttpClient", ".", "Builder", "." ]
d6d30b19d5b90c2d3269eb9d6f88fe76fb6fcb55
https://github.com/line/line-bot-sdk-java/blob/d6d30b19d5b90c2d3269eb9d6f88fe76fb6fcb55/line-bot-api-client/src/main/java/com/linecorp/bot/client/LineMessagingClientBuilder.java#L153-L160
27,180
line/line-bot-sdk-java
line-bot-model/src/main/java/com/linecorp/bot/model/event/beacon/BeaconContentUtil.java
BeaconContentUtil.parseBytesOrNull
static byte[] parseBytesOrNull(final String deviceMessageAsHex) { if (deviceMessageAsHex == null) { return null; } final int length = deviceMessageAsHex.length(); final int resultSize = length / 2; if (length % 2 != 0) { throw new IllegalArgumentException("hex string needs to be even-length: " + deviceMessageAsHex); } final byte[] bytes = new byte[resultSize]; for (int pos = 0; pos < resultSize; pos++) { bytes[pos] = (byte) Integer.parseInt(deviceMessageAsHex.substring(pos * 2, pos * 2 + 2), 16); // Byte.parseByte doesn't support >= 0x80. } return bytes; }
java
static byte[] parseBytesOrNull(final String deviceMessageAsHex) { if (deviceMessageAsHex == null) { return null; } final int length = deviceMessageAsHex.length(); final int resultSize = length / 2; if (length % 2 != 0) { throw new IllegalArgumentException("hex string needs to be even-length: " + deviceMessageAsHex); } final byte[] bytes = new byte[resultSize]; for (int pos = 0; pos < resultSize; pos++) { bytes[pos] = (byte) Integer.parseInt(deviceMessageAsHex.substring(pos * 2, pos * 2 + 2), 16); // Byte.parseByte doesn't support >= 0x80. } return bytes; }
[ "static", "byte", "[", "]", "parseBytesOrNull", "(", "final", "String", "deviceMessageAsHex", ")", "{", "if", "(", "deviceMessageAsHex", "==", "null", ")", "{", "return", "null", ";", "}", "final", "int", "length", "=", "deviceMessageAsHex", ".", "length", "(", ")", ";", "final", "int", "resultSize", "=", "length", "/", "2", ";", "if", "(", "length", "%", "2", "!=", "0", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"hex string needs to be even-length: \"", "+", "deviceMessageAsHex", ")", ";", "}", "final", "byte", "[", "]", "bytes", "=", "new", "byte", "[", "resultSize", "]", ";", "for", "(", "int", "pos", "=", "0", ";", "pos", "<", "resultSize", ";", "pos", "++", ")", "{", "bytes", "[", "pos", "]", "=", "(", "byte", ")", "Integer", ".", "parseInt", "(", "deviceMessageAsHex", ".", "substring", "(", "pos", "*", "2", ",", "pos", "*", "2", "+", "2", ")", ",", "16", ")", ";", "// Byte.parseByte doesn't support >= 0x80.", "}", "return", "bytes", ";", "}" ]
Parse hext presentation to byte array. @return byte array or null if input is null. @throws IllegalArgumentException occurred when arguments is not null and illegal hex string.
[ "Parse", "hext", "presentation", "to", "byte", "array", "." ]
d6d30b19d5b90c2d3269eb9d6f88fe76fb6fcb55
https://github.com/line/line-bot-sdk-java/blob/d6d30b19d5b90c2d3269eb9d6f88fe76fb6fcb55/line-bot-model/src/main/java/com/linecorp/bot/model/event/beacon/BeaconContentUtil.java#L34-L54
27,181
line/line-bot-sdk-java
line-bot-cli/src/main/java/com/linecorp/bot/cli/Application.java
Application.main
public static void main(final String... args) throws Exception { try (ConfigurableApplicationContext context = SpringApplication.run(Application.class, args)) { log.info("Arguments: {}", Arrays.asList(args)); try { context.getBean(Application.class).run(context); } catch (Exception e) { log.error("Exception in command execution", e); } } }
java
public static void main(final String... args) throws Exception { try (ConfigurableApplicationContext context = SpringApplication.run(Application.class, args)) { log.info("Arguments: {}", Arrays.asList(args)); try { context.getBean(Application.class).run(context); } catch (Exception e) { log.error("Exception in command execution", e); } } }
[ "public", "static", "void", "main", "(", "final", "String", "...", "args", ")", "throws", "Exception", "{", "try", "(", "ConfigurableApplicationContext", "context", "=", "SpringApplication", ".", "run", "(", "Application", ".", "class", ",", "args", ")", ")", "{", "log", ".", "info", "(", "\"Arguments: {}\"", ",", "Arrays", ".", "asList", "(", "args", ")", ")", ";", "try", "{", "context", ".", "getBean", "(", "Application", ".", "class", ")", ".", "run", "(", "context", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "log", ".", "error", "(", "\"Exception in command execution\"", ",", "e", ")", ";", "}", "}", "}" ]
Entry point of line-bot-cli.
[ "Entry", "point", "of", "line", "-", "bot", "-", "cli", "." ]
d6d30b19d5b90c2d3269eb9d6f88fe76fb6fcb55
https://github.com/line/line-bot-sdk-java/blob/d6d30b19d5b90c2d3269eb9d6f88fe76fb6fcb55/line-bot-cli/src/main/java/com/linecorp/bot/cli/Application.java#L35-L45
27,182
ksoichiro/Android-ObservableScrollView
samples/src/main/java/com/github/ksoichiro/android/observablescrollview/samples/FlexibleSpaceWithImageWithViewPagerTabActivity.java
FlexibleSpaceWithImageWithViewPagerTabActivity.onScrollChanged
public void onScrollChanged(int scrollY, Scrollable s) { FlexibleSpaceWithImageBaseFragment fragment = (FlexibleSpaceWithImageBaseFragment) mPagerAdapter.getItemAt(mPager.getCurrentItem()); if (fragment == null) { return; } View view = fragment.getView(); if (view == null) { return; } Scrollable scrollable = (Scrollable) view.findViewById(R.id.scroll); if (scrollable == null) { return; } if (scrollable == s) { // This method is called by not only the current fragment but also other fragments // when their scrollY is changed. // So we need to check the caller(S) is the current fragment. int adjustedScrollY = Math.min(scrollY, mFlexibleSpaceHeight - mTabHeight); translateTab(adjustedScrollY, false); propagateScroll(adjustedScrollY); } }
java
public void onScrollChanged(int scrollY, Scrollable s) { FlexibleSpaceWithImageBaseFragment fragment = (FlexibleSpaceWithImageBaseFragment) mPagerAdapter.getItemAt(mPager.getCurrentItem()); if (fragment == null) { return; } View view = fragment.getView(); if (view == null) { return; } Scrollable scrollable = (Scrollable) view.findViewById(R.id.scroll); if (scrollable == null) { return; } if (scrollable == s) { // This method is called by not only the current fragment but also other fragments // when their scrollY is changed. // So we need to check the caller(S) is the current fragment. int adjustedScrollY = Math.min(scrollY, mFlexibleSpaceHeight - mTabHeight); translateTab(adjustedScrollY, false); propagateScroll(adjustedScrollY); } }
[ "public", "void", "onScrollChanged", "(", "int", "scrollY", ",", "Scrollable", "s", ")", "{", "FlexibleSpaceWithImageBaseFragment", "fragment", "=", "(", "FlexibleSpaceWithImageBaseFragment", ")", "mPagerAdapter", ".", "getItemAt", "(", "mPager", ".", "getCurrentItem", "(", ")", ")", ";", "if", "(", "fragment", "==", "null", ")", "{", "return", ";", "}", "View", "view", "=", "fragment", ".", "getView", "(", ")", ";", "if", "(", "view", "==", "null", ")", "{", "return", ";", "}", "Scrollable", "scrollable", "=", "(", "Scrollable", ")", "view", ".", "findViewById", "(", "R", ".", "id", ".", "scroll", ")", ";", "if", "(", "scrollable", "==", "null", ")", "{", "return", ";", "}", "if", "(", "scrollable", "==", "s", ")", "{", "// This method is called by not only the current fragment but also other fragments", "// when their scrollY is changed.", "// So we need to check the caller(S) is the current fragment.", "int", "adjustedScrollY", "=", "Math", ".", "min", "(", "scrollY", ",", "mFlexibleSpaceHeight", "-", "mTabHeight", ")", ";", "translateTab", "(", "adjustedScrollY", ",", "false", ")", ";", "propagateScroll", "(", "adjustedScrollY", ")", ";", "}", "}" ]
Called by children Fragments when their scrollY are changed. They all call this method even when they are inactive but this Activity should listen only the active child, so each Fragments will pass themselves for Activity to check if they are active. @param scrollY scroll position of Scrollable @param s caller Scrollable view
[ "Called", "by", "children", "Fragments", "when", "their", "scrollY", "are", "changed", ".", "They", "all", "call", "this", "method", "even", "when", "they", "are", "inactive", "but", "this", "Activity", "should", "listen", "only", "the", "active", "child", "so", "each", "Fragments", "will", "pass", "themselves", "for", "Activity", "to", "check", "if", "they", "are", "active", "." ]
47a5fb2db5e93d923a8c6772cde48bbb7d932345
https://github.com/ksoichiro/Android-ObservableScrollView/blob/47a5fb2db5e93d923a8c6772cde48bbb7d932345/samples/src/main/java/com/github/ksoichiro/android/observablescrollview/samples/FlexibleSpaceWithImageWithViewPagerTabActivity.java#L104-L126
27,183
ksoichiro/Android-ObservableScrollView
library/src/main/java/com/github/ksoichiro/android/observablescrollview/ScrollUtils.java
ScrollUtils.cmykFromRgb
public static float[] cmykFromRgb(int rgbColor) { int red = (0xff0000 & rgbColor) >> 16; int green = (0xff00 & rgbColor) >> 8; int blue = (0xff & rgbColor); float black = Math.min(1.0f - red / 255.0f, Math.min(1.0f - green / 255.0f, 1.0f - blue / 255.0f)); float cyan = 1.0f; float magenta = 1.0f; float yellow = 1.0f; if (black != 1.0f) { // black 1.0 causes zero divide cyan = (1.0f - (red / 255.0f) - black) / (1.0f - black); magenta = (1.0f - (green / 255.0f) - black) / (1.0f - black); yellow = (1.0f - (blue / 255.0f) - black) / (1.0f - black); } return new float[]{cyan, magenta, yellow, black}; }
java
public static float[] cmykFromRgb(int rgbColor) { int red = (0xff0000 & rgbColor) >> 16; int green = (0xff00 & rgbColor) >> 8; int blue = (0xff & rgbColor); float black = Math.min(1.0f - red / 255.0f, Math.min(1.0f - green / 255.0f, 1.0f - blue / 255.0f)); float cyan = 1.0f; float magenta = 1.0f; float yellow = 1.0f; if (black != 1.0f) { // black 1.0 causes zero divide cyan = (1.0f - (red / 255.0f) - black) / (1.0f - black); magenta = (1.0f - (green / 255.0f) - black) / (1.0f - black); yellow = (1.0f - (blue / 255.0f) - black) / (1.0f - black); } return new float[]{cyan, magenta, yellow, black}; }
[ "public", "static", "float", "[", "]", "cmykFromRgb", "(", "int", "rgbColor", ")", "{", "int", "red", "=", "(", "0xff0000", "&", "rgbColor", ")", ">>", "16", ";", "int", "green", "=", "(", "0xff00", "&", "rgbColor", ")", ">>", "8", ";", "int", "blue", "=", "(", "0xff", "&", "rgbColor", ")", ";", "float", "black", "=", "Math", ".", "min", "(", "1.0f", "-", "red", "/", "255.0f", ",", "Math", ".", "min", "(", "1.0f", "-", "green", "/", "255.0f", ",", "1.0f", "-", "blue", "/", "255.0f", ")", ")", ";", "float", "cyan", "=", "1.0f", ";", "float", "magenta", "=", "1.0f", ";", "float", "yellow", "=", "1.0f", ";", "if", "(", "black", "!=", "1.0f", ")", "{", "// black 1.0 causes zero divide", "cyan", "=", "(", "1.0f", "-", "(", "red", "/", "255.0f", ")", "-", "black", ")", "/", "(", "1.0f", "-", "black", ")", ";", "magenta", "=", "(", "1.0f", "-", "(", "green", "/", "255.0f", ")", "-", "black", ")", "/", "(", "1.0f", "-", "black", ")", ";", "yellow", "=", "(", "1.0f", "-", "(", "blue", "/", "255.0f", ")", "-", "black", ")", "/", "(", "1.0f", "-", "black", ")", ";", "}", "return", "new", "float", "[", "]", "{", "cyan", ",", "magenta", ",", "yellow", ",", "black", "}", ";", "}" ]
Convert RGB color to CMYK color. @param rgbColor Target color. @return CMYK array.
[ "Convert", "RGB", "color", "to", "CMYK", "color", "." ]
47a5fb2db5e93d923a8c6772cde48bbb7d932345
https://github.com/ksoichiro/Android-ObservableScrollView/blob/47a5fb2db5e93d923a8c6772cde48bbb7d932345/library/src/main/java/com/github/ksoichiro/android/observablescrollview/ScrollUtils.java#L109-L124
27,184
ksoichiro/Android-ObservableScrollView
library/src/main/java/com/github/ksoichiro/android/observablescrollview/ScrollUtils.java
ScrollUtils.rgbFromCmyk
public static int rgbFromCmyk(float[] cmyk) { float cyan = cmyk[0]; float magenta = cmyk[1]; float yellow = cmyk[2]; float black = cmyk[3]; int red = (int) ((1.0f - Math.min(1.0f, cyan * (1.0f - black) + black)) * 255); int green = (int) ((1.0f - Math.min(1.0f, magenta * (1.0f - black) + black)) * 255); int blue = (int) ((1.0f - Math.min(1.0f, yellow * (1.0f - black) + black)) * 255); return ((0xff & red) << 16) + ((0xff & green) << 8) + (0xff & blue); }
java
public static int rgbFromCmyk(float[] cmyk) { float cyan = cmyk[0]; float magenta = cmyk[1]; float yellow = cmyk[2]; float black = cmyk[3]; int red = (int) ((1.0f - Math.min(1.0f, cyan * (1.0f - black) + black)) * 255); int green = (int) ((1.0f - Math.min(1.0f, magenta * (1.0f - black) + black)) * 255); int blue = (int) ((1.0f - Math.min(1.0f, yellow * (1.0f - black) + black)) * 255); return ((0xff & red) << 16) + ((0xff & green) << 8) + (0xff & blue); }
[ "public", "static", "int", "rgbFromCmyk", "(", "float", "[", "]", "cmyk", ")", "{", "float", "cyan", "=", "cmyk", "[", "0", "]", ";", "float", "magenta", "=", "cmyk", "[", "1", "]", ";", "float", "yellow", "=", "cmyk", "[", "2", "]", ";", "float", "black", "=", "cmyk", "[", "3", "]", ";", "int", "red", "=", "(", "int", ")", "(", "(", "1.0f", "-", "Math", ".", "min", "(", "1.0f", ",", "cyan", "*", "(", "1.0f", "-", "black", ")", "+", "black", ")", ")", "*", "255", ")", ";", "int", "green", "=", "(", "int", ")", "(", "(", "1.0f", "-", "Math", ".", "min", "(", "1.0f", ",", "magenta", "*", "(", "1.0f", "-", "black", ")", "+", "black", ")", ")", "*", "255", ")", ";", "int", "blue", "=", "(", "int", ")", "(", "(", "1.0f", "-", "Math", ".", "min", "(", "1.0f", ",", "yellow", "*", "(", "1.0f", "-", "black", ")", "+", "black", ")", ")", "*", "255", ")", ";", "return", "(", "(", "0xff", "&", "red", ")", "<<", "16", ")", "+", "(", "(", "0xff", "&", "green", ")", "<<", "8", ")", "+", "(", "0xff", "&", "blue", ")", ";", "}" ]
Convert CYMK color to RGB color. This method doesn't check if cmyk is not null or have 4 elements in array. @param cmyk Target CYMK color. Each value should be between 0.0f to 1.0f, and should be set in this order: cyan, magenta, yellow, black. @return ARGB color. Alpha is fixed value (255).
[ "Convert", "CYMK", "color", "to", "RGB", "color", ".", "This", "method", "doesn", "t", "check", "if", "cmyk", "is", "not", "null", "or", "have", "4", "elements", "in", "array", "." ]
47a5fb2db5e93d923a8c6772cde48bbb7d932345
https://github.com/ksoichiro/Android-ObservableScrollView/blob/47a5fb2db5e93d923a8c6772cde48bbb7d932345/library/src/main/java/com/github/ksoichiro/android/observablescrollview/ScrollUtils.java#L134-L143
27,185
ksoichiro/Android-ObservableScrollView
samples/src/main/java/com/github/ksoichiro/android/observablescrollview/samples/FragmentTransitionActivity.java
FragmentTransitionActivity.initFragment
private void initFragment() { FragmentManager fm = getSupportFragmentManager(); if (fm.findFragmentByTag(FragmentTransitionDefaultFragment.FRAGMENT_TAG) == null) { FragmentTransaction ft = fm.beginTransaction(); ft.add(R.id.fragment, new FragmentTransitionDefaultFragment(), FragmentTransitionDefaultFragment.FRAGMENT_TAG); ft.commit(); fm.executePendingTransactions(); } }
java
private void initFragment() { FragmentManager fm = getSupportFragmentManager(); if (fm.findFragmentByTag(FragmentTransitionDefaultFragment.FRAGMENT_TAG) == null) { FragmentTransaction ft = fm.beginTransaction(); ft.add(R.id.fragment, new FragmentTransitionDefaultFragment(), FragmentTransitionDefaultFragment.FRAGMENT_TAG); ft.commit(); fm.executePendingTransactions(); } }
[ "private", "void", "initFragment", "(", ")", "{", "FragmentManager", "fm", "=", "getSupportFragmentManager", "(", ")", ";", "if", "(", "fm", ".", "findFragmentByTag", "(", "FragmentTransitionDefaultFragment", ".", "FRAGMENT_TAG", ")", "==", "null", ")", "{", "FragmentTransaction", "ft", "=", "fm", ".", "beginTransaction", "(", ")", ";", "ft", ".", "add", "(", "R", ".", "id", ".", "fragment", ",", "new", "FragmentTransitionDefaultFragment", "(", ")", ",", "FragmentTransitionDefaultFragment", ".", "FRAGMENT_TAG", ")", ";", "ft", ".", "commit", "(", ")", ";", "fm", ".", "executePendingTransactions", "(", ")", ";", "}", "}" ]
Fragment should be added programmatically. Using fragment tag in XML causes IllegalStateException on rotation of screen or restoring states of activity.
[ "Fragment", "should", "be", "added", "programmatically", ".", "Using", "fragment", "tag", "in", "XML", "causes", "IllegalStateException", "on", "rotation", "of", "screen", "or", "restoring", "states", "of", "activity", "." ]
47a5fb2db5e93d923a8c6772cde48bbb7d932345
https://github.com/ksoichiro/Android-ObservableScrollView/blob/47a5fb2db5e93d923a8c6772cde48bbb7d932345/samples/src/main/java/com/github/ksoichiro/android/observablescrollview/samples/FragmentTransitionActivity.java#L46-L54
27,186
casbin/jcasbin
src/main/java/org/casbin/jcasbin/main/Enforcer.java
Enforcer.getRolesForUser
public List<String> getRolesForUser(String name) { try { return model.model.get("g").get("g").rm.getRoles(name); } catch (Error e) { if (!e.getMessage().equals("error: name does not exist")) { throw e; } } return null; }
java
public List<String> getRolesForUser(String name) { try { return model.model.get("g").get("g").rm.getRoles(name); } catch (Error e) { if (!e.getMessage().equals("error: name does not exist")) { throw e; } } return null; }
[ "public", "List", "<", "String", ">", "getRolesForUser", "(", "String", "name", ")", "{", "try", "{", "return", "model", ".", "model", ".", "get", "(", "\"g\"", ")", ".", "get", "(", "\"g\"", ")", ".", "rm", ".", "getRoles", "(", "name", ")", ";", "}", "catch", "(", "Error", "e", ")", "{", "if", "(", "!", "e", ".", "getMessage", "(", ")", ".", "equals", "(", "\"error: name does not exist\"", ")", ")", "{", "throw", "e", ";", "}", "}", "return", "null", ";", "}" ]
getRolesForUser gets the roles that a user has. @param name the user. @return the roles that the user has.
[ "getRolesForUser", "gets", "the", "roles", "that", "a", "user", "has", "." ]
b46d7a756b6c39cdb17e0600607e5fcdc66edd11
https://github.com/casbin/jcasbin/blob/b46d7a756b6c39cdb17e0600607e5fcdc66edd11/src/main/java/org/casbin/jcasbin/main/Enforcer.java#L116-L125
27,187
casbin/jcasbin
src/main/java/org/casbin/jcasbin/main/Enforcer.java
Enforcer.getUsersForRole
public List<String> getUsersForRole(String name) { try { return model.model.get("g").get("g").rm.getUsers(name); } catch (Error e) { if (!e.getMessage().equals("error: name does not exist")) { throw e; } } return null; }
java
public List<String> getUsersForRole(String name) { try { return model.model.get("g").get("g").rm.getUsers(name); } catch (Error e) { if (!e.getMessage().equals("error: name does not exist")) { throw e; } } return null; }
[ "public", "List", "<", "String", ">", "getUsersForRole", "(", "String", "name", ")", "{", "try", "{", "return", "model", ".", "model", ".", "get", "(", "\"g\"", ")", ".", "get", "(", "\"g\"", ")", ".", "rm", ".", "getUsers", "(", "name", ")", ";", "}", "catch", "(", "Error", "e", ")", "{", "if", "(", "!", "e", ".", "getMessage", "(", ")", ".", "equals", "(", "\"error: name does not exist\"", ")", ")", "{", "throw", "e", ";", "}", "}", "return", "null", ";", "}" ]
getUsersForRole gets the users that has a role. @param name the role. @return the users that has the role.
[ "getUsersForRole", "gets", "the", "users", "that", "has", "a", "role", "." ]
b46d7a756b6c39cdb17e0600607e5fcdc66edd11
https://github.com/casbin/jcasbin/blob/b46d7a756b6c39cdb17e0600607e5fcdc66edd11/src/main/java/org/casbin/jcasbin/main/Enforcer.java#L133-L142
27,188
casbin/jcasbin
src/main/java/org/casbin/jcasbin/main/Enforcer.java
Enforcer.hasRoleForUser
public boolean hasRoleForUser(String name, String role) { List<String> roles = getRolesForUser(name); boolean hasRole = false; for (String r : roles) { if (r.equals(role)) { hasRole = true; break; } } return hasRole; }
java
public boolean hasRoleForUser(String name, String role) { List<String> roles = getRolesForUser(name); boolean hasRole = false; for (String r : roles) { if (r.equals(role)) { hasRole = true; break; } } return hasRole; }
[ "public", "boolean", "hasRoleForUser", "(", "String", "name", ",", "String", "role", ")", "{", "List", "<", "String", ">", "roles", "=", "getRolesForUser", "(", "name", ")", ";", "boolean", "hasRole", "=", "false", ";", "for", "(", "String", "r", ":", "roles", ")", "{", "if", "(", "r", ".", "equals", "(", "role", ")", ")", "{", "hasRole", "=", "true", ";", "break", ";", "}", "}", "return", "hasRole", ";", "}" ]
hasRoleForUser determines whether a user has a role. @param name the user. @param role the role. @return whether the user has the role.
[ "hasRoleForUser", "determines", "whether", "a", "user", "has", "a", "role", "." ]
b46d7a756b6c39cdb17e0600607e5fcdc66edd11
https://github.com/casbin/jcasbin/blob/b46d7a756b6c39cdb17e0600607e5fcdc66edd11/src/main/java/org/casbin/jcasbin/main/Enforcer.java#L151-L163
27,189
casbin/jcasbin
src/main/java/org/casbin/jcasbin/main/Enforcer.java
Enforcer.getPermissionsForUserInDomain
public List<List<String>> getPermissionsForUserInDomain(String user, String domain) { return getFilteredPolicy(0, user, domain); }
java
public List<List<String>> getPermissionsForUserInDomain(String user, String domain) { return getFilteredPolicy(0, user, domain); }
[ "public", "List", "<", "List", "<", "String", ">", ">", "getPermissionsForUserInDomain", "(", "String", "user", ",", "String", "domain", ")", "{", "return", "getFilteredPolicy", "(", "0", ",", "user", ",", "domain", ")", ";", "}" ]
getPermissionsForUserInDomain gets permissions for a user or role inside a domain. @param user the user. @param domain the domain. @return the permissions, a permission is usually like (obj, act). It is actually the rule without the subject.
[ "getPermissionsForUserInDomain", "gets", "permissions", "for", "a", "user", "or", "role", "inside", "a", "domain", "." ]
b46d7a756b6c39cdb17e0600607e5fcdc66edd11
https://github.com/casbin/jcasbin/blob/b46d7a756b6c39cdb17e0600607e5fcdc66edd11/src/main/java/org/casbin/jcasbin/main/Enforcer.java#L374-L376
27,190
casbin/jcasbin
src/main/java/org/casbin/jcasbin/rbac/DefaultRoleManager.java
DefaultRoleManager.getRoles
@Override public List<String> getRoles(String name, String... domain) { if (domain.length == 1) { name = domain[0] + "::" + name; } else if (domain.length > 1) { throw new Error("error: domain should be 1 parameter"); } if (!hasRole(name)) { throw new Error("error: name does not exist"); } List<String> roles = createRole(name).getRoles(); if (domain.length == 1) { for (int i = 0; i < roles.size(); i ++) { roles.set(i, roles.get(i).substring(domain[0].length() + 2, roles.get(i).length())); } } return roles; }
java
@Override public List<String> getRoles(String name, String... domain) { if (domain.length == 1) { name = domain[0] + "::" + name; } else if (domain.length > 1) { throw new Error("error: domain should be 1 parameter"); } if (!hasRole(name)) { throw new Error("error: name does not exist"); } List<String> roles = createRole(name).getRoles(); if (domain.length == 1) { for (int i = 0; i < roles.size(); i ++) { roles.set(i, roles.get(i).substring(domain[0].length() + 2, roles.get(i).length())); } } return roles; }
[ "@", "Override", "public", "List", "<", "String", ">", "getRoles", "(", "String", "name", ",", "String", "...", "domain", ")", "{", "if", "(", "domain", ".", "length", "==", "1", ")", "{", "name", "=", "domain", "[", "0", "]", "+", "\"::\"", "+", "name", ";", "}", "else", "if", "(", "domain", ".", "length", ">", "1", ")", "{", "throw", "new", "Error", "(", "\"error: domain should be 1 parameter\"", ")", ";", "}", "if", "(", "!", "hasRole", "(", "name", ")", ")", "{", "throw", "new", "Error", "(", "\"error: name does not exist\"", ")", ";", "}", "List", "<", "String", ">", "roles", "=", "createRole", "(", "name", ")", ".", "getRoles", "(", ")", ";", "if", "(", "domain", ".", "length", "==", "1", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "roles", ".", "size", "(", ")", ";", "i", "++", ")", "{", "roles", ".", "set", "(", "i", ",", "roles", ".", "get", "(", "i", ")", ".", "substring", "(", "domain", "[", "0", "]", ".", "length", "(", ")", "+", "2", ",", "roles", ".", "get", "(", "i", ")", ".", "length", "(", ")", ")", ")", ";", "}", "}", "return", "roles", ";", "}" ]
getRoles gets the roles that a subject inherits. domain is a prefix to the roles.
[ "getRoles", "gets", "the", "roles", "that", "a", "subject", "inherits", ".", "domain", "is", "a", "prefix", "to", "the", "roles", "." ]
b46d7a756b6c39cdb17e0600607e5fcdc66edd11
https://github.com/casbin/jcasbin/blob/b46d7a756b6c39cdb17e0600607e5fcdc66edd11/src/main/java/org/casbin/jcasbin/rbac/DefaultRoleManager.java#L132-L151
27,191
casbin/jcasbin
src/main/java/org/casbin/jcasbin/rbac/DefaultRoleManager.java
DefaultRoleManager.getUsers
@Override public List<String> getUsers(String name) { if (!hasRole(name)) { throw new Error("error: name does not exist"); } List<String> names = new ArrayList<>(); for (Role role : allRoles.values()) { if (role.hasDirectRole(name)) { names.add(role.name); } } return names; }
java
@Override public List<String> getUsers(String name) { if (!hasRole(name)) { throw new Error("error: name does not exist"); } List<String> names = new ArrayList<>(); for (Role role : allRoles.values()) { if (role.hasDirectRole(name)) { names.add(role.name); } } return names; }
[ "@", "Override", "public", "List", "<", "String", ">", "getUsers", "(", "String", "name", ")", "{", "if", "(", "!", "hasRole", "(", "name", ")", ")", "{", "throw", "new", "Error", "(", "\"error: name does not exist\"", ")", ";", "}", "List", "<", "String", ">", "names", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "Role", "role", ":", "allRoles", ".", "values", "(", ")", ")", "{", "if", "(", "role", ".", "hasDirectRole", "(", "name", ")", ")", "{", "names", ".", "add", "(", "role", ".", "name", ")", ";", "}", "}", "return", "names", ";", "}" ]
getUsers gets the users that inherits a subject. domain is an unreferenced parameter here, may be used in other implementations.
[ "getUsers", "gets", "the", "users", "that", "inherits", "a", "subject", ".", "domain", "is", "an", "unreferenced", "parameter", "here", "may", "be", "used", "in", "other", "implementations", "." ]
b46d7a756b6c39cdb17e0600607e5fcdc66edd11
https://github.com/casbin/jcasbin/blob/b46d7a756b6c39cdb17e0600607e5fcdc66edd11/src/main/java/org/casbin/jcasbin/rbac/DefaultRoleManager.java#L157-L170
27,192
casbin/jcasbin
src/main/java/org/casbin/jcasbin/rbac/DefaultRoleManager.java
DefaultRoleManager.printRoles
@Override public void printRoles() { for (Role role : allRoles.values()) { Util.logPrint(role.toString()); } }
java
@Override public void printRoles() { for (Role role : allRoles.values()) { Util.logPrint(role.toString()); } }
[ "@", "Override", "public", "void", "printRoles", "(", ")", "{", "for", "(", "Role", "role", ":", "allRoles", ".", "values", "(", ")", ")", "{", "Util", ".", "logPrint", "(", "role", ".", "toString", "(", ")", ")", ";", "}", "}" ]
printRoles prints all the roles to log.
[ "printRoles", "prints", "all", "the", "roles", "to", "log", "." ]
b46d7a756b6c39cdb17e0600607e5fcdc66edd11
https://github.com/casbin/jcasbin/blob/b46d7a756b6c39cdb17e0600607e5fcdc66edd11/src/main/java/org/casbin/jcasbin/rbac/DefaultRoleManager.java#L175-L180
27,193
casbin/jcasbin
src/main/java/org/casbin/jcasbin/model/Policy.java
Policy.buildRoleLinks
public void buildRoleLinks(RoleManager rm) { if (model.containsKey("g")) { for (Assertion ast : model.get("g").values()) { ast.buildRoleLinks(rm); } } }
java
public void buildRoleLinks(RoleManager rm) { if (model.containsKey("g")) { for (Assertion ast : model.get("g").values()) { ast.buildRoleLinks(rm); } } }
[ "public", "void", "buildRoleLinks", "(", "RoleManager", "rm", ")", "{", "if", "(", "model", ".", "containsKey", "(", "\"g\"", ")", ")", "{", "for", "(", "Assertion", "ast", ":", "model", ".", "get", "(", "\"g\"", ")", ".", "values", "(", ")", ")", "{", "ast", ".", "buildRoleLinks", "(", "rm", ")", ";", "}", "}", "}" ]
buildRoleLinks initializes the roles in RBAC. @param rm the role manager.
[ "buildRoleLinks", "initializes", "the", "roles", "in", "RBAC", "." ]
b46d7a756b6c39cdb17e0600607e5fcdc66edd11
https://github.com/casbin/jcasbin/blob/b46d7a756b6c39cdb17e0600607e5fcdc66edd11/src/main/java/org/casbin/jcasbin/model/Policy.java#L32-L38
27,194
casbin/jcasbin
src/main/java/org/casbin/jcasbin/model/Policy.java
Policy.printPolicy
public void printPolicy() { Util.logPrint("Policy:"); if (model.containsKey("p")) { for (Map.Entry<String, Assertion> entry : model.get("p").entrySet()) { String key = entry.getKey(); Assertion ast = entry.getValue(); Util.logPrint(key + ": " + ast.value + ": " + ast.policy); } } if (model.containsKey("g")) { for (Map.Entry<String, Assertion> entry : model.get("g").entrySet()) { String key = entry.getKey(); Assertion ast = entry.getValue(); Util.logPrint(key + ": " + ast.value + ": " + ast.policy); } } }
java
public void printPolicy() { Util.logPrint("Policy:"); if (model.containsKey("p")) { for (Map.Entry<String, Assertion> entry : model.get("p").entrySet()) { String key = entry.getKey(); Assertion ast = entry.getValue(); Util.logPrint(key + ": " + ast.value + ": " + ast.policy); } } if (model.containsKey("g")) { for (Map.Entry<String, Assertion> entry : model.get("g").entrySet()) { String key = entry.getKey(); Assertion ast = entry.getValue(); Util.logPrint(key + ": " + ast.value + ": " + ast.policy); } } }
[ "public", "void", "printPolicy", "(", ")", "{", "Util", ".", "logPrint", "(", "\"Policy:\"", ")", ";", "if", "(", "model", ".", "containsKey", "(", "\"p\"", ")", ")", "{", "for", "(", "Map", ".", "Entry", "<", "String", ",", "Assertion", ">", "entry", ":", "model", ".", "get", "(", "\"p\"", ")", ".", "entrySet", "(", ")", ")", "{", "String", "key", "=", "entry", ".", "getKey", "(", ")", ";", "Assertion", "ast", "=", "entry", ".", "getValue", "(", ")", ";", "Util", ".", "logPrint", "(", "key", "+", "\": \"", "+", "ast", ".", "value", "+", "\": \"", "+", "ast", ".", "policy", ")", ";", "}", "}", "if", "(", "model", ".", "containsKey", "(", "\"g\"", ")", ")", "{", "for", "(", "Map", ".", "Entry", "<", "String", ",", "Assertion", ">", "entry", ":", "model", ".", "get", "(", "\"g\"", ")", ".", "entrySet", "(", ")", ")", "{", "String", "key", "=", "entry", ".", "getKey", "(", ")", ";", "Assertion", "ast", "=", "entry", ".", "getValue", "(", ")", ";", "Util", ".", "logPrint", "(", "key", "+", "\": \"", "+", "ast", ".", "value", "+", "\": \"", "+", "ast", ".", "policy", ")", ";", "}", "}", "}" ]
printPolicy prints the policy to log.
[ "printPolicy", "prints", "the", "policy", "to", "log", "." ]
b46d7a756b6c39cdb17e0600607e5fcdc66edd11
https://github.com/casbin/jcasbin/blob/b46d7a756b6c39cdb17e0600607e5fcdc66edd11/src/main/java/org/casbin/jcasbin/model/Policy.java#L43-L60
27,195
casbin/jcasbin
src/main/java/org/casbin/jcasbin/model/Policy.java
Policy.clearPolicy
public void clearPolicy() { if (model.containsKey("p")) { for (Assertion ast : model.get("p").values()) { ast.policy = new ArrayList<>(); } } if (model.containsKey("g")) { for (Assertion ast : model.get("g").values()) { ast.policy = new ArrayList<>(); } } }
java
public void clearPolicy() { if (model.containsKey("p")) { for (Assertion ast : model.get("p").values()) { ast.policy = new ArrayList<>(); } } if (model.containsKey("g")) { for (Assertion ast : model.get("g").values()) { ast.policy = new ArrayList<>(); } } }
[ "public", "void", "clearPolicy", "(", ")", "{", "if", "(", "model", ".", "containsKey", "(", "\"p\"", ")", ")", "{", "for", "(", "Assertion", "ast", ":", "model", ".", "get", "(", "\"p\"", ")", ".", "values", "(", ")", ")", "{", "ast", ".", "policy", "=", "new", "ArrayList", "<>", "(", ")", ";", "}", "}", "if", "(", "model", ".", "containsKey", "(", "\"g\"", ")", ")", "{", "for", "(", "Assertion", "ast", ":", "model", ".", "get", "(", "\"g\"", ")", ".", "values", "(", ")", ")", "{", "ast", ".", "policy", "=", "new", "ArrayList", "<>", "(", ")", ";", "}", "}", "}" ]
clearPolicy clears all current policy.
[ "clearPolicy", "clears", "all", "current", "policy", "." ]
b46d7a756b6c39cdb17e0600607e5fcdc66edd11
https://github.com/casbin/jcasbin/blob/b46d7a756b6c39cdb17e0600607e5fcdc66edd11/src/main/java/org/casbin/jcasbin/model/Policy.java#L65-L77
27,196
casbin/jcasbin
src/main/java/org/casbin/jcasbin/model/Policy.java
Policy.getPolicy
public List<List<String>> getPolicy(String sec, String ptype) { return model.get(sec).get(ptype).policy; }
java
public List<List<String>> getPolicy(String sec, String ptype) { return model.get(sec).get(ptype).policy; }
[ "public", "List", "<", "List", "<", "String", ">", ">", "getPolicy", "(", "String", "sec", ",", "String", "ptype", ")", "{", "return", "model", ".", "get", "(", "sec", ")", ".", "get", "(", "ptype", ")", ".", "policy", ";", "}" ]
getPolicy gets all rules in a policy. @param sec the section, "p" or "g". @param ptype the policy type, "p", "p2", .. or "g", "g2", .. @return the policy rules of section sec and policy type ptype.
[ "getPolicy", "gets", "all", "rules", "in", "a", "policy", "." ]
b46d7a756b6c39cdb17e0600607e5fcdc66edd11
https://github.com/casbin/jcasbin/blob/b46d7a756b6c39cdb17e0600607e5fcdc66edd11/src/main/java/org/casbin/jcasbin/model/Policy.java#L86-L88
27,197
casbin/jcasbin
src/main/java/org/casbin/jcasbin/model/Policy.java
Policy.getFilteredPolicy
public List<List<String>> getFilteredPolicy(String sec, String ptype, int fieldIndex, String... fieldValues) { List<List<String>> res = new ArrayList<>(); for (List<String> rule : model.get(sec).get(ptype).policy) { boolean matched = true; for (int i = 0; i < fieldValues.length; i ++) { String fieldValue = fieldValues[i]; if (!fieldValue.equals("") && !rule.get(fieldIndex + i).equals(fieldValue)) { matched = false; break; } } if (matched) { res.add(rule); } } return res; }
java
public List<List<String>> getFilteredPolicy(String sec, String ptype, int fieldIndex, String... fieldValues) { List<List<String>> res = new ArrayList<>(); for (List<String> rule : model.get(sec).get(ptype).policy) { boolean matched = true; for (int i = 0; i < fieldValues.length; i ++) { String fieldValue = fieldValues[i]; if (!fieldValue.equals("") && !rule.get(fieldIndex + i).equals(fieldValue)) { matched = false; break; } } if (matched) { res.add(rule); } } return res; }
[ "public", "List", "<", "List", "<", "String", ">", ">", "getFilteredPolicy", "(", "String", "sec", ",", "String", "ptype", ",", "int", "fieldIndex", ",", "String", "...", "fieldValues", ")", "{", "List", "<", "List", "<", "String", ">>", "res", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "List", "<", "String", ">", "rule", ":", "model", ".", "get", "(", "sec", ")", ".", "get", "(", "ptype", ")", ".", "policy", ")", "{", "boolean", "matched", "=", "true", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "fieldValues", ".", "length", ";", "i", "++", ")", "{", "String", "fieldValue", "=", "fieldValues", "[", "i", "]", ";", "if", "(", "!", "fieldValue", ".", "equals", "(", "\"\"", ")", "&&", "!", "rule", ".", "get", "(", "fieldIndex", "+", "i", ")", ".", "equals", "(", "fieldValue", ")", ")", "{", "matched", "=", "false", ";", "break", ";", "}", "}", "if", "(", "matched", ")", "{", "res", ".", "add", "(", "rule", ")", ";", "}", "}", "return", "res", ";", "}" ]
getFilteredPolicy gets rules based on field filters from a policy. @param sec the section, "p" or "g". @param ptype the policy type, "p", "p2", .. or "g", "g2", .. @param fieldIndex the policy rule's start index to be matched. @param fieldValues the field values to be matched, value "" means not to match this field. @return the filtered policy rules of section sec and policy type ptype.
[ "getFilteredPolicy", "gets", "rules", "based", "on", "field", "filters", "from", "a", "policy", "." ]
b46d7a756b6c39cdb17e0600607e5fcdc66edd11
https://github.com/casbin/jcasbin/blob/b46d7a756b6c39cdb17e0600607e5fcdc66edd11/src/main/java/org/casbin/jcasbin/model/Policy.java#L100-L119
27,198
casbin/jcasbin
src/main/java/org/casbin/jcasbin/model/Policy.java
Policy.hasPolicy
public boolean hasPolicy(String sec, String ptype, List<String> rule) { for (List<String> r : model.get(sec).get(ptype).policy) { if (Util.arrayEquals(rule, r)) { return true; } } return false; }
java
public boolean hasPolicy(String sec, String ptype, List<String> rule) { for (List<String> r : model.get(sec).get(ptype).policy) { if (Util.arrayEquals(rule, r)) { return true; } } return false; }
[ "public", "boolean", "hasPolicy", "(", "String", "sec", ",", "String", "ptype", ",", "List", "<", "String", ">", "rule", ")", "{", "for", "(", "List", "<", "String", ">", "r", ":", "model", ".", "get", "(", "sec", ")", ".", "get", "(", "ptype", ")", ".", "policy", ")", "{", "if", "(", "Util", ".", "arrayEquals", "(", "rule", ",", "r", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
hasPolicy determines whether a model has the specified policy rule. @param sec the section, "p" or "g". @param ptype the policy type, "p", "p2", .. or "g", "g2", .. @param rule the policy rule. @return whether the rule exists.
[ "hasPolicy", "determines", "whether", "a", "model", "has", "the", "specified", "policy", "rule", "." ]
b46d7a756b6c39cdb17e0600607e5fcdc66edd11
https://github.com/casbin/jcasbin/blob/b46d7a756b6c39cdb17e0600607e5fcdc66edd11/src/main/java/org/casbin/jcasbin/model/Policy.java#L129-L137
27,199
casbin/jcasbin
src/main/java/org/casbin/jcasbin/model/Policy.java
Policy.addPolicy
public boolean addPolicy(String sec, String ptype, List<String> rule) { if (!hasPolicy(sec, ptype, rule)) { model.get(sec).get(ptype).policy.add(rule); return true; } return false; }
java
public boolean addPolicy(String sec, String ptype, List<String> rule) { if (!hasPolicy(sec, ptype, rule)) { model.get(sec).get(ptype).policy.add(rule); return true; } return false; }
[ "public", "boolean", "addPolicy", "(", "String", "sec", ",", "String", "ptype", ",", "List", "<", "String", ">", "rule", ")", "{", "if", "(", "!", "hasPolicy", "(", "sec", ",", "ptype", ",", "rule", ")", ")", "{", "model", ".", "get", "(", "sec", ")", ".", "get", "(", "ptype", ")", ".", "policy", ".", "add", "(", "rule", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
addPolicy adds a policy rule to the model. @param sec the section, "p" or "g". @param ptype the policy type, "p", "p2", .. or "g", "g2", .. @param rule the policy rule. @return succeeds or not.
[ "addPolicy", "adds", "a", "policy", "rule", "to", "the", "model", "." ]
b46d7a756b6c39cdb17e0600607e5fcdc66edd11
https://github.com/casbin/jcasbin/blob/b46d7a756b6c39cdb17e0600607e5fcdc66edd11/src/main/java/org/casbin/jcasbin/model/Policy.java#L147-L153