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.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); return transformer; } catch (TransformerConfigurationException e) { throw LOG.unableToCreateTransformer(e); } }
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(Exception e) { // ignore } } // else try the classloader which loaded the dataformat cl = dataFormat.getClass().getClassLoader(); try { LOG.tryLoadingClass(classname, cl); return cl.loadClass(classname); } catch (ClassNotFoundException e) { throw LOG.classNotFound(classname, e); } }
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) { throw LOG.indexOutOfBounds(index, size); } // the index is greater as the actual size if(index > size) { throw LOG.indexOutOfBounds(index, size); } return newIndex; }
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 != null) { try { Process process = new ProcessBuilder("rm", "-r", projectDirectory.getAbsolutePath()).start(); if (process.waitFor() != 0) { throw new IOException( "Temporary project directory deletion exited with " + process.exitValue()); } } catch (IOException e) { throw new IllegalStateException("Could not delete temporary project directory", e); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IllegalStateException("Could not delete temporary project directory", e); } } } }
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(method); connection.getOutputStream().close(); if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new DatastoreEmulatorException( String.format( "%s request to %s returned HTTP status %s", method, path, connection.getResponseCode())); } } catch (IOException e) { throw new DatastoreEmulatorException( String.format("Exception connecting to emulator on %s request to %s", method, path), e); } finally { if (connection != null) { connection.disconnect(); } } }
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 payload = new ProtoHttpContent(request); HttpRequest httpRequest = client.buildPostRequest(resolveURL(methodName), payload); httpRequest.getHeaders().put(API_FORMAT_VERSION_HEADER, API_FORMAT_VERSION); // Don't throw an HTTPResponseException on error. It converts the response to a String and // throws away the original, whereas we need the raw bytes to parse it as a proto. httpRequest.setThrowExceptionOnExecuteError(false); // Datastore requests typically time out after 60s; set the read timeout to slightly longer // than that by default (can be overridden via the HttpRequestInitializer). httpRequest.setReadTimeout(65 * 1000); if (initializer != null) { initializer.initialize(httpRequest); } httpResponse = httpRequest.execute(); if (!httpResponse.isSuccessStatusCode()) { try (InputStream content = GzipFixingInputStream.maybeWrap(httpResponse.getContent())) { throw makeException(url, methodName, content, httpResponse.getContentType(), httpResponse.getContentCharset(), null, httpResponse.getStatusCode()); } } return GzipFixingInputStream.maybeWrap(httpResponse.getContent()); } catch (SocketTimeoutException e) { throw makeException(url, methodName, Code.DEADLINE_EXCEEDED, "Deadline exceeded", e); } catch (IOException e) { throw makeException(url, methodName, Code.UNAVAILABLE, "I/O error", e); } } finally { long elapsedTime = System.currentTimeMillis() - startTime; logger.fine("remote datastore call " + methodName + " took " + elapsedTime + " ms"); } }
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()); greeting.getMutableProperties().put(MESSAGE_PROPERTY, makeValue(message).build()); greeting.getMutableProperties().put(DATE_PROPERTY, makeValue(new Date()).build()); Key greetingKey = insert(greeting.build()); System.out.println("greeting key is: " + greetingKey); }
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)))); query.addOrder(makeOrder(DATE_PROPERTY, PropertyOrder.Direction.DESCENDING)); List<Entity> greetings = runQuery(query.build()); if (greetings.size() == 0) { System.out.println("no greetings in " + guestbookName); } for (Entity greeting : greetings) { Map<String, Value> propertyMap = greeting.getProperties(); System.out.println( DatastoreHelper.toDate(propertyMap.get(DATE_PROPERTY)) + ": " + DatastoreHelper.getString(propertyMap.get(USER_PROPERTY)) + " says " + DatastoreHelper.getString(propertyMap.get(MESSAGE_PROPERTY))); } }
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.NOT_FINISHED) { System.err.println("WARNING: partial results\n"); } List<EntityResult> results = response.getBatch().getEntityResultsList(); List<Entity> entities = new ArrayList<Entity>(results.size()); for (EntityResult result : results) { entities.add(result.getEntity()); } return entities; }
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: if (UNSUPPORTED_OPERATORS.contains(filter.getPropertyFilter().getOp())) { throw new IllegalArgumentException("Query cannot have any inequality filters."); } break; default: throw new IllegalArgumentException( "Unsupported filter type: " + filter.getFilterTypeCase()); } }
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."); } if (query.hasFilter()) { validateFilter(query.getFilter()); } }
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 { RunQueryRequest scatterRequest = RunQueryRequest.newBuilder() .setPartitionId(partition) .setQuery(scatterPointQuery) .build(); batch = datastore.runQuery(scatterRequest).getBatch(); for (EntityResult result : batch.getEntityResultsList()) { keySplits.add(result.getEntity().getKey()); } scatterPointQuery.setStartCursor(batch.getEndCursor()); scatterPointQuery.getLimitBuilder().setValue( scatterPointQuery.getLimit().getValue() - batch.getEntityResultsCount()); } while (batch.getMoreResults() == MoreResultsType.NOT_FINISHED); Collections.sort(keySplits, DatastoreHelper.getKeyComparator()); return keySplits; }
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 ancestor and inequality queries fall into // the same category. Query.Builder scatterPointQuery = Query.newBuilder(); scatterPointQuery.addAllKind(query.getKindList()); scatterPointQuery.addOrder(DatastoreHelper.makeOrder( DatastoreHelper.SCATTER_PROPERTY_NAME, Direction.ASCENDING)); // There is a split containing entities before and after each scatter entity: // ||---*------*------*------*------*------*------*---|| = scatter entity // If we represent each split as a region before a scatter entity, there is an extra region // following the last scatter point. Thus, we do not need the scatter entities for the last // region. scatterPointQuery.getLimitBuilder().setValue((numSplits - 1) * KEYS_PER_SPLIT); scatterPointQuery.addProjection(Projection.newBuilder().setProperty( PropertyReference.newBuilder().setName("__key__"))); return scatterPointQuery; }
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 KEYS_PER_SPLIT, but may // be less if there are not KEYS_PER_SPLIT * (numSplits - 1) scatter entities. // // Consider the following dataset, where - represents an entity and * represents an entity // that is returned as a scatter entity: // ||---*-----*----*-----*-----*------*----*----|| // If we want 4 splits in this data, the optimal split would look like: // ||---*-----*----*-----*-----*------*----*----|| // | | | // The scatter keys in the last region are not useful to us, so we never request them: // ||---*-----*----*-----*-----*------*---------|| // | | | // With 6 scatter keys we want to set scatter points at indexes: 1, 3, 5. // // We keep this as a double so that any "fractional" keys per split get distributed throughout // the splits and don't make the last split significantly larger than the rest. double numKeysPerSplit = Math.max(1.0, ((double) keys.size()) / (numSplits - 1)); List<Key> keysList = new ArrayList<Key>(numSplits - 1); // Grab the last sample for each split, otherwise the first split will be too small. for (int i = 1; i < numSplits; i++) { int splitIndex = (int) Math.round(i * numKeysPerSplit) - 1; keysList.add(keys.get(splitIndex)); } return keysList; }
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 == null ? new NetHttpTransport() : transport; } return transport.createRequestFactory(credential); }
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() != null) { return validateUrl(String.format("https://%s/%s/projects/%s", options.getHost(), VERSION, projectId)); } else if (options.getLocalHost() != null) { return validateUrl(String.format("http://%s/%s/projects/%s", options.getLocalHost(), VERSION, projectId)); } return validateUrl(String.format("%s/%s/projects/%s", DEFAULT_HOST, VERSION, projectId)); }
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"; } }); methodHandler.setLevel(Level.FINE); } return methodHandler; }
java
public static Credential getServiceAccountCredential(String serviceAccountId, String privateKeyFile, Collection<String> serviceAccountScopes) throws GeneralSecurityException, IOException { return getCredentialBuilderWithoutPrivateKey(serviceAccountId, serviceAccountScopes) .setServiceAccountPrivateKeyFromP12File(new File(privateKeyFile)) .build(); }
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 = receiver.getClass(); Field f = getDeclaredField(clazz, fieldName); if (!f.isAccessible()) f.setAccessible(true); f.set(receiver, value); }
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<? extends Object> clazz = receiver.getClass(); Field f = getDeclaredField(clazz, fieldName); if (!f.isAccessible()) f.setAccessible(true); return (T) f.get(receiver); }
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) { StringConcatenation other = (StringConcatenation) object; List<String> otherSegments = other.getSignificantContent(); appendSegments(indentation, index, otherSegments, other.lineDelimiter); } else if (object instanceof StringConcatenationClient) { StringConcatenationClient other = (StringConcatenationClient) object; other.appendTo(new IndentedTarget(this, indentation, index)); } else { final String text = getStringRepresentation(object); if (text != null) { append(indentation, text, index); } } }
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; } } } append(object, indentation, 0); }
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 (!WhitespaceMatcher.isWhitespace(segment.charAt(j))) { newLine(); return; } } } segments.clear(); cachedToString = null; }
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.apply(argument, p2, p3); } }; }
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 public void apply(P2 p2, P3 p3, P4 p4, P5 p5) { procedure.apply(argument, p2, p3, p4, p5); } }; }
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.startsWith(this)) { return internalRelativize(other, this); } return null; }
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.getValue())); }
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 = map.get(entry.getKey()); if (!Objects.equal(storedValue, entry.getValue()) || (storedValue == null && !map.containsKey(key))) { return false; } map.remove(key); return true; }
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.getValue(), right.getValue()); } }); }
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 input.getValue() == null && right.containsKey(input.getKey()); } return !Objects.equal(input.getValue(), value); } }); }
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) { return function.apply(argument, p); } }; }
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 RESULT apply(P2 p2, P3 p3) { return function.apply(argument, p2, p3); } }; }
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>() { @Override public RESULT apply(P2 p2, P3 p3, P4 p4) { return function.apply(argument, p2, p3, p4); } }; }
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 assignable from the actual type %s", expectedComponentType.getCanonicalName(), actualComponentType.getCanonicalName())); } return array; }
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, serialNumber, model, manufacturer)); return root; }
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( t -> { logger.error("Could not retrieve value " + this.getClass().getName(), t); return null; }) .thenApply( value -> { JsonArrayBuilder perms = Json.createArrayBuilder(); if (isWritable) { perms.add("pw"); } if (isReadable) { perms.add("pr"); } if (isEventable) { perms.add("ev"); } JsonObjectBuilder builder = Json.createObjectBuilder() .add("iid", instanceId) .add("type", shortType) .add("perms", perms.build()) .add("format", format) .add("ev", false) .add("description", description); setJsonValue(builder, value); return builder; }); }
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) value); } else if (value instanceof Integer) { builder.add("value", (Integer) value); } else if (value instanceof Long) { builder.add("value", (Long) value); } else if (value instanceof BigInteger) { builder.add("value", (BigInteger) value); } else if (value instanceof BigDecimal) { builder.add("value", (BigDecimal) value); } else if (value == null) { builder.addNull("value"); } else { builder.add("value", value.toString()); } }
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 {}", connection.hashCode()); removeConnection(connection); } LOGGER.debug("Subscription sizes are {} and {}", reverse.size(), subscriptions.size()); }
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(request); }
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()); if (destinationFile.exists()) { destinationFile.delete(); } } }
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 are added. request.setDownloadId(downloadId); mDownloadQueue.add(request); return downloadId; }
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; i++) { mDownloadDispatchers[i] = null; } mDownloadDispatchers = null; } }
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