Java Code Examples for com.google.common.collect.Iterables#toArray()

The following examples show how to use com.google.common.collect.Iterables#toArray() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@Test
public void serviceAccountToJwt() throws Exception {
  KeyPair pair = KeyPairGenerator.getInstance("RSA").generateKeyPair();
  @SuppressWarnings("deprecation")
  ServiceAccountCredentials credentials = new ServiceAccountCredentials(
      null, "[email protected]", pair.getPrivate(), null, null) {
    @Override
    public AccessToken refreshAccessToken() {
      throw new AssertionError();
    }
  };

  GoogleAuthLibraryCallCredentials callCredentials =
      new GoogleAuthLibraryCallCredentials(credentials);
  callCredentials.applyRequestMetadata(new RequestInfoImpl(), executor, applier);
  assertEquals(0, runPendingRunnables());

  verify(applier).apply(headersCaptor.capture());
  Metadata headers = headersCaptor.getValue();
  String[] authorization = Iterables.toArray(headers.getAll(AUTHORIZATION), String.class);
  assertEquals(1, authorization.length);
  assertTrue(authorization[0], authorization[0].startsWith("Bearer "));
  // JWT is reasonably long. Normal tokens aren't.
  assertTrue(authorization[0], authorization[0].length() > 300);
}
 
Example 2
Source Project: envelope   File: NestDeriver.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Row call(Tuple2<Iterable<Row>, Iterable<Row>> cogrouped) throws Exception {
  // There should only be one 'into' record per key
  Row intoRow = cogrouped._1().iterator().next();
  Row[] fromRows = Iterables.toArray(cogrouped._2(), Row.class);
  int intoRowNumFields = intoRow.size();

  Object[] nestedValues = new Object[intoRowNumFields + 1];
  for (int i = 0; i < intoRowNumFields; i++) {
    nestedValues[i] = intoRow.get(i);
  }
  nestedValues[intoRowNumFields] = fromRows;

  Row nested = RowFactory.create(nestedValues);

  return nested;
}
 
Example 3
Source Project: big-c   File: Dispatcher.java    License: Apache License 2.0 6 votes vote down vote up
private void setMoreParams(RequestContext rc, String pathInfo, Dest dest) {
  checkState(pathInfo.startsWith(dest.prefix), "prefix should match");
  if (dest.pathParams.size() == 0 ||
      dest.prefix.length() == pathInfo.length()) {
    return;
  }
  String[] parts = Iterables.toArray(WebApp.pathSplitter.split(
      pathInfo.substring(dest.prefix.length())), String.class);
  LOG.debug("parts={}, params={}", parts, dest.pathParams);
  for (int i = 0; i < dest.pathParams.size() && i < parts.length; ++i) {
    String key = dest.pathParams.get(i);
    if (key.charAt(0) == ':') {
      rc.moreParams().put(key.substring(1), parts[i]);
    }
  }
}
 
Example 4
private void findRowGetSlicesAndAssertColsFound(ColumnFamilyStore cfs, SliceQueryFilter filter, String rowKey,
        String... colNames)
{
    List<Row> rows = cfs.getRangeSlice(new Bounds<RowPosition>(rp(rowKey), rp(rowKey)),
                                       null,
                                       filter,
                                       Integer.MAX_VALUE,
                                       System.currentTimeMillis(),
                                       false,
                                       false);
    assertSame("unexpected number of rows ", 1, rows.size());
    Row row = rows.get(0);
    Collection<Cell> cols = !filter.isReversed() ? row.cf.getSortedColumns() : row.cf.getReverseSortedColumns();
    // printRow(cfs, new String(row.key.key.array()), cols);
    String[] returnedColsNames = Iterables.toArray(Iterables.transform(cols, new Function<Cell, String>()
    {
        public String apply(Cell arg0)
        {
            return Util.string(arg0.name().toByteBuffer());
        }
    }), String.class);

    assertTrue(
            "Columns did not match. Expected: " + Arrays.toString(colNames) + " but got:"
                    + Arrays.toString(returnedColsNames), Arrays.equals(colNames, returnedColsNames));
    int i = 0;
    for (Cell col : cols)
    {
        assertEquals(colNames[i++], Util.string(col.name().toByteBuffer()));
    }
}
 
Example 5
@Override
public Object[] getElements(Object inputElement) {
	if (content != null) {
		return Iterables.toArray(content, Object.class);
	} else {
		return new Object[0];
	}
}
 
