code
stringlengths
73
34.1k
label
stringclasses
1 value
public static void ensureXPathNotNull(Node node, String expression) { if (node == null) { throw LOG.unableToFindXPathExpression(expression); } }
java
public static void ensureXPathNotEmpty(NodeList nodeList, String expression) { if (nodeList == null || nodeList.getLength() == 0) { throw LOG.unableToFindXPathExpression(expression); } }
java
public String getCanonicalTypeName(Object object) { ensureNotNull("object", object); for (TypeDetector typeDetector : typeDetectors) { if (typeDetector.canHandle(object)) { return typeDetector.detectType(object); } } throw LOG.unableToDetectCanonicalType(object); }
java
protected Transformer getTransformer() { TransformerFactory transformerFactory = domXmlDataFormat.getTransformerFactory(); try { Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys....
java
public static Class<?> loadClass(String classname, DataFormat<?> dataFormat) { // first try context classoader ClassLoader cl = Thread.currentThread().getContextClassLoader(); if(cl != null) { LOG.tryLoadingClass(classname, cl); try { return cl.loadClass(classname); } catch(...
java
public static String getExtension(String language) { language = language.toLowerCase(); if("ecmascript".equals(language)) { language = "javascript"; } return extensions.get(language); }
java
public static String get(String language) { language = language.toLowerCase(); if("ecmascript".equals(language)) { language = "javascript"; } String extension = extensions.get(language); if(extension == null) { return null; } else { return loadScriptEnv(language, extension); ...
java
protected Integer getCorrectIndex(Integer index) { Integer size = jsonNode.size(); Integer newIndex = index; // reverse walking through the array if(index < 0) { newIndex = size + index; } // the negative index would be greater than the size a second time! if(newIndex < 0) { th...
java
public void setNamespace(String prefix, String namespaceURI) { ensureNotNull("Prefix", prefix); ensureNotNull("Namespace URI", namespaceURI); namespaces.put(prefix, namespaceURI); }
java
public static <T extends Spin<?>> T S(Object input, DataFormat<T> format) { return SpinFactory.INSTANCE.createSpin(input, format); }
java
public static SpinXmlElement XML(Object input) { return SpinFactory.INSTANCE.createSpin(input, DataFormats.xml()); }
java
public static SpinJsonNode JSON(Object input) { return SpinFactory.INSTANCE.createSpin(input, DataFormats.json()); }
java
public synchronized void stop() throws DatastoreEmulatorException { // We intentionally don't check the internal state. If people want to try and stop the server // multiple times that's fine. stopEmulatorInternal(); if (state != State.STOPPED) { state = State.STOPPED; if (projectDirectory !...
java
private void sendEmptyRequest(String path, String method) throws DatastoreEmulatorException { HttpURLConnection connection = null; try { URL url = new URL(this.host + path); connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod(m...
java
public InputStream call(String methodName, MessageLite request) throws DatastoreException { logger.fine("remote datastore call " + methodName); long startTime = System.currentTimeMillis(); try { HttpResponse httpResponse; try { rpcCount.incrementAndGet(); ProtoHttpContent payloa...
java
private void addGreeting(String guestbookName, String user, String message) throws DatastoreException { Entity.Builder greeting = Entity.newBuilder(); greeting.setKey(makeKey(GUESTBOOK_KIND, guestbookName, GREETING_KIND)); greeting.getMutableProperties().put(USER_PROPERTY, makeValue(user).build()); ...
java
private void listGreetings(String guestbookName) throws DatastoreException { Query.Builder query = Query.newBuilder(); query.addKindBuilder().setName(GREETING_KIND); query.setFilter(makeFilter(KEY_PROPERTY, PropertyFilter.Operator.HAS_ANCESTOR, makeValue(makeKey(GUESTBOOK_KIND, guestbookName)))); ...
java
private Key insert(Entity entity) throws DatastoreException { CommitRequest req = CommitRequest.newBuilder() .addMutations(Mutation.newBuilder() .setInsert(entity)) .setMode(CommitRequest.Mode.NON_TRANSACTIONAL) .build(); return datastore.commit(req).getMutationResults(0).getKey(); }
java
private List<Entity> runQuery(Query query) throws DatastoreException { RunQueryRequest.Builder request = RunQueryRequest.newBuilder(); request.setQuery(query); RunQueryResponse response = datastore.runQuery(request.build()); if (response.getBatch().getMoreResults() == QueryResultBatch.MoreResultsType.N...
java
private void validateFilter(Filter filter) throws IllegalArgumentException { switch (filter.getFilterTypeCase()) { case COMPOSITE_FILTER: for (Filter subFilter : filter.getCompositeFilter().getFiltersList()) { validateFilter(subFilter); } break; case PROPERTY_FILTER: ...
java
private void validateQuery(Query query) throws IllegalArgumentException { if (query.getKindCount() != 1) { throw new IllegalArgumentException("Query must have exactly one kind."); } if (query.getOrderCount() != 0) { throw new IllegalArgumentException("Query cannot have any sort orders."); } ...
java
private List<Key> getScatterKeys( int numSplits, Query query, PartitionId partition, Datastore datastore) throws DatastoreException { Query.Builder scatterPointQuery = createScatterQuery(query, numSplits); List<Key> keySplits = new ArrayList<Key>(); QueryResultBatch batch; do { RunQu...
java
private Query.Builder createScatterQuery(Query query, int numSplits) { // TODO(pcostello): We can potentially support better splits with equality filters in our query // if there exists a composite index on property, __scatter__, __key__. Until an API for // metadata exists, this isn't possible. Note that a...
java
private Iterable<Key> getSplitKey(List<Key> keys, int numSplits) { // If the number of keys is less than the number of splits, we are limited in the number of // splits we can make. if (keys.size() < numSplits - 1) { return keys; } // Calculate the number of keys per split. This should be KEY...
java
public HttpRequestFactory makeClient(DatastoreOptions options) { Credential credential = options.getCredential(); HttpTransport transport = options.getTransport(); if (transport == null) { transport = credential == null ? new NetHttpTransport() : credential.getTransport(); transport = transport ...
java
String buildProjectEndpoint(DatastoreOptions options) { if (options.getProjectEndpoint() != null) { return options.getProjectEndpoint(); } // DatastoreOptions ensures either project endpoint or project ID is set. String projectId = checkNotNull(options.getProjectId()); if (options.getHost() !=...
java
private static synchronized StreamHandler getStreamHandler() { if (methodHandler == null) { methodHandler = new ConsoleHandler(); methodHandler.setFormatter(new Formatter() { @Override public String format(LogRecord record) { return record.getMessage() + "\n"; } }...
java
public static Credential getServiceAccountCredential(String serviceAccountId, String privateKeyFile, Collection<String> serviceAccountScopes) throws GeneralSecurityException, IOException { return getCredentialBuilderWithoutPrivateKey(serviceAccountId, serviceAccountScopes) .setServiceAccount...
java
public static PropertyOrder.Builder makeOrder(String property, PropertyOrder.Direction direction) { return PropertyOrder.newBuilder() .setProperty(makePropertyReference(property)) .setDirection(direction); }
java
public static Filter.Builder makeAncestorFilter(Key ancestor) { return makeFilter( DatastoreHelper.KEY_PROPERTY_NAME, PropertyFilter.Operator.HAS_ANCESTOR, makeValue(ancestor)); }
java
public static Filter.Builder makeAndFilter(Iterable<Filter> subfilters) { return Filter.newBuilder() .setCompositeFilter(CompositeFilter.newBuilder() .addAllFilters(subfilters) .setOp(CompositeFilter.Operator.AND)); }
java
public static Value.Builder makeValue(Value value1, Value value2, Value... rest) { ArrayValue.Builder arrayValue = ArrayValue.newBuilder(); arrayValue.addValues(value1); arrayValue.addValues(value2); arrayValue.addAllValues(Arrays.asList(rest)); return Value.newBuilder().setArrayValue(arrayValue); ...
java
public static Value.Builder makeValue(Date date) { return Value.newBuilder().setTimestampValue(toTimestamp(date.getTime() * 1000L)); }
java
public static <T extends Comparable<? super T>> List<T> sortInplace(List<T> list) { Collections.sort(list); return list; }
java
public static <T, C extends Comparable<? super C>> List<T> sortInplaceBy(List<T> list, final Functions.Function1<? super T, C> key) { if (key == null) throw new NullPointerException("key"); Collections.sort(list, new KeyComparator<T, C>(key)); return list; }
java
@Pure public static <T> List<T> reverseView(List<T> list) { return Lists.reverse(list); }
java
public void set(Object receiver, String fieldName, /* @Nullable */ Object value) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { Preconditions.checkNotNull(receiver,"receiver"); Preconditions.checkNotNull(fieldName,"fieldName"); Class<? extends Object> clazz = re...
java
@SuppressWarnings("unchecked") /* @Nullable */ public <T> T get(Object receiver, String fieldName) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { Preconditions.checkNotNull(receiver,"receiver"); Preconditions.checkNotNull(fieldName,"fieldName"); Class<? ext...
java
public void append(Object object, String indentation) { append(object, indentation, segments.size()); }
java
public void append(String str, String indentation) { if (indentation.isEmpty()) { append(str); } else if (str != null) append(indentation, str, segments.size()); }
java
protected void append(Object object, String indentation, int index) { if (indentation.length() == 0) { append(object, index); return; } if (object == null) return; if (object instanceof String) { append(indentation, (String)object, index); } else if (object instanceof StringConcatenation) { Str...
java
public void appendImmediate(Object object, String indentation) { for (int i = segments.size() - 1; i >= 0; i--) { String segment = segments.get(i); for (int j = 0; j < segment.length(); j++) { if (!WhitespaceMatcher.isWhitespace(segment.charAt(j))) { append(object, indentation, i + 1); return; ...
java
public void newLineIfNotEmpty() { for (int i = segments.size() - 1; i >= 0; i--) { String segment = segments.get(i); if (lineDelimiter.equals(segment)) { segments.subList(i + 1, segments.size()).clear(); cachedToString = null; return; } for (int j = 0; j < segment.length(); j++) { if (!Whi...
java
protected List<String> splitLinesAndNewLines(String text) { if (text == null) return Collections.emptyList(); int idx = initialSegmentSize(text); if (idx == text.length()) { return Collections.singletonList(text); } return continueSplitting(text, idx); }
java
@Pure public static <K, V> Pair<K, V> of(K k, V v) { return new Pair<K, V>(k, v); }
java
@Pure public static <P1> Procedure0 curry(final Procedure1<? super P1> procedure, final P1 argument) { if (procedure == null) throw new NullPointerException("procedure"); return new Procedure0() { @Override public void apply() { procedure.apply(argument); } }; }
java
@Pure public static <P1, P2> Procedure1<P2> curry(final Procedure2<? super P1, ? super P2> procedure, final P1 argument) { if (procedure == null) throw new NullPointerException("procedure"); return new Procedure1<P2>() { @Override public void apply(P2 p) { procedure.apply(argument, p); } }; }
java
@Pure public static <P1, P2, P3> Procedure2<P2, P3> curry(final Procedure3<? super P1, ? super P2, ? super P3> procedure, final P1 argument) { if (procedure == null) throw new NullPointerException("procedure"); return new Procedure2<P2, P3>() { @Override public void apply(P2 p2, P3 p3) { procedure.app...
java
@Pure public static <P1, P2, P3, P4, P5> Procedure4<P2, P3, P4, P5> curry(final Procedure5<? super P1, ? super P2, ? super P3, ? super P4, ? super P5> procedure, final P1 argument) { if (procedure == null) throw new NullPointerException("procedure"); return new Procedure4<P2, P3, P4, P5>() { @Override ...
java
public Path getParent() { if (!isAbsolute()) throw new IllegalStateException("path is not absolute: " + toString()); if (segments.isEmpty()) return null; return new Path(segments.subList(0, segments.size()-1), true); }
java
public Path relativize(Path other) { if (other.isAbsolute() != isAbsolute()) throw new IllegalArgumentException("This path and the given path are not both absolute or both relative: " + toString() + " | " + other.toString()); if (startsWith(other)) { return internalRelativize(this, other); } else if (other....
java
@Inline(value = "$1.put($2.getKey(), $2.getValue())", statementExpression = true) public static <K, V> V operator_add(Map<K, V> map, Pair<? extends K, ? extends V> entry) { return map.put(entry.getKey(), entry.getValue()); }
java
@Inline(value = "$1.putAll($2)", statementExpression = true) public static <K, V> void operator_add(Map<K, V> outputMap, Map<? extends K, ? extends V> inputMap) { outputMap.putAll(inputMap); }
java
@Pure @Inline(value = "$3.union($1, $4.singletonMap($2.getKey(), $2.getValue()))", imported = { MapExtensions.class, Collections.class }) public static <K, V> Map<K, V> operator_plus(Map<K, V> left, final Pair<? extends K, ? extends V> right) { return union(left, Collections.singletonMap(right.getKey(), right.ge...
java
@Pure @Inline(value = "$3.union($1, $2)", imported = MapExtensions.class) public static <K, V> Map<K, V> operator_plus(Map<K, V> left, Map<? extends K, ? extends V> right) { return union(left, right); }
java
@Inline(value = "$1.remove($2)", statementExpression = true) public static <K, V> V operator_remove(Map<K, V> map, K key) { return map.remove(key); }
java
@Inline(value = "$1.remove($2.getKey(), $2.getValue())", statementExpression = true) public static <K, V> boolean operator_remove(Map<K, V> map, Pair<? extends K, ? extends V> entry) { //TODO use the JRE 1.8 API: map.remove(entry.getKey(), entry.getValue()); final K key = entry.getKey(); final V storedValue = ma...
java
public static <K, V> void operator_remove(Map<K, V> map, Iterable<? super K> keysToRemove) { for (final Object key : keysToRemove) { map.remove(key); } }
java
@Pure public static <K, V> Map<K, V> operator_minus(Map<K, V> left, final Pair<? extends K, ? extends V> right) { return Maps.filterEntries(left, new Predicate<Entry<K, V>>() { @Override public boolean apply(Entry<K, V> input) { return !Objects.equal(input.getKey(), right.getKey()) || !Objects.equal(input....
java
@Pure public static <K, V> Map<K, V> operator_minus(Map<K, V> map, final K key) { return Maps.filterKeys(map, new Predicate<K>() { @Override public boolean apply(K input) { return !Objects.equal(input, key); } }); }
java
@Pure public static <K, V> Map<K, V> operator_minus(Map<K, V> left, final Map<? extends K, ? extends V> right) { return Maps.filterEntries(left, new Predicate<Entry<K, V>>() { @Override public boolean apply(Entry<K, V> input) { final V value = right.get(input.getKey()); if (value == null) { return...
java
@Pure public static <K, V> Map<K, V> operator_minus(Map<K, V> map, final Iterable<?> keys) { return Maps.filterKeys(map, new Predicate<K>() { @Override public boolean apply(K input) { return !Iterables.contains(keys, input); } }); }
java
@Pure @Inline(value = "(new $3<$5, $6>($1, $2))", imported = UnmodifiableMergingMapView.class, constantExpression = true) public static <K, V> Map<K, V> union(Map<? extends K, ? extends V> left, Map<? extends K, ? extends V> right) { return new UnmodifiableMergingMapView<K, V>(left, right); }
java
@Pure public static <P1, RESULT> Function0<RESULT> curry(final Function1<? super P1, ? extends RESULT> function, final P1 argument) { if (function == null) throw new NullPointerException("function"); return new Function0<RESULT>() { @Override public RESULT apply() { return function.apply(argument); ...
java
@Pure public static <P1, P2, RESULT> Function1<P2, RESULT> curry(final Function2<? super P1, ? super P2, ? extends RESULT> function, final P1 argument) { if (function == null) throw new NullPointerException("function"); return new Function1<P2, RESULT>() { @Override public RESULT apply(P2 p) { retu...
java
@Pure public static <P1, P2, P3, RESULT> Function2<P2, P3, RESULT> curry(final Function3<? super P1, ? super P2, ? super P3, ? extends RESULT> function, final P1 argument) { if (function == null) throw new NullPointerException("function"); return new Function2<P2, P3, RESULT>() { @Override public RESUL...
java
@Pure public static <P1, P2, P3, P4, RESULT> Function3<P2, P3, P4, RESULT> curry( final Function4<? super P1, ? super P2, ? super P3, ? super P4, ? extends RESULT> function, final P1 argument) { if (function == null) throw new NullPointerException("function"); return new Function3<P2, P3, P4, RESULT>() { ...
java
@Pure public static <T> Iterable<T> filterNull(Iterable<T> unfiltered) { return Iterables.filter(unfiltered, Predicates.notNull()); }
java
public static <T extends Comparable<? super T>> List<T> sort(Iterable<T> iterable) { List<T> asList = Lists.newArrayList(iterable); if (iterable instanceof SortedSet<?>) { if (((SortedSet<T>) iterable).comparator() == null) { return asList; } } return ListExtensions.sortInplace(asList); }
java
public static <T> List<T> sortWith(Iterable<T> iterable, Comparator<? super T> comparator) { return ListExtensions.sortInplace(Lists.newArrayList(iterable), comparator); }
java
public static <T, C extends Comparable<? super C>> List<T> sortBy(Iterable<T> iterable, final Functions.Function1<? super T, C> key) { return ListExtensions.sortInplaceBy(Lists.newArrayList(iterable), key); }
java
private static Object checkComponentType(Object array, Class<?> expectedComponentType) { Class<?> actualComponentType = array.getClass().getComponentType(); if (!expectedComponentType.isAssignableFrom(actualComponentType)) { throw new ArrayStoreException( String.format("The expected component type %s is not...
java
@GwtIncompatible("Class.getDeclaredFields") public ToStringBuilder addDeclaredFields() { Field[] fields = instance.getClass().getDeclaredFields(); for(Field field : fields) { addField(field); } return this; }
java
@GwtIncompatible("Class.getDeclaredFields") public ToStringBuilder addAllFields() { List<Field> fields = getAllDeclaredFields(instance.getClass()); for(Field field : fields) { addField(field); } return this; }
java
@Pure public static <T> Iterator<T> filterNull(Iterator<T> unfiltered) { return Iterators.filter(unfiltered, Predicates.notNull()); }
java
public static <T> List<T> toList(Iterator<? extends T> iterator) { return Lists.newArrayList(iterator); }
java
public static <T> Set<T> toSet(Iterator<? extends T> iterator) { return Sets.newLinkedHashSet(toIterable(iterator)); }
java
public HomekitRoot createBridge( HomekitAuthInfo authInfo, String label, String manufacturer, String model, String serialNumber) throws IOException { HomekitRoot root = new HomekitRoot(label, http, localAddress, authInfo); root.addAccessory(new HomekitBridge(label, serialNumb...
java
protected CompletableFuture<JsonObjectBuilder> makeBuilder(int instanceId) { CompletableFuture<T> futureValue = getValue(); if (futureValue == null) { logger.error("Could not retrieve value " + this.getClass().getName()); return null; } return futureValue .exceptionally( ...
java
protected void setJsonValue(JsonObjectBuilder builder, T value) { // I don't like this - there should really be a way to construct a disconnected JSONValue... if (value instanceof Boolean) { builder.add("value", (Boolean) value); } else if (value instanceof Double) { builder.add("value", (Double...
java
public void removeAll() { LOGGER.debug("Removing {} reverse connections from subscription manager", reverse.size()); Iterator<HomekitClientConnection> i = reverse.keySet().iterator(); while (i.hasNext()) { HomekitClientConnection connection = i.next(); LOGGER.debug("Removing connection {}", conn...
java
public void addAccessory(HomekitAccessory accessory) { if (accessory.getId() <= 1 && !(accessory instanceof Bridge)) { throw new IndexOutOfBoundsException( "The ID of an accessory used in a bridge must be greater than 1"); } addAccessorySkipRangeCheck(accessory); }
java
public void removeAccessory(HomekitAccessory accessory) { this.registry.remove(accessory); logger.info("Removed accessory " + accessory.getLabel()); if (started) { registry.reset(); webHandler.resetConnections(); } }
java
@Override public int add(DownloadRequest request) throws IllegalArgumentException { checkReleased("add(...) called on a released ThinDownloadManager."); if (request == null) { throw new IllegalArgumentException("DownloadRequest cannot be null"); } return mRequestQueue.add...
java
public DownloadRequest addCustomHeader(String key, String value) { mCustomHeader.put(key, value); return this; }
java
private void cleanupDestination(DownloadRequest request, boolean forceClean) { if (!request.isResumable() || forceClean) { Log.d("cleanupDestination() deleting " + request.getDestinationURI().getPath()); File destinationFile = new File(request.getDestinationURI().getPath()); ...
java
int add(DownloadRequest request) { int downloadId = getDownloadId(); // Tag the request as belonging to this queue and add it to the set of current requests. request.setDownloadRequestQueue(this); synchronized (mCurrentRequests) { mCurrentRequests.add(request); } // Process requests in the order they a...
java
int query(int downloadId) { synchronized (mCurrentRequests) { for (DownloadRequest request : mCurrentRequests) { if (request.getDownloadId() == downloadId) { return request.getDownloadState(); } } } return DownloadManager.STATUS_NOT_FOUND; }
java
int cancel(int downloadId) { synchronized (mCurrentRequests) { for (DownloadRequest request : mCurrentRequests) { if (request.getDownloadId() == downloadId) { request.cancel(); return 1; } } } return 0; }
java
void release() { if (mCurrentRequests != null) { synchronized (mCurrentRequests) { mCurrentRequests.clear(); mCurrentRequests = null; } } if (mDownloadQueue != null) { mDownloadQueue = null; } if (mDownloadDispatchers != null) { stop(); for (int i = 0; i < mDownloadDispatchers.length...
java
private void initialize(Handler callbackHandler) { int processors = Runtime.getRuntime().availableProcessors(); mDownloadDispatchers = new DownloadDispatcher[processors]; mDelivery = new CallBackDelivery(callbackHandler); }
java
private void initialize(Handler callbackHandler, int threadPoolSize) { mDownloadDispatchers = new DownloadDispatcher[threadPoolSize]; mDelivery = new CallBackDelivery(callbackHandler); }
java
private void stop() { for (int i = 0; i < mDownloadDispatchers.length; i++) { if (mDownloadDispatchers[i] != null) { mDownloadDispatchers[i].quit(); } } }
java
@SuppressWarnings("unchecked") public Map<String, Field> getValueAsMap() { return (Map<String, Field>) type.convert(getValue(), Type.MAP); }
java
@SuppressWarnings("unchecked") public List<Field> getValueAsList() { return (List<Field>) type.convert(getValue(), Type.LIST); }
java
@SuppressWarnings("unchecked") public LinkedHashMap<String, Field> getValueAsListMap() { return (LinkedHashMap<String, Field>) type.convert(getValue(), Type.LIST_MAP); }
java
public Set<String> getAttributeNames() { if (attributes == null) { return Collections.emptySet(); } else { return Collections.unmodifiableSet(attributes.keySet()); } }
java
public Map<String, String> getAttributes() { if (attributes == null) { return null; } else { return Collections.unmodifiableMap(attributes); } }
java
public static Object formatL(final String template, final Object... args) { return new Object() { @Override public String toString() { return format(template, args); } }; }
java
@Override public List<ConfigIssue> init(Service.Context context) { this.context = context; return init(); }
java