Java Code Examples for com.google.common.collect.Iterables#toArray()
The following examples show how to use
com.google.common.collect.Iterables#toArray() .
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
Source File: GoogleAuthLibraryCallCredentialsTest.java From grpc-nebula-java with Apache License 2.0 | 6 votes |
@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 File: NestDeriver.java From envelope with Apache License 2.0 | 6 votes |
@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 File: Dispatcher.java From big-c with Apache License 2.0 | 6 votes |
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
Source File: CqlSession.java From ob1k with Apache License 2.0 | 5 votes |
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 5
Source File: Configs.java From kite with Apache License 2.0 | 5 votes |
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 6
Source File: ConvertUtil.java From youran with Apache License 2.0 | 5 votes |
/** * 逗号分割字符串转换成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 File: EPackageChooser.java From xtext-eclipse with Eclipse Public License 2.0 | 5 votes |
@Override public Object[] getElements(Object inputElement) { if (content != null) { return Iterables.toArray(content, Object.class); } else { return new Object[0]; } }
Example 8
Source File: ColumnFamilyStoreTest.java From stratio-cassandra with Apache License 2.0 | 5 votes |
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 9
Source File: WorkingSetManagerImpl.java From n4js with Eclipse Public License 1.0 | 4 votes |
@Override public WorkingSet[] getWorkingSets() { return Iterables.toArray(getOrCreateVisibleWorkingSets(), WorkingSet.class); }
Example 10
Source File: AccessLogGenerator.java From servicecomb-java-chassis with Apache License 2.0 | 4 votes |
@SuppressWarnings("unchecked") public AccessLogGenerator(String rawPattern) { List<AccessLogItem<RoutingContext>> accessLogItemList = logPatternParser.parsePattern(rawPattern); accessLogItems = Iterables.toArray(accessLogItemList, AccessLogItem.class); }
Example 11
Source File: StringUtil.java From kylin-on-parquet-v2 with Apache License 2.0 | 4 votes |
public static String[] split(String str, String splitBy) { return Iterables.toArray(Splitter.on(splitBy).split(str), String.class); }
Example 12
Source File: ProjectLocationAwareWorkingSetManager.java From n4js with Eclipse Public License 1.0 | 4 votes |
@Override public IAdaptable[] getElements() { return Iterables.toArray(getWorkingSetManager().projectLocations.get(getId()), IAdaptable.class); }
Example 13
Source File: OrderOfLossesInputPanel.java From triplea with GNU General Public License v3.0 | 4 votes |
@VisibleForTesting static String[] splitOrderOfLossSection(final String orderOfLossSection) { return Iterables.toArray( Splitter.on(OOL_AMOUNT_DESCRIPTOR).split(orderOfLossSection), String.class); }
Example 14
Source File: LogFileServiceTest.java From c5-replicator with Apache License 2.0 | 4 votes |
private ByteBuffer[] serializedHeader(OLogHeader header) { List<ByteBuffer> buffers = encodeWithLengthAndCrc(OLogHeader.getSchema(), header); return Iterables.toArray(buffers, ByteBuffer.class); }
Example 15
Source File: MergingException.java From buck with Apache License 2.0 | 4 votes |
public static void throwIfNonEmpty(Collection<Message> messages) throws MergingException { if (!messages.isEmpty()) { throw new MergingException(null, Iterables.toArray(messages, Message.class)); } }
Example 16
Source File: Striped.java From codebuff with BSD 2-Clause "Simplified" License | 4 votes |
/** * 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 17
Source File: WorkingSetManagerImpl.java From n4js with Eclipse Public License 1.0 | 4 votes |
@Override public WorkingSet[] getAllWorkingSets() { return Iterables.toArray(getOrCreateAllWorkingSets(), WorkingSet.class); }
Example 18
Source File: ConvertUtil.java From youran with Apache License 2.0 | 3 votes |
/** * 自定义转换器进行数组转换 * * @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
Source File: TimeGraphControl.java From tracecompass with Eclipse Public License 2.0 | 2 votes |
/** * 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 File: GitUtils.java From onedev with MIT License | 2 votes |
/** * 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); }