Example 6
Source Project: youran   File: ConvertUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 逗号分割字符串转换成Double数组
 *
 * @param str
 * @return
 */
public static Double[] convertDoubleArray(String str) {
    if (StringUtils.isBlank(str)) {
        return null;
    }
    Iterable<String> split = Splitter.on(',').omitEmptyStrings().split(str);
    Iterable<Double> transform = Iterables.transform(split, SafeUtil::getDouble);
    return Iterables.toArray(transform, Double.class);
}
 
Example 7
Source Project: kite   File: Configs.java    License: Apache License 2.0 5 votes vote down vote up
public Locale getLocale(Config config, String path) {
  addRecognizedArgument(path);
  String str = config.getString(path);
  String[] parts = Iterables.toArray(Splitter.on('_').split(str), String.class);
  if (parts.length == 1) {
    return new Locale(parts[0]);
  } else if (parts.length == 2) {
    return new Locale(parts[0], parts[1]);
  } else if (parts.length == 3) {
    return new Locale(parts[0], parts[1], parts[2]);
  } else {
    throw new MorphlineCompilationException("Illegal locale: " + str, config);
  }
}
 
Example 8
Source Project: ob1k   File: CqlSession.java    License: Apache License 2.0 5 votes vote down vote up
public CqlSession(final String nodes, final int port, final String keyspace, final SocketOptions socketOptions,
                  final RetryPolicy retryPolicy, final QueryOptions queryOptions,
                  final LoadBalancingPolicy loadBalancingPolicy, final int maxConnectionsPerHost,
                  final MetricFactory metricFactory) {

  // this is temp. to reuse current hosts properties:
  final Iterable<String> nodesIter = Splitter.on(",").split(nodes);
  final String[] nodesArr = Iterables.toArray(
    StreamSupport.stream(nodesIter.spliterator(), false).map(input -> {
    if (input == null) return null;

    final int idx = input.lastIndexOf(":");
    return input.substring(0, idx);
  }).collect(Collectors.toList()), String.class);


  /*PoolingOptions poolingOptions = new PoolingOptions();
  poolingOptions.setMaxConnectionsPerHost(HostDistance.LOCAL, maxConnectionsPerHost);
  poolingOptions.setMaxConnectionsPerHost(HostDistance.REMOTE, maxConnectionsPerHost);*/


  final Cluster cluster = Cluster.builder().
          withPort(port).
          withSocketOptions(socketOptions).
          withQueryOptions(queryOptions).
          withLoadBalancingPolicy(loadBalancingPolicy).
          //  withPoolingOptions(poolingOptions).
                  addContactPoints(nodesArr).build();
  //cluster.init();
  this.session = cluster.connect(keyspace);
  this.retryPolicy = Preconditions.checkNotNull(retryPolicy);
  this.metricFactory = Preconditions.checkNotNull(metricFactory);
}
 
Example 9
@Override
public WorkingSet[] getAllWorkingSets() {
	return Iterables.toArray(getOrCreateAllWorkingSets(), WorkingSet.class);
}
 
Example 10
Source Project: codebuff   File: Striped.java    License: BSD 2-Clause "Simplified" License 4 votes vote down vote up
/**
 * Returns the stripes that correspond to the passed objects, in ascending (as per
 * {@link #getAt(int)}) order. Thus, threads that use the stripes in the order returned by this
 * method are guaranteed to not deadlock each other.
 *
 * <p>It should be noted that using a {@code Striped<L>} with relatively few stripes, and
 * {@code bulkGet(keys)} with a relative large number of keys can cause an excessive number of
 * shared stripes (much like the birthday paradox, where much fewer than anticipated birthdays are
 * needed for a pair of them to match). Please consider carefully the implications of the number
 * of stripes, the intended concurrency level, and the typical number of keys used in a
 * {@code bulkGet(keys)} operation. See <a href="http://www.mathpages.com/home/kmath199.htm">Balls
 * in Bins model</a> for mathematical formulas that can be used to estimate the probability of
 * collisions.
 *
 * @param keys arbitrary non-null keys
 * @return the stripes corresponding to the objects (one per each object, derived by delegating to
 *     {@link #get(Object)}; may contain duplicates), in an increasing index order.
 */


