id
int32
0
165k
repo
stringlengths
7
58
path
stringlengths
12
218
func_name
stringlengths
3
140
original_string
stringlengths
73
34.1k
language
stringclasses
1 value
code
stringlengths
73
34.1k
code_tokens
list
docstring
stringlengths
3
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
105
339
9,800
bThink-BGU/BPjs
src/main/java/il/ac/bgu/cs/bp/bpjs/internal/ScriptableUtils.java
ScriptableUtils.jsHash
public static int jsHash(Object jsObj) { if (jsObj == null) { return 1; } // Concatenated strings in Rhino have a different type. We need to manually // resolve to String semantics, which is what the following lines do. if (jsObj instanceof ConsString) { return jsObj.toString().hashCode(); } return (jsObj instanceof ScriptableObject) ? jsScriptableObjectHashCode((ScriptableObject) jsObj) : jsObj.hashCode(); }
java
public static int jsHash(Object jsObj) { if (jsObj == null) { return 1; } // Concatenated strings in Rhino have a different type. We need to manually // resolve to String semantics, which is what the following lines do. if (jsObj instanceof ConsString) { return jsObj.toString().hashCode(); } return (jsObj instanceof ScriptableObject) ? jsScriptableObjectHashCode((ScriptableObject) jsObj) : jsObj.hashCode(); }
[ "public", "static", "int", "jsHash", "(", "Object", "jsObj", ")", "{", "if", "(", "jsObj", "==", "null", ")", "{", "return", "1", ";", "}", "// Concatenated strings in Rhino have a different type. We need to manually", "// resolve to String semantics, which is what the following lines do.", "if", "(", "jsObj", "instanceof", "ConsString", ")", "{", "return", "jsObj", ".", "toString", "(", ")", ".", "hashCode", "(", ")", ";", "}", "return", "(", "jsObj", "instanceof", "ScriptableObject", ")", "?", "jsScriptableObjectHashCode", "(", "(", "ScriptableObject", ")", "jsObj", ")", ":", "jsObj", ".", "hashCode", "(", ")", ";", "}" ]
Deep-hash of an object. <em>DOES NOT DEAL WITH CIRCULAR REFERENCES!</em> @param jsObj @return {@code o1}'s hash code.
[ "Deep", "-", "hash", "of", "an", "object", "." ]
2d388365a27ad79ded108eaf98a35a7ef292ae1f
https://github.com/bThink-BGU/BPjs/blob/2d388365a27ad79ded108eaf98a35a7ef292ae1f/src/main/java/il/ac/bgu/cs/bp/bpjs/internal/ScriptableUtils.java#L111-L125
9,801
bThink-BGU/BPjs
src/main/java/il/ac/bgu/cs/bp/bpjs/execution/listeners/InMemoryEventLoggingListener.java
InMemoryEventLoggingListener.eventNames
public List<String> eventNames() { return events.stream().map(BEvent::getName).collect( toList() ); }
java
public List<String> eventNames() { return events.stream().map(BEvent::getName).collect( toList() ); }
[ "public", "List", "<", "String", ">", "eventNames", "(", ")", "{", "return", "events", ".", "stream", "(", ")", ".", "map", "(", "BEvent", "::", "getName", ")", ".", "collect", "(", "toList", "(", ")", ")", ";", "}" ]
Convenience method for getting only the names of the events. @return list of event names, by order of selection.
[ "Convenience", "method", "for", "getting", "only", "the", "names", "of", "the", "events", "." ]
2d388365a27ad79ded108eaf98a35a7ef292ae1f
https://github.com/bThink-BGU/BPjs/blob/2d388365a27ad79ded108eaf98a35a7ef292ae1f/src/main/java/il/ac/bgu/cs/bp/bpjs/execution/listeners/InMemoryEventLoggingListener.java#L38-L40
9,802
bThink-BGU/BPjs
src/main/java/il/ac/bgu/cs/bp/bpjs/model/internal/ContinuationProgramState.java
ContinuationProgramState.collectJsValue
private Object collectJsValue(Object jsValue) { if ( jsValue == null ) { return null; } else if ( jsValue instanceof NativeFunction ) { return ((NativeFunction)jsValue).getEncodedSource(); } else if ( jsValue instanceof NativeArray ) { NativeArray jsArr = (NativeArray) jsValue; List<Object> retVal = new ArrayList<>((int)jsArr.getLength()); for ( int idx=0; idx<jsArr.getLength(); idx++ ) { retVal.add( collectJsValue(jsArr.get(idx)) ); } return retVal; } else if ( jsValue instanceof ScriptableObject ) { ScriptableObject jsObj = (ScriptableObject) jsValue; Map<Object, Object> retVal = new HashMap<>(); for ( Object key:jsObj.getIds() ) { retVal.put(key, collectJsValue(jsObj.get(key)) ); } return retVal; } else if ( jsValue instanceof ConsString ) { return ((ConsString)jsValue).toString(); } else if ( jsValue instanceof NativeJavaObject ) { NativeJavaObject jsJavaObj = (NativeJavaObject) jsValue; Object obj = jsJavaObj.unwrap(); return obj; } else { String cn = jsValue.getClass().getCanonicalName(); if ( !cn.startsWith("java.") && (!cn.startsWith("il.ac.bgu")) ) { System.out.println("collectJsValue: blind translation to java: " + jsValue + " (" + jsValue.getClass() + ")"); } return jsValue; } }
java
private Object collectJsValue(Object jsValue) { if ( jsValue == null ) { return null; } else if ( jsValue instanceof NativeFunction ) { return ((NativeFunction)jsValue).getEncodedSource(); } else if ( jsValue instanceof NativeArray ) { NativeArray jsArr = (NativeArray) jsValue; List<Object> retVal = new ArrayList<>((int)jsArr.getLength()); for ( int idx=0; idx<jsArr.getLength(); idx++ ) { retVal.add( collectJsValue(jsArr.get(idx)) ); } return retVal; } else if ( jsValue instanceof ScriptableObject ) { ScriptableObject jsObj = (ScriptableObject) jsValue; Map<Object, Object> retVal = new HashMap<>(); for ( Object key:jsObj.getIds() ) { retVal.put(key, collectJsValue(jsObj.get(key)) ); } return retVal; } else if ( jsValue instanceof ConsString ) { return ((ConsString)jsValue).toString(); } else if ( jsValue instanceof NativeJavaObject ) { NativeJavaObject jsJavaObj = (NativeJavaObject) jsValue; Object obj = jsJavaObj.unwrap(); return obj; } else { String cn = jsValue.getClass().getCanonicalName(); if ( !cn.startsWith("java.") && (!cn.startsWith("il.ac.bgu")) ) { System.out.println("collectJsValue: blind translation to java: " + jsValue + " (" + jsValue.getClass() + ")"); } return jsValue; } }
[ "private", "Object", "collectJsValue", "(", "Object", "jsValue", ")", "{", "if", "(", "jsValue", "==", "null", ")", "{", "return", "null", ";", "}", "else", "if", "(", "jsValue", "instanceof", "NativeFunction", ")", "{", "return", "(", "(", "NativeFunction", ")", "jsValue", ")", ".", "getEncodedSource", "(", ")", ";", "}", "else", "if", "(", "jsValue", "instanceof", "NativeArray", ")", "{", "NativeArray", "jsArr", "=", "(", "NativeArray", ")", "jsValue", ";", "List", "<", "Object", ">", "retVal", "=", "new", "ArrayList", "<>", "(", "(", "int", ")", "jsArr", ".", "getLength", "(", ")", ")", ";", "for", "(", "int", "idx", "=", "0", ";", "idx", "<", "jsArr", ".", "getLength", "(", ")", ";", "idx", "++", ")", "{", "retVal", ".", "add", "(", "collectJsValue", "(", "jsArr", ".", "get", "(", "idx", ")", ")", ")", ";", "}", "return", "retVal", ";", "}", "else", "if", "(", "jsValue", "instanceof", "ScriptableObject", ")", "{", "ScriptableObject", "jsObj", "=", "(", "ScriptableObject", ")", "jsValue", ";", "Map", "<", "Object", ",", "Object", ">", "retVal", "=", "new", "HashMap", "<>", "(", ")", ";", "for", "(", "Object", "key", ":", "jsObj", ".", "getIds", "(", ")", ")", "{", "retVal", ".", "put", "(", "key", ",", "collectJsValue", "(", "jsObj", ".", "get", "(", "key", ")", ")", ")", ";", "}", "return", "retVal", ";", "}", "else", "if", "(", "jsValue", "instanceof", "ConsString", ")", "{", "return", "(", "(", "ConsString", ")", "jsValue", ")", ".", "toString", "(", ")", ";", "}", "else", "if", "(", "jsValue", "instanceof", "NativeJavaObject", ")", "{", "NativeJavaObject", "jsJavaObj", "=", "(", "NativeJavaObject", ")", "jsValue", ";", "Object", "obj", "=", "jsJavaObj", ".", "unwrap", "(", ")", ";", "return", "obj", ";", "}", "else", "{", "String", "cn", "=", "jsValue", ".", "getClass", "(", ")", ".", "getCanonicalName", "(", ")", ";", "if", "(", "!", "cn", ".", "startsWith", "(", "\"java.\"", ")", "&&", "(", "!", "cn", ".", "startsWith", "(", "\"il.ac.bgu\"", ")", ")", ")", "{", "System", ".", "out", ".", "println", "(", "\"collectJsValue: blind translation to java: \"", "+", "jsValue", "+", "\" (\"", "+", "jsValue", ".", "getClass", "(", ")", "+", "\")\"", ")", ";", "}", "return", "jsValue", ";", "}", "}" ]
Take a Javascript value from Rhino, build a Java value for it. @param jsValue @return
[ "Take", "a", "Javascript", "value", "from", "Rhino", "build", "a", "Java", "value", "for", "it", "." ]
2d388365a27ad79ded108eaf98a35a7ef292ae1f
https://github.com/bThink-BGU/BPjs/blob/2d388365a27ad79ded108eaf98a35a7ef292ae1f/src/main/java/il/ac/bgu/cs/bp/bpjs/model/internal/ContinuationProgramState.java#L134-L173
9,803
bThink-BGU/BPjs
src/main/java/il/ac/bgu/cs/bp/bpjs/model/BProgram.java
BProgram.evaluate
protected Object evaluate(InputStream inStrm, String scriptName) { InputStreamReader streamReader = new InputStreamReader(inStrm, StandardCharsets.UTF_8); BufferedReader br = new BufferedReader(streamReader); StringBuilder sb = new StringBuilder(); String line; try { while ((line = br.readLine()) != null) { sb.append(line).append("\n"); } } catch (IOException e) { throw new RuntimeException("error while reading javascript from stream", e); } String script = sb.toString(); return evaluate(script, scriptName); }
java
protected Object evaluate(InputStream inStrm, String scriptName) { InputStreamReader streamReader = new InputStreamReader(inStrm, StandardCharsets.UTF_8); BufferedReader br = new BufferedReader(streamReader); StringBuilder sb = new StringBuilder(); String line; try { while ((line = br.readLine()) != null) { sb.append(line).append("\n"); } } catch (IOException e) { throw new RuntimeException("error while reading javascript from stream", e); } String script = sb.toString(); return evaluate(script, scriptName); }
[ "protected", "Object", "evaluate", "(", "InputStream", "inStrm", ",", "String", "scriptName", ")", "{", "InputStreamReader", "streamReader", "=", "new", "InputStreamReader", "(", "inStrm", ",", "StandardCharsets", ".", "UTF_8", ")", ";", "BufferedReader", "br", "=", "new", "BufferedReader", "(", "streamReader", ")", ";", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "String", "line", ";", "try", "{", "while", "(", "(", "line", "=", "br", ".", "readLine", "(", ")", ")", "!=", "null", ")", "{", "sb", ".", "append", "(", "line", ")", ".", "append", "(", "\"\\n\"", ")", ";", "}", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "\"error while reading javascript from stream\"", ",", "e", ")", ";", "}", "String", "script", "=", "sb", ".", "toString", "(", ")", ";", "return", "evaluate", "(", "script", ",", "scriptName", ")", ";", "}" ]
Reads and evaluates the code at the passed input stream. The stream is read to its end, but is not closed. @param inStrm Input stream for reading the script to be evaluated. @param scriptName for error reporting purposes. @return Result of evaluating the code at {@code inStrm}.
[ "Reads", "and", "evaluates", "the", "code", "at", "the", "passed", "input", "stream", ".", "The", "stream", "is", "read", "to", "its", "end", "but", "is", "not", "closed", "." ]
2d388365a27ad79ded108eaf98a35a7ef292ae1f
https://github.com/bThink-BGU/BPjs/blob/2d388365a27ad79ded108eaf98a35a7ef292ae1f/src/main/java/il/ac/bgu/cs/bp/bpjs/model/BProgram.java#L185-L199
9,804
bThink-BGU/BPjs
src/main/java/il/ac/bgu/cs/bp/bpjs/model/BProgram.java
BProgram.evaluate
protected Object evaluate(String script, String scriptName) { try { Context curCtx = Context.getCurrentContext(); curCtx.setLanguageVersion(Context.VERSION_1_8); return curCtx.evaluateString(programScope, script, scriptName, 1, null); } catch (EcmaError rerr) { throw new BPjsCodeEvaluationException(rerr); } catch (WrappedException wrapped) { try { throw wrapped.getCause(); } catch (BPjsException be ) { throw be; } catch ( IllegalStateException ise ) { String msg = ise.getMessage(); if ( msg.contains("Cannot capture continuation") && msg.contains("executeScriptWithContinuations or callFunctionWithContinuations") ){ throw new BPjsCodeEvaluationException("bp.sync called outside of a b-thread"); } else { throw ise; } } catch ( Throwable generalException ) { throw new BPjsRuntimeException("(Wrapped) Exception evaluating BProgram code: " + generalException.getMessage(), generalException); } } catch (EvaluatorException evalExp) { throw new BPjsCodeEvaluationException(evalExp); } catch ( Exception exp ) { throw new BPjsRuntimeException("Error evaluating BProgram code: " + exp.getMessage(), exp); } }
java
protected Object evaluate(String script, String scriptName) { try { Context curCtx = Context.getCurrentContext(); curCtx.setLanguageVersion(Context.VERSION_1_8); return curCtx.evaluateString(programScope, script, scriptName, 1, null); } catch (EcmaError rerr) { throw new BPjsCodeEvaluationException(rerr); } catch (WrappedException wrapped) { try { throw wrapped.getCause(); } catch (BPjsException be ) { throw be; } catch ( IllegalStateException ise ) { String msg = ise.getMessage(); if ( msg.contains("Cannot capture continuation") && msg.contains("executeScriptWithContinuations or callFunctionWithContinuations") ){ throw new BPjsCodeEvaluationException("bp.sync called outside of a b-thread"); } else { throw ise; } } catch ( Throwable generalException ) { throw new BPjsRuntimeException("(Wrapped) Exception evaluating BProgram code: " + generalException.getMessage(), generalException); } } catch (EvaluatorException evalExp) { throw new BPjsCodeEvaluationException(evalExp); } catch ( Exception exp ) { throw new BPjsRuntimeException("Error evaluating BProgram code: " + exp.getMessage(), exp); } }
[ "protected", "Object", "evaluate", "(", "String", "script", ",", "String", "scriptName", ")", "{", "try", "{", "Context", "curCtx", "=", "Context", ".", "getCurrentContext", "(", ")", ";", "curCtx", ".", "setLanguageVersion", "(", "Context", ".", "VERSION_1_8", ")", ";", "return", "curCtx", ".", "evaluateString", "(", "programScope", ",", "script", ",", "scriptName", ",", "1", ",", "null", ")", ";", "}", "catch", "(", "EcmaError", "rerr", ")", "{", "throw", "new", "BPjsCodeEvaluationException", "(", "rerr", ")", ";", "}", "catch", "(", "WrappedException", "wrapped", ")", "{", "try", "{", "throw", "wrapped", ".", "getCause", "(", ")", ";", "}", "catch", "(", "BPjsException", "be", ")", "{", "throw", "be", ";", "}", "catch", "(", "IllegalStateException", "ise", ")", "{", "String", "msg", "=", "ise", ".", "getMessage", "(", ")", ";", "if", "(", "msg", ".", "contains", "(", "\"Cannot capture continuation\"", ")", "&&", "msg", ".", "contains", "(", "\"executeScriptWithContinuations or callFunctionWithContinuations\"", ")", ")", "{", "throw", "new", "BPjsCodeEvaluationException", "(", "\"bp.sync called outside of a b-thread\"", ")", ";", "}", "else", "{", "throw", "ise", ";", "}", "}", "catch", "(", "Throwable", "generalException", ")", "{", "throw", "new", "BPjsRuntimeException", "(", "\"(Wrapped) Exception evaluating BProgram code: \"", "+", "generalException", ".", "getMessage", "(", ")", ",", "generalException", ")", ";", "}", "}", "catch", "(", "EvaluatorException", "evalExp", ")", "{", "throw", "new", "BPjsCodeEvaluationException", "(", "evalExp", ")", ";", "}", "catch", "(", "Exception", "exp", ")", "{", "throw", "new", "BPjsRuntimeException", "(", "\"Error evaluating BProgram code: \"", "+", "exp", ".", "getMessage", "(", ")", ",", "exp", ")", ";", "}", "}" ]
Runs the passed code in the passed scope. @param script Code to evaluate @param scriptName For error reporting purposes. @return Result of code evaluation.
[ "Runs", "the", "passed", "code", "in", "the", "passed", "scope", "." ]
2d388365a27ad79ded108eaf98a35a7ef292ae1f
https://github.com/bThink-BGU/BPjs/blob/2d388365a27ad79ded108eaf98a35a7ef292ae1f/src/main/java/il/ac/bgu/cs/bp/bpjs/model/BProgram.java#L208-L238
9,805
bThink-BGU/BPjs
src/main/java/il/ac/bgu/cs/bp/bpjs/model/BProgram.java
BProgram.registerBThread
public void registerBThread(BThreadSyncSnapshot bt) { recentlyRegisteredBthreads.add(bt); addBThreadCallback.ifPresent(cb -> cb.bthreadAdded(this, bt)); }
java
public void registerBThread(BThreadSyncSnapshot bt) { recentlyRegisteredBthreads.add(bt); addBThreadCallback.ifPresent(cb -> cb.bthreadAdded(this, bt)); }
[ "public", "void", "registerBThread", "(", "BThreadSyncSnapshot", "bt", ")", "{", "recentlyRegisteredBthreads", ".", "add", "(", "bt", ")", ";", "addBThreadCallback", ".", "ifPresent", "(", "cb", "->", "cb", ".", "bthreadAdded", "(", "this", ",", "bt", ")", ")", ";", "}" ]
Registers a BThread into the program. If the program started, the BThread will take part in the current bstep. @param bt the BThread to be registered.
[ "Registers", "a", "BThread", "into", "the", "program", ".", "If", "the", "program", "started", "the", "BThread", "will", "take", "part", "in", "the", "current", "bstep", "." ]
2d388365a27ad79ded108eaf98a35a7ef292ae1f
https://github.com/bThink-BGU/BPjs/blob/2d388365a27ad79ded108eaf98a35a7ef292ae1f/src/main/java/il/ac/bgu/cs/bp/bpjs/model/BProgram.java#L246-L249
9,806
bThink-BGU/BPjs
src/main/java/il/ac/bgu/cs/bp/bpjs/model/BProgram.java
BProgram.setup
public BProgramSyncSnapshot setup() { if (started) { throw new IllegalStateException("Program already set up."); } Set<BThreadSyncSnapshot> bthreads = drainRecentlyRegisteredBthreads(); if (eventSelectionStrategy == null) { eventSelectionStrategy = new SimpleEventSelectionStrategy(); } FailedAssertion failedAssertion = null; try { Context cx = ContextFactory.getGlobal().enterContext(); cx.setOptimizationLevel(-1); // must use interpreter mode initProgramScope(cx); // evaluate code in order if (prependedCode != null) { prependedCode.forEach(s -> evaluate(s, "prependedCode")); prependedCode = null; } setupProgramScope(programScope); if (appendedCode != null) { appendedCode.forEach(s -> evaluate(s, "appendedCode")); appendedCode = null; } } catch (FailedAssertionException fae) { failedAssertion = new FailedAssertion(fae.getMessage(), "---init_code"); } finally { Context.exit(); } started = true; return new BProgramSyncSnapshot(this, bthreads, Collections.emptyList(), failedAssertion); }
java
public BProgramSyncSnapshot setup() { if (started) { throw new IllegalStateException("Program already set up."); } Set<BThreadSyncSnapshot> bthreads = drainRecentlyRegisteredBthreads(); if (eventSelectionStrategy == null) { eventSelectionStrategy = new SimpleEventSelectionStrategy(); } FailedAssertion failedAssertion = null; try { Context cx = ContextFactory.getGlobal().enterContext(); cx.setOptimizationLevel(-1); // must use interpreter mode initProgramScope(cx); // evaluate code in order if (prependedCode != null) { prependedCode.forEach(s -> evaluate(s, "prependedCode")); prependedCode = null; } setupProgramScope(programScope); if (appendedCode != null) { appendedCode.forEach(s -> evaluate(s, "appendedCode")); appendedCode = null; } } catch (FailedAssertionException fae) { failedAssertion = new FailedAssertion(fae.getMessage(), "---init_code"); } finally { Context.exit(); } started = true; return new BProgramSyncSnapshot(this, bthreads, Collections.emptyList(), failedAssertion); }
[ "public", "BProgramSyncSnapshot", "setup", "(", ")", "{", "if", "(", "started", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Program already set up.\"", ")", ";", "}", "Set", "<", "BThreadSyncSnapshot", ">", "bthreads", "=", "drainRecentlyRegisteredBthreads", "(", ")", ";", "if", "(", "eventSelectionStrategy", "==", "null", ")", "{", "eventSelectionStrategy", "=", "new", "SimpleEventSelectionStrategy", "(", ")", ";", "}", "FailedAssertion", "failedAssertion", "=", "null", ";", "try", "{", "Context", "cx", "=", "ContextFactory", ".", "getGlobal", "(", ")", ".", "enterContext", "(", ")", ";", "cx", ".", "setOptimizationLevel", "(", "-", "1", ")", ";", "// must use interpreter mode", "initProgramScope", "(", "cx", ")", ";", "// evaluate code in order", "if", "(", "prependedCode", "!=", "null", ")", "{", "prependedCode", ".", "forEach", "(", "s", "->", "evaluate", "(", "s", ",", "\"prependedCode\"", ")", ")", ";", "prependedCode", "=", "null", ";", "}", "setupProgramScope", "(", "programScope", ")", ";", "if", "(", "appendedCode", "!=", "null", ")", "{", "appendedCode", ".", "forEach", "(", "s", "->", "evaluate", "(", "s", ",", "\"appendedCode\"", ")", ")", ";", "appendedCode", "=", "null", ";", "}", "}", "catch", "(", "FailedAssertionException", "fae", ")", "{", "failedAssertion", "=", "new", "FailedAssertion", "(", "fae", ".", "getMessage", "(", ")", ",", "\"---init_code\"", ")", ";", "}", "finally", "{", "Context", ".", "exit", "(", ")", ";", "}", "started", "=", "true", ";", "return", "new", "BProgramSyncSnapshot", "(", "this", ",", "bthreads", ",", "Collections", ".", "emptyList", "(", ")", ",", "failedAssertion", ")", ";", "}" ]
Sets up the program scope and evaluates the program source. <em>This method can only be called once per instance.</em> @return a snapshot of the program, after source code was executed, and before any registered b-threads have run. @throws IllegalStateException for repeated calls.
[ "Sets", "up", "the", "program", "scope", "and", "evaluates", "the", "program", "source", "." ]
2d388365a27ad79ded108eaf98a35a7ef292ae1f
https://github.com/bThink-BGU/BPjs/blob/2d388365a27ad79ded108eaf98a35a7ef292ae1f/src/main/java/il/ac/bgu/cs/bp/bpjs/model/BProgram.java#L277-L312
9,807
bThink-BGU/BPjs
src/main/java/il/ac/bgu/cs/bp/bpjs/model/BProgram.java
BProgram.setWaitForExternalEvents
public void setWaitForExternalEvents(boolean shouldWait) { if (waitForExternalEvents && !shouldWait) { waitForExternalEvents = false; recentlyEnqueuedExternalEvents.add(NO_MORE_WAIT_EXTERNAL); } else { waitForExternalEvents = shouldWait; } }
java
public void setWaitForExternalEvents(boolean shouldWait) { if (waitForExternalEvents && !shouldWait) { waitForExternalEvents = false; recentlyEnqueuedExternalEvents.add(NO_MORE_WAIT_EXTERNAL); } else { waitForExternalEvents = shouldWait; } }
[ "public", "void", "setWaitForExternalEvents", "(", "boolean", "shouldWait", ")", "{", "if", "(", "waitForExternalEvents", "&&", "!", "shouldWait", ")", "{", "waitForExternalEvents", "=", "false", ";", "recentlyEnqueuedExternalEvents", ".", "add", "(", "NO_MORE_WAIT_EXTERNAL", ")", ";", "}", "else", "{", "waitForExternalEvents", "=", "shouldWait", ";", "}", "}" ]
Sets whether this program waits for external events or not. When set to {@code false}, when no events are available for selection, the program terminates. @param shouldWait {@code true} causes the system to wait for external events. {@code false} causes it to not wait.
[ "Sets", "whether", "this", "program", "waits", "for", "external", "events", "or", "not", "." ]
2d388365a27ad79ded108eaf98a35a7ef292ae1f
https://github.com/bThink-BGU/BPjs/blob/2d388365a27ad79ded108eaf98a35a7ef292ae1f/src/main/java/il/ac/bgu/cs/bp/bpjs/model/BProgram.java#L366-L373
9,808
bThink-BGU/BPjs
src/main/java/il/ac/bgu/cs/bp/bpjs/model/BProgram.java
BProgram.getFromGlobalScope
public <T> Optional<T> getFromGlobalScope(String name, Class<T> clazz) { if (getGlobalScope().has(name, programScope)) { return Optional.of((T) Context.jsToJava(getGlobalScope().get(name, getGlobalScope()), clazz)); } else { return Optional.empty(); } }
java
public <T> Optional<T> getFromGlobalScope(String name, Class<T> clazz) { if (getGlobalScope().has(name, programScope)) { return Optional.of((T) Context.jsToJava(getGlobalScope().get(name, getGlobalScope()), clazz)); } else { return Optional.empty(); } }
[ "public", "<", "T", ">", "Optional", "<", "T", ">", "getFromGlobalScope", "(", "String", "name", ",", "Class", "<", "T", ">", "clazz", ")", "{", "if", "(", "getGlobalScope", "(", ")", ".", "has", "(", "name", ",", "programScope", ")", ")", "{", "return", "Optional", ".", "of", "(", "(", "T", ")", "Context", ".", "jsToJava", "(", "getGlobalScope", "(", ")", ".", "get", "(", "name", ",", "getGlobalScope", "(", ")", ")", ",", "clazz", ")", ")", ";", "}", "else", "{", "return", "Optional", ".", "empty", "(", ")", ";", "}", "}" ]
Gets the object pointer by the passed name in the global scope. @param <T> Class of the returned object. @param name Name of the object in the JS heap. @param clazz Class of the returned object @return The object pointer by the passed name in the JS heap, converted to the passed class.
[ "Gets", "the", "object", "pointer", "by", "the", "passed", "name", "in", "the", "global", "scope", "." ]
2d388365a27ad79ded108eaf98a35a7ef292ae1f
https://github.com/bThink-BGU/BPjs/blob/2d388365a27ad79ded108eaf98a35a7ef292ae1f/src/main/java/il/ac/bgu/cs/bp/bpjs/model/BProgram.java#L428-L434
9,809
bThink-BGU/BPjs
src/main/java/il/ac/bgu/cs/bp/bpjs/execution/jsproxy/BProgramJsProxy.java
BProgramJsProxy.registerBThread
public void registerBThread(String name, Function func) { program.registerBThread(new BThreadSyncSnapshot(name, func)); }
java
public void registerBThread(String name, Function func) { program.registerBThread(new BThreadSyncSnapshot(name, func)); }
[ "public", "void", "registerBThread", "(", "String", "name", ",", "Function", "func", ")", "{", "program", ".", "registerBThread", "(", "new", "BThreadSyncSnapshot", "(", "name", ",", "func", ")", ")", ";", "}" ]
Called from JS to add BThreads running func as their runnable code. @param name Name of the registered BThread (useful for debugging). @param func Script entry point of the BThread. @see #registerBThread(org.mozilla.javascript.Function)
[ "Called", "from", "JS", "to", "add", "BThreads", "running", "func", "as", "their", "runnable", "code", "." ]
2d388365a27ad79ded108eaf98a35a7ef292ae1f
https://github.com/bThink-BGU/BPjs/blob/2d388365a27ad79ded108eaf98a35a7ef292ae1f/src/main/java/il/ac/bgu/cs/bp/bpjs/execution/jsproxy/BProgramJsProxy.java#L122-L124
9,810
bThink-BGU/BPjs
src/main/java/il/ac/bgu/cs/bp/bpjs/model/BProgramSyncSnapshot.java
BProgramSyncSnapshot.triggerEvent
public BProgramSyncSnapshot triggerEvent(BEvent anEvent, ExecutorService exSvc, Iterable<BProgramRunnerListener> listeners) throws InterruptedException, BPjsRuntimeException { if (anEvent == null) throw new IllegalArgumentException("Cannot trigger a null event."); if ( triggered ) { throw new IllegalStateException("A BProgramSyncSnapshot is not allowed to be triggered twice."); } triggered = true; Set<BThreadSyncSnapshot> resumingThisRound = new HashSet<>(threadSnapshots.size()); Set<BThreadSyncSnapshot> sleepingThisRound = new HashSet<>(threadSnapshots.size()); Set<BThreadSyncSnapshot> nextRound = new HashSet<>(threadSnapshots.size()); List<BEvent> nextExternalEvents = new ArrayList<>(getExternalEvents()); try { Context ctxt = Context.enter(); handleInterrupts(anEvent, listeners, bprog, ctxt); nextExternalEvents.addAll(bprog.drainEnqueuedExternalEvents()); // Split threads to those that advance this round and those that sleep. threadSnapshots.forEach( snapshot -> { (snapshot.getSyncStatement().shouldWakeFor(anEvent) ? resumingThisRound : sleepingThisRound).add(snapshot); }); } finally { Context.exit(); } BPEngineTask.Listener halter = new ViolationRecorder(bprog, violationRecord); // add the run results of all those who advance this stage try { nextRound.addAll(exSvc.invokeAll( resumingThisRound.stream() .map(bt -> new ResumeBThread(bt, anEvent, halter)) .collect(toList()) ).stream().map(f -> safeGet(f)).filter(Objects::nonNull).collect(toList()) ); // inform listeners which b-threads completed Set<String> nextRoundIds = nextRound.stream().map(t->t.getName()).collect(toSet()); resumingThisRound.stream() .filter(t->!nextRoundIds.contains(t.getName())) .forEach(t->listeners.forEach(l->l.bthreadDone(bprog, t))); executeAllAddedBThreads(nextRound, exSvc, halter); } catch ( RuntimeException re ) { Throwable cause = re; while ( cause.getCause() != null ) { cause = cause.getCause(); } if ( cause instanceof BPjsRuntimeException ) { throw (BPjsRuntimeException)cause; } else if ( cause instanceof EcmaError ) { throw new BPjsRuntimeException("JavaScript Error: " + cause.getMessage(), cause ); } else throw re; } nextExternalEvents.addAll( bprog.drainEnqueuedExternalEvents() ); // carry over BThreads that did not advance this round to next round. nextRound.addAll(sleepingThisRound); return new BProgramSyncSnapshot(bprog, nextRound, nextExternalEvents, violationRecord.get()); }
java
public BProgramSyncSnapshot triggerEvent(BEvent anEvent, ExecutorService exSvc, Iterable<BProgramRunnerListener> listeners) throws InterruptedException, BPjsRuntimeException { if (anEvent == null) throw new IllegalArgumentException("Cannot trigger a null event."); if ( triggered ) { throw new IllegalStateException("A BProgramSyncSnapshot is not allowed to be triggered twice."); } triggered = true; Set<BThreadSyncSnapshot> resumingThisRound = new HashSet<>(threadSnapshots.size()); Set<BThreadSyncSnapshot> sleepingThisRound = new HashSet<>(threadSnapshots.size()); Set<BThreadSyncSnapshot> nextRound = new HashSet<>(threadSnapshots.size()); List<BEvent> nextExternalEvents = new ArrayList<>(getExternalEvents()); try { Context ctxt = Context.enter(); handleInterrupts(anEvent, listeners, bprog, ctxt); nextExternalEvents.addAll(bprog.drainEnqueuedExternalEvents()); // Split threads to those that advance this round and those that sleep. threadSnapshots.forEach( snapshot -> { (snapshot.getSyncStatement().shouldWakeFor(anEvent) ? resumingThisRound : sleepingThisRound).add(snapshot); }); } finally { Context.exit(); } BPEngineTask.Listener halter = new ViolationRecorder(bprog, violationRecord); // add the run results of all those who advance this stage try { nextRound.addAll(exSvc.invokeAll( resumingThisRound.stream() .map(bt -> new ResumeBThread(bt, anEvent, halter)) .collect(toList()) ).stream().map(f -> safeGet(f)).filter(Objects::nonNull).collect(toList()) ); // inform listeners which b-threads completed Set<String> nextRoundIds = nextRound.stream().map(t->t.getName()).collect(toSet()); resumingThisRound.stream() .filter(t->!nextRoundIds.contains(t.getName())) .forEach(t->listeners.forEach(l->l.bthreadDone(bprog, t))); executeAllAddedBThreads(nextRound, exSvc, halter); } catch ( RuntimeException re ) { Throwable cause = re; while ( cause.getCause() != null ) { cause = cause.getCause(); } if ( cause instanceof BPjsRuntimeException ) { throw (BPjsRuntimeException)cause; } else if ( cause instanceof EcmaError ) { throw new BPjsRuntimeException("JavaScript Error: " + cause.getMessage(), cause ); } else throw re; } nextExternalEvents.addAll( bprog.drainEnqueuedExternalEvents() ); // carry over BThreads that did not advance this round to next round. nextRound.addAll(sleepingThisRound); return new BProgramSyncSnapshot(bprog, nextRound, nextExternalEvents, violationRecord.get()); }
[ "public", "BProgramSyncSnapshot", "triggerEvent", "(", "BEvent", "anEvent", ",", "ExecutorService", "exSvc", ",", "Iterable", "<", "BProgramRunnerListener", ">", "listeners", ")", "throws", "InterruptedException", ",", "BPjsRuntimeException", "{", "if", "(", "anEvent", "==", "null", ")", "throw", "new", "IllegalArgumentException", "(", "\"Cannot trigger a null event.\"", ")", ";", "if", "(", "triggered", ")", "{", "throw", "new", "IllegalStateException", "(", "\"A BProgramSyncSnapshot is not allowed to be triggered twice.\"", ")", ";", "}", "triggered", "=", "true", ";", "Set", "<", "BThreadSyncSnapshot", ">", "resumingThisRound", "=", "new", "HashSet", "<>", "(", "threadSnapshots", ".", "size", "(", ")", ")", ";", "Set", "<", "BThreadSyncSnapshot", ">", "sleepingThisRound", "=", "new", "HashSet", "<>", "(", "threadSnapshots", ".", "size", "(", ")", ")", ";", "Set", "<", "BThreadSyncSnapshot", ">", "nextRound", "=", "new", "HashSet", "<>", "(", "threadSnapshots", ".", "size", "(", ")", ")", ";", "List", "<", "BEvent", ">", "nextExternalEvents", "=", "new", "ArrayList", "<>", "(", "getExternalEvents", "(", ")", ")", ";", "try", "{", "Context", "ctxt", "=", "Context", ".", "enter", "(", ")", ";", "handleInterrupts", "(", "anEvent", ",", "listeners", ",", "bprog", ",", "ctxt", ")", ";", "nextExternalEvents", ".", "addAll", "(", "bprog", ".", "drainEnqueuedExternalEvents", "(", ")", ")", ";", "// Split threads to those that advance this round and those that sleep.", "threadSnapshots", ".", "forEach", "(", "snapshot", "->", "{", "(", "snapshot", ".", "getSyncStatement", "(", ")", ".", "shouldWakeFor", "(", "anEvent", ")", "?", "resumingThisRound", ":", "sleepingThisRound", ")", ".", "add", "(", "snapshot", ")", ";", "}", ")", ";", "}", "finally", "{", "Context", ".", "exit", "(", ")", ";", "}", "BPEngineTask", ".", "Listener", "halter", "=", "new", "ViolationRecorder", "(", "bprog", ",", "violationRecord", ")", ";", "// add the run results of all those who advance this stage", "try", "{", "nextRound", ".", "addAll", "(", "exSvc", ".", "invokeAll", "(", "resumingThisRound", ".", "stream", "(", ")", ".", "map", "(", "bt", "->", "new", "ResumeBThread", "(", "bt", ",", "anEvent", ",", "halter", ")", ")", ".", "collect", "(", "toList", "(", ")", ")", ")", ".", "stream", "(", ")", ".", "map", "(", "f", "->", "safeGet", "(", "f", ")", ")", ".", "filter", "(", "Objects", "::", "nonNull", ")", ".", "collect", "(", "toList", "(", ")", ")", ")", ";", "// inform listeners which b-threads completed", "Set", "<", "String", ">", "nextRoundIds", "=", "nextRound", ".", "stream", "(", ")", ".", "map", "(", "t", "->", "t", ".", "getName", "(", ")", ")", ".", "collect", "(", "toSet", "(", ")", ")", ";", "resumingThisRound", ".", "stream", "(", ")", ".", "filter", "(", "t", "->", "!", "nextRoundIds", ".", "contains", "(", "t", ".", "getName", "(", ")", ")", ")", ".", "forEach", "(", "t", "->", "listeners", ".", "forEach", "(", "l", "->", "l", ".", "bthreadDone", "(", "bprog", ",", "t", ")", ")", ")", ";", "executeAllAddedBThreads", "(", "nextRound", ",", "exSvc", ",", "halter", ")", ";", "}", "catch", "(", "RuntimeException", "re", ")", "{", "Throwable", "cause", "=", "re", ";", "while", "(", "cause", ".", "getCause", "(", ")", "!=", "null", ")", "{", "cause", "=", "cause", ".", "getCause", "(", ")", ";", "}", "if", "(", "cause", "instanceof", "BPjsRuntimeException", ")", "{", "throw", "(", "BPjsRuntimeException", ")", "cause", ";", "}", "else", "if", "(", "cause", "instanceof", "EcmaError", ")", "{", "throw", "new", "BPjsRuntimeException", "(", "\"JavaScript Error: \"", "+", "cause", ".", "getMessage", "(", ")", ",", "cause", ")", ";", "}", "else", "throw", "re", ";", "}", "nextExternalEvents", ".", "addAll", "(", "bprog", ".", "drainEnqueuedExternalEvents", "(", ")", ")", ";", "// carry over BThreads that did not advance this round to next round.", "nextRound", ".", "addAll", "(", "sleepingThisRound", ")", ";", "return", "new", "BProgramSyncSnapshot", "(", "bprog", ",", "nextRound", ",", "nextExternalEvents", ",", "violationRecord", ".", "get", "(", ")", ")", ";", "}" ]
Runs the program from the snapshot, triggering the passed event. @param exSvc the executor service that will advance the threads. @param anEvent the event selected. @param listeners will be informed in case of b-thread interrupts @return A set of b-thread snapshots that should participate in the next cycle. @throws InterruptedException (since it's a blocking call)
[ "Runs", "the", "program", "from", "the", "snapshot", "triggering", "the", "passed", "event", "." ]
2d388365a27ad79ded108eaf98a35a7ef292ae1f
https://github.com/bThink-BGU/BPjs/blob/2d388365a27ad79ded108eaf98a35a7ef292ae1f/src/main/java/il/ac/bgu/cs/bp/bpjs/model/BProgramSyncSnapshot.java#L123-L185
9,811
bThink-BGU/BPjs
src/main/java/il/ac/bgu/cs/bp/bpjs/model/BProgramSyncSnapshot.java
BProgramSyncSnapshot.executeAllAddedBThreads
private void executeAllAddedBThreads(Set<BThreadSyncSnapshot> nextRound, ExecutorService exSvc, BPEngineTask.Listener listener) throws InterruptedException { // if any new bthreads are added, run and add their result Set<BThreadSyncSnapshot> addedBThreads = bprog.drainRecentlyRegisteredBthreads(); Set<ForkStatement> addedForks = bprog.drainRecentlyAddedForks(); while ( ((!addedBThreads.isEmpty()) || (!addedForks.isEmpty())) && !exSvc.isShutdown() ) { Stream<BPEngineTask> threadStream = addedBThreads.stream() .map(bt -> new StartBThread(bt, listener)); Stream<BPEngineTask> forkStream = addedForks.stream().flatMap( f -> convertToTasks(f, listener) ); nextRound.addAll(exSvc.invokeAll(Stream.concat(forkStream, threadStream).collect(toList())).stream() .map(f -> safeGet(f) ).filter(Objects::nonNull).collect(toList())); addedBThreads = bprog.drainRecentlyRegisteredBthreads(); addedForks = bprog.drainRecentlyAddedForks(); } }
java
private void executeAllAddedBThreads(Set<BThreadSyncSnapshot> nextRound, ExecutorService exSvc, BPEngineTask.Listener listener) throws InterruptedException { // if any new bthreads are added, run and add their result Set<BThreadSyncSnapshot> addedBThreads = bprog.drainRecentlyRegisteredBthreads(); Set<ForkStatement> addedForks = bprog.drainRecentlyAddedForks(); while ( ((!addedBThreads.isEmpty()) || (!addedForks.isEmpty())) && !exSvc.isShutdown() ) { Stream<BPEngineTask> threadStream = addedBThreads.stream() .map(bt -> new StartBThread(bt, listener)); Stream<BPEngineTask> forkStream = addedForks.stream().flatMap( f -> convertToTasks(f, listener) ); nextRound.addAll(exSvc.invokeAll(Stream.concat(forkStream, threadStream).collect(toList())).stream() .map(f -> safeGet(f) ).filter(Objects::nonNull).collect(toList())); addedBThreads = bprog.drainRecentlyRegisteredBthreads(); addedForks = bprog.drainRecentlyAddedForks(); } }
[ "private", "void", "executeAllAddedBThreads", "(", "Set", "<", "BThreadSyncSnapshot", ">", "nextRound", ",", "ExecutorService", "exSvc", ",", "BPEngineTask", ".", "Listener", "listener", ")", "throws", "InterruptedException", "{", "// if any new bthreads are added, run and add their result", "Set", "<", "BThreadSyncSnapshot", ">", "addedBThreads", "=", "bprog", ".", "drainRecentlyRegisteredBthreads", "(", ")", ";", "Set", "<", "ForkStatement", ">", "addedForks", "=", "bprog", ".", "drainRecentlyAddedForks", "(", ")", ";", "while", "(", "(", "(", "!", "addedBThreads", ".", "isEmpty", "(", ")", ")", "||", "(", "!", "addedForks", ".", "isEmpty", "(", ")", ")", ")", "&&", "!", "exSvc", ".", "isShutdown", "(", ")", ")", "{", "Stream", "<", "BPEngineTask", ">", "threadStream", "=", "addedBThreads", ".", "stream", "(", ")", ".", "map", "(", "bt", "->", "new", "StartBThread", "(", "bt", ",", "listener", ")", ")", ";", "Stream", "<", "BPEngineTask", ">", "forkStream", "=", "addedForks", ".", "stream", "(", ")", ".", "flatMap", "(", "f", "->", "convertToTasks", "(", "f", ",", "listener", ")", ")", ";", "nextRound", ".", "addAll", "(", "exSvc", ".", "invokeAll", "(", "Stream", ".", "concat", "(", "forkStream", ",", "threadStream", ")", ".", "collect", "(", "toList", "(", ")", ")", ")", ".", "stream", "(", ")", ".", "map", "(", "f", "->", "safeGet", "(", "f", ")", ")", ".", "filter", "(", "Objects", "::", "nonNull", ")", ".", "collect", "(", "toList", "(", ")", ")", ")", ";", "addedBThreads", "=", "bprog", ".", "drainRecentlyRegisteredBthreads", "(", ")", ";", "addedForks", "=", "bprog", ".", "drainRecentlyAddedForks", "(", ")", ";", "}", "}" ]
Executes and adds all newly registered b-threads, until no more new b-threads are registered. @param nextRound the set of b-threads that will participate in the next round @param exSvc The executor service to run the b-threads @param listener handling assertion failures, if they happen. @throws InterruptedException
[ "Executes", "and", "adds", "all", "newly", "registered", "b", "-", "threads", "until", "no", "more", "new", "b", "-", "threads", "are", "registered", "." ]
2d388365a27ad79ded108eaf98a35a7ef292ae1f
https://github.com/bThink-BGU/BPjs/blob/2d388365a27ad79ded108eaf98a35a7ef292ae1f/src/main/java/il/ac/bgu/cs/bp/bpjs/model/BProgramSyncSnapshot.java#L284-L299
9,812
bThink-BGU/BPjs
src/main/java/il/ac/bgu/cs/bp/bpjs/execution/BProgramRunner.java
BProgramRunner.addListener
public <R extends BProgramRunnerListener> R addListener(R aListener) { listeners.add(aListener); return aListener; }
java
public <R extends BProgramRunnerListener> R addListener(R aListener) { listeners.add(aListener); return aListener; }
[ "public", "<", "R", "extends", "BProgramRunnerListener", ">", "R", "addListener", "(", "R", "aListener", ")", "{", "listeners", ".", "add", "(", "aListener", ")", ";", "return", "aListener", ";", "}" ]
Adds a listener to the BProgram. @param <R> Actual type of listener. @param aListener the listener to add. @return The added listener, to allow call chaining.
[ "Adds", "a", "listener", "to", "the", "BProgram", "." ]
2d388365a27ad79ded108eaf98a35a7ef292ae1f
https://github.com/bThink-BGU/BPjs/blob/2d388365a27ad79ded108eaf98a35a7ef292ae1f/src/main/java/il/ac/bgu/cs/bp/bpjs/execution/BProgramRunner.java#L199-L202
9,813
bThink-BGU/BPjs
src/main/java/il/ac/bgu/cs/bp/bpjs/analysis/ExecutionTraceInspections.java
ExecutionTraceInspections.hasRequestedEvents
private static boolean hasRequestedEvents(BProgramSyncSnapshot bpss) { return bpss.getBThreadSnapshots().stream().anyMatch(btss -> (!btss.getSyncStatement().getRequest().isEmpty())); }
java
private static boolean hasRequestedEvents(BProgramSyncSnapshot bpss) { return bpss.getBThreadSnapshots().stream().anyMatch(btss -> (!btss.getSyncStatement().getRequest().isEmpty())); }
[ "private", "static", "boolean", "hasRequestedEvents", "(", "BProgramSyncSnapshot", "bpss", ")", "{", "return", "bpss", ".", "getBThreadSnapshots", "(", ")", ".", "stream", "(", ")", ".", "anyMatch", "(", "btss", "->", "(", "!", "btss", ".", "getSyncStatement", "(", ")", ".", "getRequest", "(", ")", ".", "isEmpty", "(", ")", ")", ")", ";", "}" ]
Utility methods.
[ "Utility", "methods", "." ]
2d388365a27ad79ded108eaf98a35a7ef292ae1f
https://github.com/bThink-BGU/BPjs/blob/2d388365a27ad79ded108eaf98a35a7ef292ae1f/src/main/java/il/ac/bgu/cs/bp/bpjs/analysis/ExecutionTraceInspections.java#L161-L163
9,814
bThink-BGU/BPjs
src/main/java/il/ac/bgu/cs/bp/bpjs/model/BThreadSyncSnapshot.java
BThreadSyncSnapshot.copyWith
public BThreadSyncSnapshot copyWith(Object aContinuation, SyncStatement aStatement) { BThreadSyncSnapshot retVal = new BThreadSyncSnapshot(name, entryPoint); retVal.continuation = aContinuation; retVal.setInterruptHandler(interruptHandler); retVal.syncStatement = aStatement; aStatement.setBthread(retVal); return retVal; }
java
public BThreadSyncSnapshot copyWith(Object aContinuation, SyncStatement aStatement) { BThreadSyncSnapshot retVal = new BThreadSyncSnapshot(name, entryPoint); retVal.continuation = aContinuation; retVal.setInterruptHandler(interruptHandler); retVal.syncStatement = aStatement; aStatement.setBthread(retVal); return retVal; }
[ "public", "BThreadSyncSnapshot", "copyWith", "(", "Object", "aContinuation", ",", "SyncStatement", "aStatement", ")", "{", "BThreadSyncSnapshot", "retVal", "=", "new", "BThreadSyncSnapshot", "(", "name", ",", "entryPoint", ")", ";", "retVal", ".", "continuation", "=", "aContinuation", ";", "retVal", ".", "setInterruptHandler", "(", "interruptHandler", ")", ";", "retVal", ".", "syncStatement", "=", "aStatement", ";", "aStatement", ".", "setBthread", "(", "retVal", ")", ";", "return", "retVal", ";", "}" ]
Creates the next snapshot of the BThread in a given run. @param aContinuation The BThread's continuation for the next sync. @param aStatement The BThread's statement for the next sync. @return a copy of {@code this} with updated continuation and statement.
[ "Creates", "the", "next", "snapshot", "of", "the", "BThread", "in", "a", "given", "run", "." ]
2d388365a27ad79ded108eaf98a35a7ef292ae1f
https://github.com/bThink-BGU/BPjs/blob/2d388365a27ad79ded108eaf98a35a7ef292ae1f/src/main/java/il/ac/bgu/cs/bp/bpjs/model/BThreadSyncSnapshot.java#L81-L89
9,815
bThink-BGU/BPjs
src/main/java/il/ac/bgu/cs/bp/bpjs/execution/tasks/BPEngineTask.java
BPEngineTask.handleContinuationPending
private BThreadSyncSnapshot handleContinuationPending(ContinuationPending cbs, Context jsContext) throws IllegalStateException { final Object capturedStatement = cbs.getApplicationState(); if ( capturedStatement instanceof SyncStatement ) { final SyncStatement syncStatement = (SyncStatement) cbs.getApplicationState(); return bss.copyWith(cbs.getContinuation(), syncStatement); } else if ( capturedStatement instanceof ForkStatement ) { ForkStatement forkStmt = (ForkStatement) capturedStatement; forkStmt.setForkingBThread(bss); final ScriptableObject globalScope = jsContext.initStandardObjects(); try ( ByteArrayOutputStream baos = new ByteArrayOutputStream(); BThreadSyncSnapshotOutputStream btos = new BThreadSyncSnapshotOutputStream(baos, globalScope) ) { btos.writeObject(cbs.getContinuation()); btos.flush(); baos.flush(); forkStmt.setSerializedContinuation(baos.toByteArray()); } catch (IOException ex) { Logger.getLogger(BPEngineTask.class.getName()).log(Level.SEVERE, "Error while serializing continuation during fork:" + ex.getMessage(), ex); throw new RuntimeException("Error while serializing continuation during fork:" + ex.getMessage(), ex); } listener.addFork(forkStmt); return continueParentOfFork(cbs, jsContext); } else { throw new IllegalStateException("Captured a statement of an unknown type: " + capturedStatement); } }
java
private BThreadSyncSnapshot handleContinuationPending(ContinuationPending cbs, Context jsContext) throws IllegalStateException { final Object capturedStatement = cbs.getApplicationState(); if ( capturedStatement instanceof SyncStatement ) { final SyncStatement syncStatement = (SyncStatement) cbs.getApplicationState(); return bss.copyWith(cbs.getContinuation(), syncStatement); } else if ( capturedStatement instanceof ForkStatement ) { ForkStatement forkStmt = (ForkStatement) capturedStatement; forkStmt.setForkingBThread(bss); final ScriptableObject globalScope = jsContext.initStandardObjects(); try ( ByteArrayOutputStream baos = new ByteArrayOutputStream(); BThreadSyncSnapshotOutputStream btos = new BThreadSyncSnapshotOutputStream(baos, globalScope) ) { btos.writeObject(cbs.getContinuation()); btos.flush(); baos.flush(); forkStmt.setSerializedContinuation(baos.toByteArray()); } catch (IOException ex) { Logger.getLogger(BPEngineTask.class.getName()).log(Level.SEVERE, "Error while serializing continuation during fork:" + ex.getMessage(), ex); throw new RuntimeException("Error while serializing continuation during fork:" + ex.getMessage(), ex); } listener.addFork(forkStmt); return continueParentOfFork(cbs, jsContext); } else { throw new IllegalStateException("Captured a statement of an unknown type: " + capturedStatement); } }
[ "private", "BThreadSyncSnapshot", "handleContinuationPending", "(", "ContinuationPending", "cbs", ",", "Context", "jsContext", ")", "throws", "IllegalStateException", "{", "final", "Object", "capturedStatement", "=", "cbs", ".", "getApplicationState", "(", ")", ";", "if", "(", "capturedStatement", "instanceof", "SyncStatement", ")", "{", "final", "SyncStatement", "syncStatement", "=", "(", "SyncStatement", ")", "cbs", ".", "getApplicationState", "(", ")", ";", "return", "bss", ".", "copyWith", "(", "cbs", ".", "getContinuation", "(", ")", ",", "syncStatement", ")", ";", "}", "else", "if", "(", "capturedStatement", "instanceof", "ForkStatement", ")", "{", "ForkStatement", "forkStmt", "=", "(", "ForkStatement", ")", "capturedStatement", ";", "forkStmt", ".", "setForkingBThread", "(", "bss", ")", ";", "final", "ScriptableObject", "globalScope", "=", "jsContext", ".", "initStandardObjects", "(", ")", ";", "try", "(", "ByteArrayOutputStream", "baos", "=", "new", "ByteArrayOutputStream", "(", ")", ";", "BThreadSyncSnapshotOutputStream", "btos", "=", "new", "BThreadSyncSnapshotOutputStream", "(", "baos", ",", "globalScope", ")", ")", "{", "btos", ".", "writeObject", "(", "cbs", ".", "getContinuation", "(", ")", ")", ";", "btos", ".", "flush", "(", ")", ";", "baos", ".", "flush", "(", ")", ";", "forkStmt", ".", "setSerializedContinuation", "(", "baos", ".", "toByteArray", "(", ")", ")", ";", "}", "catch", "(", "IOException", "ex", ")", "{", "Logger", ".", "getLogger", "(", "BPEngineTask", ".", "class", ".", "getName", "(", ")", ")", ".", "log", "(", "Level", ".", "SEVERE", ",", "\"Error while serializing continuation during fork:\"", "+", "ex", ".", "getMessage", "(", ")", ",", "ex", ")", ";", "throw", "new", "RuntimeException", "(", "\"Error while serializing continuation during fork:\"", "+", "ex", ".", "getMessage", "(", ")", ",", "ex", ")", ";", "}", "listener", ".", "addFork", "(", "forkStmt", ")", ";", "return", "continueParentOfFork", "(", "cbs", ",", "jsContext", ")", ";", "}", "else", "{", "throw", "new", "IllegalStateException", "(", "\"Captured a statement of an unknown type: \"", "+", "capturedStatement", ")", ";", "}", "}" ]
Handle a captures continuation. This can be because of a sync statement, or because of a fork. @param cbs @param jsContext @return Snapshot for the continued execution of the parent. @throws IllegalStateException
[ "Handle", "a", "captures", "continuation", ".", "This", "can", "be", "because", "of", "a", "sync", "statement", "or", "because", "of", "a", "fork", "." ]
2d388365a27ad79ded108eaf98a35a7ef292ae1f
https://github.com/bThink-BGU/BPjs/blob/2d388365a27ad79ded108eaf98a35a7ef292ae1f/src/main/java/il/ac/bgu/cs/bp/bpjs/execution/tasks/BPEngineTask.java#L92-L122
9,816
bThink-BGU/BPjs
src/main/java/il/ac/bgu/cs/bp/bpjs/model/BEvent.java
BEvent.dataToString
private String dataToString( Object data ) { if ( data == null ) return "<null>"; return ( data instanceof Scriptable ) ? ScriptableUtils.toString((Scriptable) data) : Objects.toString(data); }
java
private String dataToString( Object data ) { if ( data == null ) return "<null>"; return ( data instanceof Scriptable ) ? ScriptableUtils.toString((Scriptable) data) : Objects.toString(data); }
[ "private", "String", "dataToString", "(", "Object", "data", ")", "{", "if", "(", "data", "==", "null", ")", "return", "\"<null>\"", ";", "return", "(", "data", "instanceof", "Scriptable", ")", "?", "ScriptableUtils", ".", "toString", "(", "(", "Scriptable", ")", "data", ")", ":", "Objects", ".", "toString", "(", "data", ")", ";", "}" ]
Take the data field and give it some sensible string representation. @param data @return String representation of {@code data}.
[ "Take", "the", "data", "field", "and", "give", "it", "some", "sensible", "string", "representation", "." ]
2d388365a27ad79ded108eaf98a35a7ef292ae1f
https://github.com/bThink-BGU/BPjs/blob/2d388365a27ad79ded108eaf98a35a7ef292ae1f/src/main/java/il/ac/bgu/cs/bp/bpjs/model/BEvent.java#L90-L94
9,817
mp911de/spinach
src/main/java/biz/paluch/spinach/cluster/QueueListener.java
QueueListener.call
@Override public void call(Subscriber<? super Job<K, V>> subscriber) { log.debug("onSubscribe()"); if (subscriber.isUnsubscribed()) { return; } String subscriberId = getClass().getSimpleName() + "-" + id + "-" + subscriberIds.incrementAndGet(); subscriber.onStart(); try { Scheduler.Worker worker = scheduler.createWorker(); GetJobsAction<K, V> getJobsAction = new GetJobsAction<K, V>(disqueConnectionSupplier, subscriberId, subscriber, jobLocalityTracking, getJobsArgs); actions.add(getJobsAction); Subscription subscription = worker.schedulePeriodically(getJobsAction, 0, 10, TimeUnit.MILLISECONDS); getJobsAction.setSelfSubscription(subscription); if (improveLocalityTimeUnit != null && improveLocalityInterval > 0 && reconnectTrigger == null) { reconnectTrigger = worker.schedulePeriodically(new Action0() { @Override public void call() { switchNodes(); } }, improveLocalityInterval, improveLocalityInterval, improveLocalityTimeUnit); } } catch (Exception e) { if (log.isDebugEnabled()) { log.debug("QueueListener.call caught an exception: {}", e.getMessage(), e); } subscriber.onError(e); } }
java
@Override public void call(Subscriber<? super Job<K, V>> subscriber) { log.debug("onSubscribe()"); if (subscriber.isUnsubscribed()) { return; } String subscriberId = getClass().getSimpleName() + "-" + id + "-" + subscriberIds.incrementAndGet(); subscriber.onStart(); try { Scheduler.Worker worker = scheduler.createWorker(); GetJobsAction<K, V> getJobsAction = new GetJobsAction<K, V>(disqueConnectionSupplier, subscriberId, subscriber, jobLocalityTracking, getJobsArgs); actions.add(getJobsAction); Subscription subscription = worker.schedulePeriodically(getJobsAction, 0, 10, TimeUnit.MILLISECONDS); getJobsAction.setSelfSubscription(subscription); if (improveLocalityTimeUnit != null && improveLocalityInterval > 0 && reconnectTrigger == null) { reconnectTrigger = worker.schedulePeriodically(new Action0() { @Override public void call() { switchNodes(); } }, improveLocalityInterval, improveLocalityInterval, improveLocalityTimeUnit); } } catch (Exception e) { if (log.isDebugEnabled()) { log.debug("QueueListener.call caught an exception: {}", e.getMessage(), e); } subscriber.onError(e); } }
[ "@", "Override", "public", "void", "call", "(", "Subscriber", "<", "?", "super", "Job", "<", "K", ",", "V", ">", ">", "subscriber", ")", "{", "log", ".", "debug", "(", "\"onSubscribe()\"", ")", ";", "if", "(", "subscriber", ".", "isUnsubscribed", "(", ")", ")", "{", "return", ";", "}", "String", "subscriberId", "=", "getClass", "(", ")", ".", "getSimpleName", "(", ")", "+", "\"-\"", "+", "id", "+", "\"-\"", "+", "subscriberIds", ".", "incrementAndGet", "(", ")", ";", "subscriber", ".", "onStart", "(", ")", ";", "try", "{", "Scheduler", ".", "Worker", "worker", "=", "scheduler", ".", "createWorker", "(", ")", ";", "GetJobsAction", "<", "K", ",", "V", ">", "getJobsAction", "=", "new", "GetJobsAction", "<", "K", ",", "V", ">", "(", "disqueConnectionSupplier", ",", "subscriberId", ",", "subscriber", ",", "jobLocalityTracking", ",", "getJobsArgs", ")", ";", "actions", ".", "add", "(", "getJobsAction", ")", ";", "Subscription", "subscription", "=", "worker", ".", "schedulePeriodically", "(", "getJobsAction", ",", "0", ",", "10", ",", "TimeUnit", ".", "MILLISECONDS", ")", ";", "getJobsAction", ".", "setSelfSubscription", "(", "subscription", ")", ";", "if", "(", "improveLocalityTimeUnit", "!=", "null", "&&", "improveLocalityInterval", ">", "0", "&&", "reconnectTrigger", "==", "null", ")", "{", "reconnectTrigger", "=", "worker", ".", "schedulePeriodically", "(", "new", "Action0", "(", ")", "{", "@", "Override", "public", "void", "call", "(", ")", "{", "switchNodes", "(", ")", ";", "}", "}", ",", "improveLocalityInterval", ",", "improveLocalityInterval", ",", "improveLocalityTimeUnit", ")", ";", "}", "}", "catch", "(", "Exception", "e", ")", "{", "if", "(", "log", ".", "isDebugEnabled", "(", ")", ")", "{", "log", ".", "debug", "(", "\"QueueListener.call caught an exception: {}\"", ",", "e", ".", "getMessage", "(", ")", ",", "e", ")", ";", "}", "subscriber", ".", "onError", "(", "e", ")", ";", "}", "}" ]
Setup subscriptions when the Observable subscription is set up. @param subscriber the subscriber
[ "Setup", "subscriptions", "when", "the", "Observable", "subscription", "is", "set", "up", "." ]
ca8081f52de17c46dce6ffdcb519eec600c5c93d
https://github.com/mp911de/spinach/blob/ca8081f52de17c46dce6ffdcb519eec600c5c93d/src/main/java/biz/paluch/spinach/cluster/QueueListener.java#L79-L114
9,818
mp911de/spinach
src/main/java/biz/paluch/spinach/cluster/QueueListener.java
QueueListener.close
public void close(long timeout, TimeUnit timeUnit) { disable(); for (GetJobsAction<K, V> getJobsAction : actions) { getJobsAction.close(timeout, timeUnit); } if (reconnectTrigger != null) { reconnectTrigger.unsubscribe(); reconnectTrigger = null; } }
java
public void close(long timeout, TimeUnit timeUnit) { disable(); for (GetJobsAction<K, V> getJobsAction : actions) { getJobsAction.close(timeout, timeUnit); } if (reconnectTrigger != null) { reconnectTrigger.unsubscribe(); reconnectTrigger = null; } }
[ "public", "void", "close", "(", "long", "timeout", ",", "TimeUnit", "timeUnit", ")", "{", "disable", "(", ")", ";", "for", "(", "GetJobsAction", "<", "K", ",", "V", ">", "getJobsAction", ":", "actions", ")", "{", "getJobsAction", ".", "close", "(", "timeout", ",", "timeUnit", ")", ";", "}", "if", "(", "reconnectTrigger", "!=", "null", ")", "{", "reconnectTrigger", ".", "unsubscribe", "(", ")", ";", "reconnectTrigger", "=", "null", ";", "}", "}" ]
Unsubscribe and close the resources. @param timeout @param timeUnit
[ "Unsubscribe", "and", "close", "the", "resources", "." ]
ca8081f52de17c46dce6ffdcb519eec600c5c93d
https://github.com/mp911de/spinach/blob/ca8081f52de17c46dce6ffdcb519eec600c5c93d/src/main/java/biz/paluch/spinach/cluster/QueueListener.java#L131-L143
9,819
wonderpush/wonderpush-android-sdk
sdk/src/main/java/com/wonderpush/sdk/WonderPushConfiguration.java
WonderPushConfiguration.getSharedPreferences
static SharedPreferences getSharedPreferences() { if (null == getApplicationContext()) return null; SharedPreferences rtn = getApplicationContext().getSharedPreferences(PREF_FILE, Context.MODE_PRIVATE); if (null == rtn) { Log.e(WonderPush.TAG, "Could not get shared preferences", new NullPointerException("Stack")); } return rtn; }
java
static SharedPreferences getSharedPreferences() { if (null == getApplicationContext()) return null; SharedPreferences rtn = getApplicationContext().getSharedPreferences(PREF_FILE, Context.MODE_PRIVATE); if (null == rtn) { Log.e(WonderPush.TAG, "Could not get shared preferences", new NullPointerException("Stack")); } return rtn; }
[ "static", "SharedPreferences", "getSharedPreferences", "(", ")", "{", "if", "(", "null", "==", "getApplicationContext", "(", ")", ")", "return", "null", ";", "SharedPreferences", "rtn", "=", "getApplicationContext", "(", ")", ".", "getSharedPreferences", "(", "PREF_FILE", ",", "Context", ".", "MODE_PRIVATE", ")", ";", "if", "(", "null", "==", "rtn", ")", "{", "Log", ".", "e", "(", "WonderPush", ".", "TAG", ",", "\"Could not get shared preferences\"", ",", "new", "NullPointerException", "(", "\"Stack\"", ")", ")", ";", "}", "return", "rtn", ";", "}" ]
Gets the WonderPush shared preferences for that application.
[ "Gets", "the", "WonderPush", "shared", "preferences", "for", "that", "application", "." ]
ba0a1568f705cdd6206639bfab1e5cf529084b59
https://github.com/wonderpush/wonderpush-android-sdk/blob/ba0a1568f705cdd6206639bfab1e5cf529084b59/sdk/src/main/java/com/wonderpush/sdk/WonderPushConfiguration.java#L217-L225
9,820
wonderpush/wonderpush-android-sdk
sdk/src/main/java/com/wonderpush/sdk/WonderPushConfiguration.java
WonderPushConfiguration.getAccessTokenForUserId
static String getAccessTokenForUserId(String userId) { if (userId == null && getUserId() == null || userId != null && userId.equals(getUserId())) { return getAccessToken(); } else { JSONObject usersArchive = getJSONObject(PER_USER_ARCHIVE_PREF_NAME); if (usersArchive == null) usersArchive = new JSONObject(); JSONObject userArchive = usersArchive.optJSONObject(userId == null ? "" : userId); if (userArchive == null) userArchive = new JSONObject(); return JSONUtil.optString(userArchive, ACCESS_TOKEN_PREF_NAME); } }
java
static String getAccessTokenForUserId(String userId) { if (userId == null && getUserId() == null || userId != null && userId.equals(getUserId())) { return getAccessToken(); } else { JSONObject usersArchive = getJSONObject(PER_USER_ARCHIVE_PREF_NAME); if (usersArchive == null) usersArchive = new JSONObject(); JSONObject userArchive = usersArchive.optJSONObject(userId == null ? "" : userId); if (userArchive == null) userArchive = new JSONObject(); return JSONUtil.optString(userArchive, ACCESS_TOKEN_PREF_NAME); } }
[ "static", "String", "getAccessTokenForUserId", "(", "String", "userId", ")", "{", "if", "(", "userId", "==", "null", "&&", "getUserId", "(", ")", "==", "null", "||", "userId", "!=", "null", "&&", "userId", ".", "equals", "(", "getUserId", "(", ")", ")", ")", "{", "return", "getAccessToken", "(", ")", ";", "}", "else", "{", "JSONObject", "usersArchive", "=", "getJSONObject", "(", "PER_USER_ARCHIVE_PREF_NAME", ")", ";", "if", "(", "usersArchive", "==", "null", ")", "usersArchive", "=", "new", "JSONObject", "(", ")", ";", "JSONObject", "userArchive", "=", "usersArchive", ".", "optJSONObject", "(", "userId", "==", "null", "?", "\"\"", ":", "userId", ")", ";", "if", "(", "userArchive", "==", "null", ")", "userArchive", "=", "new", "JSONObject", "(", ")", ";", "return", "JSONUtil", ".", "optString", "(", "userArchive", ",", "ACCESS_TOKEN_PREF_NAME", ")", ";", "}", "}" ]
Get the access token associated to a given user's shared preferences.
[ "Get", "the", "access", "token", "associated", "to", "a", "given", "user", "s", "shared", "preferences", "." ]
ba0a1568f705cdd6206639bfab1e5cf529084b59
https://github.com/wonderpush/wonderpush-android-sdk/blob/ba0a1568f705cdd6206639bfab1e5cf529084b59/sdk/src/main/java/com/wonderpush/sdk/WonderPushConfiguration.java#L390-L401
9,821
wonderpush/wonderpush-android-sdk
sdk/src/main/java/com/wonderpush/sdk/WonderPushConfiguration.java
WonderPushConfiguration.setOverrideSetLogging
static void setOverrideSetLogging(Boolean value) { if (value == null) { remove(OVERRIDE_SET_LOGGING_PREF_NAME); } else { putBoolean(OVERRIDE_SET_LOGGING_PREF_NAME, value); } }
java
static void setOverrideSetLogging(Boolean value) { if (value == null) { remove(OVERRIDE_SET_LOGGING_PREF_NAME); } else { putBoolean(OVERRIDE_SET_LOGGING_PREF_NAME, value); } }
[ "static", "void", "setOverrideSetLogging", "(", "Boolean", "value", ")", "{", "if", "(", "value", "==", "null", ")", "{", "remove", "(", "OVERRIDE_SET_LOGGING_PREF_NAME", ")", ";", "}", "else", "{", "putBoolean", "(", "OVERRIDE_SET_LOGGING_PREF_NAME", ",", "value", ")", ";", "}", "}" ]
Sets whether to override logging.
[ "Sets", "whether", "to", "override", "logging", "." ]
ba0a1568f705cdd6206639bfab1e5cf529084b59
https://github.com/wonderpush/wonderpush-android-sdk/blob/ba0a1568f705cdd6206639bfab1e5cf529084b59/sdk/src/main/java/com/wonderpush/sdk/WonderPushConfiguration.java#L900-L906
9,822
wonderpush/wonderpush-android-sdk
sdk/src/main/java/com/wonderpush/sdk/WonderPushConfiguration.java
WonderPushConfiguration.setOverrideNotificationReceipt
static void setOverrideNotificationReceipt(Boolean value) { if (value == null) { remove(OVERRIDE_NOTIFICATION_RECEIPT_PREF_NAME); } else { putBoolean(OVERRIDE_NOTIFICATION_RECEIPT_PREF_NAME, value); } }
java
static void setOverrideNotificationReceipt(Boolean value) { if (value == null) { remove(OVERRIDE_NOTIFICATION_RECEIPT_PREF_NAME); } else { putBoolean(OVERRIDE_NOTIFICATION_RECEIPT_PREF_NAME, value); } }
[ "static", "void", "setOverrideNotificationReceipt", "(", "Boolean", "value", ")", "{", "if", "(", "value", "==", "null", ")", "{", "remove", "(", "OVERRIDE_NOTIFICATION_RECEIPT_PREF_NAME", ")", ";", "}", "else", "{", "putBoolean", "(", "OVERRIDE_NOTIFICATION_RECEIPT_PREF_NAME", ",", "value", ")", ";", "}", "}" ]
Sets whether to override notification receipts.
[ "Sets", "whether", "to", "override", "notification", "receipts", "." ]
ba0a1568f705cdd6206639bfab1e5cf529084b59
https://github.com/wonderpush/wonderpush-android-sdk/blob/ba0a1568f705cdd6206639bfab1e5cf529084b59/sdk/src/main/java/com/wonderpush/sdk/WonderPushConfiguration.java#L919-L925
9,823
wonderpush/wonderpush-android-sdk
sdk/src/main/java/com/wonderpush/sdk/WonderPushRequestVault.java
WonderPushRequestVault.put
protected void put(WonderPushRestClient.Request request, long delayMs) { long notBeforeRealTimeElapsed = delayMs <= 0 ? delayMs : SystemClock.elapsedRealtime() + delayMs; long prevNotBeforeRealtimeElapsed = mJobQueue.peekNextJobNotBeforeRealtimeElapsed(); mJobQueue.postJobWithDescription(request.toJSON(), notBeforeRealTimeElapsed); if (notBeforeRealTimeElapsed < prevNotBeforeRealtimeElapsed) { WonderPush.logDebug("RequestVault: Interrupting sleep"); // Interrupt the worker thread so that it takes into account this new job in a timely manner mThread.interrupt(); } }
java
protected void put(WonderPushRestClient.Request request, long delayMs) { long notBeforeRealTimeElapsed = delayMs <= 0 ? delayMs : SystemClock.elapsedRealtime() + delayMs; long prevNotBeforeRealtimeElapsed = mJobQueue.peekNextJobNotBeforeRealtimeElapsed(); mJobQueue.postJobWithDescription(request.toJSON(), notBeforeRealTimeElapsed); if (notBeforeRealTimeElapsed < prevNotBeforeRealtimeElapsed) { WonderPush.logDebug("RequestVault: Interrupting sleep"); // Interrupt the worker thread so that it takes into account this new job in a timely manner mThread.interrupt(); } }
[ "protected", "void", "put", "(", "WonderPushRestClient", ".", "Request", "request", ",", "long", "delayMs", ")", "{", "long", "notBeforeRealTimeElapsed", "=", "delayMs", "<=", "0", "?", "delayMs", ":", "SystemClock", ".", "elapsedRealtime", "(", ")", "+", "delayMs", ";", "long", "prevNotBeforeRealtimeElapsed", "=", "mJobQueue", ".", "peekNextJobNotBeforeRealtimeElapsed", "(", ")", ";", "mJobQueue", ".", "postJobWithDescription", "(", "request", ".", "toJSON", "(", ")", ",", "notBeforeRealTimeElapsed", ")", ";", "if", "(", "notBeforeRealTimeElapsed", "<", "prevNotBeforeRealtimeElapsed", ")", "{", "WonderPush", ".", "logDebug", "(", "\"RequestVault: Interrupting sleep\"", ")", ";", "// Interrupt the worker thread so that it takes into account this new job in a timely manner", "mThread", ".", "interrupt", "(", ")", ";", "}", "}" ]
Save a request in the vault for future retry
[ "Save", "a", "request", "in", "the", "vault", "for", "future", "retry" ]
ba0a1568f705cdd6206639bfab1e5cf529084b59
https://github.com/wonderpush/wonderpush-android-sdk/blob/ba0a1568f705cdd6206639bfab1e5cf529084b59/sdk/src/main/java/com/wonderpush/sdk/WonderPushRequestVault.java#L59-L68
9,824
wonderpush/wonderpush-android-sdk
sdk/src/main/java/com/wonderpush/sdk/TimeSync.java
TimeSync.getTime
protected static long getTime() { // Initialization if (deviceDateToServerDateUncertainty == Long.MAX_VALUE) { deviceDateToServerDateUncertainty = WonderPushConfiguration.getDeviceDateSyncUncertainty(); deviceDateToServerDateOffset = WonderPushConfiguration.getDeviceDateSyncOffset(); } long currentTimeMillis = System.currentTimeMillis(); long elapsedRealtime = SystemClock.elapsedRealtime(); long startupToDeviceOffset = currentTimeMillis - elapsedRealtime; if (startupDateToDeviceDateOffset == Long.MAX_VALUE) { startupDateToDeviceDateOffset = startupToDeviceOffset; } // Check device date consistency with startup date if (Math.abs(startupToDeviceOffset - startupDateToDeviceDateOffset) > 1000) { // System time has jumped (by at least 1 second), or has drifted with regards to elapsedRealtime. // Apply the offset difference to resynchronize the "device" sync offset onto the new system date. deviceDateToServerDateOffset -= startupToDeviceOffset - startupDateToDeviceDateOffset; WonderPushConfiguration.setDeviceDateSyncOffset(deviceDateToServerDateOffset); startupDateToDeviceDateOffset = startupToDeviceOffset; } if (startupDateToServerDateUncertainty <= deviceDateToServerDateUncertainty // Don't use the startup date if it has not been synced, use and trust last device date sync && startupDateToServerDateUncertainty != Long.MAX_VALUE) { return elapsedRealtime + startupDateToServerDateOffset; } else { return currentTimeMillis + deviceDateToServerDateOffset; } }
java
protected static long getTime() { // Initialization if (deviceDateToServerDateUncertainty == Long.MAX_VALUE) { deviceDateToServerDateUncertainty = WonderPushConfiguration.getDeviceDateSyncUncertainty(); deviceDateToServerDateOffset = WonderPushConfiguration.getDeviceDateSyncOffset(); } long currentTimeMillis = System.currentTimeMillis(); long elapsedRealtime = SystemClock.elapsedRealtime(); long startupToDeviceOffset = currentTimeMillis - elapsedRealtime; if (startupDateToDeviceDateOffset == Long.MAX_VALUE) { startupDateToDeviceDateOffset = startupToDeviceOffset; } // Check device date consistency with startup date if (Math.abs(startupToDeviceOffset - startupDateToDeviceDateOffset) > 1000) { // System time has jumped (by at least 1 second), or has drifted with regards to elapsedRealtime. // Apply the offset difference to resynchronize the "device" sync offset onto the new system date. deviceDateToServerDateOffset -= startupToDeviceOffset - startupDateToDeviceDateOffset; WonderPushConfiguration.setDeviceDateSyncOffset(deviceDateToServerDateOffset); startupDateToDeviceDateOffset = startupToDeviceOffset; } if (startupDateToServerDateUncertainty <= deviceDateToServerDateUncertainty // Don't use the startup date if it has not been synced, use and trust last device date sync && startupDateToServerDateUncertainty != Long.MAX_VALUE) { return elapsedRealtime + startupDateToServerDateOffset; } else { return currentTimeMillis + deviceDateToServerDateOffset; } }
[ "protected", "static", "long", "getTime", "(", ")", "{", "// Initialization", "if", "(", "deviceDateToServerDateUncertainty", "==", "Long", ".", "MAX_VALUE", ")", "{", "deviceDateToServerDateUncertainty", "=", "WonderPushConfiguration", ".", "getDeviceDateSyncUncertainty", "(", ")", ";", "deviceDateToServerDateOffset", "=", "WonderPushConfiguration", ".", "getDeviceDateSyncOffset", "(", ")", ";", "}", "long", "currentTimeMillis", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "long", "elapsedRealtime", "=", "SystemClock", ".", "elapsedRealtime", "(", ")", ";", "long", "startupToDeviceOffset", "=", "currentTimeMillis", "-", "elapsedRealtime", ";", "if", "(", "startupDateToDeviceDateOffset", "==", "Long", ".", "MAX_VALUE", ")", "{", "startupDateToDeviceDateOffset", "=", "startupToDeviceOffset", ";", "}", "// Check device date consistency with startup date", "if", "(", "Math", ".", "abs", "(", "startupToDeviceOffset", "-", "startupDateToDeviceDateOffset", ")", ">", "1000", ")", "{", "// System time has jumped (by at least 1 second), or has drifted with regards to elapsedRealtime.", "// Apply the offset difference to resynchronize the \"device\" sync offset onto the new system date.", "deviceDateToServerDateOffset", "-=", "startupToDeviceOffset", "-", "startupDateToDeviceDateOffset", ";", "WonderPushConfiguration", ".", "setDeviceDateSyncOffset", "(", "deviceDateToServerDateOffset", ")", ";", "startupDateToDeviceDateOffset", "=", "startupToDeviceOffset", ";", "}", "if", "(", "startupDateToServerDateUncertainty", "<=", "deviceDateToServerDateUncertainty", "// Don't use the startup date if it has not been synced, use and trust last device date sync", "&&", "startupDateToServerDateUncertainty", "!=", "Long", ".", "MAX_VALUE", ")", "{", "return", "elapsedRealtime", "+", "startupDateToServerDateOffset", ";", "}", "else", "{", "return", "currentTimeMillis", "+", "deviceDateToServerDateOffset", ";", "}", "}" ]
Get the current timestamp in milliseconds, UTC. @return A timestamp in milliseconds
[ "Get", "the", "current", "timestamp", "in", "milliseconds", "UTC", "." ]
ba0a1568f705cdd6206639bfab1e5cf529084b59
https://github.com/wonderpush/wonderpush-android-sdk/blob/ba0a1568f705cdd6206639bfab1e5cf529084b59/sdk/src/main/java/com/wonderpush/sdk/TimeSync.java#L17-L46
9,825
wonderpush/wonderpush-android-sdk
sdk/src/main/java/com/wonderpush/sdk/TimeSync.java
TimeSync.syncTimeWithServer
protected static void syncTimeWithServer(long elapsedRealtimeSend, long elapsedRealtimeReceive, long serverDate, long serverTook) { if (serverDate == 0) { return; } // We have two synchronization sources: // - The "startup" sync, bound to the process lifecycle, using SystemClock.elapsedRealtime() // This time source cannot be messed up with. // It is only valid until the device reboots, at which time a new time origin is set. // - The "device" sync, bound to the system clock, using System.currentTimeMillis() // This time source is affected each time the user changes the date and time, // but it is not affected by timezone or daylight saving changes. // The "startup" sync must be saved into a "device" sync in order to persist between runs of the process. // The "startup" sync should only be stored in memory, and no attempt to count reboot should be taken. // Initialization if (deviceDateToServerDateUncertainty == Long.MAX_VALUE) { deviceDateToServerDateUncertainty = WonderPushConfiguration.getDeviceDateSyncUncertainty(); deviceDateToServerDateOffset = WonderPushConfiguration.getDeviceDateSyncOffset(); } long startupToDeviceOffset = System.currentTimeMillis() - SystemClock.elapsedRealtime(); if (startupDateToDeviceDateOffset == Long.MAX_VALUE) { startupDateToDeviceDateOffset = startupToDeviceOffset; } long uncertainty = (elapsedRealtimeReceive - elapsedRealtimeSend - serverTook) / 2; long offset = serverDate + serverTook / 2 - (elapsedRealtimeSend + elapsedRealtimeReceive) / 2; // We must improve the quality of the "startup" sync. We can trust elaspedRealtime() based measures. if ( // Case 1. Lower uncertainty uncertainty < startupDateToServerDateUncertainty // Case 2. Additional check for exceptional server-side time gaps // Calculate whether the two offsets agree within the total uncertainty limit || Math.abs(offset - startupDateToServerDateOffset) > uncertainty+startupDateToServerDateUncertainty // note the RHS overflows with the Long.MAX_VALUE initialization, but case 1 handles that ) { // Case 1. Take the new, more accurate synchronization // Case 2. Forget the old synchronization, time have changed too much startupDateToServerDateOffset = offset; startupDateToServerDateUncertainty = uncertainty; } // We must detect whether the "device" sync is still valid, otherwise we must update it. if ( // Case 1. Lower uncertainty startupDateToServerDateUncertainty < deviceDateToServerDateUncertainty // Case 2. Local clock was updated, or the two time sources have drifted from each other || Math.abs(startupToDeviceOffset - startupDateToDeviceDateOffset) > startupDateToServerDateUncertainty // Case 3. Time gap between the "startup" and "device" sync || Math.abs(deviceDateToServerDateOffset - (startupDateToServerDateOffset - startupDateToDeviceDateOffset)) > deviceDateToServerDateUncertainty + startupDateToServerDateUncertainty // note the RHS overflows with the Long.MAX_VALUE initialization, but case 1 handles that ) { deviceDateToServerDateOffset = startupDateToServerDateOffset - startupDateToDeviceDateOffset; deviceDateToServerDateUncertainty = startupDateToServerDateUncertainty; WonderPushConfiguration.setDeviceDateSyncOffset(deviceDateToServerDateOffset); WonderPushConfiguration.setDeviceDateSyncUncertainty(deviceDateToServerDateUncertainty); } }
java
protected static void syncTimeWithServer(long elapsedRealtimeSend, long elapsedRealtimeReceive, long serverDate, long serverTook) { if (serverDate == 0) { return; } // We have two synchronization sources: // - The "startup" sync, bound to the process lifecycle, using SystemClock.elapsedRealtime() // This time source cannot be messed up with. // It is only valid until the device reboots, at which time a new time origin is set. // - The "device" sync, bound to the system clock, using System.currentTimeMillis() // This time source is affected each time the user changes the date and time, // but it is not affected by timezone or daylight saving changes. // The "startup" sync must be saved into a "device" sync in order to persist between runs of the process. // The "startup" sync should only be stored in memory, and no attempt to count reboot should be taken. // Initialization if (deviceDateToServerDateUncertainty == Long.MAX_VALUE) { deviceDateToServerDateUncertainty = WonderPushConfiguration.getDeviceDateSyncUncertainty(); deviceDateToServerDateOffset = WonderPushConfiguration.getDeviceDateSyncOffset(); } long startupToDeviceOffset = System.currentTimeMillis() - SystemClock.elapsedRealtime(); if (startupDateToDeviceDateOffset == Long.MAX_VALUE) { startupDateToDeviceDateOffset = startupToDeviceOffset; } long uncertainty = (elapsedRealtimeReceive - elapsedRealtimeSend - serverTook) / 2; long offset = serverDate + serverTook / 2 - (elapsedRealtimeSend + elapsedRealtimeReceive) / 2; // We must improve the quality of the "startup" sync. We can trust elaspedRealtime() based measures. if ( // Case 1. Lower uncertainty uncertainty < startupDateToServerDateUncertainty // Case 2. Additional check for exceptional server-side time gaps // Calculate whether the two offsets agree within the total uncertainty limit || Math.abs(offset - startupDateToServerDateOffset) > uncertainty+startupDateToServerDateUncertainty // note the RHS overflows with the Long.MAX_VALUE initialization, but case 1 handles that ) { // Case 1. Take the new, more accurate synchronization // Case 2. Forget the old synchronization, time have changed too much startupDateToServerDateOffset = offset; startupDateToServerDateUncertainty = uncertainty; } // We must detect whether the "device" sync is still valid, otherwise we must update it. if ( // Case 1. Lower uncertainty startupDateToServerDateUncertainty < deviceDateToServerDateUncertainty // Case 2. Local clock was updated, or the two time sources have drifted from each other || Math.abs(startupToDeviceOffset - startupDateToDeviceDateOffset) > startupDateToServerDateUncertainty // Case 3. Time gap between the "startup" and "device" sync || Math.abs(deviceDateToServerDateOffset - (startupDateToServerDateOffset - startupDateToDeviceDateOffset)) > deviceDateToServerDateUncertainty + startupDateToServerDateUncertainty // note the RHS overflows with the Long.MAX_VALUE initialization, but case 1 handles that ) { deviceDateToServerDateOffset = startupDateToServerDateOffset - startupDateToDeviceDateOffset; deviceDateToServerDateUncertainty = startupDateToServerDateUncertainty; WonderPushConfiguration.setDeviceDateSyncOffset(deviceDateToServerDateOffset); WonderPushConfiguration.setDeviceDateSyncUncertainty(deviceDateToServerDateUncertainty); } }
[ "protected", "static", "void", "syncTimeWithServer", "(", "long", "elapsedRealtimeSend", ",", "long", "elapsedRealtimeReceive", ",", "long", "serverDate", ",", "long", "serverTook", ")", "{", "if", "(", "serverDate", "==", "0", ")", "{", "return", ";", "}", "// We have two synchronization sources:", "// - The \"startup\" sync, bound to the process lifecycle, using SystemClock.elapsedRealtime()", "// This time source cannot be messed up with.", "// It is only valid until the device reboots, at which time a new time origin is set.", "// - The \"device\" sync, bound to the system clock, using System.currentTimeMillis()", "// This time source is affected each time the user changes the date and time,", "// but it is not affected by timezone or daylight saving changes.", "// The \"startup\" sync must be saved into a \"device\" sync in order to persist between runs of the process.", "// The \"startup\" sync should only be stored in memory, and no attempt to count reboot should be taken.", "// Initialization", "if", "(", "deviceDateToServerDateUncertainty", "==", "Long", ".", "MAX_VALUE", ")", "{", "deviceDateToServerDateUncertainty", "=", "WonderPushConfiguration", ".", "getDeviceDateSyncUncertainty", "(", ")", ";", "deviceDateToServerDateOffset", "=", "WonderPushConfiguration", ".", "getDeviceDateSyncOffset", "(", ")", ";", "}", "long", "startupToDeviceOffset", "=", "System", ".", "currentTimeMillis", "(", ")", "-", "SystemClock", ".", "elapsedRealtime", "(", ")", ";", "if", "(", "startupDateToDeviceDateOffset", "==", "Long", ".", "MAX_VALUE", ")", "{", "startupDateToDeviceDateOffset", "=", "startupToDeviceOffset", ";", "}", "long", "uncertainty", "=", "(", "elapsedRealtimeReceive", "-", "elapsedRealtimeSend", "-", "serverTook", ")", "/", "2", ";", "long", "offset", "=", "serverDate", "+", "serverTook", "/", "2", "-", "(", "elapsedRealtimeSend", "+", "elapsedRealtimeReceive", ")", "/", "2", ";", "// We must improve the quality of the \"startup\" sync. We can trust elaspedRealtime() based measures.", "if", "(", "// Case 1. Lower uncertainty", "uncertainty", "<", "startupDateToServerDateUncertainty", "// Case 2. Additional check for exceptional server-side time gaps", "// Calculate whether the two offsets agree within the total uncertainty limit", "||", "Math", ".", "abs", "(", "offset", "-", "startupDateToServerDateOffset", ")", ">", "uncertainty", "+", "startupDateToServerDateUncertainty", "// note the RHS overflows with the Long.MAX_VALUE initialization, but case 1 handles that", ")", "{", "// Case 1. Take the new, more accurate synchronization", "// Case 2. Forget the old synchronization, time have changed too much", "startupDateToServerDateOffset", "=", "offset", ";", "startupDateToServerDateUncertainty", "=", "uncertainty", ";", "}", "// We must detect whether the \"device\" sync is still valid, otherwise we must update it.", "if", "(", "// Case 1. Lower uncertainty", "startupDateToServerDateUncertainty", "<", "deviceDateToServerDateUncertainty", "// Case 2. Local clock was updated, or the two time sources have drifted from each other", "||", "Math", ".", "abs", "(", "startupToDeviceOffset", "-", "startupDateToDeviceDateOffset", ")", ">", "startupDateToServerDateUncertainty", "// Case 3. Time gap between the \"startup\" and \"device\" sync", "||", "Math", ".", "abs", "(", "deviceDateToServerDateOffset", "-", "(", "startupDateToServerDateOffset", "-", "startupDateToDeviceDateOffset", ")", ")", ">", "deviceDateToServerDateUncertainty", "+", "startupDateToServerDateUncertainty", "// note the RHS overflows with the Long.MAX_VALUE initialization, but case 1 handles that", ")", "{", "deviceDateToServerDateOffset", "=", "startupDateToServerDateOffset", "-", "startupDateToDeviceDateOffset", ";", "deviceDateToServerDateUncertainty", "=", "startupDateToServerDateUncertainty", ";", "WonderPushConfiguration", ".", "setDeviceDateSyncOffset", "(", "deviceDateToServerDateOffset", ")", ";", "WonderPushConfiguration", ".", "setDeviceDateSyncUncertainty", "(", "deviceDateToServerDateUncertainty", ")", ";", "}", "}" ]
Synchronize time with the WonderPush servers. @param elapsedRealtimeSend The time at which the request was sent. @param elapsedRealtimeReceive The time at which the response was received. @param serverDate The time at which the server received the request, as read in the response. @param serverTook The time the server took to process the request, as read in the response.
[ "Synchronize", "time", "with", "the", "WonderPush", "servers", "." ]
ba0a1568f705cdd6206639bfab1e5cf529084b59
https://github.com/wonderpush/wonderpush-android-sdk/blob/ba0a1568f705cdd6206639bfab1e5cf529084b59/sdk/src/main/java/com/wonderpush/sdk/TimeSync.java#L59-L119
9,826
wonderpush/wonderpush-android-sdk
sdk/src/main/java/com/wonderpush/sdk/DataManager.java
DataManager.downloadAllData
static boolean downloadAllData() { String data; try { data = export().get(); } catch (InterruptedException ex) { Log.e(WonderPush.TAG, "Unexpected error while exporting data", ex); return false; } catch (ExecutionException ex) { Log.e(WonderPush.TAG, "Unexpected error while exporting data", ex); return false; } try { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); File folder = new File(WonderPush.getApplicationContext().getFilesDir(), "exports"); folder.mkdirs(); String fn = "wonderpush-android-dataexport-" + sdf.format(new Date()) + ".json"; File f = new File(folder, fn); OutputStream os = new FileOutputStream(f); os.write(data.getBytes()); os.close(); File fz = new File(folder, fn + ".zip"); ZipOutputStream osz = new ZipOutputStream(new FileOutputStream(fz)); osz.putNextEntry(new ZipEntry(fn)); osz.write(data.getBytes()); osz.closeEntry(); osz.finish(); osz.close(); Uri uri = FileProvider.getUriForFile(WonderPush.getApplicationContext(), WonderPush.getApplicationContext().getPackageName() + ".wonderpush.fileprovider", fz); Intent sendIntent = new Intent(); sendIntent.setAction(Intent.ACTION_SEND); sendIntent.putExtra(Intent.EXTRA_STREAM, uri); sendIntent.setType("application/zip"); sendIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); WonderPush.getApplicationContext().startActivity(Intent.createChooser(sendIntent, WonderPush.getApplicationContext().getResources().getText(R.string.wonderpush_export_data_chooser))); return true; } catch (Exception ex) { Log.e(WonderPush.TAG, "Unexpected error while exporting data", ex); return false; } }
java
static boolean downloadAllData() { String data; try { data = export().get(); } catch (InterruptedException ex) { Log.e(WonderPush.TAG, "Unexpected error while exporting data", ex); return false; } catch (ExecutionException ex) { Log.e(WonderPush.TAG, "Unexpected error while exporting data", ex); return false; } try { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); File folder = new File(WonderPush.getApplicationContext().getFilesDir(), "exports"); folder.mkdirs(); String fn = "wonderpush-android-dataexport-" + sdf.format(new Date()) + ".json"; File f = new File(folder, fn); OutputStream os = new FileOutputStream(f); os.write(data.getBytes()); os.close(); File fz = new File(folder, fn + ".zip"); ZipOutputStream osz = new ZipOutputStream(new FileOutputStream(fz)); osz.putNextEntry(new ZipEntry(fn)); osz.write(data.getBytes()); osz.closeEntry(); osz.finish(); osz.close(); Uri uri = FileProvider.getUriForFile(WonderPush.getApplicationContext(), WonderPush.getApplicationContext().getPackageName() + ".wonderpush.fileprovider", fz); Intent sendIntent = new Intent(); sendIntent.setAction(Intent.ACTION_SEND); sendIntent.putExtra(Intent.EXTRA_STREAM, uri); sendIntent.setType("application/zip"); sendIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); WonderPush.getApplicationContext().startActivity(Intent.createChooser(sendIntent, WonderPush.getApplicationContext().getResources().getText(R.string.wonderpush_export_data_chooser))); return true; } catch (Exception ex) { Log.e(WonderPush.TAG, "Unexpected error while exporting data", ex); return false; } }
[ "static", "boolean", "downloadAllData", "(", ")", "{", "String", "data", ";", "try", "{", "data", "=", "export", "(", ")", ".", "get", "(", ")", ";", "}", "catch", "(", "InterruptedException", "ex", ")", "{", "Log", ".", "e", "(", "WonderPush", ".", "TAG", ",", "\"Unexpected error while exporting data\"", ",", "ex", ")", ";", "return", "false", ";", "}", "catch", "(", "ExecutionException", "ex", ")", "{", "Log", ".", "e", "(", "WonderPush", ".", "TAG", ",", "\"Unexpected error while exporting data\"", ",", "ex", ")", ";", "return", "false", ";", "}", "try", "{", "SimpleDateFormat", "sdf", "=", "new", "SimpleDateFormat", "(", "\"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'\"", ",", "Locale", ".", "US", ")", ";", "sdf", ".", "setTimeZone", "(", "TimeZone", ".", "getTimeZone", "(", "\"UTC\"", ")", ")", ";", "File", "folder", "=", "new", "File", "(", "WonderPush", ".", "getApplicationContext", "(", ")", ".", "getFilesDir", "(", ")", ",", "\"exports\"", ")", ";", "folder", ".", "mkdirs", "(", ")", ";", "String", "fn", "=", "\"wonderpush-android-dataexport-\"", "+", "sdf", ".", "format", "(", "new", "Date", "(", ")", ")", "+", "\".json\"", ";", "File", "f", "=", "new", "File", "(", "folder", ",", "fn", ")", ";", "OutputStream", "os", "=", "new", "FileOutputStream", "(", "f", ")", ";", "os", ".", "write", "(", "data", ".", "getBytes", "(", ")", ")", ";", "os", ".", "close", "(", ")", ";", "File", "fz", "=", "new", "File", "(", "folder", ",", "fn", "+", "\".zip\"", ")", ";", "ZipOutputStream", "osz", "=", "new", "ZipOutputStream", "(", "new", "FileOutputStream", "(", "fz", ")", ")", ";", "osz", ".", "putNextEntry", "(", "new", "ZipEntry", "(", "fn", ")", ")", ";", "osz", ".", "write", "(", "data", ".", "getBytes", "(", ")", ")", ";", "osz", ".", "closeEntry", "(", ")", ";", "osz", ".", "finish", "(", ")", ";", "osz", ".", "close", "(", ")", ";", "Uri", "uri", "=", "FileProvider", ".", "getUriForFile", "(", "WonderPush", ".", "getApplicationContext", "(", ")", ",", "WonderPush", ".", "getApplicationContext", "(", ")", ".", "getPackageName", "(", ")", "+", "\".wonderpush.fileprovider\"", ",", "fz", ")", ";", "Intent", "sendIntent", "=", "new", "Intent", "(", ")", ";", "sendIntent", ".", "setAction", "(", "Intent", ".", "ACTION_SEND", ")", ";", "sendIntent", ".", "putExtra", "(", "Intent", ".", "EXTRA_STREAM", ",", "uri", ")", ";", "sendIntent", ".", "setType", "(", "\"application/zip\"", ")", ";", "sendIntent", ".", "addFlags", "(", "Intent", ".", "FLAG_GRANT_READ_URI_PERMISSION", ")", ";", "WonderPush", ".", "getApplicationContext", "(", ")", ".", "startActivity", "(", "Intent", ".", "createChooser", "(", "sendIntent", ",", "WonderPush", ".", "getApplicationContext", "(", ")", ".", "getResources", "(", ")", ".", "getText", "(", "R", ".", "string", ".", "wonderpush_export_data_chooser", ")", ")", ")", ";", "return", "true", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "Log", ".", "e", "(", "WonderPush", ".", "TAG", ",", "\"Unexpected error while exporting data\"", ",", "ex", ")", ";", "return", "false", ";", "}", "}" ]
Blocks until interrupted or completed. @return {@code true} if successfully called startActivity() with a sharing intent.
[ "Blocks", "until", "interrupted", "or", "completed", "." ]
ba0a1568f705cdd6206639bfab1e5cf529084b59
https://github.com/wonderpush/wonderpush-android-sdk/blob/ba0a1568f705cdd6206639bfab1e5cf529084b59/sdk/src/main/java/com/wonderpush/sdk/DataManager.java#L191-L234
9,827
wonderpush/wonderpush-android-sdk
sdk/src/main/java/com/wonderpush/sdk/WonderPushRestClient.java
WonderPushRestClient.get
protected static void get(String resource, RequestParams params, ResponseHandler responseHandler) { requestAuthenticated(new Request(WonderPushConfiguration.getUserId(), HttpMethod.GET, resource, params, responseHandler)); }
java
protected static void get(String resource, RequestParams params, ResponseHandler responseHandler) { requestAuthenticated(new Request(WonderPushConfiguration.getUserId(), HttpMethod.GET, resource, params, responseHandler)); }
[ "protected", "static", "void", "get", "(", "String", "resource", ",", "RequestParams", "params", ",", "ResponseHandler", "responseHandler", ")", "{", "requestAuthenticated", "(", "new", "Request", "(", "WonderPushConfiguration", ".", "getUserId", "(", ")", ",", "HttpMethod", ".", "GET", ",", "resource", ",", "params", ",", "responseHandler", ")", ")", ";", "}" ]
A GET request @param resource The resource path, starting with / @param params AsyncHttpClient request parameters @param responseHandler An AsyncHttpClient response handler
[ "A", "GET", "request" ]
ba0a1568f705cdd6206639bfab1e5cf529084b59
https://github.com/wonderpush/wonderpush-android-sdk/blob/ba0a1568f705cdd6206639bfab1e5cf529084b59/sdk/src/main/java/com/wonderpush/sdk/WonderPushRestClient.java#L87-L89
9,828
wonderpush/wonderpush-android-sdk
sdk/src/main/java/com/wonderpush/sdk/WonderPushRestClient.java
WonderPushRestClient.post
protected static void post(String resource, RequestParams params, ResponseHandler responseHandler) { requestAuthenticated(new Request(WonderPushConfiguration.getUserId(), HttpMethod.POST, resource, params, responseHandler)); }
java
protected static void post(String resource, RequestParams params, ResponseHandler responseHandler) { requestAuthenticated(new Request(WonderPushConfiguration.getUserId(), HttpMethod.POST, resource, params, responseHandler)); }
[ "protected", "static", "void", "post", "(", "String", "resource", ",", "RequestParams", "params", ",", "ResponseHandler", "responseHandler", ")", "{", "requestAuthenticated", "(", "new", "Request", "(", "WonderPushConfiguration", ".", "getUserId", "(", ")", ",", "HttpMethod", ".", "POST", ",", "resource", ",", "params", ",", "responseHandler", ")", ")", ";", "}" ]
A POST request @param resource The resource path, starting with / @param params AsyncHttpClient request parameters @param responseHandler An AsyncHttpClient response handler
[ "A", "POST", "request" ]
ba0a1568f705cdd6206639bfab1e5cf529084b59
https://github.com/wonderpush/wonderpush-android-sdk/blob/ba0a1568f705cdd6206639bfab1e5cf529084b59/sdk/src/main/java/com/wonderpush/sdk/WonderPushRestClient.java#L101-L103
9,829
wonderpush/wonderpush-android-sdk
sdk/src/main/java/com/wonderpush/sdk/WonderPushRestClient.java
WonderPushRestClient.postEventually
protected static void postEventually(String resource, RequestParams params) { final Request request = new Request(WonderPushConfiguration.getUserId(), HttpMethod.POST, resource, params, null); WonderPushRequestVault.getDefaultVault().put(request, 0); }
java
protected static void postEventually(String resource, RequestParams params) { final Request request = new Request(WonderPushConfiguration.getUserId(), HttpMethod.POST, resource, params, null); WonderPushRequestVault.getDefaultVault().put(request, 0); }
[ "protected", "static", "void", "postEventually", "(", "String", "resource", ",", "RequestParams", "params", ")", "{", "final", "Request", "request", "=", "new", "Request", "(", "WonderPushConfiguration", ".", "getUserId", "(", ")", ",", "HttpMethod", ".", "POST", ",", "resource", ",", "params", ",", "null", ")", ";", "WonderPushRequestVault", ".", "getDefaultVault", "(", ")", ".", "put", "(", "request", ",", "0", ")", ";", "}" ]
A POST request that is guaranteed to be executed when a network connection is present, surviving application reboot. The responseHandler will be called only if the network is present when the request is first run. @param resource The resource path, starting with / @param params AsyncHttpClient request parameters
[ "A", "POST", "request", "that", "is", "guaranteed", "to", "be", "executed", "when", "a", "network", "connection", "is", "present", "surviving", "application", "reboot", ".", "The", "responseHandler", "will", "be", "called", "only", "if", "the", "network", "is", "present", "when", "the", "request", "is", "first", "run", "." ]
ba0a1568f705cdd6206639bfab1e5cf529084b59
https://github.com/wonderpush/wonderpush-android-sdk/blob/ba0a1568f705cdd6206639bfab1e5cf529084b59/sdk/src/main/java/com/wonderpush/sdk/WonderPushRestClient.java#L115-L118
9,830
wonderpush/wonderpush-android-sdk
sdk/src/main/java/com/wonderpush/sdk/WonderPushRestClient.java
WonderPushRestClient.put
protected static void put(String resource, RequestParams params, ResponseHandler responseHandler) { requestAuthenticated(new Request(WonderPushConfiguration.getUserId(), HttpMethod.PUT, resource, params, responseHandler)); }
java
protected static void put(String resource, RequestParams params, ResponseHandler responseHandler) { requestAuthenticated(new Request(WonderPushConfiguration.getUserId(), HttpMethod.PUT, resource, params, responseHandler)); }
[ "protected", "static", "void", "put", "(", "String", "resource", ",", "RequestParams", "params", ",", "ResponseHandler", "responseHandler", ")", "{", "requestAuthenticated", "(", "new", "Request", "(", "WonderPushConfiguration", ".", "getUserId", "(", ")", ",", "HttpMethod", ".", "PUT", ",", "resource", ",", "params", ",", "responseHandler", ")", ")", ";", "}" ]
A PUT request @param resource The resource path, starting with / @param params AsyncHttpClient request parameters @param responseHandler An AsyncHttpClient response handler
[ "A", "PUT", "request" ]
ba0a1568f705cdd6206639bfab1e5cf529084b59
https://github.com/wonderpush/wonderpush-android-sdk/blob/ba0a1568f705cdd6206639bfab1e5cf529084b59/sdk/src/main/java/com/wonderpush/sdk/WonderPushRestClient.java#L130-L132
9,831
wonderpush/wonderpush-android-sdk
sdk/src/main/java/com/wonderpush/sdk/WonderPushRestClient.java
WonderPushRestClient.delete
protected static void delete(String resource, ResponseHandler responseHandler) { requestAuthenticated(new Request(WonderPushConfiguration.getUserId(), HttpMethod.DELETE, resource, null, responseHandler)); }
java
protected static void delete(String resource, ResponseHandler responseHandler) { requestAuthenticated(new Request(WonderPushConfiguration.getUserId(), HttpMethod.DELETE, resource, null, responseHandler)); }
[ "protected", "static", "void", "delete", "(", "String", "resource", ",", "ResponseHandler", "responseHandler", ")", "{", "requestAuthenticated", "(", "new", "Request", "(", "WonderPushConfiguration", ".", "getUserId", "(", ")", ",", "HttpMethod", ".", "DELETE", ",", "resource", ",", "null", ",", "responseHandler", ")", ")", ";", "}" ]
A DELETE request @param resource The resource path, starting with / @param responseHandler An AsyncHttpClient response handler
[ "A", "DELETE", "request" ]
ba0a1568f705cdd6206639bfab1e5cf529084b59
https://github.com/wonderpush/wonderpush-android-sdk/blob/ba0a1568f705cdd6206639bfab1e5cf529084b59/sdk/src/main/java/com/wonderpush/sdk/WonderPushRestClient.java#L142-L144
9,832
wonderpush/wonderpush-android-sdk
sdk/src/main/java/com/wonderpush/sdk/WonderPushRestClient.java
WonderPushRestClient.fetchAnonymousAccessTokenIfNeeded
protected static boolean fetchAnonymousAccessTokenIfNeeded(final String userId, final ResponseHandler onFetchedHandler) { if (!WonderPush.isInitialized()) { // Note: Could use WonderPush.safeDefer() here but as we require consent to proceed, // let's use WonderPush.safeDeferWithConsent() to additionally passively wait for SDK initialization. WonderPush.safeDeferWithConsent(new Runnable() { @Override public void run() { if (!fetchAnonymousAccessTokenIfNeeded(userId, onFetchedHandler)) { // Call the handler anyway onFetchedHandler.onSuccess(null); } } }, null); return true; // true: the handler will be called } if (null == WonderPushConfiguration.getAccessToken()) { fetchAnonymousAccessToken(userId, onFetchedHandler); return true; } return false; }
java
protected static boolean fetchAnonymousAccessTokenIfNeeded(final String userId, final ResponseHandler onFetchedHandler) { if (!WonderPush.isInitialized()) { // Note: Could use WonderPush.safeDefer() here but as we require consent to proceed, // let's use WonderPush.safeDeferWithConsent() to additionally passively wait for SDK initialization. WonderPush.safeDeferWithConsent(new Runnable() { @Override public void run() { if (!fetchAnonymousAccessTokenIfNeeded(userId, onFetchedHandler)) { // Call the handler anyway onFetchedHandler.onSuccess(null); } } }, null); return true; // true: the handler will be called } if (null == WonderPushConfiguration.getAccessToken()) { fetchAnonymousAccessToken(userId, onFetchedHandler); return true; } return false; }
[ "protected", "static", "boolean", "fetchAnonymousAccessTokenIfNeeded", "(", "final", "String", "userId", ",", "final", "ResponseHandler", "onFetchedHandler", ")", "{", "if", "(", "!", "WonderPush", ".", "isInitialized", "(", ")", ")", "{", "// Note: Could use WonderPush.safeDefer() here but as we require consent to proceed,", "// let's use WonderPush.safeDeferWithConsent() to additionally passively wait for SDK initialization.", "WonderPush", ".", "safeDeferWithConsent", "(", "new", "Runnable", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "if", "(", "!", "fetchAnonymousAccessTokenIfNeeded", "(", "userId", ",", "onFetchedHandler", ")", ")", "{", "// Call the handler anyway", "onFetchedHandler", ".", "onSuccess", "(", "null", ")", ";", "}", "}", "}", ",", "null", ")", ";", "return", "true", ";", "// true: the handler will be called", "}", "if", "(", "null", "==", "WonderPushConfiguration", ".", "getAccessToken", "(", ")", ")", "{", "fetchAnonymousAccessToken", "(", "userId", ",", "onFetchedHandler", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
If no access token is found in the user's preferences, fetch an anonymous access token. @param onFetchedHandler A handler called if a request to fetch an access token has been executed successfully, never called if retrieved from cache @return Whether or not a request has been executed to fetch an anonymous access token (true fetching, false retrieved from local cache)
[ "If", "no", "access", "token", "is", "found", "in", "the", "user", "s", "preferences", "fetch", "an", "anonymous", "access", "token", "." ]
ba0a1568f705cdd6206639bfab1e5cf529084b59
https://github.com/wonderpush/wonderpush-android-sdk/blob/ba0a1568f705cdd6206639bfab1e5cf529084b59/sdk/src/main/java/com/wonderpush/sdk/WonderPushRestClient.java#L155-L176
9,833
wonderpush/wonderpush-android-sdk
sdk/src/main/java/com/wonderpush/sdk/WonderPushRestClient.java
WonderPushRestClient.fetchAnonymousAccessTokenAndRunRequest
protected static void fetchAnonymousAccessTokenAndRunRequest(final Request request) { fetchAnonymousAccessToken(request.getUserId(), new ResponseHandler() { @Override public void onSuccess(Response response) { requestAuthenticated(request); } @Override public void onFailure(Throwable e, Response errorResponse) { } }); }
java
protected static void fetchAnonymousAccessTokenAndRunRequest(final Request request) { fetchAnonymousAccessToken(request.getUserId(), new ResponseHandler() { @Override public void onSuccess(Response response) { requestAuthenticated(request); } @Override public void onFailure(Throwable e, Response errorResponse) { } }); }
[ "protected", "static", "void", "fetchAnonymousAccessTokenAndRunRequest", "(", "final", "Request", "request", ")", "{", "fetchAnonymousAccessToken", "(", "request", ".", "getUserId", "(", ")", ",", "new", "ResponseHandler", "(", ")", "{", "@", "Override", "public", "void", "onSuccess", "(", "Response", "response", ")", "{", "requestAuthenticated", "(", "request", ")", ";", "}", "@", "Override", "public", "void", "onFailure", "(", "Throwable", "e", ",", "Response", "errorResponse", ")", "{", "}", "}", ")", ";", "}" ]
Fetches an anonymous access token and run the given request with that token. Retries when access token cannot be fetched. @param request The request to be run
[ "Fetches", "an", "anonymous", "access", "token", "and", "run", "the", "given", "request", "with", "that", "token", ".", "Retries", "when", "access", "token", "cannot", "be", "fetched", "." ]
ba0a1568f705cdd6206639bfab1e5cf529084b59
https://github.com/wonderpush/wonderpush-android-sdk/blob/ba0a1568f705cdd6206639bfab1e5cf529084b59/sdk/src/main/java/com/wonderpush/sdk/WonderPushRestClient.java#L530-L541
9,834
wonderpush/wonderpush-android-sdk
sdk/src/main/java/com/wonderpush/sdk/WonderPushUserPreferences.java
WonderPushUserPreferences.setDefaultChannelId
public static synchronized void setDefaultChannelId(String id) { try { if (_setDefaultChannelId(id)) { save(); } } catch (Exception ex) { Log.e(WonderPush.TAG, "Unexpected error while setting default channel id to " + id, ex); } }
java
public static synchronized void setDefaultChannelId(String id) { try { if (_setDefaultChannelId(id)) { save(); } } catch (Exception ex) { Log.e(WonderPush.TAG, "Unexpected error while setting default channel id to " + id, ex); } }
[ "public", "static", "synchronized", "void", "setDefaultChannelId", "(", "String", "id", ")", "{", "try", "{", "if", "(", "_setDefaultChannelId", "(", "id", ")", ")", "{", "save", "(", ")", ";", "}", "}", "catch", "(", "Exception", "ex", ")", "{", "Log", ".", "e", "(", "WonderPush", ".", "TAG", ",", "\"Unexpected error while setting default channel id to \"", "+", "id", ",", "ex", ")", ";", "}", "}" ]
Set the default channel id. <p> This function does not enforce the existence of the given channel until a notification is to be posted to the default channel. This way you are free to call this function either before or after creating the given channel, either using this class or directly using Android O APIs. </p> @param id The identifier of the default channel.
[ "Set", "the", "default", "channel", "id", "." ]
ba0a1568f705cdd6206639bfab1e5cf529084b59
https://github.com/wonderpush/wonderpush-android-sdk/blob/ba0a1568f705cdd6206639bfab1e5cf529084b59/sdk/src/main/java/com/wonderpush/sdk/WonderPushUserPreferences.java#L183-L191
9,835
wonderpush/wonderpush-android-sdk
sdk/src/main/java/com/wonderpush/sdk/WonderPushUserPreferences.java
WonderPushUserPreferences.getChannelGroup
public static synchronized WonderPushChannelGroup getChannelGroup(String groupId) { try { WonderPushChannelGroup rtn = sChannelGroups.get(groupId); if (rtn != null) { try { rtn = (WonderPushChannelGroup) rtn.clone(); } catch (CloneNotSupportedException ex) { Log.e(WonderPush.TAG, "Unexpected error while cloning gotten channel group " + rtn, ex); return null; } } return rtn; } catch (Exception ex) { Log.e(WonderPush.TAG, "Unexpected error while getting channel group " + groupId, ex); return null; } }
java
public static synchronized WonderPushChannelGroup getChannelGroup(String groupId) { try { WonderPushChannelGroup rtn = sChannelGroups.get(groupId); if (rtn != null) { try { rtn = (WonderPushChannelGroup) rtn.clone(); } catch (CloneNotSupportedException ex) { Log.e(WonderPush.TAG, "Unexpected error while cloning gotten channel group " + rtn, ex); return null; } } return rtn; } catch (Exception ex) { Log.e(WonderPush.TAG, "Unexpected error while getting channel group " + groupId, ex); return null; } }
[ "public", "static", "synchronized", "WonderPushChannelGroup", "getChannelGroup", "(", "String", "groupId", ")", "{", "try", "{", "WonderPushChannelGroup", "rtn", "=", "sChannelGroups", ".", "get", "(", "groupId", ")", ";", "if", "(", "rtn", "!=", "null", ")", "{", "try", "{", "rtn", "=", "(", "WonderPushChannelGroup", ")", "rtn", ".", "clone", "(", ")", ";", "}", "catch", "(", "CloneNotSupportedException", "ex", ")", "{", "Log", ".", "e", "(", "WonderPush", ".", "TAG", ",", "\"Unexpected error while cloning gotten channel group \"", "+", "rtn", ",", "ex", ")", ";", "return", "null", ";", "}", "}", "return", "rtn", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "Log", ".", "e", "(", "WonderPush", ".", "TAG", ",", "\"Unexpected error while getting channel group \"", "+", "groupId", ",", "ex", ")", ";", "return", "null", ";", "}", "}" ]
Get a channel group. @param groupId The identifier of the channel group to get. @return The channel group, if it has previously been created using this class, {@code null} otherwise, in particular if an Android {@link android.app.NotificationChannelGroup} exists but has not been registered with this class.
[ "Get", "a", "channel", "group", "." ]
ba0a1568f705cdd6206639bfab1e5cf529084b59
https://github.com/wonderpush/wonderpush-android-sdk/blob/ba0a1568f705cdd6206639bfab1e5cf529084b59/sdk/src/main/java/com/wonderpush/sdk/WonderPushUserPreferences.java#L257-L273
9,836
wonderpush/wonderpush-android-sdk
sdk/src/main/java/com/wonderpush/sdk/WonderPushUserPreferences.java
WonderPushUserPreferences.removeChannelGroup
public static synchronized void removeChannelGroup(String groupId) { try { if (_removeChannelGroup(groupId)) { save(); } } catch (Exception ex) { Log.e(WonderPush.TAG, "Unexpected error while removing channel group " + groupId, ex); } }
java
public static synchronized void removeChannelGroup(String groupId) { try { if (_removeChannelGroup(groupId)) { save(); } } catch (Exception ex) { Log.e(WonderPush.TAG, "Unexpected error while removing channel group " + groupId, ex); } }
[ "public", "static", "synchronized", "void", "removeChannelGroup", "(", "String", "groupId", ")", "{", "try", "{", "if", "(", "_removeChannelGroup", "(", "groupId", ")", ")", "{", "save", "(", ")", ";", "}", "}", "catch", "(", "Exception", "ex", ")", "{", "Log", ".", "e", "(", "WonderPush", ".", "TAG", ",", "\"Unexpected error while removing channel group \"", "+", "groupId", ",", "ex", ")", ";", "}", "}" ]
Remove a channel group. <p>Remove a channel group both from this class registry and from Android.</p> @param groupId The identifier of the channel group to remove.
[ "Remove", "a", "channel", "group", "." ]
ba0a1568f705cdd6206639bfab1e5cf529084b59
https://github.com/wonderpush/wonderpush-android-sdk/blob/ba0a1568f705cdd6206639bfab1e5cf529084b59/sdk/src/main/java/com/wonderpush/sdk/WonderPushUserPreferences.java#L282-L290
9,837
wonderpush/wonderpush-android-sdk
sdk/src/main/java/com/wonderpush/sdk/WonderPushUserPreferences.java
WonderPushUserPreferences.putChannelGroup
public static synchronized void putChannelGroup(WonderPushChannelGroup channelGroup) { try { if (_putChannelGroup(channelGroup)) { save(); } } catch (Exception ex) { Log.e(WonderPush.TAG, "Unexpected error while putting channel group " + channelGroup, ex); } }
java
public static synchronized void putChannelGroup(WonderPushChannelGroup channelGroup) { try { if (_putChannelGroup(channelGroup)) { save(); } } catch (Exception ex) { Log.e(WonderPush.TAG, "Unexpected error while putting channel group " + channelGroup, ex); } }
[ "public", "static", "synchronized", "void", "putChannelGroup", "(", "WonderPushChannelGroup", "channelGroup", ")", "{", "try", "{", "if", "(", "_putChannelGroup", "(", "channelGroup", ")", ")", "{", "save", "(", ")", ";", "}", "}", "catch", "(", "Exception", "ex", ")", "{", "Log", ".", "e", "(", "WonderPush", ".", "TAG", ",", "\"Unexpected error while putting channel group \"", "+", "channelGroup", ",", "ex", ")", ";", "}", "}" ]
Create or update a channel group. <p>Creates or updates a channel group both in this class registry and in Android.</p> @param channelGroup The channel group to create or update.
[ "Create", "or", "update", "a", "channel", "group", "." ]
ba0a1568f705cdd6206639bfab1e5cf529084b59
https://github.com/wonderpush/wonderpush-android-sdk/blob/ba0a1568f705cdd6206639bfab1e5cf529084b59/sdk/src/main/java/com/wonderpush/sdk/WonderPushUserPreferences.java#L308-L316
9,838
wonderpush/wonderpush-android-sdk
sdk/src/main/java/com/wonderpush/sdk/WonderPushUserPreferences.java
WonderPushUserPreferences.setChannelGroups
public static synchronized void setChannelGroups(Collection<WonderPushChannelGroup> channelGroups) { if (channelGroups == null) return; boolean save = false; try { Set<String> groupIdsToRemove = new HashSet<>(sChannelGroups.keySet()); for (WonderPushChannelGroup channelGroup : channelGroups) { if (channelGroup == null) continue; groupIdsToRemove.remove(channelGroup.getId()); if (_putChannelGroup(channelGroup)) save = true; } for (String groupId : groupIdsToRemove) { if (_removeChannelGroup(groupId)) save = true; } } catch (Exception ex) { Log.e(WonderPush.TAG, "Unexpected error while setting channel groups " + channelGroups, ex); } finally { try { if (save) { save(); } } catch (Exception ex) { Log.e(WonderPush.TAG, "Unexpected error while setting channel groups " + channelGroups, ex); } } }
java
public static synchronized void setChannelGroups(Collection<WonderPushChannelGroup> channelGroups) { if (channelGroups == null) return; boolean save = false; try { Set<String> groupIdsToRemove = new HashSet<>(sChannelGroups.keySet()); for (WonderPushChannelGroup channelGroup : channelGroups) { if (channelGroup == null) continue; groupIdsToRemove.remove(channelGroup.getId()); if (_putChannelGroup(channelGroup)) save = true; } for (String groupId : groupIdsToRemove) { if (_removeChannelGroup(groupId)) save = true; } } catch (Exception ex) { Log.e(WonderPush.TAG, "Unexpected error while setting channel groups " + channelGroups, ex); } finally { try { if (save) { save(); } } catch (Exception ex) { Log.e(WonderPush.TAG, "Unexpected error while setting channel groups " + channelGroups, ex); } } }
[ "public", "static", "synchronized", "void", "setChannelGroups", "(", "Collection", "<", "WonderPushChannelGroup", ">", "channelGroups", ")", "{", "if", "(", "channelGroups", "==", "null", ")", "return", ";", "boolean", "save", "=", "false", ";", "try", "{", "Set", "<", "String", ">", "groupIdsToRemove", "=", "new", "HashSet", "<>", "(", "sChannelGroups", ".", "keySet", "(", ")", ")", ";", "for", "(", "WonderPushChannelGroup", "channelGroup", ":", "channelGroups", ")", "{", "if", "(", "channelGroup", "==", "null", ")", "continue", ";", "groupIdsToRemove", ".", "remove", "(", "channelGroup", ".", "getId", "(", ")", ")", ";", "if", "(", "_putChannelGroup", "(", "channelGroup", ")", ")", "save", "=", "true", ";", "}", "for", "(", "String", "groupId", ":", "groupIdsToRemove", ")", "{", "if", "(", "_removeChannelGroup", "(", "groupId", ")", ")", "save", "=", "true", ";", "}", "}", "catch", "(", "Exception", "ex", ")", "{", "Log", ".", "e", "(", "WonderPush", ".", "TAG", ",", "\"Unexpected error while setting channel groups \"", "+", "channelGroups", ",", "ex", ")", ";", "}", "finally", "{", "try", "{", "if", "(", "save", ")", "{", "save", "(", ")", ";", "}", "}", "catch", "(", "Exception", "ex", ")", "{", "Log", ".", "e", "(", "WonderPush", ".", "TAG", ",", "\"Unexpected error while setting channel groups \"", "+", "channelGroups", ",", "ex", ")", ";", "}", "}", "}" ]
Create, update and remove channel existing groups to match the given channel groups. <p>Creates, updates and removes channel groups both in this class registry and in Android.</p> <p>Any non listed, previously existing channel group will be removed.</p> @param channelGroups The channel groups to create or update. Any non listed, previously existing channel group will be removed.
[ "Create", "update", "and", "remove", "channel", "existing", "groups", "to", "match", "the", "given", "channel", "groups", "." ]
ba0a1568f705cdd6206639bfab1e5cf529084b59
https://github.com/wonderpush/wonderpush-android-sdk/blob/ba0a1568f705cdd6206639bfab1e5cf529084b59/sdk/src/main/java/com/wonderpush/sdk/WonderPushUserPreferences.java#L344-L368
9,839
wonderpush/wonderpush-android-sdk
sdk/src/main/java/com/wonderpush/sdk/WonderPushUserPreferences.java
WonderPushUserPreferences.getChannel
public static synchronized WonderPushChannel getChannel(String channelId) { try { WonderPushChannel rtn = sChannels.get(channelId); if (rtn != null) { try { rtn = (WonderPushChannel) rtn.clone(); } catch (CloneNotSupportedException ex) { Log.e(WonderPush.TAG, "Unexpected error while cloning gotten channel " + rtn, ex); return null; } } return rtn; } catch (Exception ex) { Log.e(WonderPush.TAG, "Unexpected error while getting channel " + channelId, ex); return null; } }
java
public static synchronized WonderPushChannel getChannel(String channelId) { try { WonderPushChannel rtn = sChannels.get(channelId); if (rtn != null) { try { rtn = (WonderPushChannel) rtn.clone(); } catch (CloneNotSupportedException ex) { Log.e(WonderPush.TAG, "Unexpected error while cloning gotten channel " + rtn, ex); return null; } } return rtn; } catch (Exception ex) { Log.e(WonderPush.TAG, "Unexpected error while getting channel " + channelId, ex); return null; } }
[ "public", "static", "synchronized", "WonderPushChannel", "getChannel", "(", "String", "channelId", ")", "{", "try", "{", "WonderPushChannel", "rtn", "=", "sChannels", ".", "get", "(", "channelId", ")", ";", "if", "(", "rtn", "!=", "null", ")", "{", "try", "{", "rtn", "=", "(", "WonderPushChannel", ")", "rtn", ".", "clone", "(", ")", ";", "}", "catch", "(", "CloneNotSupportedException", "ex", ")", "{", "Log", ".", "e", "(", "WonderPush", ".", "TAG", ",", "\"Unexpected error while cloning gotten channel \"", "+", "rtn", ",", "ex", ")", ";", "return", "null", ";", "}", "}", "return", "rtn", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "Log", ".", "e", "(", "WonderPush", ".", "TAG", ",", "\"Unexpected error while getting channel \"", "+", "channelId", ",", "ex", ")", ";", "return", "null", ";", "}", "}" ]
Get a channel. @param channelId The identifier of the channel to get. @return The channel, if it has previously been created using this class, {@code null} otherwise, in particular if an Android {@link android.app.NotificationChannel} exists but has not been registered with this class.
[ "Get", "a", "channel", "." ]
ba0a1568f705cdd6206639bfab1e5cf529084b59
https://github.com/wonderpush/wonderpush-android-sdk/blob/ba0a1568f705cdd6206639bfab1e5cf529084b59/sdk/src/main/java/com/wonderpush/sdk/WonderPushUserPreferences.java#L377-L393
9,840
wonderpush/wonderpush-android-sdk
sdk/src/main/java/com/wonderpush/sdk/WonderPushUserPreferences.java
WonderPushUserPreferences.removeChannel
public static synchronized void removeChannel(String channelId) { try { if (_removeChannel(channelId)) { save(); } } catch (Exception ex) { Log.e(WonderPush.TAG, "Unexpected error while removing channel " + channelId, ex); } }
java
public static synchronized void removeChannel(String channelId) { try { if (_removeChannel(channelId)) { save(); } } catch (Exception ex) { Log.e(WonderPush.TAG, "Unexpected error while removing channel " + channelId, ex); } }
[ "public", "static", "synchronized", "void", "removeChannel", "(", "String", "channelId", ")", "{", "try", "{", "if", "(", "_removeChannel", "(", "channelId", ")", ")", "{", "save", "(", ")", ";", "}", "}", "catch", "(", "Exception", "ex", ")", "{", "Log", ".", "e", "(", "WonderPush", ".", "TAG", ",", "\"Unexpected error while removing channel \"", "+", "channelId", ",", "ex", ")", ";", "}", "}" ]
Remove a channel. <p>Remove a channel both from this class registry and from Android.</p> @param channelId The identifier of the channel to remove.
[ "Remove", "a", "channel", "." ]
ba0a1568f705cdd6206639bfab1e5cf529084b59
https://github.com/wonderpush/wonderpush-android-sdk/blob/ba0a1568f705cdd6206639bfab1e5cf529084b59/sdk/src/main/java/com/wonderpush/sdk/WonderPushUserPreferences.java#L402-L410
9,841
wonderpush/wonderpush-android-sdk
sdk/src/main/java/com/wonderpush/sdk/WonderPushUserPreferences.java
WonderPushUserPreferences.putChannel
public static synchronized void putChannel(WonderPushChannel channel) { try { if (_putChannel(channel)) { save(); } } catch (Exception ex) { Log.e(WonderPush.TAG, "Unexpected error while putting channel " + channel, ex); } }
java
public static synchronized void putChannel(WonderPushChannel channel) { try { if (_putChannel(channel)) { save(); } } catch (Exception ex) { Log.e(WonderPush.TAG, "Unexpected error while putting channel " + channel, ex); } }
[ "public", "static", "synchronized", "void", "putChannel", "(", "WonderPushChannel", "channel", ")", "{", "try", "{", "if", "(", "_putChannel", "(", "channel", ")", ")", "{", "save", "(", ")", ";", "}", "}", "catch", "(", "Exception", "ex", ")", "{", "Log", ".", "e", "(", "WonderPush", ".", "TAG", ",", "\"Unexpected error while putting channel \"", "+", "channel", ",", "ex", ")", ";", "}", "}" ]
Create or update a channel. <p>Creates or updates a channel both in this class registry and in Android.</p> @param channel The channel to create or update.
[ "Create", "or", "update", "a", "channel", "." ]
ba0a1568f705cdd6206639bfab1e5cf529084b59
https://github.com/wonderpush/wonderpush-android-sdk/blob/ba0a1568f705cdd6206639bfab1e5cf529084b59/sdk/src/main/java/com/wonderpush/sdk/WonderPushUserPreferences.java#L428-L436
9,842
wonderpush/wonderpush-android-sdk
sdk/src/main/java/com/wonderpush/sdk/WonderPushUserPreferences.java
WonderPushUserPreferences.setChannels
public static synchronized void setChannels(Collection<WonderPushChannel> channels) { if (channels == null) return; boolean save = false; try { Set<String> channelIdsToRemove = new HashSet<>(sChannels.keySet()); for (WonderPushChannel channel : channels) { if (channel == null) continue; channelIdsToRemove.remove(channel.getId()); if (_putChannel(channel)) save = true; } for (String channelId : channelIdsToRemove) { if (_removeChannel(channelId)) save = true; } } catch (Exception ex) { Log.e(WonderPush.TAG, "Unexpected error while setting channels " + channels, ex); } finally { try { if (save) { save(); } } catch (Exception ex) { Log.e(WonderPush.TAG, "Unexpected error while setting channels " + channels, ex); } } }
java
public static synchronized void setChannels(Collection<WonderPushChannel> channels) { if (channels == null) return; boolean save = false; try { Set<String> channelIdsToRemove = new HashSet<>(sChannels.keySet()); for (WonderPushChannel channel : channels) { if (channel == null) continue; channelIdsToRemove.remove(channel.getId()); if (_putChannel(channel)) save = true; } for (String channelId : channelIdsToRemove) { if (_removeChannel(channelId)) save = true; } } catch (Exception ex) { Log.e(WonderPush.TAG, "Unexpected error while setting channels " + channels, ex); } finally { try { if (save) { save(); } } catch (Exception ex) { Log.e(WonderPush.TAG, "Unexpected error while setting channels " + channels, ex); } } }
[ "public", "static", "synchronized", "void", "setChannels", "(", "Collection", "<", "WonderPushChannel", ">", "channels", ")", "{", "if", "(", "channels", "==", "null", ")", "return", ";", "boolean", "save", "=", "false", ";", "try", "{", "Set", "<", "String", ">", "channelIdsToRemove", "=", "new", "HashSet", "<>", "(", "sChannels", ".", "keySet", "(", ")", ")", ";", "for", "(", "WonderPushChannel", "channel", ":", "channels", ")", "{", "if", "(", "channel", "==", "null", ")", "continue", ";", "channelIdsToRemove", ".", "remove", "(", "channel", ".", "getId", "(", ")", ")", ";", "if", "(", "_putChannel", "(", "channel", ")", ")", "save", "=", "true", ";", "}", "for", "(", "String", "channelId", ":", "channelIdsToRemove", ")", "{", "if", "(", "_removeChannel", "(", "channelId", ")", ")", "save", "=", "true", ";", "}", "}", "catch", "(", "Exception", "ex", ")", "{", "Log", ".", "e", "(", "WonderPush", ".", "TAG", ",", "\"Unexpected error while setting channels \"", "+", "channels", ",", "ex", ")", ";", "}", "finally", "{", "try", "{", "if", "(", "save", ")", "{", "save", "(", ")", ";", "}", "}", "catch", "(", "Exception", "ex", ")", "{", "Log", ".", "e", "(", "WonderPush", ".", "TAG", ",", "\"Unexpected error while setting channels \"", "+", "channels", ",", "ex", ")", ";", "}", "}", "}" ]
Create, update and remove channels to match the given channels. <p>Creates, updates and removes channels both in this class registry and in Android.</p> <p>Any non listed, previously existing channel will be removed.</p> @param channels The channels to create or update. Any non listed, previously existing channel will be removed.
[ "Create", "update", "and", "remove", "channels", "to", "match", "the", "given", "channels", "." ]
ba0a1568f705cdd6206639bfab1e5cf529084b59
https://github.com/wonderpush/wonderpush-android-sdk/blob/ba0a1568f705cdd6206639bfab1e5cf529084b59/sdk/src/main/java/com/wonderpush/sdk/WonderPushUserPreferences.java#L509-L533
9,843
mp911de/spinach
src/main/java/biz/paluch/spinach/cluster/NodeIdAwareSocketAddressSupplier.java
NodeIdAwareSocketAddressSupplier.setPreferredNodeIdPrefix
public void setPreferredNodeIdPrefix(String preferredNodeIdPrefix) { LettuceAssert.notNull(preferredNodeIdPrefix, "preferredNodeIdPrefix must not be null"); boolean resetRoundRobin = false; if (this.preferredNodeIdPrefix == null || !preferredNodeIdPrefix.equals(this.preferredNodeIdPrefix)) { resetRoundRobin = true; } this.preferredNodeIdPrefix = preferredNodeIdPrefix; if (resetRoundRobin) { resetRoundRobin(preferredNodeIdPrefix); } }
java
public void setPreferredNodeIdPrefix(String preferredNodeIdPrefix) { LettuceAssert.notNull(preferredNodeIdPrefix, "preferredNodeIdPrefix must not be null"); boolean resetRoundRobin = false; if (this.preferredNodeIdPrefix == null || !preferredNodeIdPrefix.equals(this.preferredNodeIdPrefix)) { resetRoundRobin = true; } this.preferredNodeIdPrefix = preferredNodeIdPrefix; if (resetRoundRobin) { resetRoundRobin(preferredNodeIdPrefix); } }
[ "public", "void", "setPreferredNodeIdPrefix", "(", "String", "preferredNodeIdPrefix", ")", "{", "LettuceAssert", ".", "notNull", "(", "preferredNodeIdPrefix", ",", "\"preferredNodeIdPrefix must not be null\"", ")", ";", "boolean", "resetRoundRobin", "=", "false", ";", "if", "(", "this", ".", "preferredNodeIdPrefix", "==", "null", "||", "!", "preferredNodeIdPrefix", ".", "equals", "(", "this", ".", "preferredNodeIdPrefix", ")", ")", "{", "resetRoundRobin", "=", "true", ";", "}", "this", ".", "preferredNodeIdPrefix", "=", "preferredNodeIdPrefix", ";", "if", "(", "resetRoundRobin", ")", "{", "resetRoundRobin", "(", "preferredNodeIdPrefix", ")", ";", "}", "}" ]
Set the id prefix of the preferred node. @param preferredNodeIdPrefix the id prefix of the preferred node
[ "Set", "the", "id", "prefix", "of", "the", "preferred", "node", "." ]
ca8081f52de17c46dce6ffdcb519eec600c5c93d
https://github.com/mp911de/spinach/blob/ca8081f52de17c46dce6ffdcb519eec600c5c93d/src/main/java/biz/paluch/spinach/cluster/NodeIdAwareSocketAddressSupplier.java#L96-L109
9,844
wonderpush/wonderpush-android-sdk
sdk/src/main/java/com/wonderpush/sdk/WonderPushView.java
WonderPushView.setResource
public void setResource(String resource, RequestParams params) { if (null == resource) { WonderPush.logError("null resource provided to WonderPushView"); return; } mInitialResource = resource; mInitialRequestParams = params; mIsPreloading = false; if (null == params) params = new RequestParams(); WonderPushRequestParamsDecorator.decorate(resource, params); String url = String.format(Locale.getDefault(), "%s?%s", WonderPushUriHelper.getNonSecureAbsoluteUrl(resource), params.getURLEncodedString()); mWebView.loadUrl(url); }
java
public void setResource(String resource, RequestParams params) { if (null == resource) { WonderPush.logError("null resource provided to WonderPushView"); return; } mInitialResource = resource; mInitialRequestParams = params; mIsPreloading = false; if (null == params) params = new RequestParams(); WonderPushRequestParamsDecorator.decorate(resource, params); String url = String.format(Locale.getDefault(), "%s?%s", WonderPushUriHelper.getNonSecureAbsoluteUrl(resource), params.getURLEncodedString()); mWebView.loadUrl(url); }
[ "public", "void", "setResource", "(", "String", "resource", ",", "RequestParams", "params", ")", "{", "if", "(", "null", "==", "resource", ")", "{", "WonderPush", ".", "logError", "(", "\"null resource provided to WonderPushView\"", ")", ";", "return", ";", "}", "mInitialResource", "=", "resource", ";", "mInitialRequestParams", "=", "params", ";", "mIsPreloading", "=", "false", ";", "if", "(", "null", "==", "params", ")", "params", "=", "new", "RequestParams", "(", ")", ";", "WonderPushRequestParamsDecorator", ".", "decorate", "(", "resource", ",", "params", ")", ";", "String", "url", "=", "String", ".", "format", "(", "Locale", ".", "getDefault", "(", ")", ",", "\"%s?%s\"", ",", "WonderPushUriHelper", ".", "getNonSecureAbsoluteUrl", "(", "resource", ")", ",", "params", ".", "getURLEncodedString", "(", ")", ")", ";", "mWebView", ".", "loadUrl", "(", "url", ")", ";", "}" ]
Sets the resource for the web content displayed in this WonderPushView's WebView.
[ "Sets", "the", "resource", "for", "the", "web", "content", "displayed", "in", "this", "WonderPushView", "s", "WebView", "." ]
ba0a1568f705cdd6206639bfab1e5cf529084b59
https://github.com/wonderpush/wonderpush-android-sdk/blob/ba0a1568f705cdd6206639bfab1e5cf529084b59/sdk/src/main/java/com/wonderpush/sdk/WonderPushView.java#L261-L278
9,845
wonderpush/wonderpush-android-sdk
sdk/src/main/java/com/wonderpush/sdk/WonderPushView.java
WonderPushView.setFullUrl
public void setFullUrl(String fullUrl) { if (fullUrl == null) { return; } Uri parsedUri = Uri.parse(fullUrl); if (!WonderPushUriHelper.isAPIUri(parsedUri)) { mWebView.loadUrl(fullUrl); } else { setResource(WonderPushUriHelper.getResource(parsedUri), WonderPushUriHelper.getParams(parsedUri)); } }
java
public void setFullUrl(String fullUrl) { if (fullUrl == null) { return; } Uri parsedUri = Uri.parse(fullUrl); if (!WonderPushUriHelper.isAPIUri(parsedUri)) { mWebView.loadUrl(fullUrl); } else { setResource(WonderPushUriHelper.getResource(parsedUri), WonderPushUriHelper.getParams(parsedUri)); } }
[ "public", "void", "setFullUrl", "(", "String", "fullUrl", ")", "{", "if", "(", "fullUrl", "==", "null", ")", "{", "return", ";", "}", "Uri", "parsedUri", "=", "Uri", ".", "parse", "(", "fullUrl", ")", ";", "if", "(", "!", "WonderPushUriHelper", ".", "isAPIUri", "(", "parsedUri", ")", ")", "{", "mWebView", ".", "loadUrl", "(", "fullUrl", ")", ";", "}", "else", "{", "setResource", "(", "WonderPushUriHelper", ".", "getResource", "(", "parsedUri", ")", ",", "WonderPushUriHelper", ".", "getParams", "(", "parsedUri", ")", ")", ";", "}", "}" ]
Sets the full URL for the web content displayed in this WonderPushView's WebView. @param fullUrl A full URL, with host.
[ "Sets", "the", "full", "URL", "for", "the", "web", "content", "displayed", "in", "this", "WonderPushView", "s", "WebView", "." ]
ba0a1568f705cdd6206639bfab1e5cf529084b59
https://github.com/wonderpush/wonderpush-android-sdk/blob/ba0a1568f705cdd6206639bfab1e5cf529084b59/sdk/src/main/java/com/wonderpush/sdk/WonderPushView.java#L286-L298
9,846
mp911de/spinach
src/main/java/biz/paluch/spinach/cluster/QueueListenerFactory.java
QueueListenerFactory.getjobs
public Observable<Job<K, V>> getjobs(long timeout, TimeUnit timeUnit, long count) { return new GetJobsBuilder().getjobs(timeout, timeUnit, count); }
java
public Observable<Job<K, V>> getjobs(long timeout, TimeUnit timeUnit, long count) { return new GetJobsBuilder().getjobs(timeout, timeUnit, count); }
[ "public", "Observable", "<", "Job", "<", "K", ",", "V", ">", ">", "getjobs", "(", "long", "timeout", ",", "TimeUnit", "timeUnit", ",", "long", "count", ")", "{", "return", "new", "GetJobsBuilder", "(", ")", ".", "getjobs", "(", "timeout", ",", "timeUnit", ",", "count", ")", ";", "}" ]
Get jobs from the specified queues. <p> When there are jobs in more than one of the queues, the command guarantees to return jobs in the order the queues are specified. If COUNT allows more jobs to be returned, queues are scanned again and again in the same order popping more elements. </p> <p> The {@link Observable} emits {@link Job} objects as soon as a job is received from Disque. The terminal event is emitted as soon as the {@link rx.Subscriber subscriber} unsubscribes from the {@link Observable}. </p> @param timeout timeout to wait @param timeUnit timeout unit @param count count of jobs to return @return an Observable that emits {@link Job} elements until the subscriber terminates the subscription
[ "Get", "jobs", "from", "the", "specified", "queues", "." ]
ca8081f52de17c46dce6ffdcb519eec600c5c93d
https://github.com/mp911de/spinach/blob/ca8081f52de17c46dce6ffdcb519eec600c5c93d/src/main/java/biz/paluch/spinach/cluster/QueueListenerFactory.java#L184-L186
9,847
wonderpush/wonderpush-android-sdk
sdk/src/main/java/com/wonderpush/sdk/WonderPushJobQueue.java
WonderPushJobQueue.postJobWithDescription
protected Job postJobWithDescription(JSONObject jobDescription, long notBeforeRealtimeElapsed) { String jobId = UUID.randomUUID().toString(); InternalJob job = new InternalJob(jobId, jobDescription, notBeforeRealtimeElapsed); return post(job); }
java
protected Job postJobWithDescription(JSONObject jobDescription, long notBeforeRealtimeElapsed) { String jobId = UUID.randomUUID().toString(); InternalJob job = new InternalJob(jobId, jobDescription, notBeforeRealtimeElapsed); return post(job); }
[ "protected", "Job", "postJobWithDescription", "(", "JSONObject", "jobDescription", ",", "long", "notBeforeRealtimeElapsed", ")", "{", "String", "jobId", "=", "UUID", ".", "randomUUID", "(", ")", ".", "toString", "(", ")", ";", "InternalJob", "job", "=", "new", "InternalJob", "(", "jobId", ",", "jobDescription", ",", "notBeforeRealtimeElapsed", ")", ";", "return", "post", "(", "job", ")", ";", "}" ]
Creates and stores a job in the queue based on the provided description @return The stored job or null if something went wrong (the queue is full for instance)
[ "Creates", "and", "stores", "a", "job", "in", "the", "queue", "based", "on", "the", "provided", "description" ]
ba0a1568f705cdd6206639bfab1e5cf529084b59
https://github.com/wonderpush/wonderpush-android-sdk/blob/ba0a1568f705cdd6206639bfab1e5cf529084b59/sdk/src/main/java/com/wonderpush/sdk/WonderPushJobQueue.java#L80-L84
9,848
wonderpush/wonderpush-android-sdk
sdk/src/main/java/com/wonderpush/sdk/WonderPushJobQueue.java
WonderPushJobQueue.post
protected Job post(Job job) { if (mQueue.offer(job)) { save(); return job; } else { return null; } }
java
protected Job post(Job job) { if (mQueue.offer(job)) { save(); return job; } else { return null; } }
[ "protected", "Job", "post", "(", "Job", "job", ")", "{", "if", "(", "mQueue", ".", "offer", "(", "job", ")", ")", "{", "save", "(", ")", ";", "return", "job", ";", "}", "else", "{", "return", "null", ";", "}", "}" ]
Stores an existing job in the queue. @return The input job or null if something went wrong (the queue is full for instance)
[ "Stores", "an", "existing", "job", "in", "the", "queue", "." ]
ba0a1568f705cdd6206639bfab1e5cf529084b59
https://github.com/wonderpush/wonderpush-android-sdk/blob/ba0a1568f705cdd6206639bfab1e5cf529084b59/sdk/src/main/java/com/wonderpush/sdk/WonderPushJobQueue.java#L91-L98
9,849
wonderpush/wonderpush-android-sdk
sdk/src/main/java/com/wonderpush/sdk/WonderPushJobQueue.java
WonderPushJobQueue.save
protected synchronized void save() { try { JSONArray jsonArray = new JSONArray(); for (Job job : mQueue) { if (!(job instanceof InternalJob)) continue; InternalJob internalJob = (InternalJob) job; jsonArray.put(internalJob.toJSON()); } SharedPreferences prefs = WonderPushConfiguration.getSharedPreferences(); SharedPreferences.Editor editor = prefs.edit(); editor.putString(getPrefName(), jsonArray.toString()); editor.apply(); } catch (JSONException e) { Log.e(TAG, "Could not save job queue", e); } catch (Exception e) { Log.e(TAG, "Could not save job queue", e); } }
java
protected synchronized void save() { try { JSONArray jsonArray = new JSONArray(); for (Job job : mQueue) { if (!(job instanceof InternalJob)) continue; InternalJob internalJob = (InternalJob) job; jsonArray.put(internalJob.toJSON()); } SharedPreferences prefs = WonderPushConfiguration.getSharedPreferences(); SharedPreferences.Editor editor = prefs.edit(); editor.putString(getPrefName(), jsonArray.toString()); editor.apply(); } catch (JSONException e) { Log.e(TAG, "Could not save job queue", e); } catch (Exception e) { Log.e(TAG, "Could not save job queue", e); } }
[ "protected", "synchronized", "void", "save", "(", ")", "{", "try", "{", "JSONArray", "jsonArray", "=", "new", "JSONArray", "(", ")", ";", "for", "(", "Job", "job", ":", "mQueue", ")", "{", "if", "(", "!", "(", "job", "instanceof", "InternalJob", ")", ")", "continue", ";", "InternalJob", "internalJob", "=", "(", "InternalJob", ")", "job", ";", "jsonArray", ".", "put", "(", "internalJob", ".", "toJSON", "(", ")", ")", ";", "}", "SharedPreferences", "prefs", "=", "WonderPushConfiguration", ".", "getSharedPreferences", "(", ")", ";", "SharedPreferences", ".", "Editor", "editor", "=", "prefs", ".", "edit", "(", ")", ";", "editor", ".", "putString", "(", "getPrefName", "(", ")", ",", "jsonArray", ".", "toString", "(", ")", ")", ";", "editor", ".", "apply", "(", ")", ";", "}", "catch", "(", "JSONException", "e", ")", "{", "Log", ".", "e", "(", "TAG", ",", "\"Could not save job queue\"", ",", "e", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "Log", ".", "e", "(", "TAG", ",", "\"Could not save job queue\"", ",", "e", ")", ";", "}", "}" ]
Saves the job queue on disk.
[ "Saves", "the", "job", "queue", "on", "disk", "." ]
ba0a1568f705cdd6206639bfab1e5cf529084b59
https://github.com/wonderpush/wonderpush-android-sdk/blob/ba0a1568f705cdd6206639bfab1e5cf529084b59/sdk/src/main/java/com/wonderpush/sdk/WonderPushJobQueue.java#L124-L142
9,850
wonderpush/wonderpush-android-sdk
sdk/src/main/java/com/wonderpush/sdk/WonderPushJobQueue.java
WonderPushJobQueue.restore
protected synchronized void restore() { try { SharedPreferences prefs = WonderPushConfiguration.getSharedPreferences(); String jsonString = prefs.getString(getPrefName(), "[]"); JSONArray jsonArray = new JSONArray(jsonString); mQueue.clear(); for (int i = 0 ; i < jsonArray.length() ; i++) { try { mQueue.add(new InternalJob(jsonArray.getJSONObject(i))); } catch (JSONException ex) { Log.e(TAG, "Failed to restore malformed job", ex); } catch (Exception ex) { Log.e(TAG, "Unexpected error while restoring a job", ex); } } } catch (JSONException e) { Log.e(TAG, "Could not restore job queue", e); } catch (Exception e) { Log.e(TAG, "Could not restore job queue", e); } }
java
protected synchronized void restore() { try { SharedPreferences prefs = WonderPushConfiguration.getSharedPreferences(); String jsonString = prefs.getString(getPrefName(), "[]"); JSONArray jsonArray = new JSONArray(jsonString); mQueue.clear(); for (int i = 0 ; i < jsonArray.length() ; i++) { try { mQueue.add(new InternalJob(jsonArray.getJSONObject(i))); } catch (JSONException ex) { Log.e(TAG, "Failed to restore malformed job", ex); } catch (Exception ex) { Log.e(TAG, "Unexpected error while restoring a job", ex); } } } catch (JSONException e) { Log.e(TAG, "Could not restore job queue", e); } catch (Exception e) { Log.e(TAG, "Could not restore job queue", e); } }
[ "protected", "synchronized", "void", "restore", "(", ")", "{", "try", "{", "SharedPreferences", "prefs", "=", "WonderPushConfiguration", ".", "getSharedPreferences", "(", ")", ";", "String", "jsonString", "=", "prefs", ".", "getString", "(", "getPrefName", "(", ")", ",", "\"[]\"", ")", ";", "JSONArray", "jsonArray", "=", "new", "JSONArray", "(", "jsonString", ")", ";", "mQueue", ".", "clear", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "jsonArray", ".", "length", "(", ")", ";", "i", "++", ")", "{", "try", "{", "mQueue", ".", "add", "(", "new", "InternalJob", "(", "jsonArray", ".", "getJSONObject", "(", "i", ")", ")", ")", ";", "}", "catch", "(", "JSONException", "ex", ")", "{", "Log", ".", "e", "(", "TAG", ",", "\"Failed to restore malformed job\"", ",", "ex", ")", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "Log", ".", "e", "(", "TAG", ",", "\"Unexpected error while restoring a job\"", ",", "ex", ")", ";", "}", "}", "}", "catch", "(", "JSONException", "e", ")", "{", "Log", ".", "e", "(", "TAG", ",", "\"Could not restore job queue\"", ",", "e", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "Log", ".", "e", "(", "TAG", ",", "\"Could not restore job queue\"", ",", "e", ")", ";", "}", "}" ]
Restores the job queue from its on-disk version.
[ "Restores", "the", "job", "queue", "from", "its", "on", "-", "disk", "version", "." ]
ba0a1568f705cdd6206639bfab1e5cf529084b59
https://github.com/wonderpush/wonderpush-android-sdk/blob/ba0a1568f705cdd6206639bfab1e5cf529084b59/sdk/src/main/java/com/wonderpush/sdk/WonderPushJobQueue.java#L147-L169
9,851
mp911de/spinach
src/main/java/biz/paluch/spinach/api/GetJobArgs.java
GetJobArgs.copyBuilder
public Builder copyBuilder() { return GetJobArgs.builder().noHang(noHang).timeout(timeout).withCounters(withCounters); }
java
public Builder copyBuilder() { return GetJobArgs.builder().noHang(noHang).timeout(timeout).withCounters(withCounters); }
[ "public", "Builder", "copyBuilder", "(", ")", "{", "return", "GetJobArgs", ".", "builder", "(", ")", ".", "noHang", "(", "noHang", ")", ".", "timeout", "(", "timeout", ")", ".", "withCounters", "(", "withCounters", ")", ";", "}" ]
Create a new builder populated with the current settings. @return a new {@link biz.paluch.spinach.api.GetJobArgs.Builder}
[ "Create", "a", "new", "builder", "populated", "with", "the", "current", "settings", "." ]
ca8081f52de17c46dce6ffdcb519eec600c5c93d
https://github.com/mp911de/spinach/blob/ca8081f52de17c46dce6ffdcb519eec600c5c93d/src/main/java/biz/paluch/spinach/api/GetJobArgs.java#L75-L77
9,852
wonderpush/wonderpush-android-sdk
sdk/src/main/java/com/wonderpush/sdk/WonderPush.java
WonderPush.get
protected static void get(String resource, RequestParams params, ResponseHandler responseHandler) { WonderPushRestClient.get(resource, params, responseHandler); }
java
protected static void get(String resource, RequestParams params, ResponseHandler responseHandler) { WonderPushRestClient.get(resource, params, responseHandler); }
[ "protected", "static", "void", "get", "(", "String", "resource", ",", "RequestParams", "params", ",", "ResponseHandler", "responseHandler", ")", "{", "WonderPushRestClient", ".", "get", "(", "resource", ",", "params", ",", "responseHandler", ")", ";", "}" ]
A GET request. @param resource The resource path, starting with /. @param params AsyncHttpClient request parameters. @param responseHandler An AsyncHttpClient response handler.
[ "A", "GET", "request", "." ]
ba0a1568f705cdd6206639bfab1e5cf529084b59
https://github.com/wonderpush/wonderpush-android-sdk/blob/ba0a1568f705cdd6206639bfab1e5cf529084b59/sdk/src/main/java/com/wonderpush/sdk/WonderPush.java#L492-L495
9,853
wonderpush/wonderpush-android-sdk
sdk/src/main/java/com/wonderpush/sdk/WonderPush.java
WonderPush.post
protected static void post(String resource, RequestParams params, ResponseHandler responseHandler) { WonderPushRestClient.post(resource, params, responseHandler); }
java
protected static void post(String resource, RequestParams params, ResponseHandler responseHandler) { WonderPushRestClient.post(resource, params, responseHandler); }
[ "protected", "static", "void", "post", "(", "String", "resource", ",", "RequestParams", "params", ",", "ResponseHandler", "responseHandler", ")", "{", "WonderPushRestClient", ".", "post", "(", "resource", ",", "params", ",", "responseHandler", ")", ";", "}" ]
A POST request. @param resource The resource path, starting with /. @param params AsyncHttpClient request parameters. @param responseHandler An AsyncHttpClient response handler.
[ "A", "POST", "request", "." ]
ba0a1568f705cdd6206639bfab1e5cf529084b59
https://github.com/wonderpush/wonderpush-android-sdk/blob/ba0a1568f705cdd6206639bfab1e5cf529084b59/sdk/src/main/java/com/wonderpush/sdk/WonderPush.java#L507-L510
9,854
wonderpush/wonderpush-android-sdk
sdk/src/main/java/com/wonderpush/sdk/WonderPush.java
WonderPush.put
protected static void put(String resource, RequestParams params, ResponseHandler responseHandler) { WonderPushRestClient.put(resource, params, responseHandler); }
java
protected static void put(String resource, RequestParams params, ResponseHandler responseHandler) { WonderPushRestClient.put(resource, params, responseHandler); }
[ "protected", "static", "void", "put", "(", "String", "resource", ",", "RequestParams", "params", ",", "ResponseHandler", "responseHandler", ")", "{", "WonderPushRestClient", ".", "put", "(", "resource", ",", "params", ",", "responseHandler", ")", ";", "}" ]
A PUT request. @param resource The resource path, starting with /. @param params AsyncHttpClient request parameters. @param responseHandler An AsyncHttpClient response handler.
[ "A", "PUT", "request", "." ]
ba0a1568f705cdd6206639bfab1e5cf529084b59
https://github.com/wonderpush/wonderpush-android-sdk/blob/ba0a1568f705cdd6206639bfab1e5cf529084b59/sdk/src/main/java/com/wonderpush/sdk/WonderPush.java#L538-L541
9,855
wonderpush/wonderpush-android-sdk
sdk/src/main/java/com/wonderpush/sdk/WonderPush.java
WonderPush.getLang
protected static String getLang() { Locale locale = Locale.getDefault(); if (null == locale) return DEFAULT_LANGUAGE_CODE; String language = locale.getLanguage(); String country = locale.getCountry(); String localeString = String.format("%s_%s", language != null ? language.toLowerCase(Locale.ENGLISH) : "", country != null ? country.toUpperCase(Locale.ENGLISH) : ""); // 1. if no language is specified, return the default language if (null == language) return DEFAULT_LANGUAGE_CODE; // 2. try to match the language or the entire locale string among the // list of available language codes String matchedLanguageCode = null; for (String languageCode : VALID_LANGUAGE_CODES) { if (languageCode.equals(localeString)) { // return here as this is the most precise match we can get return localeString; } if (languageCode.equals(language)) { // set the matched language code, and continue iterating as we // may match the localeString in a later iteration. matchedLanguageCode = language; } } if (null != matchedLanguageCode) return matchedLanguageCode; return DEFAULT_LANGUAGE_CODE; }
java
protected static String getLang() { Locale locale = Locale.getDefault(); if (null == locale) return DEFAULT_LANGUAGE_CODE; String language = locale.getLanguage(); String country = locale.getCountry(); String localeString = String.format("%s_%s", language != null ? language.toLowerCase(Locale.ENGLISH) : "", country != null ? country.toUpperCase(Locale.ENGLISH) : ""); // 1. if no language is specified, return the default language if (null == language) return DEFAULT_LANGUAGE_CODE; // 2. try to match the language or the entire locale string among the // list of available language codes String matchedLanguageCode = null; for (String languageCode : VALID_LANGUAGE_CODES) { if (languageCode.equals(localeString)) { // return here as this is the most precise match we can get return localeString; } if (languageCode.equals(language)) { // set the matched language code, and continue iterating as we // may match the localeString in a later iteration. matchedLanguageCode = language; } } if (null != matchedLanguageCode) return matchedLanguageCode; return DEFAULT_LANGUAGE_CODE; }
[ "protected", "static", "String", "getLang", "(", ")", "{", "Locale", "locale", "=", "Locale", ".", "getDefault", "(", ")", ";", "if", "(", "null", "==", "locale", ")", "return", "DEFAULT_LANGUAGE_CODE", ";", "String", "language", "=", "locale", ".", "getLanguage", "(", ")", ";", "String", "country", "=", "locale", ".", "getCountry", "(", ")", ";", "String", "localeString", "=", "String", ".", "format", "(", "\"%s_%s\"", ",", "language", "!=", "null", "?", "language", ".", "toLowerCase", "(", "Locale", ".", "ENGLISH", ")", ":", "\"\"", ",", "country", "!=", "null", "?", "country", ".", "toUpperCase", "(", "Locale", ".", "ENGLISH", ")", ":", "\"\"", ")", ";", "// 1. if no language is specified, return the default language", "if", "(", "null", "==", "language", ")", "return", "DEFAULT_LANGUAGE_CODE", ";", "// 2. try to match the language or the entire locale string among the", "// list of available language codes", "String", "matchedLanguageCode", "=", "null", ";", "for", "(", "String", "languageCode", ":", "VALID_LANGUAGE_CODES", ")", "{", "if", "(", "languageCode", ".", "equals", "(", "localeString", ")", ")", "{", "// return here as this is the most precise match we can get", "return", "localeString", ";", "}", "if", "(", "languageCode", ".", "equals", "(", "language", ")", ")", "{", "// set the matched language code, and continue iterating as we", "// may match the localeString in a later iteration.", "matchedLanguageCode", "=", "language", ";", "}", "}", "if", "(", "null", "!=", "matchedLanguageCode", ")", "return", "matchedLanguageCode", ";", "return", "DEFAULT_LANGUAGE_CODE", ";", "}" ]
Gets the current language, guessed from the system. @return The locale in use.
[ "Gets", "the", "current", "language", "guessed", "from", "the", "system", "." ]
ba0a1568f705cdd6206639bfab1e5cf529084b59
https://github.com/wonderpush/wonderpush-android-sdk/blob/ba0a1568f705cdd6206639bfab1e5cf529084b59/sdk/src/main/java/com/wonderpush/sdk/WonderPush.java#L622-L658
9,856
wonderpush/wonderpush-android-sdk
sdk/src/main/java/com/wonderpush/sdk/WonderPush.java
WonderPush.initialize
@SuppressWarnings("unused") public static void initialize(final Context context) { try { ensureInitialized(context); } catch (Exception e) { Log.e(TAG, "Unexpected error while initializing the SDK", e); } }
java
@SuppressWarnings("unused") public static void initialize(final Context context) { try { ensureInitialized(context); } catch (Exception e) { Log.e(TAG, "Unexpected error while initializing the SDK", e); } }
[ "@", "SuppressWarnings", "(", "\"unused\"", ")", "public", "static", "void", "initialize", "(", "final", "Context", "context", ")", "{", "try", "{", "ensureInitialized", "(", "context", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "Log", ".", "e", "(", "TAG", ",", "\"Unexpected error while initializing the SDK\"", ",", "e", ")", ";", "}", "}" ]
Initialize WonderPush. <p> Using automatic initialization, you do not need to take care of this yourself. You must otherwise call this method before using the SDK. A good place for that is in the {@link Application#onCreate()} of your {@link Application} class. </p> @param context And {@link Activity} or {@link Application} context.
[ "Initialize", "WonderPush", "." ]
ba0a1568f705cdd6206639bfab1e5cf529084b59
https://github.com/wonderpush/wonderpush-android-sdk/blob/ba0a1568f705cdd6206639bfab1e5cf529084b59/sdk/src/main/java/com/wonderpush/sdk/WonderPush.java#L1001-L1008
9,857
wonderpush/wonderpush-android-sdk
sdk/src/main/java/com/wonderpush/sdk/WonderPush.java
WonderPush.setRequiresUserConsent
public static void setRequiresUserConsent(boolean value) { if (!sIsInitialized) { // We can't read hasUserConsent() before we're initialized sRequiresUserConsent = value; } else { boolean hadUserConsent = hasUserConsent(); sRequiresUserConsent = value; Log.w(TAG, "WonderPush.setRequiresUserConsent(" + value + ") called after WonderPush.initialize(). Although supported, a proper implementation typically only calls it before."); // Refresh user consent boolean nowHasUserConsent = hasUserConsent(); if (hadUserConsent != nowHasUserConsent) { hasUserConsentChanged(nowHasUserConsent); } } }
java
public static void setRequiresUserConsent(boolean value) { if (!sIsInitialized) { // We can't read hasUserConsent() before we're initialized sRequiresUserConsent = value; } else { boolean hadUserConsent = hasUserConsent(); sRequiresUserConsent = value; Log.w(TAG, "WonderPush.setRequiresUserConsent(" + value + ") called after WonderPush.initialize(). Although supported, a proper implementation typically only calls it before."); // Refresh user consent boolean nowHasUserConsent = hasUserConsent(); if (hadUserConsent != nowHasUserConsent) { hasUserConsentChanged(nowHasUserConsent); } } }
[ "public", "static", "void", "setRequiresUserConsent", "(", "boolean", "value", ")", "{", "if", "(", "!", "sIsInitialized", ")", "{", "// We can't read hasUserConsent() before we're initialized", "sRequiresUserConsent", "=", "value", ";", "}", "else", "{", "boolean", "hadUserConsent", "=", "hasUserConsent", "(", ")", ";", "sRequiresUserConsent", "=", "value", ";", "Log", ".", "w", "(", "TAG", ",", "\"WonderPush.setRequiresUserConsent(\"", "+", "value", "+", "\") called after WonderPush.initialize(). Although supported, a proper implementation typically only calls it before.\"", ")", ";", "// Refresh user consent", "boolean", "nowHasUserConsent", "=", "hasUserConsent", "(", ")", ";", "if", "(", "hadUserConsent", "!=", "nowHasUserConsent", ")", "{", "hasUserConsentChanged", "(", "nowHasUserConsent", ")", ";", "}", "}", "}" ]
Sets whether user consent is required before the SDK is allowed to work. <p>Call this method before {@link #initialize(Context)}.</p> @param value Whether user consent is required before the SDK is allowed to work. @see #setUserConsent(boolean)
[ "Sets", "whether", "user", "consent", "is", "required", "before", "the", "SDK", "is", "allowed", "to", "work", "." ]
ba0a1568f705cdd6206639bfab1e5cf529084b59
https://github.com/wonderpush/wonderpush-android-sdk/blob/ba0a1568f705cdd6206639bfab1e5cf529084b59/sdk/src/main/java/com/wonderpush/sdk/WonderPush.java#L1412-L1426
9,858
wonderpush/wonderpush-android-sdk
sdk/src/main/java/com/wonderpush/sdk/WonderPush.java
WonderPush.setUserConsent
public static void setUserConsent(boolean value) { boolean hadUserConsent = hasUserConsent(); WonderPushConfiguration.setUserConsent(value); boolean nowHasUserConsent = hasUserConsent(); if (sIsInitialized && hadUserConsent != nowHasUserConsent) { hasUserConsentChanged(nowHasUserConsent); } }
java
public static void setUserConsent(boolean value) { boolean hadUserConsent = hasUserConsent(); WonderPushConfiguration.setUserConsent(value); boolean nowHasUserConsent = hasUserConsent(); if (sIsInitialized && hadUserConsent != nowHasUserConsent) { hasUserConsentChanged(nowHasUserConsent); } }
[ "public", "static", "void", "setUserConsent", "(", "boolean", "value", ")", "{", "boolean", "hadUserConsent", "=", "hasUserConsent", "(", ")", ";", "WonderPushConfiguration", ".", "setUserConsent", "(", "value", ")", ";", "boolean", "nowHasUserConsent", "=", "hasUserConsent", "(", ")", ";", "if", "(", "sIsInitialized", "&&", "hadUserConsent", "!=", "nowHasUserConsent", ")", "{", "hasUserConsentChanged", "(", "nowHasUserConsent", ")", ";", "}", "}" ]
Provides or withdraws user consent. <p>Call this method after {@link #initialize(Context)}.</p> @param value Whether the user provided or withdrew consent. @see #setRequiresUserConsent(boolean)
[ "Provides", "or", "withdraws", "user", "consent", "." ]
ba0a1568f705cdd6206639bfab1e5cf529084b59
https://github.com/wonderpush/wonderpush-android-sdk/blob/ba0a1568f705cdd6206639bfab1e5cf529084b59/sdk/src/main/java/com/wonderpush/sdk/WonderPush.java#L1453-L1460
9,859
wonderpush/wonderpush-android-sdk
sdk/src/main/java/com/wonderpush/sdk/WonderPush.java
WonderPush.setUserId
@SuppressWarnings("unused") public static void setUserId(String userId) { try { if ("".equals(userId)) userId = null; logDebug("setUserId(" + userId + ")"); // Do nothing if not initialized if (!isInitialized()) { logDebug("setting user id for next initialization"); sBeforeInitializationUserIdSet = true; sBeforeInitializationUserId = userId; return; } sBeforeInitializationUserIdSet = false; sBeforeInitializationUserId = null; String oldUserId = WonderPushConfiguration.getUserId(); if (userId == null && oldUserId == null || userId != null && userId.equals(oldUserId)) { // User id is the same as before, nothing needs to be done } else { // The user id changed, we must reset the access token initForNewUser(userId); } } catch (Exception e) { Log.e(TAG, "Unexpected error while setting userId to \"" + userId + "\"", e); } }
java
@SuppressWarnings("unused") public static void setUserId(String userId) { try { if ("".equals(userId)) userId = null; logDebug("setUserId(" + userId + ")"); // Do nothing if not initialized if (!isInitialized()) { logDebug("setting user id for next initialization"); sBeforeInitializationUserIdSet = true; sBeforeInitializationUserId = userId; return; } sBeforeInitializationUserIdSet = false; sBeforeInitializationUserId = null; String oldUserId = WonderPushConfiguration.getUserId(); if (userId == null && oldUserId == null || userId != null && userId.equals(oldUserId)) { // User id is the same as before, nothing needs to be done } else { // The user id changed, we must reset the access token initForNewUser(userId); } } catch (Exception e) { Log.e(TAG, "Unexpected error while setting userId to \"" + userId + "\"", e); } }
[ "@", "SuppressWarnings", "(", "\"unused\"", ")", "public", "static", "void", "setUserId", "(", "String", "userId", ")", "{", "try", "{", "if", "(", "\"\"", ".", "equals", "(", "userId", ")", ")", "userId", "=", "null", ";", "logDebug", "(", "\"setUserId(\"", "+", "userId", "+", "\")\"", ")", ";", "// Do nothing if not initialized", "if", "(", "!", "isInitialized", "(", ")", ")", "{", "logDebug", "(", "\"setting user id for next initialization\"", ")", ";", "sBeforeInitializationUserIdSet", "=", "true", ";", "sBeforeInitializationUserId", "=", "userId", ";", "return", ";", "}", "sBeforeInitializationUserIdSet", "=", "false", ";", "sBeforeInitializationUserId", "=", "null", ";", "String", "oldUserId", "=", "WonderPushConfiguration", ".", "getUserId", "(", ")", ";", "if", "(", "userId", "==", "null", "&&", "oldUserId", "==", "null", "||", "userId", "!=", "null", "&&", "userId", ".", "equals", "(", "oldUserId", ")", ")", "{", "// User id is the same as before, nothing needs to be done", "}", "else", "{", "// The user id changed, we must reset the access token", "initForNewUser", "(", "userId", ")", ";", "}", "}", "catch", "(", "Exception", "e", ")", "{", "Log", ".", "e", "(", "TAG", ",", "\"Unexpected error while setting userId to \\\"\"", "+", "userId", "+", "\"\\\"\"", ",", "e", ")", ";", "}", "}" ]
Sets the user id, used to identify a single identity across multiple devices, and to correctly identify multiple users on a single device. <p>If not called, the last used user id it assumed. Defaulting to {@code null} if none is known.</p> <p>Prefer calling this method just before calling {@link #initialize(Context)}, rather than just after.</p> <p> Upon changing userId, the access token is wiped, so avoid unnecessary calls, like calling with {@code null} just before calling with a user id. </p> @param userId The user id, unique to your application. Use {@code null} for anonymous users.<br /> You are strongly encouraged to use your own unique internal identifier.
[ "Sets", "the", "user", "id", "used", "to", "identify", "a", "single", "identity", "across", "multiple", "devices", "and", "to", "correctly", "identify", "multiple", "users", "on", "a", "single", "device", "." ]
ba0a1568f705cdd6206639bfab1e5cf529084b59
https://github.com/wonderpush/wonderpush-android-sdk/blob/ba0a1568f705cdd6206639bfab1e5cf529084b59/sdk/src/main/java/com/wonderpush/sdk/WonderPush.java#L1569-L1596
9,860
wonderpush/wonderpush-android-sdk
sdk/src/main/java/com/wonderpush/sdk/WonderPush.java
WonderPush.getUserId
@SuppressWarnings("unused") public static String getUserId() { String userId = null; try { userId = WonderPushConfiguration.getUserId(); } catch (Exception e) { Log.e(TAG, "Unexpected error while getting userId", e); } return userId; }
java
@SuppressWarnings("unused") public static String getUserId() { String userId = null; try { userId = WonderPushConfiguration.getUserId(); } catch (Exception e) { Log.e(TAG, "Unexpected error while getting userId", e); } return userId; }
[ "@", "SuppressWarnings", "(", "\"unused\"", ")", "public", "static", "String", "getUserId", "(", ")", "{", "String", "userId", "=", "null", ";", "try", "{", "userId", "=", "WonderPushConfiguration", ".", "getUserId", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "Log", ".", "e", "(", "TAG", ",", "\"Unexpected error while getting userId\"", ",", "e", ")", ";", "}", "return", "userId", ";", "}" ]
Gets the user id, used to identify a single identity across multiple devices, and to correctly identify multiple users on a single device. <p>You should not call this method before initializing the SDK.</p> @return The user id, which may be {@code null} for anonymous users. @see #setUserId(String) @see #initialize(Context)
[ "Gets", "the", "user", "id", "used", "to", "identify", "a", "single", "identity", "across", "multiple", "devices", "and", "to", "correctly", "identify", "multiple", "users", "on", "a", "single", "device", "." ]
ba0a1568f705cdd6206639bfab1e5cf529084b59
https://github.com/wonderpush/wonderpush-android-sdk/blob/ba0a1568f705cdd6206639bfab1e5cf529084b59/sdk/src/main/java/com/wonderpush/sdk/WonderPush.java#L1608-L1617
9,861
wonderpush/wonderpush-android-sdk
sdk/src/main/java/com/wonderpush/sdk/WonderPushUriHelper.java
WonderPushUriHelper.getResource
protected static String getResource(Uri uri) { if (!isAPIUri(uri)) { return null; } String scheme = uri.getScheme(); String apiScheme = getBaseUri().getScheme(); // Strip out the protocol and store the result in the "remainder" variable String remainder = uri.toString().substring(scheme.length()); // Strip out the protocol from the base URI String apiRemainder = getBaseUri().toString().substring(apiScheme.length()); // Check that the remainder starts with the apiRemainder if (!remainder.startsWith(apiRemainder)) { return null; } // Return the path, stripped out of the base uri's path return uri.getPath().substring(getBaseUri().getPath().length()); }
java
protected static String getResource(Uri uri) { if (!isAPIUri(uri)) { return null; } String scheme = uri.getScheme(); String apiScheme = getBaseUri().getScheme(); // Strip out the protocol and store the result in the "remainder" variable String remainder = uri.toString().substring(scheme.length()); // Strip out the protocol from the base URI String apiRemainder = getBaseUri().toString().substring(apiScheme.length()); // Check that the remainder starts with the apiRemainder if (!remainder.startsWith(apiRemainder)) { return null; } // Return the path, stripped out of the base uri's path return uri.getPath().substring(getBaseUri().getPath().length()); }
[ "protected", "static", "String", "getResource", "(", "Uri", "uri", ")", "{", "if", "(", "!", "isAPIUri", "(", "uri", ")", ")", "{", "return", "null", ";", "}", "String", "scheme", "=", "uri", ".", "getScheme", "(", ")", ";", "String", "apiScheme", "=", "getBaseUri", "(", ")", ".", "getScheme", "(", ")", ";", "// Strip out the protocol and store the result in the \"remainder\" variable", "String", "remainder", "=", "uri", ".", "toString", "(", ")", ".", "substring", "(", "scheme", ".", "length", "(", ")", ")", ";", "// Strip out the protocol from the base URI", "String", "apiRemainder", "=", "getBaseUri", "(", ")", ".", "toString", "(", ")", ".", "substring", "(", "apiScheme", ".", "length", "(", ")", ")", ";", "// Check that the remainder starts with the apiRemainder", "if", "(", "!", "remainder", ".", "startsWith", "(", "apiRemainder", ")", ")", "{", "return", "null", ";", "}", "// Return the path, stripped out of the base uri's path", "return", "uri", ".", "getPath", "(", ")", ".", "substring", "(", "getBaseUri", "(", ")", ".", "getPath", "(", ")", ".", "length", "(", ")", ")", ";", "}" ]
Extracts the resource path from a Uri. @return The resource path for that Uri, starting with a '/' after the API version number. null if the provided Uri is not a WonderPush uri (isAPIUri returns false).
[ "Extracts", "the", "resource", "path", "from", "a", "Uri", "." ]
ba0a1568f705cdd6206639bfab1e5cf529084b59
https://github.com/wonderpush/wonderpush-android-sdk/blob/ba0a1568f705cdd6206639bfab1e5cf529084b59/sdk/src/main/java/com/wonderpush/sdk/WonderPushUriHelper.java#L24-L45
9,862
wonderpush/wonderpush-android-sdk
sdk/src/main/java/com/wonderpush/sdk/WonderPushUriHelper.java
WonderPushUriHelper.isAPIUri
protected static boolean isAPIUri(Uri uri) { if (uri == null) { return false; } return getBaseUri().getHost().equals(uri.getHost()); }
java
protected static boolean isAPIUri(Uri uri) { if (uri == null) { return false; } return getBaseUri().getHost().equals(uri.getHost()); }
[ "protected", "static", "boolean", "isAPIUri", "(", "Uri", "uri", ")", "{", "if", "(", "uri", "==", "null", ")", "{", "return", "false", ";", "}", "return", "getBaseUri", "(", ")", ".", "getHost", "(", ")", ".", "equals", "(", "uri", ".", "getHost", "(", ")", ")", ";", "}" ]
Checks that the provided URI points to the WonderPush REST server
[ "Checks", "that", "the", "provided", "URI", "points", "to", "the", "WonderPush", "REST", "server" ]
ba0a1568f705cdd6206639bfab1e5cf529084b59
https://github.com/wonderpush/wonderpush-android-sdk/blob/ba0a1568f705cdd6206639bfab1e5cf529084b59/sdk/src/main/java/com/wonderpush/sdk/WonderPushUriHelper.java#L97-L103
9,863
wonderpush/wonderpush-android-sdk
sdk/src/main/java/com/wonderpush/sdk/WonderPushUriHelper.java
WonderPushUriHelper.getAbsoluteUrl
protected static String getAbsoluteUrl(String resource) { if (resource.startsWith("/" + WonderPush.API_VERSION)) { resource = resource.substring(1 + WonderPush.API_VERSION.length()); } return WonderPush.getBaseURL() + resource; }
java
protected static String getAbsoluteUrl(String resource) { if (resource.startsWith("/" + WonderPush.API_VERSION)) { resource = resource.substring(1 + WonderPush.API_VERSION.length()); } return WonderPush.getBaseURL() + resource; }
[ "protected", "static", "String", "getAbsoluteUrl", "(", "String", "resource", ")", "{", "if", "(", "resource", ".", "startsWith", "(", "\"/\"", "+", "WonderPush", ".", "API_VERSION", ")", ")", "{", "resource", "=", "resource", ".", "substring", "(", "1", "+", "WonderPush", ".", "API_VERSION", ".", "length", "(", ")", ")", ";", "}", "return", "WonderPush", ".", "getBaseURL", "(", ")", "+", "resource", ";", "}" ]
Returns the absolute URL for the given resource @param resource The resource path, which may or may not start with "/"+WonderPush.API_VERSION
[ "Returns", "the", "absolute", "URL", "for", "the", "given", "resource" ]
ba0a1568f705cdd6206639bfab1e5cf529084b59
https://github.com/wonderpush/wonderpush-android-sdk/blob/ba0a1568f705cdd6206639bfab1e5cf529084b59/sdk/src/main/java/com/wonderpush/sdk/WonderPushUriHelper.java#L122-L127
9,864
wonderpush/wonderpush-android-sdk
sdk/src/main/java/com/wonderpush/sdk/WonderPushUriHelper.java
WonderPushUriHelper.getNonSecureAbsoluteUrl
protected static String getNonSecureAbsoluteUrl(String resource) { if (resource.startsWith("/" + WonderPush.API_VERSION)) { resource = resource.substring(1 + WonderPush.API_VERSION.length()); } return WonderPush.getNonSecureBaseURL() + resource; }
java
protected static String getNonSecureAbsoluteUrl(String resource) { if (resource.startsWith("/" + WonderPush.API_VERSION)) { resource = resource.substring(1 + WonderPush.API_VERSION.length()); } return WonderPush.getNonSecureBaseURL() + resource; }
[ "protected", "static", "String", "getNonSecureAbsoluteUrl", "(", "String", "resource", ")", "{", "if", "(", "resource", ".", "startsWith", "(", "\"/\"", "+", "WonderPush", ".", "API_VERSION", ")", ")", "{", "resource", "=", "resource", ".", "substring", "(", "1", "+", "WonderPush", ".", "API_VERSION", ".", "length", "(", ")", ")", ";", "}", "return", "WonderPush", ".", "getNonSecureBaseURL", "(", ")", "+", "resource", ";", "}" ]
Returns the non secure absolute url for the given resource @param resource The resource path, which may or may not start with "/"+WonderPush.API_VERSION
[ "Returns", "the", "non", "secure", "absolute", "url", "for", "the", "given", "resource" ]
ba0a1568f705cdd6206639bfab1e5cf529084b59
https://github.com/wonderpush/wonderpush-android-sdk/blob/ba0a1568f705cdd6206639bfab1e5cf529084b59/sdk/src/main/java/com/wonderpush/sdk/WonderPushUriHelper.java#L136-L141
9,865
wonderpush/wonderpush-android-sdk
sdk/src/main/java/com/wonderpush/sdk/InstallationManager.java
InstallationManager.getDeviceName
protected static String getDeviceName() { try { if (WonderPush.getApplicationContext().getPackageManager().checkPermission(android.Manifest.permission.BLUETOOTH, WonderPush.getApplicationContext().getPackageName()) == PackageManager.PERMISSION_GRANTED) { BluetoothAdapter btDevice = BluetoothAdapter.getDefaultAdapter(); return btDevice.getName(); } } catch (Exception ex) { // Ignore } return null; }
java
protected static String getDeviceName() { try { if (WonderPush.getApplicationContext().getPackageManager().checkPermission(android.Manifest.permission.BLUETOOTH, WonderPush.getApplicationContext().getPackageName()) == PackageManager.PERMISSION_GRANTED) { BluetoothAdapter btDevice = BluetoothAdapter.getDefaultAdapter(); return btDevice.getName(); } } catch (Exception ex) { // Ignore } return null; }
[ "protected", "static", "String", "getDeviceName", "(", ")", "{", "try", "{", "if", "(", "WonderPush", ".", "getApplicationContext", "(", ")", ".", "getPackageManager", "(", ")", ".", "checkPermission", "(", "android", ".", "Manifest", ".", "permission", ".", "BLUETOOTH", ",", "WonderPush", ".", "getApplicationContext", "(", ")", ".", "getPackageName", "(", ")", ")", "==", "PackageManager", ".", "PERMISSION_GRANTED", ")", "{", "BluetoothAdapter", "btDevice", "=", "BluetoothAdapter", ".", "getDefaultAdapter", "(", ")", ";", "return", "btDevice", ".", "getName", "(", ")", ";", "}", "}", "catch", "(", "Exception", "ex", ")", "{", "// Ignore", "}", "return", "null", ";", "}" ]
Returns the Bluetooth device name, if permissions are granted, and provided the device actually has Bluetooth.
[ "Returns", "the", "Bluetooth", "device", "name", "if", "permissions", "are", "granted", "and", "provided", "the", "device", "actually", "has", "Bluetooth", "." ]
ba0a1568f705cdd6206639bfab1e5cf529084b59
https://github.com/wonderpush/wonderpush-android-sdk/blob/ba0a1568f705cdd6206639bfab1e5cf529084b59/sdk/src/main/java/com/wonderpush/sdk/InstallationManager.java#L293-L303
9,866
wonderpush/wonderpush-android-sdk
sdk/src/main/java/com/wonderpush/sdk/QueryStringParser.java
QueryStringParser.next
public boolean next() { int len = queryString.length(); while (true) { if (paramEnd == len) { return false; } paramBegin = paramEnd == -1 ? 0 : paramEnd + 1; int idx = queryString.indexOf('&', paramBegin); paramEnd = idx == -1 ? len : idx; if (paramEnd > paramBegin) { idx = queryString.indexOf('=', paramBegin); paramNameEnd = idx == -1 || idx > paramEnd ? paramEnd : idx; paramName = null; paramValue = null; return true; } } }
java
public boolean next() { int len = queryString.length(); while (true) { if (paramEnd == len) { return false; } paramBegin = paramEnd == -1 ? 0 : paramEnd + 1; int idx = queryString.indexOf('&', paramBegin); paramEnd = idx == -1 ? len : idx; if (paramEnd > paramBegin) { idx = queryString.indexOf('=', paramBegin); paramNameEnd = idx == -1 || idx > paramEnd ? paramEnd : idx; paramName = null; paramValue = null; return true; } } }
[ "public", "boolean", "next", "(", ")", "{", "int", "len", "=", "queryString", ".", "length", "(", ")", ";", "while", "(", "true", ")", "{", "if", "(", "paramEnd", "==", "len", ")", "{", "return", "false", ";", "}", "paramBegin", "=", "paramEnd", "==", "-", "1", "?", "0", ":", "paramEnd", "+", "1", ";", "int", "idx", "=", "queryString", ".", "indexOf", "(", "'", "'", ",", "paramBegin", ")", ";", "paramEnd", "=", "idx", "==", "-", "1", "?", "len", ":", "idx", ";", "if", "(", "paramEnd", ">", "paramBegin", ")", "{", "idx", "=", "queryString", ".", "indexOf", "(", "'", "'", ",", "paramBegin", ")", ";", "paramNameEnd", "=", "idx", "==", "-", "1", "||", "idx", ">", "paramEnd", "?", "paramEnd", ":", "idx", ";", "paramName", "=", "null", ";", "paramValue", "=", "null", ";", "return", "true", ";", "}", "}", "}" ]
Move to the next parameter in the query string. @return <code>true</code> if a parameter has been found; <code>false</code> if there are no more parameters
[ "Move", "to", "the", "next", "parameter", "in", "the", "query", "string", "." ]
ba0a1568f705cdd6206639bfab1e5cf529084b59
https://github.com/wonderpush/wonderpush-android-sdk/blob/ba0a1568f705cdd6206639bfab1e5cf529084b59/sdk/src/main/java/com/wonderpush/sdk/QueryStringParser.java#L58-L75
9,867
wonderpush/wonderpush-android-sdk
sdk/src/main/java/com/wonderpush/sdk/QueryStringParser.java
QueryStringParser.search
public boolean search(Collection<String> names) { while (next()) { if (names.contains(getName())) { return true; } } return false; }
java
public boolean search(Collection<String> names) { while (next()) { if (names.contains(getName())) { return true; } } return false; }
[ "public", "boolean", "search", "(", "Collection", "<", "String", ">", "names", ")", "{", "while", "(", "next", "(", ")", ")", "{", "if", "(", "names", ".", "contains", "(", "getName", "(", ")", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Search for a parameter with a name in a given collection. This method iterates over the parameters until a parameter with a matching name has been found. Note that the current parameter is not considered.
[ "Search", "for", "a", "parameter", "with", "a", "name", "in", "a", "given", "collection", ".", "This", "method", "iterates", "over", "the", "parameters", "until", "a", "parameter", "with", "a", "matching", "name", "has", "been", "found", ".", "Note", "that", "the", "current", "parameter", "is", "not", "considered", "." ]
ba0a1568f705cdd6206639bfab1e5cf529084b59
https://github.com/wonderpush/wonderpush-android-sdk/blob/ba0a1568f705cdd6206639bfab1e5cf529084b59/sdk/src/main/java/com/wonderpush/sdk/QueryStringParser.java#L83-L90
9,868
wonderpush/wonderpush-android-sdk
sdk/src/main/java/com/wonderpush/sdk/QueryStringParser.java
QueryStringParser.getRequestParams
public static RequestParams getRequestParams(String queryString) { if (null == queryString) return null; QueryStringParser parser = new QueryStringParser(queryString); RequestParams result = new RequestParams(); while (parser.next()) { result.put(parser.getName(), parser.getValue()); } return result; }
java
public static RequestParams getRequestParams(String queryString) { if (null == queryString) return null; QueryStringParser parser = new QueryStringParser(queryString); RequestParams result = new RequestParams(); while (parser.next()) { result.put(parser.getName(), parser.getValue()); } return result; }
[ "public", "static", "RequestParams", "getRequestParams", "(", "String", "queryString", ")", "{", "if", "(", "null", "==", "queryString", ")", "return", "null", ";", "QueryStringParser", "parser", "=", "new", "QueryStringParser", "(", "queryString", ")", ";", "RequestParams", "result", "=", "new", "RequestParams", "(", ")", ";", "while", "(", "parser", ".", "next", "(", ")", ")", "{", "result", ".", "put", "(", "parser", ".", "getName", "(", ")", ",", "parser", ".", "getValue", "(", ")", ")", ";", "}", "return", "result", ";", "}" ]
Create a WonderPush.RequestParams from this query string
[ "Create", "a", "WonderPush", ".", "RequestParams", "from", "this", "query", "string" ]
ba0a1568f705cdd6206639bfab1e5cf529084b59
https://github.com/wonderpush/wonderpush-android-sdk/blob/ba0a1568f705cdd6206639bfab1e5cf529084b59/sdk/src/main/java/com/wonderpush/sdk/QueryStringParser.java#L132-L142
9,869
GeoLatte/geolatte-common
src/main/java/org/geolatte/common/transformer/TransformationChainFactory.java
TransformationChainFactory.first
public <Intermediate> TransformationConcatenator<Intermediate, Target> first(Transformation<Source, Intermediate> firstTransformation) { transformationChain = new TransformationChain<Source, Target>(); transformationChain.chain.add(firstTransformation); return new TransformationConcatenator<Intermediate, Target>(); }
java
public <Intermediate> TransformationConcatenator<Intermediate, Target> first(Transformation<Source, Intermediate> firstTransformation) { transformationChain = new TransformationChain<Source, Target>(); transformationChain.chain.add(firstTransformation); return new TransformationConcatenator<Intermediate, Target>(); }
[ "public", "<", "Intermediate", ">", "TransformationConcatenator", "<", "Intermediate", ",", "Target", ">", "first", "(", "Transformation", "<", "Source", ",", "Intermediate", ">", "firstTransformation", ")", "{", "transformationChain", "=", "new", "TransformationChain", "<", "Source", ",", "Target", ">", "(", ")", ";", "transformationChain", ".", "chain", ".", "add", "(", "firstTransformation", ")", ";", "return", "new", "TransformationConcatenator", "<", "Intermediate", ",", "Target", ">", "(", ")", ";", "}" ]
Adds the first sub-transformation to the chain. Subsequent transformations can be added by invoking methods on the TransformationConcatenator returned by this method. @param firstTransformation The first transformation in the chain. @param <Intermediate> The type of the output produced by the (intermediate) transformation added. @return A TransformationConcatenator that allows to add additional transformations to the chain or close the chain.
[ "Adds", "the", "first", "sub", "-", "transformation", "to", "the", "chain", ".", "Subsequent", "transformations", "can", "be", "added", "by", "invoking", "methods", "on", "the", "TransformationConcatenator", "returned", "by", "this", "method", "." ]
dc7f92b04d8c6cb706e78cb95e746d8f12089d95
https://github.com/GeoLatte/geolatte-common/blob/dc7f92b04d8c6cb706e78cb95e746d8f12089d95/src/main/java/org/geolatte/common/transformer/TransformationChainFactory.java#L65-L71
9,870
GeoLatte/geolatte-common
src/main/java/org/geolatte/common/reflection/EntityClassReader.java
EntityClassReader.getPropertyMethods
private static List<Method> getPropertyMethods(Class entityClass) { List<Method> result = new ArrayList<Method>(); for (Method m : entityClass.getMethods()) { if (m.getParameterTypes().length == 0 && m.getName().startsWith("get") && m.getReturnType() != void.class) { if (m.getName().equals("getClass")) continue; result.add(m); } } return result; }
java
private static List<Method> getPropertyMethods(Class entityClass) { List<Method> result = new ArrayList<Method>(); for (Method m : entityClass.getMethods()) { if (m.getParameterTypes().length == 0 && m.getName().startsWith("get") && m.getReturnType() != void.class) { if (m.getName().equals("getClass")) continue; result.add(m); } } return result; }
[ "private", "static", "List", "<", "Method", ">", "getPropertyMethods", "(", "Class", "entityClass", ")", "{", "List", "<", "Method", ">", "result", "=", "new", "ArrayList", "<", "Method", ">", "(", ")", ";", "for", "(", "Method", "m", ":", "entityClass", ".", "getMethods", "(", ")", ")", "{", "if", "(", "m", ".", "getParameterTypes", "(", ")", ".", "length", "==", "0", "&&", "m", ".", "getName", "(", ")", ".", "startsWith", "(", "\"get\"", ")", "&&", "m", ".", "getReturnType", "(", ")", "!=", "void", ".", "class", ")", "{", "if", "(", "m", ".", "getName", "(", ")", ".", "equals", "(", "\"getClass\"", ")", ")", "continue", ";", "result", ".", "add", "(", "m", ")", ";", "}", "}", "return", "result", ";", "}" ]
Returns the property-accessors for the specified class; @param entityClass @return
[ "Returns", "the", "property", "-", "accessors", "for", "the", "specified", "class", ";" ]
dc7f92b04d8c6cb706e78cb95e746d8f12089d95
https://github.com/GeoLatte/geolatte-common/blob/dc7f92b04d8c6cb706e78cb95e746d8f12089d95/src/main/java/org/geolatte/common/reflection/EntityClassReader.java#L113-L122
9,871
GeoLatte/geolatte-common
src/main/java/org/geolatte/common/reflection/EntityClassReader.java
EntityClassReader.getGeometryName
public String getGeometryName() { String result = null; if (geometryAccessor != null) { result = geometryAccessor.getPropertyName(); } return result; }
java
public String getGeometryName() { String result = null; if (geometryAccessor != null) { result = geometryAccessor.getPropertyName(); } return result; }
[ "public", "String", "getGeometryName", "(", ")", "{", "String", "result", "=", "null", ";", "if", "(", "geometryAccessor", "!=", "null", ")", "{", "result", "=", "geometryAccessor", ".", "getPropertyName", "(", ")", ";", "}", "return", "result", ";", "}" ]
Returns the name of the geometryfield of the given entity. If no geometry field exists, null is returned. @return the name of the geometryproperty, or null if no geometryproperty exists
[ "Returns", "the", "name", "of", "the", "geometryfield", "of", "the", "given", "entity", ".", "If", "no", "geometry", "field", "exists", "null", "is", "returned", "." ]
dc7f92b04d8c6cb706e78cb95e746d8f12089d95
https://github.com/GeoLatte/geolatte-common/blob/dc7f92b04d8c6cb706e78cb95e746d8f12089d95/src/main/java/org/geolatte/common/reflection/EntityClassReader.java#L243-L249
9,872
GeoLatte/geolatte-common
src/main/java/org/geolatte/common/reflection/EntityClassReader.java
EntityClassReader.getIdName
public String getIdName() { String result = null; if (idAccessor != null) { result = idAccessor.getPropertyName(); } return result; }
java
public String getIdName() { String result = null; if (idAccessor != null) { result = idAccessor.getPropertyName(); } return result; }
[ "public", "String", "getIdName", "(", ")", "{", "String", "result", "=", "null", ";", "if", "(", "idAccessor", "!=", "null", ")", "{", "result", "=", "idAccessor", ".", "getPropertyName", "(", ")", ";", "}", "return", "result", ";", "}" ]
Returns the name of the idfield of the given entity. If no id field exists, null is returned. @return the name of the idproperty, or null if no geometryproperty exists
[ "Returns", "the", "name", "of", "the", "idfield", "of", "the", "given", "entity", ".", "If", "no", "id", "field", "exists", "null", "is", "returned", "." ]
dc7f92b04d8c6cb706e78cb95e746d8f12089d95
https://github.com/GeoLatte/geolatte-common/blob/dc7f92b04d8c6cb706e78cb95e746d8f12089d95/src/main/java/org/geolatte/common/reflection/EntityClassReader.java#L256-L262
9,873
GeoLatte/geolatte-common
src/main/java/org/geolatte/common/reflection/EntityClassReader.java
EntityClassReader.getId
public Object getId(Object objectToGet) throws InvalidObjectReaderException { if (objectToGet == null) { throw new IllegalArgumentException("Given object may not be null"); } if (objectToGet.getClass() != entityClass) { throw new InvalidObjectReaderException("Class of target object does not correspond with entityclass of this reader."); } if (idAccessor == null) { return null; } else { return idAccessor.getValueFrom(objectToGet); } }
java
public Object getId(Object objectToGet) throws InvalidObjectReaderException { if (objectToGet == null) { throw new IllegalArgumentException("Given object may not be null"); } if (objectToGet.getClass() != entityClass) { throw new InvalidObjectReaderException("Class of target object does not correspond with entityclass of this reader."); } if (idAccessor == null) { return null; } else { return idAccessor.getValueFrom(objectToGet); } }
[ "public", "Object", "getId", "(", "Object", "objectToGet", ")", "throws", "InvalidObjectReaderException", "{", "if", "(", "objectToGet", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Given object may not be null\"", ")", ";", "}", "if", "(", "objectToGet", ".", "getClass", "(", ")", "!=", "entityClass", ")", "{", "throw", "new", "InvalidObjectReaderException", "(", "\"Class of target object does not correspond with entityclass of this reader.\"", ")", ";", "}", "if", "(", "idAccessor", "==", "null", ")", "{", "return", "null", ";", "}", "else", "{", "return", "idAccessor", ".", "getValueFrom", "(", "objectToGet", ")", ";", "}", "}" ]
Returns the value of the id of the given object if it is present. If no id property could be found, null is returned. @param objectToGet the object from which the id is desired. @return the value of the id property of the given object @throws IllegalStateException if no value can be retrieved from the object. @throws InvalidObjectReaderException object and entity class mismatch
[ "Returns", "the", "value", "of", "the", "id", "of", "the", "given", "object", "if", "it", "is", "present", ".", "If", "no", "id", "property", "could", "be", "found", "null", "is", "returned", "." ]
dc7f92b04d8c6cb706e78cb95e746d8f12089d95
https://github.com/GeoLatte/geolatte-common/blob/dc7f92b04d8c6cb706e78cb95e746d8f12089d95/src/main/java/org/geolatte/common/reflection/EntityClassReader.java#L273-L286
9,874
GeoLatte/geolatte-common
src/main/java/org/geolatte/common/reflection/EntityClassReader.java
EntityClassReader.getGeometry
public Geometry getGeometry(Object objectToGet) throws InvalidObjectReaderException { if (objectToGet == null) { throw new IllegalArgumentException("The given object may not be null"); } if (objectToGet.getClass() != entityClass) { throw new InvalidObjectReaderException("Class of target object does not correspond with entityclass of this reader."); } if (geometryAccessor == null) { return null; } else { return (Geometry) geometryAccessor.getValueFrom(objectToGet); } }
java
public Geometry getGeometry(Object objectToGet) throws InvalidObjectReaderException { if (objectToGet == null) { throw new IllegalArgumentException("The given object may not be null"); } if (objectToGet.getClass() != entityClass) { throw new InvalidObjectReaderException("Class of target object does not correspond with entityclass of this reader."); } if (geometryAccessor == null) { return null; } else { return (Geometry) geometryAccessor.getValueFrom(objectToGet); } }
[ "public", "Geometry", "getGeometry", "(", "Object", "objectToGet", ")", "throws", "InvalidObjectReaderException", "{", "if", "(", "objectToGet", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"The given object may not be null\"", ")", ";", "}", "if", "(", "objectToGet", ".", "getClass", "(", ")", "!=", "entityClass", ")", "{", "throw", "new", "InvalidObjectReaderException", "(", "\"Class of target object does not correspond with entityclass of this reader.\"", ")", ";", "}", "if", "(", "geometryAccessor", "==", "null", ")", "{", "return", "null", ";", "}", "else", "{", "return", "(", "Geometry", ")", "geometryAccessor", ".", "getValueFrom", "(", "objectToGet", ")", ";", "}", "}" ]
Will retrieve the value of the geometryfield in the given object. If no geometryfield exists, null is returned. If more than one exist, a random one is returned. @param objectToGet the object from which the geometry is to be fetched. @return the geometry of the given object @throws InvalidObjectReaderException If the class of objectToGet does not correspond with the entityclass of this reader. @throws IllegalArgumentException the given object may not be null
[ "Will", "retrieve", "the", "value", "of", "the", "geometryfield", "in", "the", "given", "object", ".", "If", "no", "geometryfield", "exists", "null", "is", "returned", ".", "If", "more", "than", "one", "exist", "a", "random", "one", "is", "returned", "." ]
dc7f92b04d8c6cb706e78cb95e746d8f12089d95
https://github.com/GeoLatte/geolatte-common/blob/dc7f92b04d8c6cb706e78cb95e746d8f12089d95/src/main/java/org/geolatte/common/reflection/EntityClassReader.java#L297-L309
9,875
GeoLatte/geolatte-common
src/main/java/org/geolatte/common/reflection/EntityClassReader.java
EntityClassReader.getPropertyValue
public Object getPropertyValue(Object objectToGet, String propertyPath) throws InvalidObjectReaderException { if (objectToGet == null || propertyPath == null) { throw new IllegalArgumentException("Given object/propertyname may not be null"); } if (objectToGet.getClass() != entityClass) { throw new InvalidObjectReaderException("Class of target object does not correspond with entityclass of this reader."); } StringTokenizer tokenizer = new StringTokenizer(propertyPath, ".", false); return getPropertyValue(objectToGet, tokenizer); }
java
public Object getPropertyValue(Object objectToGet, String propertyPath) throws InvalidObjectReaderException { if (objectToGet == null || propertyPath == null) { throw new IllegalArgumentException("Given object/propertyname may not be null"); } if (objectToGet.getClass() != entityClass) { throw new InvalidObjectReaderException("Class of target object does not correspond with entityclass of this reader."); } StringTokenizer tokenizer = new StringTokenizer(propertyPath, ".", false); return getPropertyValue(objectToGet, tokenizer); }
[ "public", "Object", "getPropertyValue", "(", "Object", "objectToGet", ",", "String", "propertyPath", ")", "throws", "InvalidObjectReaderException", "{", "if", "(", "objectToGet", "==", "null", "||", "propertyPath", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Given object/propertyname may not be null\"", ")", ";", "}", "if", "(", "objectToGet", ".", "getClass", "(", ")", "!=", "entityClass", ")", "{", "throw", "new", "InvalidObjectReaderException", "(", "\"Class of target object does not correspond with entityclass of this reader.\"", ")", ";", "}", "StringTokenizer", "tokenizer", "=", "new", "StringTokenizer", "(", "propertyPath", ",", "\".\"", ",", "false", ")", ";", "return", "getPropertyValue", "(", "objectToGet", ",", "tokenizer", ")", ";", "}" ]
Returns the value of the property with a given name from the given object @param objectToGet The object from which the property value is to be retrieved @param propertyPath The dot-separated path of the property to retrieve. E.g. directly property: "name", sub property: "streetAddress.number" @return The value of the named property in the given object or null if the property can not be found @throws InvalidObjectReaderException If the class of the given object does not correspond with the entityclass of this reader @throws IllegalArgumentException if the given objectToGet or propertyValue is null
[ "Returns", "the", "value", "of", "the", "property", "with", "a", "given", "name", "from", "the", "given", "object" ]
dc7f92b04d8c6cb706e78cb95e746d8f12089d95
https://github.com/GeoLatte/geolatte-common/blob/dc7f92b04d8c6cb706e78cb95e746d8f12089d95/src/main/java/org/geolatte/common/reflection/EntityClassReader.java#L323-L334
9,876
GeoLatte/geolatte-common
src/main/java/org/geolatte/common/reflection/EntityClassReader.java
EntityClassReader.getPropertyValue
private Object getPropertyValue(Object objectToGet, StringTokenizer propertyPathParts) { String propertyName = propertyPathParts.nextToken(); Object propertyValue = null; if (accessorMap.containsKey(propertyName)) { propertyValue = accessorMap.get(propertyName).getValueFrom(objectToGet); } if (!propertyPathParts.hasMoreTokens() || propertyValue == null) return propertyValue; else { EntityClassReader currentPathReader = EntityClassReader.getClassReaderFor(propertyValue.getClass()); return currentPathReader.getPropertyValue(propertyValue, propertyPathParts); } }
java
private Object getPropertyValue(Object objectToGet, StringTokenizer propertyPathParts) { String propertyName = propertyPathParts.nextToken(); Object propertyValue = null; if (accessorMap.containsKey(propertyName)) { propertyValue = accessorMap.get(propertyName).getValueFrom(objectToGet); } if (!propertyPathParts.hasMoreTokens() || propertyValue == null) return propertyValue; else { EntityClassReader currentPathReader = EntityClassReader.getClassReaderFor(propertyValue.getClass()); return currentPathReader.getPropertyValue(propertyValue, propertyPathParts); } }
[ "private", "Object", "getPropertyValue", "(", "Object", "objectToGet", ",", "StringTokenizer", "propertyPathParts", ")", "{", "String", "propertyName", "=", "propertyPathParts", ".", "nextToken", "(", ")", ";", "Object", "propertyValue", "=", "null", ";", "if", "(", "accessorMap", ".", "containsKey", "(", "propertyName", ")", ")", "{", "propertyValue", "=", "accessorMap", ".", "get", "(", "propertyName", ")", ".", "getValueFrom", "(", "objectToGet", ")", ";", "}", "if", "(", "!", "propertyPathParts", ".", "hasMoreTokens", "(", ")", "||", "propertyValue", "==", "null", ")", "return", "propertyValue", ";", "else", "{", "EntityClassReader", "currentPathReader", "=", "EntityClassReader", ".", "getClassReaderFor", "(", "propertyValue", ".", "getClass", "(", ")", ")", ";", "return", "currentPathReader", ".", "getPropertyValue", "(", "propertyValue", ",", "propertyPathParts", ")", ";", "}", "}" ]
Recursive method to get the value of a property path. @param objectToGet The object from which the property value is to be retrieved. @param propertyPathParts A set of property names, with enumeration pointer pointed at the last handled part. @return The value of the named property in the given object or null if the property can not be found.
[ "Recursive", "method", "to", "get", "the", "value", "of", "a", "property", "path", "." ]
dc7f92b04d8c6cb706e78cb95e746d8f12089d95
https://github.com/GeoLatte/geolatte-common/blob/dc7f92b04d8c6cb706e78cb95e746d8f12089d95/src/main/java/org/geolatte/common/reflection/EntityClassReader.java#L343-L359
9,877
GeoLatte/geolatte-common
src/main/java/org/geolatte/common/reflection/EntityClassReader.java
EntityClassReader.getPropertyType
public Class getPropertyType(String propertyPath) { if (propertyPath == null) { throw new IllegalArgumentException("Propertyname may not be null"); } StringTokenizer tokenizer = new StringTokenizer(propertyPath, ".", false); return getPropertyType(tokenizer); }
java
public Class getPropertyType(String propertyPath) { if (propertyPath == null) { throw new IllegalArgumentException("Propertyname may not be null"); } StringTokenizer tokenizer = new StringTokenizer(propertyPath, ".", false); return getPropertyType(tokenizer); }
[ "public", "Class", "getPropertyType", "(", "String", "propertyPath", ")", "{", "if", "(", "propertyPath", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Propertyname may not be null\"", ")", ";", "}", "StringTokenizer", "tokenizer", "=", "new", "StringTokenizer", "(", "propertyPath", ",", "\".\"", ",", "false", ")", ";", "return", "getPropertyType", "(", "tokenizer", ")", ";", "}" ]
Retrieves the type of the given property path. @param propertyPath The dot-separated path of the property type to retrieve. E.g. directly property: "name", sub property: "streetAddress.number" @return the type of the property with the given name or null if the propertyName is not a property of the class managed by this reader. @throws IllegalArgumentException if propertyName is null.
[ "Retrieves", "the", "type", "of", "the", "given", "property", "path", "." ]
dc7f92b04d8c6cb706e78cb95e746d8f12089d95
https://github.com/GeoLatte/geolatte-common/blob/dc7f92b04d8c6cb706e78cb95e746d8f12089d95/src/main/java/org/geolatte/common/reflection/EntityClassReader.java#L370-L378
9,878
GeoLatte/geolatte-common
src/main/java/org/geolatte/common/reflection/EntityClassReader.java
EntityClassReader.getPropertyType
private Class getPropertyType(StringTokenizer propertyPathParts) { String propertyName = propertyPathParts.nextToken(); Class propertyType = null; if (accessorMap.containsKey(propertyName)) { propertyType = accessorMap.get(propertyName).getReturnType(); } else if (propertyName.equals(getIdName())) { propertyType = idAccessor.getReturnType(); } else if (propertyName.equals(getGeometryName())) { propertyType = geometryAccessor.getReturnType(); } if (!propertyPathParts.hasMoreTokens() || propertyType == null) return propertyType; else { EntityClassReader currentPathReader = EntityClassReader.getClassReaderFor(propertyType); return currentPathReader.getPropertyType(propertyPathParts); } }
java
private Class getPropertyType(StringTokenizer propertyPathParts) { String propertyName = propertyPathParts.nextToken(); Class propertyType = null; if (accessorMap.containsKey(propertyName)) { propertyType = accessorMap.get(propertyName).getReturnType(); } else if (propertyName.equals(getIdName())) { propertyType = idAccessor.getReturnType(); } else if (propertyName.equals(getGeometryName())) { propertyType = geometryAccessor.getReturnType(); } if (!propertyPathParts.hasMoreTokens() || propertyType == null) return propertyType; else { EntityClassReader currentPathReader = EntityClassReader.getClassReaderFor(propertyType); return currentPathReader.getPropertyType(propertyPathParts); } }
[ "private", "Class", "getPropertyType", "(", "StringTokenizer", "propertyPathParts", ")", "{", "String", "propertyName", "=", "propertyPathParts", ".", "nextToken", "(", ")", ";", "Class", "propertyType", "=", "null", ";", "if", "(", "accessorMap", ".", "containsKey", "(", "propertyName", ")", ")", "{", "propertyType", "=", "accessorMap", ".", "get", "(", "propertyName", ")", ".", "getReturnType", "(", ")", ";", "}", "else", "if", "(", "propertyName", ".", "equals", "(", "getIdName", "(", ")", ")", ")", "{", "propertyType", "=", "idAccessor", ".", "getReturnType", "(", ")", ";", "}", "else", "if", "(", "propertyName", ".", "equals", "(", "getGeometryName", "(", ")", ")", ")", "{", "propertyType", "=", "geometryAccessor", ".", "getReturnType", "(", ")", ";", "}", "if", "(", "!", "propertyPathParts", ".", "hasMoreTokens", "(", ")", "||", "propertyType", "==", "null", ")", "return", "propertyType", ";", "else", "{", "EntityClassReader", "currentPathReader", "=", "EntityClassReader", ".", "getClassReaderFor", "(", "propertyType", ")", ";", "return", "currentPathReader", ".", "getPropertyType", "(", "propertyPathParts", ")", ";", "}", "}" ]
Recursive method to retrieve the type of the given property path. @param propertyPathParts A set of property names, with enumeration pointer pointed at the last handled part. @return The value of the named property in the given object or null if the property can not be found.
[ "Recursive", "method", "to", "retrieve", "the", "type", "of", "the", "given", "property", "path", "." ]
dc7f92b04d8c6cb706e78cb95e746d8f12089d95
https://github.com/GeoLatte/geolatte-common/blob/dc7f92b04d8c6cb706e78cb95e746d8f12089d95/src/main/java/org/geolatte/common/reflection/EntityClassReader.java#L386-L406
9,879
GeoLatte/geolatte-common
src/main/java/org/geolatte/common/reflection/ObjectToFeatureTransformation.java
ObjectToFeatureTransformation.transform
public Feature transform(Source input) throws TransformationException { if (input == null) { return null; } else { EntityClassReader reader = EntityClassReader.getClassReaderFor(input.getClass()); try { return reader.asFeature(input); } catch (InvalidObjectReaderException e) { // Can't happen! throw new TransformationException("Transformation failed", e); } } }
java
public Feature transform(Source input) throws TransformationException { if (input == null) { return null; } else { EntityClassReader reader = EntityClassReader.getClassReaderFor(input.getClass()); try { return reader.asFeature(input); } catch (InvalidObjectReaderException e) { // Can't happen! throw new TransformationException("Transformation failed", e); } } }
[ "public", "Feature", "transform", "(", "Source", "input", ")", "throws", "TransformationException", "{", "if", "(", "input", "==", "null", ")", "{", "return", "null", ";", "}", "else", "{", "EntityClassReader", "reader", "=", "EntityClassReader", ".", "getClassReaderFor", "(", "input", ".", "getClass", "(", ")", ")", ";", "try", "{", "return", "reader", ".", "asFeature", "(", "input", ")", ";", "}", "catch", "(", "InvalidObjectReaderException", "e", ")", "{", "// Can't happen!", "throw", "new", "TransformationException", "(", "\"Transformation failed\"", ",", "e", ")", ";", "}", "}", "}" ]
Transforms any object into a feature. If the given object is null, null is returned. @param input The given input @return a feature-wrapper around the given object @throws TransformationException if the object can not be completed
[ "Transforms", "any", "object", "into", "a", "feature", ".", "If", "the", "given", "object", "is", "null", "null", "is", "returned", "." ]
dc7f92b04d8c6cb706e78cb95e746d8f12089d95
https://github.com/GeoLatte/geolatte-common/blob/dc7f92b04d8c6cb706e78cb95e746d8f12089d95/src/main/java/org/geolatte/common/reflection/ObjectToFeatureTransformation.java#L52-L64
9,880
GeoLatte/geolatte-common
src/main/java/org/geolatte/common/dataformats/json/jackson/GeometrySerializer.java
GeometrySerializer.writeCrs
protected void writeCrs(JsonGenerator jgen, Geometry shape) throws IOException { /* "crs": { "type": "name", "properties": { "name": "EPSG:xxxx" } } */ if (shape.getSRID() > 0) { jgen.writeFieldName("crs"); jgen.writeStartObject(); jgen.writeStringField("type", "name"); jgen.writeFieldName("properties"); jgen.writeStartObject(); jgen.writeStringField("name", "EPSG:" + shape.getSRID()); jgen.writeEndObject(); jgen.writeEndObject(); } }
java
protected void writeCrs(JsonGenerator jgen, Geometry shape) throws IOException { /* "crs": { "type": "name", "properties": { "name": "EPSG:xxxx" } } */ if (shape.getSRID() > 0) { jgen.writeFieldName("crs"); jgen.writeStartObject(); jgen.writeStringField("type", "name"); jgen.writeFieldName("properties"); jgen.writeStartObject(); jgen.writeStringField("name", "EPSG:" + shape.getSRID()); jgen.writeEndObject(); jgen.writeEndObject(); } }
[ "protected", "void", "writeCrs", "(", "JsonGenerator", "jgen", ",", "Geometry", "shape", ")", "throws", "IOException", "{", "/*\n \"crs\": {\n \"type\": \"name\",\n \"properties\": {\n \"name\": \"EPSG:xxxx\"\n }\n }\n */", "if", "(", "shape", ".", "getSRID", "(", ")", ">", "0", ")", "{", "jgen", ".", "writeFieldName", "(", "\"crs\"", ")", ";", "jgen", ".", "writeStartObject", "(", ")", ";", "jgen", ".", "writeStringField", "(", "\"type\"", ",", "\"name\"", ")", ";", "jgen", ".", "writeFieldName", "(", "\"properties\"", ")", ";", "jgen", ".", "writeStartObject", "(", ")", ";", "jgen", ".", "writeStringField", "(", "\"name\"", ",", "\"EPSG:\"", "+", "shape", ".", "getSRID", "(", ")", ")", ";", "jgen", ".", "writeEndObject", "(", ")", ";", "jgen", ".", "writeEndObject", "(", ")", ";", "}", "}" ]
Writes out the crs information in the GeoJSON string @param jgen the jsongenerator used for the geojson construction @param shape the geometry for which the contents is to be retrieved @throws java.io.IOException If the underlying jsongenerator fails writing the contents
[ "Writes", "out", "the", "crs", "information", "in", "the", "GeoJSON", "string" ]
dc7f92b04d8c6cb706e78cb95e746d8f12089d95
https://github.com/GeoLatte/geolatte-common/blob/dc7f92b04d8c6cb706e78cb95e746d8f12089d95/src/main/java/org/geolatte/common/dataformats/json/jackson/GeometrySerializer.java#L125-L145
9,881
GeoLatte/geolatte-common
src/main/java/org/geolatte/common/dataformats/json/to/GeoJsonToAssembler.java
GeoJsonToAssembler.toTransferObject
public GeoJsonTo toTransferObject(Geometry geometry) { if (geometry instanceof Point) { return toTransferObject((Point) geometry); } else if (geometry instanceof LineString) { return toTransferObject((LineString) geometry); } else if (geometry instanceof MultiPoint) { return toTransferObject((MultiPoint) geometry); } else if (geometry instanceof MultiLineString) { return toTransferObject((MultiLineString) geometry); } else if (geometry instanceof Polygon) { return toTransferObject((Polygon) geometry); } else if (geometry instanceof MultiPolygon) { return toTransferObject((MultiPolygon) geometry); } else if (geometry instanceof GeometryCollection) { return toTransferObject((GeometryCollection) geometry); } return null; }
java
public GeoJsonTo toTransferObject(Geometry geometry) { if (geometry instanceof Point) { return toTransferObject((Point) geometry); } else if (geometry instanceof LineString) { return toTransferObject((LineString) geometry); } else if (geometry instanceof MultiPoint) { return toTransferObject((MultiPoint) geometry); } else if (geometry instanceof MultiLineString) { return toTransferObject((MultiLineString) geometry); } else if (geometry instanceof Polygon) { return toTransferObject((Polygon) geometry); } else if (geometry instanceof MultiPolygon) { return toTransferObject((MultiPolygon) geometry); } else if (geometry instanceof GeometryCollection) { return toTransferObject((GeometryCollection) geometry); } return null; }
[ "public", "GeoJsonTo", "toTransferObject", "(", "Geometry", "geometry", ")", "{", "if", "(", "geometry", "instanceof", "Point", ")", "{", "return", "toTransferObject", "(", "(", "Point", ")", "geometry", ")", ";", "}", "else", "if", "(", "geometry", "instanceof", "LineString", ")", "{", "return", "toTransferObject", "(", "(", "LineString", ")", "geometry", ")", ";", "}", "else", "if", "(", "geometry", "instanceof", "MultiPoint", ")", "{", "return", "toTransferObject", "(", "(", "MultiPoint", ")", "geometry", ")", ";", "}", "else", "if", "(", "geometry", "instanceof", "MultiLineString", ")", "{", "return", "toTransferObject", "(", "(", "MultiLineString", ")", "geometry", ")", ";", "}", "else", "if", "(", "geometry", "instanceof", "Polygon", ")", "{", "return", "toTransferObject", "(", "(", "Polygon", ")", "geometry", ")", ";", "}", "else", "if", "(", "geometry", "instanceof", "MultiPolygon", ")", "{", "return", "toTransferObject", "(", "(", "MultiPolygon", ")", "geometry", ")", ";", "}", "else", "if", "(", "geometry", "instanceof", "GeometryCollection", ")", "{", "return", "toTransferObject", "(", "(", "GeometryCollection", ")", "geometry", ")", ";", "}", "return", "null", ";", "}" ]
Creates the correct TO starting from any geolatte geometry. @param geometry the geometry to convert @return a TO that, once serialized, results in a valid geoJSON representation of the geometry
[ "Creates", "the", "correct", "TO", "starting", "from", "any", "geolatte", "geometry", "." ]
dc7f92b04d8c6cb706e78cb95e746d8f12089d95
https://github.com/GeoLatte/geolatte-common/blob/dc7f92b04d8c6cb706e78cb95e746d8f12089d95/src/main/java/org/geolatte/common/dataformats/json/to/GeoJsonToAssembler.java#L45-L63
9,882
GeoLatte/geolatte-common
src/main/java/org/geolatte/common/dataformats/json/to/GeoJsonToAssembler.java
GeoJsonToAssembler.toTransferObject
public PolygonTo toTransferObject(Polygon input) { PolygonTo result = new PolygonTo(); result.setCrs(GeoJsonTo.createCrsTo("EPSG:" + input.getSRID())); double[][][] rings = new double[input.getNumInteriorRing() + 1][][]; // Exterior ring: rings[0] = getPoints(input.getExteriorRing()); // Interior rings! for (int i = 0; i < input.getNumInteriorRing(); i++) { rings[i + 1] = getPoints(input.getInteriorRingN(i)); } result.setCoordinates(rings); return result; }
java
public PolygonTo toTransferObject(Polygon input) { PolygonTo result = new PolygonTo(); result.setCrs(GeoJsonTo.createCrsTo("EPSG:" + input.getSRID())); double[][][] rings = new double[input.getNumInteriorRing() + 1][][]; // Exterior ring: rings[0] = getPoints(input.getExteriorRing()); // Interior rings! for (int i = 0; i < input.getNumInteriorRing(); i++) { rings[i + 1] = getPoints(input.getInteriorRingN(i)); } result.setCoordinates(rings); return result; }
[ "public", "PolygonTo", "toTransferObject", "(", "Polygon", "input", ")", "{", "PolygonTo", "result", "=", "new", "PolygonTo", "(", ")", ";", "result", ".", "setCrs", "(", "GeoJsonTo", ".", "createCrsTo", "(", "\"EPSG:\"", "+", "input", ".", "getSRID", "(", ")", ")", ")", ";", "double", "[", "]", "[", "]", "[", "]", "rings", "=", "new", "double", "[", "input", ".", "getNumInteriorRing", "(", ")", "+", "1", "]", "[", "", "]", "[", "", "]", ";", "// Exterior ring:", "rings", "[", "0", "]", "=", "getPoints", "(", "input", ".", "getExteriorRing", "(", ")", ")", ";", "// Interior rings!", "for", "(", "int", "i", "=", "0", ";", "i", "<", "input", ".", "getNumInteriorRing", "(", ")", ";", "i", "++", ")", "{", "rings", "[", "i", "+", "1", "]", "=", "getPoints", "(", "input", ".", "getInteriorRingN", "(", "i", ")", ")", ";", "}", "result", ".", "setCoordinates", "(", "rings", ")", ";", "return", "result", ";", "}" ]
Converts a polygon to its corresponding Transfer Object @param input a polygon object @return a transfer object for the polygon
[ "Converts", "a", "polygon", "to", "its", "corresponding", "Transfer", "Object" ]
dc7f92b04d8c6cb706e78cb95e746d8f12089d95
https://github.com/GeoLatte/geolatte-common/blob/dc7f92b04d8c6cb706e78cb95e746d8f12089d95/src/main/java/org/geolatte/common/dataformats/json/to/GeoJsonToAssembler.java#L71-L83
9,883
GeoLatte/geolatte-common
src/main/java/org/geolatte/common/dataformats/json/to/GeoJsonToAssembler.java
GeoJsonToAssembler.toTransferObject
public MultiLineStringTo toTransferObject(MultiLineString input) { MultiLineStringTo result = new MultiLineStringTo(); double[][][] resultCoordinates = new double[input.getNumGeometries()][][]; for (int i = 0; i < input.getNumGeometries(); i++) { resultCoordinates[i] = getPoints(input.getGeometryN(i)); } result.setCoordinates(resultCoordinates); result.setCrs(GeoJsonTo.createCrsTo("EPSG:" + input.getSRID())); return result; }
java
public MultiLineStringTo toTransferObject(MultiLineString input) { MultiLineStringTo result = new MultiLineStringTo(); double[][][] resultCoordinates = new double[input.getNumGeometries()][][]; for (int i = 0; i < input.getNumGeometries(); i++) { resultCoordinates[i] = getPoints(input.getGeometryN(i)); } result.setCoordinates(resultCoordinates); result.setCrs(GeoJsonTo.createCrsTo("EPSG:" + input.getSRID())); return result; }
[ "public", "MultiLineStringTo", "toTransferObject", "(", "MultiLineString", "input", ")", "{", "MultiLineStringTo", "result", "=", "new", "MultiLineStringTo", "(", ")", ";", "double", "[", "]", "[", "]", "[", "]", "resultCoordinates", "=", "new", "double", "[", "input", ".", "getNumGeometries", "(", ")", "]", "[", "", "]", "[", "", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "input", ".", "getNumGeometries", "(", ")", ";", "i", "++", ")", "{", "resultCoordinates", "[", "i", "]", "=", "getPoints", "(", "input", ".", "getGeometryN", "(", "i", ")", ")", ";", "}", "result", ".", "setCoordinates", "(", "resultCoordinates", ")", ";", "result", ".", "setCrs", "(", "GeoJsonTo", ".", "createCrsTo", "(", "\"EPSG:\"", "+", "input", ".", "getSRID", "(", ")", ")", ")", ";", "return", "result", ";", "}" ]
Converts a multilinestring to its corresponding Transfer Object @param input the multilinestring @return a transfer object for the multilinestring
[ "Converts", "a", "multilinestring", "to", "its", "corresponding", "Transfer", "Object" ]
dc7f92b04d8c6cb706e78cb95e746d8f12089d95
https://github.com/GeoLatte/geolatte-common/blob/dc7f92b04d8c6cb706e78cb95e746d8f12089d95/src/main/java/org/geolatte/common/dataformats/json/to/GeoJsonToAssembler.java#L91-L100
9,884
GeoLatte/geolatte-common
src/main/java/org/geolatte/common/dataformats/json/to/GeoJsonToAssembler.java
GeoJsonToAssembler.toTransferObject
public MultiPointTo toTransferObject(MultiPoint input) { MultiPointTo result = new MultiPointTo(); result.setCrs(GeoJsonTo.createCrsTo("EPSG:" + input.getSRID())); result.setCoordinates(getPoints(input)); return result; }
java
public MultiPointTo toTransferObject(MultiPoint input) { MultiPointTo result = new MultiPointTo(); result.setCrs(GeoJsonTo.createCrsTo("EPSG:" + input.getSRID())); result.setCoordinates(getPoints(input)); return result; }
[ "public", "MultiPointTo", "toTransferObject", "(", "MultiPoint", "input", ")", "{", "MultiPointTo", "result", "=", "new", "MultiPointTo", "(", ")", ";", "result", ".", "setCrs", "(", "GeoJsonTo", ".", "createCrsTo", "(", "\"EPSG:\"", "+", "input", ".", "getSRID", "(", ")", ")", ")", ";", "result", ".", "setCoordinates", "(", "getPoints", "(", "input", ")", ")", ";", "return", "result", ";", "}" ]
Converts a multipoint to its corresponding Transfer Object @param input the multipoint @return a transfer object for the multipoint
[ "Converts", "a", "multipoint", "to", "its", "corresponding", "Transfer", "Object" ]
dc7f92b04d8c6cb706e78cb95e746d8f12089d95
https://github.com/GeoLatte/geolatte-common/blob/dc7f92b04d8c6cb706e78cb95e746d8f12089d95/src/main/java/org/geolatte/common/dataformats/json/to/GeoJsonToAssembler.java#L108-L113
9,885
GeoLatte/geolatte-common
src/main/java/org/geolatte/common/dataformats/json/to/GeoJsonToAssembler.java
GeoJsonToAssembler.toTransferObject
public PointTo toTransferObject(Point input) { PointTo result = new PointTo(); result.setCrs(GeoJsonTo.createCrsTo("EPSG:" + input.getSRID())); result.setCoordinates(getPoints(input)[0]); return result; }
java
public PointTo toTransferObject(Point input) { PointTo result = new PointTo(); result.setCrs(GeoJsonTo.createCrsTo("EPSG:" + input.getSRID())); result.setCoordinates(getPoints(input)[0]); return result; }
[ "public", "PointTo", "toTransferObject", "(", "Point", "input", ")", "{", "PointTo", "result", "=", "new", "PointTo", "(", ")", ";", "result", ".", "setCrs", "(", "GeoJsonTo", ".", "createCrsTo", "(", "\"EPSG:\"", "+", "input", ".", "getSRID", "(", ")", ")", ")", ";", "result", ".", "setCoordinates", "(", "getPoints", "(", "input", ")", "[", "0", "]", ")", ";", "return", "result", ";", "}" ]
Converts a point to its corresponding Transfer Object @param input the point object @return the transfer object for the point
[ "Converts", "a", "point", "to", "its", "corresponding", "Transfer", "Object" ]
dc7f92b04d8c6cb706e78cb95e746d8f12089d95
https://github.com/GeoLatte/geolatte-common/blob/dc7f92b04d8c6cb706e78cb95e746d8f12089d95/src/main/java/org/geolatte/common/dataformats/json/to/GeoJsonToAssembler.java#L121-L126
9,886
GeoLatte/geolatte-common
src/main/java/org/geolatte/common/dataformats/json/to/GeoJsonToAssembler.java
GeoJsonToAssembler.toTransferObject
public LineStringTo toTransferObject(LineString input) { LineStringTo result = new LineStringTo(); result.setCrs(GeoJsonTo.createCrsTo("EPSG:" + input.getSRID())); result.setCoordinates(getPoints(input)); return result; }
java
public LineStringTo toTransferObject(LineString input) { LineStringTo result = new LineStringTo(); result.setCrs(GeoJsonTo.createCrsTo("EPSG:" + input.getSRID())); result.setCoordinates(getPoints(input)); return result; }
[ "public", "LineStringTo", "toTransferObject", "(", "LineString", "input", ")", "{", "LineStringTo", "result", "=", "new", "LineStringTo", "(", ")", ";", "result", ".", "setCrs", "(", "GeoJsonTo", ".", "createCrsTo", "(", "\"EPSG:\"", "+", "input", ".", "getSRID", "(", ")", ")", ")", ";", "result", ".", "setCoordinates", "(", "getPoints", "(", "input", ")", ")", ";", "return", "result", ";", "}" ]
Converts a linestring to its corresponding Transfer Object @param input the linestring object to convert @return the transfer object for the linestring
[ "Converts", "a", "linestring", "to", "its", "corresponding", "Transfer", "Object" ]
dc7f92b04d8c6cb706e78cb95e746d8f12089d95
https://github.com/GeoLatte/geolatte-common/blob/dc7f92b04d8c6cb706e78cb95e746d8f12089d95/src/main/java/org/geolatte/common/dataformats/json/to/GeoJsonToAssembler.java#L134-L139
9,887
GeoLatte/geolatte-common
src/main/java/org/geolatte/common/dataformats/json/to/GeoJsonToAssembler.java
GeoJsonToAssembler.fromTransferObject
public Geometry fromTransferObject(GeoJsonTo input, CrsId crsId) throws IllegalArgumentException { if (input instanceof PointTo) { return fromTransferObject((PointTo) input, crsId); } else if (input instanceof MultiPointTo) { return fromTransferObject((MultiPointTo) input, crsId); } else if (input instanceof LineStringTo) { return fromTransferObject((LineStringTo) input, crsId); } else if (input instanceof MultiLineStringTo) { return fromTransferObject((MultiLineStringTo) input, crsId); } else if (input instanceof PolygonTo) { return fromTransferObject((PolygonTo) input, crsId); } else if (input instanceof MultiPolygonTo) { return fromTransferObject((MultiPolygonTo) input, crsId); } else if (input instanceof GeometryCollectionTo) { return fromTransferObject((GeometryCollectionTo) input, crsId); } return null; }
java
public Geometry fromTransferObject(GeoJsonTo input, CrsId crsId) throws IllegalArgumentException { if (input instanceof PointTo) { return fromTransferObject((PointTo) input, crsId); } else if (input instanceof MultiPointTo) { return fromTransferObject((MultiPointTo) input, crsId); } else if (input instanceof LineStringTo) { return fromTransferObject((LineStringTo) input, crsId); } else if (input instanceof MultiLineStringTo) { return fromTransferObject((MultiLineStringTo) input, crsId); } else if (input instanceof PolygonTo) { return fromTransferObject((PolygonTo) input, crsId); } else if (input instanceof MultiPolygonTo) { return fromTransferObject((MultiPolygonTo) input, crsId); } else if (input instanceof GeometryCollectionTo) { return fromTransferObject((GeometryCollectionTo) input, crsId); } return null; }
[ "public", "Geometry", "fromTransferObject", "(", "GeoJsonTo", "input", ",", "CrsId", "crsId", ")", "throws", "IllegalArgumentException", "{", "if", "(", "input", "instanceof", "PointTo", ")", "{", "return", "fromTransferObject", "(", "(", "PointTo", ")", "input", ",", "crsId", ")", ";", "}", "else", "if", "(", "input", "instanceof", "MultiPointTo", ")", "{", "return", "fromTransferObject", "(", "(", "MultiPointTo", ")", "input", ",", "crsId", ")", ";", "}", "else", "if", "(", "input", "instanceof", "LineStringTo", ")", "{", "return", "fromTransferObject", "(", "(", "LineStringTo", ")", "input", ",", "crsId", ")", ";", "}", "else", "if", "(", "input", "instanceof", "MultiLineStringTo", ")", "{", "return", "fromTransferObject", "(", "(", "MultiLineStringTo", ")", "input", ",", "crsId", ")", ";", "}", "else", "if", "(", "input", "instanceof", "PolygonTo", ")", "{", "return", "fromTransferObject", "(", "(", "PolygonTo", ")", "input", ",", "crsId", ")", ";", "}", "else", "if", "(", "input", "instanceof", "MultiPolygonTo", ")", "{", "return", "fromTransferObject", "(", "(", "MultiPolygonTo", ")", "input", ",", "crsId", ")", ";", "}", "else", "if", "(", "input", "instanceof", "GeometryCollectionTo", ")", "{", "return", "fromTransferObject", "(", "(", "GeometryCollectionTo", ")", "input", ",", "crsId", ")", ";", "}", "return", "null", ";", "}" ]
Creates a geolatte geometry object starting from a GeoJsonTo. @param input the geojson to to start from @param crsId the crs id to use (ignores the crs of the input). If null, uses the crs of the input. @return the corresponding geometry @throws IllegalArgumentException If the geometry could not be constructed due to an invalid geojsonto
[ "Creates", "a", "geolatte", "geometry", "object", "starting", "from", "a", "GeoJsonTo", "." ]
dc7f92b04d8c6cb706e78cb95e746d8f12089d95
https://github.com/GeoLatte/geolatte-common/blob/dc7f92b04d8c6cb706e78cb95e746d8f12089d95/src/main/java/org/geolatte/common/dataformats/json/to/GeoJsonToAssembler.java#L202-L220
9,888
GeoLatte/geolatte-common
src/main/java/org/geolatte/common/dataformats/json/to/GeoJsonToAssembler.java
GeoJsonToAssembler.fromTransferObject
public Polygon fromTransferObject(PolygonTo input, CrsId crsId) { if (input == null) { return null; } crsId = getCrsId(input, crsId); isValid(input); return createPolygon(input.getCoordinates(), crsId); }
java
public Polygon fromTransferObject(PolygonTo input, CrsId crsId) { if (input == null) { return null; } crsId = getCrsId(input, crsId); isValid(input); return createPolygon(input.getCoordinates(), crsId); }
[ "public", "Polygon", "fromTransferObject", "(", "PolygonTo", "input", ",", "CrsId", "crsId", ")", "{", "if", "(", "input", "==", "null", ")", "{", "return", "null", ";", "}", "crsId", "=", "getCrsId", "(", "input", ",", "crsId", ")", ";", "isValid", "(", "input", ")", ";", "return", "createPolygon", "(", "input", ".", "getCoordinates", "(", ")", ",", "crsId", ")", ";", "}" ]
Creates a polygon object starting from a transfer object. @param input the polygon transfer object @param crsId the crs id to use (ignores the crs of the input). If null, uses the crs of the input. @return the corresponding geometry @throws IllegalArgumentException If the geometry could not be constructed due to an invalid transfer object
[ "Creates", "a", "polygon", "object", "starting", "from", "a", "transfer", "object", "." ]
dc7f92b04d8c6cb706e78cb95e746d8f12089d95
https://github.com/GeoLatte/geolatte-common/blob/dc7f92b04d8c6cb706e78cb95e746d8f12089d95/src/main/java/org/geolatte/common/dataformats/json/to/GeoJsonToAssembler.java#L242-L249
9,889
GeoLatte/geolatte-common
src/main/java/org/geolatte/common/dataformats/json/to/GeoJsonToAssembler.java
GeoJsonToAssembler.fromTransferObject
public GeometryCollection fromTransferObject(GeometryCollectionTo input, CrsId crsId) { if (input == null) { return null; } crsId = getCrsId(input, crsId); isValid(input); Geometry[] geoms = new Geometry[input.getGeometries().length]; for (int i = 0; i < geoms.length; i++) { geoms[i] = fromTransferObject(input.getGeometries()[i], crsId); } return new GeometryCollection(geoms); }
java
public GeometryCollection fromTransferObject(GeometryCollectionTo input, CrsId crsId) { if (input == null) { return null; } crsId = getCrsId(input, crsId); isValid(input); Geometry[] geoms = new Geometry[input.getGeometries().length]; for (int i = 0; i < geoms.length; i++) { geoms[i] = fromTransferObject(input.getGeometries()[i], crsId); } return new GeometryCollection(geoms); }
[ "public", "GeometryCollection", "fromTransferObject", "(", "GeometryCollectionTo", "input", ",", "CrsId", "crsId", ")", "{", "if", "(", "input", "==", "null", ")", "{", "return", "null", ";", "}", "crsId", "=", "getCrsId", "(", "input", ",", "crsId", ")", ";", "isValid", "(", "input", ")", ";", "Geometry", "[", "]", "geoms", "=", "new", "Geometry", "[", "input", ".", "getGeometries", "(", ")", ".", "length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "geoms", ".", "length", ";", "i", "++", ")", "{", "geoms", "[", "i", "]", "=", "fromTransferObject", "(", "input", ".", "getGeometries", "(", ")", "[", "i", "]", ",", "crsId", ")", ";", "}", "return", "new", "GeometryCollection", "(", "geoms", ")", ";", "}" ]
Creates a geometrycollection object starting from a transfer object. @param input the geometry collection transfer object @param crsId the crs id to use (ignores the crs of the input). If null, uses the crs of the input. @return the corresponding geometry @throws IllegalArgumentException If the geometry could not be constructed due to an invalid transfer object
[ "Creates", "a", "geometrycollection", "object", "starting", "from", "a", "transfer", "object", "." ]
dc7f92b04d8c6cb706e78cb95e746d8f12089d95
https://github.com/GeoLatte/geolatte-common/blob/dc7f92b04d8c6cb706e78cb95e746d8f12089d95/src/main/java/org/geolatte/common/dataformats/json/to/GeoJsonToAssembler.java#L271-L282
9,890
GeoLatte/geolatte-common
src/main/java/org/geolatte/common/dataformats/json/to/GeoJsonToAssembler.java
GeoJsonToAssembler.fromTransferObject
public MultiPolygon fromTransferObject(MultiPolygonTo input, CrsId crsId) { if (input == null) { return null; } crsId = getCrsId(input, crsId); isValid(input); Polygon[] polygons = new Polygon[input.getCoordinates().length]; for (int i = 0; i < polygons.length; i++) { polygons[i] = createPolygon(input.getCoordinates()[i], crsId); } return new MultiPolygon(polygons); }
java
public MultiPolygon fromTransferObject(MultiPolygonTo input, CrsId crsId) { if (input == null) { return null; } crsId = getCrsId(input, crsId); isValid(input); Polygon[] polygons = new Polygon[input.getCoordinates().length]; for (int i = 0; i < polygons.length; i++) { polygons[i] = createPolygon(input.getCoordinates()[i], crsId); } return new MultiPolygon(polygons); }
[ "public", "MultiPolygon", "fromTransferObject", "(", "MultiPolygonTo", "input", ",", "CrsId", "crsId", ")", "{", "if", "(", "input", "==", "null", ")", "{", "return", "null", ";", "}", "crsId", "=", "getCrsId", "(", "input", ",", "crsId", ")", ";", "isValid", "(", "input", ")", ";", "Polygon", "[", "]", "polygons", "=", "new", "Polygon", "[", "input", ".", "getCoordinates", "(", ")", ".", "length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "polygons", ".", "length", ";", "i", "++", ")", "{", "polygons", "[", "i", "]", "=", "createPolygon", "(", "input", ".", "getCoordinates", "(", ")", "[", "i", "]", ",", "crsId", ")", ";", "}", "return", "new", "MultiPolygon", "(", "polygons", ")", ";", "}" ]
Creates a multipolygon object starting from a transfer object. @param input the multipolygon transfer object @param crsId the crs id to use (ignores the crs of the input). If null, uses the crs of the input. @return the corresponding geometry @throws IllegalArgumentException If the geometry could not be constructed due to an invalid transfer object
[ "Creates", "a", "multipolygon", "object", "starting", "from", "a", "transfer", "object", "." ]
dc7f92b04d8c6cb706e78cb95e746d8f12089d95
https://github.com/GeoLatte/geolatte-common/blob/dc7f92b04d8c6cb706e78cb95e746d8f12089d95/src/main/java/org/geolatte/common/dataformats/json/to/GeoJsonToAssembler.java#L304-L315
9,891
GeoLatte/geolatte-common
src/main/java/org/geolatte/common/dataformats/json/to/GeoJsonToAssembler.java
GeoJsonToAssembler.fromTransferObject
public MultiLineString fromTransferObject(MultiLineStringTo input, CrsId crsId) { if (input == null) { return null; } crsId = getCrsId(input, crsId); isValid(input); LineString[] lineStrings = new LineString[input.getCoordinates().length]; for (int i = 0; i < lineStrings.length; i++) { lineStrings[i] = new LineString(createPointSequence(input.getCoordinates()[i], crsId)); } return new MultiLineString(lineStrings); }
java
public MultiLineString fromTransferObject(MultiLineStringTo input, CrsId crsId) { if (input == null) { return null; } crsId = getCrsId(input, crsId); isValid(input); LineString[] lineStrings = new LineString[input.getCoordinates().length]; for (int i = 0; i < lineStrings.length; i++) { lineStrings[i] = new LineString(createPointSequence(input.getCoordinates()[i], crsId)); } return new MultiLineString(lineStrings); }
[ "public", "MultiLineString", "fromTransferObject", "(", "MultiLineStringTo", "input", ",", "CrsId", "crsId", ")", "{", "if", "(", "input", "==", "null", ")", "{", "return", "null", ";", "}", "crsId", "=", "getCrsId", "(", "input", ",", "crsId", ")", ";", "isValid", "(", "input", ")", ";", "LineString", "[", "]", "lineStrings", "=", "new", "LineString", "[", "input", ".", "getCoordinates", "(", ")", ".", "length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "lineStrings", ".", "length", ";", "i", "++", ")", "{", "lineStrings", "[", "i", "]", "=", "new", "LineString", "(", "createPointSequence", "(", "input", ".", "getCoordinates", "(", ")", "[", "i", "]", ",", "crsId", ")", ")", ";", "}", "return", "new", "MultiLineString", "(", "lineStrings", ")", ";", "}" ]
Creates a multilinestring object starting from a transfer object. @param input the multilinestring transfer object @param crsId the crs id to use (ignores the crs of the input). If null, uses the crs of the input. @return the corresponding geometry @throws IllegalArgumentException If the geometry could not be constructed due to an invalid transfer object
[ "Creates", "a", "multilinestring", "object", "starting", "from", "a", "transfer", "object", "." ]
dc7f92b04d8c6cb706e78cb95e746d8f12089d95
https://github.com/GeoLatte/geolatte-common/blob/dc7f92b04d8c6cb706e78cb95e746d8f12089d95/src/main/java/org/geolatte/common/dataformats/json/to/GeoJsonToAssembler.java#L336-L347
9,892
GeoLatte/geolatte-common
src/main/java/org/geolatte/common/dataformats/json/to/GeoJsonToAssembler.java
GeoJsonToAssembler.fromTransferObject
public LineString fromTransferObject(LineStringTo input, CrsId crsId) { if (input == null) { return null; } crsId = getCrsId(input, crsId); isValid(input); return new LineString(createPointSequence(input.getCoordinates(), crsId)); }
java
public LineString fromTransferObject(LineStringTo input, CrsId crsId) { if (input == null) { return null; } crsId = getCrsId(input, crsId); isValid(input); return new LineString(createPointSequence(input.getCoordinates(), crsId)); }
[ "public", "LineString", "fromTransferObject", "(", "LineStringTo", "input", ",", "CrsId", "crsId", ")", "{", "if", "(", "input", "==", "null", ")", "{", "return", "null", ";", "}", "crsId", "=", "getCrsId", "(", "input", ",", "crsId", ")", ";", "isValid", "(", "input", ")", ";", "return", "new", "LineString", "(", "createPointSequence", "(", "input", ".", "getCoordinates", "(", ")", ",", "crsId", ")", ")", ";", "}" ]
Creates a linestring object starting from a transfer object. @param input the linestring transfer object @param crsId the crs id to use (ignores the crs of the input). If null, uses the crs of the input. @return the corresponding geometry @throws IllegalArgumentException If the geometry could not be constructed due to an invalid transfer object
[ "Creates", "a", "linestring", "object", "starting", "from", "a", "transfer", "object", "." ]
dc7f92b04d8c6cb706e78cb95e746d8f12089d95
https://github.com/GeoLatte/geolatte-common/blob/dc7f92b04d8c6cb706e78cb95e746d8f12089d95/src/main/java/org/geolatte/common/dataformats/json/to/GeoJsonToAssembler.java#L368-L375
9,893
GeoLatte/geolatte-common
src/main/java/org/geolatte/common/dataformats/json/to/GeoJsonToAssembler.java
GeoJsonToAssembler.fromTransferObject
public MultiPoint fromTransferObject(MultiPointTo input, CrsId crsId) { if (input == null) { return null; } crsId = getCrsId(input, crsId); isValid(input); Point[] points = new Point[input.getCoordinates().length]; for (int i = 0; i < points.length; i++) { points[i] = createPoint(input.getCoordinates()[i], crsId); } return new MultiPoint(points); }
java
public MultiPoint fromTransferObject(MultiPointTo input, CrsId crsId) { if (input == null) { return null; } crsId = getCrsId(input, crsId); isValid(input); Point[] points = new Point[input.getCoordinates().length]; for (int i = 0; i < points.length; i++) { points[i] = createPoint(input.getCoordinates()[i], crsId); } return new MultiPoint(points); }
[ "public", "MultiPoint", "fromTransferObject", "(", "MultiPointTo", "input", ",", "CrsId", "crsId", ")", "{", "if", "(", "input", "==", "null", ")", "{", "return", "null", ";", "}", "crsId", "=", "getCrsId", "(", "input", ",", "crsId", ")", ";", "isValid", "(", "input", ")", ";", "Point", "[", "]", "points", "=", "new", "Point", "[", "input", ".", "getCoordinates", "(", ")", ".", "length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "points", ".", "length", ";", "i", "++", ")", "{", "points", "[", "i", "]", "=", "createPoint", "(", "input", ".", "getCoordinates", "(", ")", "[", "i", "]", ",", "crsId", ")", ";", "}", "return", "new", "MultiPoint", "(", "points", ")", ";", "}" ]
Creates a multipoint object starting from a transfer object. @param input the multipoint transfer object @param crsId the crs id to use (ignores the crs of the input). If null, uses the crs of the input. @return the corresponding geometry @throws IllegalArgumentException If the geometry could not be constructed due to an invalid transfer object
[ "Creates", "a", "multipoint", "object", "starting", "from", "a", "transfer", "object", "." ]
dc7f92b04d8c6cb706e78cb95e746d8f12089d95
https://github.com/GeoLatte/geolatte-common/blob/dc7f92b04d8c6cb706e78cb95e746d8f12089d95/src/main/java/org/geolatte/common/dataformats/json/to/GeoJsonToAssembler.java#L396-L407
9,894
GeoLatte/geolatte-common
src/main/java/org/geolatte/common/dataformats/json/to/GeoJsonToAssembler.java
GeoJsonToAssembler.fromTransferObject
public Point fromTransferObject(PointTo input, CrsId crsId) { if (input == null) { return null; } crsId = getCrsId(input, crsId); isValid(input); return createPoint(input.getCoordinates(), crsId); }
java
public Point fromTransferObject(PointTo input, CrsId crsId) { if (input == null) { return null; } crsId = getCrsId(input, crsId); isValid(input); return createPoint(input.getCoordinates(), crsId); }
[ "public", "Point", "fromTransferObject", "(", "PointTo", "input", ",", "CrsId", "crsId", ")", "{", "if", "(", "input", "==", "null", ")", "{", "return", "null", ";", "}", "crsId", "=", "getCrsId", "(", "input", ",", "crsId", ")", ";", "isValid", "(", "input", ")", ";", "return", "createPoint", "(", "input", ".", "getCoordinates", "(", ")", ",", "crsId", ")", ";", "}" ]
Creates a point object starting from a transfer object. @param input the point transfer object @param crsId the crs id to use (ignores the crs of the input). If null, uses the crs of the input. @return the corresponding geometry @throws IllegalArgumentException If the geometry could not be constructed due to an invalid transfer object
[ "Creates", "a", "point", "object", "starting", "from", "a", "transfer", "object", "." ]
dc7f92b04d8c6cb706e78cb95e746d8f12089d95
https://github.com/GeoLatte/geolatte-common/blob/dc7f92b04d8c6cb706e78cb95e746d8f12089d95/src/main/java/org/geolatte/common/dataformats/json/to/GeoJsonToAssembler.java#L428-L435
9,895
GeoLatte/geolatte-common
src/main/java/org/geolatte/common/dataformats/json/to/GeoJsonToAssembler.java
GeoJsonToAssembler.createPolygon
private Polygon createPolygon(double[][][] coordinates, CrsId crsId) { LinearRing[] rings = new LinearRing[coordinates.length]; for (int i = 0; i < coordinates.length; i++) { rings[i] = new LinearRing(createPointSequence(coordinates[i], crsId)); } return new Polygon(rings); }
java
private Polygon createPolygon(double[][][] coordinates, CrsId crsId) { LinearRing[] rings = new LinearRing[coordinates.length]; for (int i = 0; i < coordinates.length; i++) { rings[i] = new LinearRing(createPointSequence(coordinates[i], crsId)); } return new Polygon(rings); }
[ "private", "Polygon", "createPolygon", "(", "double", "[", "]", "[", "]", "[", "]", "coordinates", ",", "CrsId", "crsId", ")", "{", "LinearRing", "[", "]", "rings", "=", "new", "LinearRing", "[", "coordinates", ".", "length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "coordinates", ".", "length", ";", "i", "++", ")", "{", "rings", "[", "i", "]", "=", "new", "LinearRing", "(", "createPointSequence", "(", "coordinates", "[", "i", "]", ",", "crsId", ")", ")", ";", "}", "return", "new", "Polygon", "(", "rings", ")", ";", "}" ]
Creates a polygon starting from its geojson coordinate array @param coordinates the geojson coordinate array @param crsId the srid of the crs to use @return a geolatte polygon instance
[ "Creates", "a", "polygon", "starting", "from", "its", "geojson", "coordinate", "array" ]
dc7f92b04d8c6cb706e78cb95e746d8f12089d95
https://github.com/GeoLatte/geolatte-common/blob/dc7f92b04d8c6cb706e78cb95e746d8f12089d95/src/main/java/org/geolatte/common/dataformats/json/to/GeoJsonToAssembler.java#L446-L452
9,896
GeoLatte/geolatte-common
src/main/java/org/geolatte/common/dataformats/json/to/GeoJsonToAssembler.java
GeoJsonToAssembler.createPointSequence
private PointSequence createPointSequence(double[][] coordinates, CrsId crsId) { if (coordinates == null) { return null; } else if (coordinates.length == 0) { return PointCollectionFactory.createEmpty(); } DimensionalFlag df = coordinates[0].length == 4 ? DimensionalFlag.d3DM : coordinates[0].length == 3 ? DimensionalFlag.d3D : DimensionalFlag.d2D; PointSequenceBuilder psb = PointSequenceBuilders.variableSized(df, crsId); for (double[] point : coordinates) { psb.add(point); } return psb.toPointSequence(); }
java
private PointSequence createPointSequence(double[][] coordinates, CrsId crsId) { if (coordinates == null) { return null; } else if (coordinates.length == 0) { return PointCollectionFactory.createEmpty(); } DimensionalFlag df = coordinates[0].length == 4 ? DimensionalFlag.d3DM : coordinates[0].length == 3 ? DimensionalFlag.d3D : DimensionalFlag.d2D; PointSequenceBuilder psb = PointSequenceBuilders.variableSized(df, crsId); for (double[] point : coordinates) { psb.add(point); } return psb.toPointSequence(); }
[ "private", "PointSequence", "createPointSequence", "(", "double", "[", "]", "[", "]", "coordinates", ",", "CrsId", "crsId", ")", "{", "if", "(", "coordinates", "==", "null", ")", "{", "return", "null", ";", "}", "else", "if", "(", "coordinates", ".", "length", "==", "0", ")", "{", "return", "PointCollectionFactory", ".", "createEmpty", "(", ")", ";", "}", "DimensionalFlag", "df", "=", "coordinates", "[", "0", "]", ".", "length", "==", "4", "?", "DimensionalFlag", ".", "d3DM", ":", "coordinates", "[", "0", "]", ".", "length", "==", "3", "?", "DimensionalFlag", ".", "d3D", ":", "DimensionalFlag", ".", "d2D", ";", "PointSequenceBuilder", "psb", "=", "PointSequenceBuilders", ".", "variableSized", "(", "df", ",", "crsId", ")", ";", "for", "(", "double", "[", "]", "point", ":", "coordinates", ")", "{", "psb", ".", "add", "(", "point", ")", ";", "}", "return", "psb", ".", "toPointSequence", "(", ")", ";", "}" ]
Helpermethod that creates a geolatte pointsequence starting from an array containing coordinate arrays @param coordinates an array containing coordinate arrays @return a geolatte pointsequence or null if the coordinatesequence was null
[ "Helpermethod", "that", "creates", "a", "geolatte", "pointsequence", "starting", "from", "an", "array", "containing", "coordinate", "arrays" ]
dc7f92b04d8c6cb706e78cb95e746d8f12089d95
https://github.com/GeoLatte/geolatte-common/blob/dc7f92b04d8c6cb706e78cb95e746d8f12089d95/src/main/java/org/geolatte/common/dataformats/json/to/GeoJsonToAssembler.java#L460-L473
9,897
GeoLatte/geolatte-common
src/main/java/org/geolatte/common/dataformats/json/to/GeoJsonToAssembler.java
GeoJsonToAssembler.createPoint
private Point createPoint(double[] input, CrsId crsIdValue) { if (input == null) { return null; } if (input.length == 2) { return Points.create2D(input[0], input[1], crsIdValue); } else if(input.length == 3){ return Points.create3D(input[0], input[1], input[2], crsIdValue); } else { double z = input[2]; double m = input[3]; if(Double.isNaN(z)) { return Points.create2DM(input[0],input[1],m,crsIdValue); } else { return Points.create3DM(input[0], input[1], z, m, crsIdValue); } } }
java
private Point createPoint(double[] input, CrsId crsIdValue) { if (input == null) { return null; } if (input.length == 2) { return Points.create2D(input[0], input[1], crsIdValue); } else if(input.length == 3){ return Points.create3D(input[0], input[1], input[2], crsIdValue); } else { double z = input[2]; double m = input[3]; if(Double.isNaN(z)) { return Points.create2DM(input[0],input[1],m,crsIdValue); } else { return Points.create3DM(input[0], input[1], z, m, crsIdValue); } } }
[ "private", "Point", "createPoint", "(", "double", "[", "]", "input", ",", "CrsId", "crsIdValue", ")", "{", "if", "(", "input", "==", "null", ")", "{", "return", "null", ";", "}", "if", "(", "input", ".", "length", "==", "2", ")", "{", "return", "Points", ".", "create2D", "(", "input", "[", "0", "]", ",", "input", "[", "1", "]", ",", "crsIdValue", ")", ";", "}", "else", "if", "(", "input", ".", "length", "==", "3", ")", "{", "return", "Points", ".", "create3D", "(", "input", "[", "0", "]", ",", "input", "[", "1", "]", ",", "input", "[", "2", "]", ",", "crsIdValue", ")", ";", "}", "else", "{", "double", "z", "=", "input", "[", "2", "]", ";", "double", "m", "=", "input", "[", "3", "]", ";", "if", "(", "Double", ".", "isNaN", "(", "z", ")", ")", "{", "return", "Points", ".", "create2DM", "(", "input", "[", "0", "]", ",", "input", "[", "1", "]", ",", "m", ",", "crsIdValue", ")", ";", "}", "else", "{", "return", "Points", ".", "create3DM", "(", "input", "[", "0", "]", ",", "input", "[", "1", "]", ",", "z", ",", "m", ",", "crsIdValue", ")", ";", "}", "}", "}" ]
Helpermethod that creates a point starting from its geojsonto coordinate array @param input the coordinate array to convert to a point @param crsIdValue the sridvalue of the crs in which the point is defined @return an instance of a geolatte point corresponding to the given to or null if the given array is null
[ "Helpermethod", "that", "creates", "a", "point", "starting", "from", "its", "geojsonto", "coordinate", "array" ]
dc7f92b04d8c6cb706e78cb95e746d8f12089d95
https://github.com/GeoLatte/geolatte-common/blob/dc7f92b04d8c6cb706e78cb95e746d8f12089d95/src/main/java/org/geolatte/common/dataformats/json/to/GeoJsonToAssembler.java#L482-L499
9,898
GeoLatte/geolatte-common
src/main/java/org/geolatte/common/dataformats/json/to/GeoJsonToAssembler.java
GeoJsonToAssembler.getPoints
private double[][] getPoints(Geometry input) { double[][] result = new double[input.getNumPoints()][]; for (int i = 0; i < input.getPoints().size(); i++) { Point p = input.getPointN(i); if(p.isMeasured() && p.is3D()) { result[i] = new double[]{p.getX(), p.getY(), p.getZ(), p.getM()}; } else if(p.isMeasured()) { // ideally we'd use something like Double.Nan, but JSON doesn't support that. result[i] = new double[]{p.getX(), p.getY(), 0, p.getM()}; } else if(p.is3D()) { result[i] = new double[]{p.getX(), p.getY(), p.getZ()}; } else { result[i] = new double[]{p.getX(), p.getY()}; } } return result; }
java
private double[][] getPoints(Geometry input) { double[][] result = new double[input.getNumPoints()][]; for (int i = 0; i < input.getPoints().size(); i++) { Point p = input.getPointN(i); if(p.isMeasured() && p.is3D()) { result[i] = new double[]{p.getX(), p.getY(), p.getZ(), p.getM()}; } else if(p.isMeasured()) { // ideally we'd use something like Double.Nan, but JSON doesn't support that. result[i] = new double[]{p.getX(), p.getY(), 0, p.getM()}; } else if(p.is3D()) { result[i] = new double[]{p.getX(), p.getY(), p.getZ()}; } else { result[i] = new double[]{p.getX(), p.getY()}; } } return result; }
[ "private", "double", "[", "]", "[", "]", "getPoints", "(", "Geometry", "input", ")", "{", "double", "[", "]", "[", "]", "result", "=", "new", "double", "[", "input", ".", "getNumPoints", "(", ")", "]", "[", "", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "input", ".", "getPoints", "(", ")", ".", "size", "(", ")", ";", "i", "++", ")", "{", "Point", "p", "=", "input", ".", "getPointN", "(", "i", ")", ";", "if", "(", "p", ".", "isMeasured", "(", ")", "&&", "p", ".", "is3D", "(", ")", ")", "{", "result", "[", "i", "]", "=", "new", "double", "[", "]", "{", "p", ".", "getX", "(", ")", ",", "p", ".", "getY", "(", ")", ",", "p", ".", "getZ", "(", ")", ",", "p", ".", "getM", "(", ")", "}", ";", "}", "else", "if", "(", "p", ".", "isMeasured", "(", ")", ")", "{", "// ideally we'd use something like Double.Nan, but JSON doesn't support that.", "result", "[", "i", "]", "=", "new", "double", "[", "]", "{", "p", ".", "getX", "(", ")", ",", "p", ".", "getY", "(", ")", ",", "0", ",", "p", ".", "getM", "(", ")", "}", ";", "}", "else", "if", "(", "p", ".", "is3D", "(", ")", ")", "{", "result", "[", "i", "]", "=", "new", "double", "[", "]", "{", "p", ".", "getX", "(", ")", ",", "p", ".", "getY", "(", ")", ",", "p", ".", "getZ", "(", ")", "}", ";", "}", "else", "{", "result", "[", "i", "]", "=", "new", "double", "[", "]", "{", "p", ".", "getX", "(", ")", ",", "p", ".", "getY", "(", ")", "}", ";", "}", "}", "return", "result", ";", "}" ]
Serializes all points of the input into a list of their coordinates @param input a geometry whose points are to be converted to a list of coordinates @return an array containing arrays with x,y and optionally z and m values.
[ "Serializes", "all", "points", "of", "the", "input", "into", "a", "list", "of", "their", "coordinates" ]
dc7f92b04d8c6cb706e78cb95e746d8f12089d95
https://github.com/GeoLatte/geolatte-common/blob/dc7f92b04d8c6cb706e78cb95e746d8f12089d95/src/main/java/org/geolatte/common/dataformats/json/to/GeoJsonToAssembler.java#L507-L523
9,899
DjDCH/Log4j-StaticShutdown
src/main/java/com/djdch/log4j/StaticShutdownCallbackRegistry.java
StaticShutdownCallbackRegistry.invoke
public static void invoke() { for (final Runnable instance : instances) { try { instance.run(); } catch (final Throwable t) { LOGGER.error(SHUTDOWN_HOOK_MARKER, "Caught exception executing shutdown hook {}", instance, t); } } }
java
public static void invoke() { for (final Runnable instance : instances) { try { instance.run(); } catch (final Throwable t) { LOGGER.error(SHUTDOWN_HOOK_MARKER, "Caught exception executing shutdown hook {}", instance, t); } } }
[ "public", "static", "void", "invoke", "(", ")", "{", "for", "(", "final", "Runnable", "instance", ":", "instances", ")", "{", "try", "{", "instance", ".", "run", "(", ")", ";", "}", "catch", "(", "final", "Throwable", "t", ")", "{", "LOGGER", ".", "error", "(", "SHUTDOWN_HOOK_MARKER", ",", "\"Caught exception executing shutdown hook {}\"", ",", "instance", ",", "t", ")", ";", "}", "}", "}" ]
Invoke all ShutdownCallbackRegistry instances.
[ "Invoke", "all", "ShutdownCallbackRegistry", "instances", "." ]
4b3b30742950d1834f0613d241c58097e2d313b7
https://github.com/DjDCH/Log4j-StaticShutdown/blob/4b3b30742950d1834f0613d241c58097e2d313b7/src/main/java/com/djdch/log4j/StaticShutdownCallbackRegistry.java#L41-L49