public Iterable<L> bulkGet(Iterable<?> keys) {
  // Initially using the array to store the keys, then reusing it to store the respective L's
         final Object[] array = Iterables.toArray(keys, Object.class);
         if (array.length == 0) {
           return ImmutableList.of();
         }
         int[] stripes = new int[array.length];
         for (int i = 0; i < array.length; i++) {
           stripes[i] = indexFor(array[i]);
         }
         Arrays.sort(stripes);
  // optimize for runs of identical stripes
         int previousStripe = stripes[0];
         array[0] = getAt(previousStripe);
         for (int i = 1; i < array.length; i++) {
           int currentStripe = stripes[i];
           if (currentStripe == previousStripe) {
             array[i] = array[i - 1];
           } else {
             array[i] = getAt(currentStripe);
             previousStripe = currentStripe;
           }
         }
  /*
   * Note that the returned Iterable holds references to the returned stripes, to avoid
   * error-prone code like:
   *
   * Striped<Lock> stripedLock = Striped.lazyWeakXXX(...)'
   * Iterable<Lock> locks = stripedLock.bulkGet(keys);
   * for (Lock lock : locks) {
   *   lock.lock();
   * }
   * operation();
   * for (Lock lock : locks) {
   *   lock.unlock();
   * }
   *
   * If we only held the int[] stripes, translating it on the fly to L's, the original locks might
   * be garbage collected after locking them, ending up in a huge mess.
   */
         @SuppressWarnings("unchecked") // we carefully replaced all keys with their respective L's
         List<L> asList = (List<L>) Arrays.asList(array);
         return Collections.unmodifiableList(asList);
}
 
Example 11
@Override
public WorkingSet[] getWorkingSets() {
	return Iterables.toArray(getOrCreateVisibleWorkingSets(), WorkingSet.class);
}
 
Example 12
@SuppressWarnings("unchecked")
public AccessLogGenerator(String rawPattern) {
  List<AccessLogItem<RoutingContext>> accessLogItemList = logPatternParser.parsePattern(rawPattern);
  accessLogItems = Iterables.toArray(accessLogItemList, AccessLogItem.class);
}
 
Example 13
Source Project: kylin-on-parquet-v2   File: StringUtil.java    License: Apache License 2.0 4 votes vote down vote up
public static String[] split(String str, String splitBy) {
    return Iterables.toArray(Splitter.on(splitBy).split(str), String.class);
}
 
Example 14
@Override
public IAdaptable[] getElements() {
	return Iterables.toArray(getWorkingSetManager().projectLocations.get(getId()), IAdaptable.class);
}
 
Example 15
@VisibleForTesting
static String[] splitOrderOfLossSection(final String orderOfLossSection) {
  return Iterables.toArray(
      Splitter.on(OOL_AMOUNT_DESCRIPTOR).split(orderOfLossSection), String.class);
}
 
Example 16
private ByteBuffer[] serializedHeader(OLogHeader header) {
  List<ByteBuffer> buffers = encodeWithLengthAndCrc(OLogHeader.getSchema(), header);
  return Iterables.toArray(buffers, ByteBuffer.class);
}
 
Example 17
Source Project: buck   File: MergingException.java    License: Apache License 2.0 4 votes vote down vote up
public static void throwIfNonEmpty(Collection<Message> messages) throws MergingException {
    if (!messages.isEmpty()) {
        throw new MergingException(null, Iterables.toArray(messages, Message.class));
    }
}
 
Example 18
Source Project: youran   File: ConvertUtil.java    License: Apache License 2.0 3 votes vote down vote up
/**
 * 自定义转换器进行数组转换
 *
 * @param list
 * @param function
 * @param clazz
 * @param <F>
 * @param <T>
 * @return
 */
public static <F, T> T[] convertListToArray(List<F> list, Function<F, T> function, Class<T> clazz) {
    if (list == null) {
        return null;
    }
    Iterable<T> transform = Iterables.transform(list, function);
    return Iterables.toArray(transform, clazz);
}
 
Example 19
/**
 * Returns this control's filters.
 *
 * @return an array of viewer filters
 * @since 1.2
 */
public @NonNull ViewerFilter[] getFilters() {
    return Iterables.toArray(fFilters, ViewerFilter.class);
}
 
Example 20
Source Project: onedev   File: GitUtils.java    License: MIT License 2 votes vote down vote up
/**
 * Parse the original git raw date to Java date. The raw git date is in
 * unix timestamp with timezone like:
 * 1392312299 -0800
 * 
 * @param input the input raw date string
 * @return Java date
 */
public static Date parseRawDate(String input) {
	String[] pieces = Iterables.toArray(Splitter.on(" ").split(input), String.class);
	return new Date(Long.valueOf(pieces[0]) * 1000L);
}