Java Code Examples for java.util.List#toArray()

The following examples show how to use java.util.List#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: FramesDecoder.java    From openjdk-jdk9 with GNU General Public License v2.0 7 votes vote down vote up
private ByteBufferReference[] getBuffers(boolean isDataFrame, int bytecount) {
    List<ByteBufferReference> res = new ArrayList<>();
    while (bytecount > 0) {
        ByteBuffer buf = currentBuffer.get();
        int remaining = buf.remaining();
        int extract = Math.min(remaining, bytecount);
        ByteBuffer extractedBuf;
        if (isDataFrame) {
            extractedBuf = Utils.slice(buf, extract);
            slicedToDataFrame = true;
        } else {
            // Header frames here
            // HPACK decoding should performed under lock and immediately after frame decoding.
            // in that case it is safe to release original buffer,
            // because of sliced buffer has a very short life
            extractedBuf = Utils.slice(buf, extract);
        }
        res.add(ByteBufferReference.of(extractedBuf));
        bytecount -= extract;
        nextBuffer();
    }
    return res.toArray(new ByteBufferReference[0]);
}
 
Example 2
Source File: C4BaseTest.java    From couchbase-lite-java with Apache License 2.0 6 votes vote down vote up
/**
 * @param flags C4RevisionFlags
 */
private void createRev(C4Database db, String docID, String revID, byte[] body, int flags)
    throws LiteCoreException {
    boolean commit = false;
    db.beginTransaction();
    try {
        C4Document curDoc = db.get(docID, false);
        assertNotNull(curDoc);
        List<String> revIDs = new ArrayList<>();
        revIDs.add(revID);
        if (curDoc.getRevID() != null) { revIDs.add(curDoc.getRevID()); }
        String[] history = revIDs.toArray(new String[0]);
        C4Document doc = db.put(body, docID, flags,
            true, false, history, true,
            0, 0);
        assertNotNull(doc);
        doc.free();
        curDoc.free();
        commit = true;
    }
    finally {
        db.endTransaction(commit);
    }
}
 
Example 3
Source File: WrappedFile.java    From gama with GNU General Public License v3.0 6 votes vote down vote up
public Object[] getFileChildren() {
	final IFile p = getResource();
	try {
		final IContainer folder = p.getParent();
		final List<WrappedFile> sub = new ArrayList<>();
		for (final IResource r : folder.members()) {
			if (r instanceof IFile && isSupport(p, (IFile) r)) {
				sub.add((WrappedFile) getManager().findWrappedInstanceOf(r));
			}
		}
		return sub.toArray();
	} catch (final CoreException e) {
		e.printStackTrace();
	}
	return VirtualContent.EMPTY;
}
 
Example 4
Source File: Invoker.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates a classloader for loading JAXB/WS 2.2 jar and tools.jar
 */
private static URL[] findIstack22APIs(ClassLoader cl) throws ClassNotFoundException, IOException, ToolsJarNotFoundException {
    List<URL> urls = new ArrayList<URL>();

    if(Service.class.getClassLoader()==null) {
        // JAX-WS API is loaded from bootstrap classloader
        URL res = cl.getResource("javax/xml/ws/EndpointContext.class");
        if(res==null)
            throw new ClassNotFoundException("There's no JAX-WS 2.2 API in the classpath");
        urls.add(ParallelWorldClassLoader.toJarUrl(res));
        res = cl.getResource("javax/xml/bind/JAXBPermission.class");
        if(res==null)
            throw new ClassNotFoundException("There's no JAXB 2.2 API in the classpath");
        urls.add(ParallelWorldClassLoader.toJarUrl(res));
    }

    findToolsJar(cl, urls);

    return urls.toArray(new URL[urls.size()]);
}
 
Example 5
Source File: TsFileUtils.java    From incubator-iotdb with Apache License 2.0 6 votes vote down vote up
public static String[] readTsFile(String tsFilePath, List<Path> paths) throws IOException {
  QueryExpression expression = QueryExpression.create(paths, null);
  TsFileSequenceReader reader = new TsFileSequenceReader(tsFilePath);
  try (ReadOnlyTsFile readTsFile = new ReadOnlyTsFile(reader)) {
    QueryDataSet queryDataSet = readTsFile.query(expression);
    List<String> result = new ArrayList<>();
    while (queryDataSet.hasNext()) {
      RowRecord rowRecord = queryDataSet.next();
      String row = rowRecord.getFields().stream()
          .map(f -> f == null ? "null" : f.getStringValue())
          .collect(Collectors.joining(","));
      result.add(rowRecord.getTimestamp() + "," + row);
    }
    return result.toArray(new String[0]);
  }
}
 
Example 6
Source File: InfiniteStreamWithLimitOpTest.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
@DataProvider(name = "DoubleStream.limit")
public static Object[][] doubleSliceFunctionsDataProvider() {
    Function<String, String> f = s -> String.format(s, SKIP_LIMIT_SIZE);

    List<Object[]> data = new ArrayList<>();

    data.add(new Object[]{f.apply("DoubleStream.limit(%d)"),
            (UnaryOperator<DoubleStream>) s -> s.limit(SKIP_LIMIT_SIZE)});
    data.add(new Object[]{f.apply("DoubleStream.skip(%1$d).limit(%1$d)"),
            (UnaryOperator<DoubleStream>) s -> s.skip(SKIP_LIMIT_SIZE).limit(SKIP_LIMIT_SIZE)});

    return data.toArray(new Object[0][]);
}
 
Example 7
Source File: ResultSetHelperService.java    From NightWidget with GNU General Public License v2.0 5 votes vote down vote up
public String[] getColumnNames(ResultSet rs) throws SQLException {
    List<String> names = new ArrayList<String>();
    ResultSetMetaData metadata = rs.getMetaData();

    for (int i = 0; i < metadata.getColumnCount(); i++) {
        names.add(metadata.getColumnName(i+1));
    }

    String[] nameArray = new String[names.size()];
    return names.toArray(nameArray);
}
 
Example 8
Source File: ClientNotifForwarder.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public synchronized Integer[]
    removeNotificationListener(ObjectName name,
                               NotificationListener listener)
    throws ListenerNotFoundException, IOException {

    beforeRemove();

    if (logger.traceOn()) {
        logger.trace("removeNotificationListener",
                     "Remove the listener "+listener+" from "+name);
    }

    List<Integer> ids = new ArrayList<Integer>();
    List<ClientListenerInfo> values =
            new ArrayList<ClientListenerInfo>(infoList.values());
    for (int i=values.size()-1; i>=0; i--) {
        ClientListenerInfo li = values.get(i);

        if (li.sameAs(name, listener)) {
            ids.add(li.getListenerID());

            infoList.remove(li.getListenerID());
        }
    }

    if (ids.isEmpty())
        throw new ListenerNotFoundException("Listener not found");

    return ids.toArray(new Integer[0]);
}
 
Example 9
Source File: AbstractSerialStateHolder.java    From mybaties with Apache License 2.0 5 votes vote down vote up
public AbstractSerialStateHolder(
        final Object userBean,
        final Map<String, ResultLoaderMap.LoadPair> unloadedProperties,
        final ObjectFactory objectFactory,
        List<Class<?>> constructorArgTypes,
        List<Object> constructorArgs) {
  this.userBean = userBean;
  this.unloadedProperties = new HashMap<String, ResultLoaderMap.LoadPair>(unloadedProperties);
  this.objectFactory = objectFactory;
  this.constructorArgTypes = constructorArgTypes.toArray(new Class<?>[constructorArgTypes.size()]);
  this.constructorArgs = constructorArgs.toArray(new Object[constructorArgs.size()]);
}
 
Example 10
Source File: UnionBugs.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
private String[] createCommandArgumentsArray(List<File> fileList) {
    List<String> parts = new ArrayList<>();
    parts.add("-withMessages");
    parts.add("-output");
    parts.add(into);

    parts.add(into);

    for (File f : fileList) {
        parts.add(f.getAbsolutePath());
    }

    String[] args = parts.toArray(new String[parts.size()]);
    return args;
}
 
Example 11
Source File: FlutterSdk.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public FlutterCommand flutterCreate(@NotNull VirtualFile appDir, @Nullable FlutterCreateAdditionalSettings additionalSettings) {
  final List<String> args = new ArrayList<>();
  if (additionalSettings != null) {
    args.addAll(additionalSettings.getArgs());
  }

  // keep as the last argument
  args.add(appDir.getName());

  final String[] vargs = args.toArray(new String[0]);

  return new FlutterCommand(this, appDir.getParent(), FlutterCommand.Type.CREATE, vargs);
}
 
Example 12
Source File: SaveLoad.java    From ssj with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @param serializer XmlSerializer
 * @param object     Object
 * @throws IOException
 */
private static void addOptions(XmlSerializer serializer, Object object) throws IOException
{
	serializer.startTag(null, OPTIONS);
	Option[] options = PipelineBuilder.getOptionList(object);
	if (options != null)
	{
		for (Option option : options)
		{
			if (option.isAssignableByString() && option.get() != null)
			{
				serializer.startTag(null, OPTION);
				serializer.attribute(null, NAME, option.getName());
				if (option.getType().isArray())
				{
					Object value = option.get();
					List ar = new ArrayList();
					int length = Array.getLength(value);
					for (int i = 0; i < length; i++)
					{
						ar.add(Array.get(value, i));
					}
					Object[] objects = ar.toArray();
					serializer.attribute(null, VALUE, Arrays.toString(objects));
				}
				else
				{
					serializer.attribute(null, VALUE, String.valueOf(option.get()));
				}
				serializer.endTag(null, OPTION);
			}
		}
	}
	serializer.endTag(null, OPTIONS);
}
 
Example 13
Source File: EjbJarProvider.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public File[] getRequiredLibraries() {
    ClassPath cp = ClassPathFactory.createClassPath(
                ProjectClassPathSupport.createPropertyBasedClassPathImplementation(
                FileUtil.toFile(project.getProjectDirectory()), project.evaluator(), new String[]{"javac.classpath"}));
    List<File> files = new ArrayList<File>();
    for (FileObject fo : cp.getRoots()) {
        fo = FileUtil.getArchiveFile(fo);
        if (fo == null) {
            continue;
        }
        files.add(FileUtil.toFile(fo));
    }
    return files.toArray(new File[files.size()]);
}
 
Example 14
Source File: Guavate.java    From Strata with Apache License 2.0 5 votes vote down vote up
/**
 * Converts a list of futures to a single future, combining the values into a list.
 * <p>
 * The {@link CompletableFuture#allOf(CompletableFuture...)} method is useful
 * but it returns {@code Void}. This method combines the futures but also
 * returns the resulting value as a list.
 * Effectively, this converts {@code List<CompletableFuture<T>>} to {@code CompletableFuture<List<T>>}.
 * <p>
 * If any input future completes exceptionally, the result will also complete exceptionally.
 *
 * @param <T> the type of the values in the list
 * @param futures the futures to convert, may be empty
 * @return a future that combines the input futures as a list
 */
public static <T> CompletableFuture<List<T>> combineFuturesAsList(
    List<? extends CompletableFuture<? extends T>> futures) {

  int size = futures.size();
  CompletableFuture<? extends T>[] futuresArray = futures.toArray(new CompletableFuture[size]);
  return CompletableFuture.allOf(futuresArray)
      .thenApply(unused -> {
        List<T> builder = new ArrayList<>(size);
        for (int i = 0; i < size; i++) {
          builder.add(futuresArray[i].join());
        }
        return builder;
      });
}
 
Example 15
Source File: MatOfByte.java    From FaceT with Mozilla Public License 2.0 5 votes vote down vote up
public void fromList(List<Byte> lb) {
    if(lb==null || lb.size()==0)
        return;
    Byte ab[] = lb.toArray(new Byte[0]);
    byte a[] = new byte[ab.length];
    for(int i=0; i<ab.length; i++)
        a[i] = ab[i];
    fromArray(a);
}
 
Example 16
Source File: SharedFileResource.java    From baleen with Apache License 2.0 5 votes vote down vote up
/**
 * Read the file and return all the lines, with any leading or trailing 'empty' lines omitted.
 * Lines that consist solely of whitespace are assumed to be empty. Lines are trimmed of any
 * leading or trailing whitespace as they are read.
 *
 * <p>Implemented as per BufferedReader.
 *
 * @param file the file to load
 * @return non-null, but potentially empty, array of string (one line per string)
 * @throws IOException on error accessing or reading from the file.
 */
public static String[] readFileLines(File file) throws IOException {
  List<String> lines = new LinkedList<>();
  try (Stream<String> stream = Files.lines(file.toPath())) {
    stream.forEach(l -> lines.add(StringUtils.strip(l.replaceAll("\r\n", "\n"))));
  }
  while (StringUtils.strip(lines.get(0)).isEmpty()) {
    lines.remove(0);
  }
  while (StringUtils.strip(lines.get(lines.size() - 1)).isEmpty()) {
    lines.remove(lines.size() - 1);
  }

  return lines.toArray(new String[lines.size()]);
}
 
Example 17
Source File: CacheManager.java    From j2cache with Apache License 2.0 5 votes vote down vote up
public static ICache<?,?>[] getAllCaches() {
	List<ICache<?,?>> values = new ArrayList<ICache<?,?>>();
	for (CacheObject item: caches.values()) {
		values.add(item.getCache());
	}
		
	return values.toArray(new ICache<?,?>[values.size()]);
}
 
Example 18
Source File: StarsTransition2D.java    From Pixelitor with GNU General Public License v3.0 4 votes vote down vote up
@Override
public Shape[] getShapes(float progress, Dimension size) {
    progress = 1 - progress;

    GeneralPath star1 = new GeneralPath(star[8]);
    GeneralPath star2 = new GeneralPath(star[5]);
    GeneralPath star3 = new GeneralPath(star[8]);
    GeneralPath star4 = new GeneralPath(star[5]);
    GeneralPath star5 = new GeneralPath(star[7]);
    GeneralPath star6 = new GeneralPath(star[5]);
    GeneralPath star7 = new GeneralPath(star[8]);
    GeneralPath star8 = new GeneralPath(star[6]);

    Random random = new Random(2);

    star1.transform(AffineTransform.getRotateInstance(random.nextDouble()));
    star2.transform(AffineTransform.getRotateInstance(random.nextDouble()));
    star3.transform(AffineTransform.getRotateInstance(random.nextDouble()));
    star4.transform(AffineTransform.getRotateInstance(random.nextDouble()));
    star5.transform(AffineTransform.getRotateInstance(random.nextDouble()));
    star6.transform(AffineTransform.getRotateInstance(random.nextDouble()));
    star7.transform(AffineTransform.getRotateInstance(random.nextDouble()));
    star8.transform(AffineTransform.getRotateInstance(random.nextDouble()));

    float big = Math.min(size.width, size.height) * 0.7f;
    float base1 = (float) (Math.pow(progress, 2.2) * 0.5f + 0.0f / 8.0f * 0.3f);
    float base2 = (float) (Math.pow(progress, 2.2) * 0.5f + 1.0f / 8.0f * 0.3f);
    float base3 = (float) (Math.pow(progress, 2.2) * 0.5f + 2.0f / 8.0f * 0.3f);
    float base4 = (float) (Math.pow(progress, 2.2) * 0.5f + 3.0f / 8.0f * 0.3f);
    float base5 = (float) (Math.pow(progress, 2.2) * 0.5f + 4.0f / 8.0f * 0.3f);
    float base6 = (float) (Math.pow(progress, 2.2) * 0.5f + 5.0f / 8.0f * 0.3f);
    float base7 = (float) (Math.pow(progress, 2.2) * 0.5f + 6.0f / 8.0f * 0.3f);
    float base8 = (float) (Math.pow(progress, 2.2) * 0.5f + 7.0f / 8.0f * 0.3f);
    float progress1 = (progress - base1) / (1 - base1);
    float progress2 = (progress - base2) / (1 - base2);
    float progress3 = (progress - base3) / (1 - base3);
    float progress4 = (progress - base4) / (1 - base4);
    float progress5 = (progress - base5) / (1 - base5);
    float progress6 = (progress - base6) / (1 - base6);
    float progress7 = (progress - base7) / (1 - base7);
    float progress8 = (progress - base8) / (1 - base8);
    List<GeneralPath> v = new ArrayList<>();

    if (progress1 > 0) {
        fit(star1, big, size.width * 2.0f / 3.0f, size.height * 3.0f / 4.0f, paths[0], size, progress1 * 2);
        v.add(star1);
    }
    if (progress2 > 0) {
        fit(star2, big, size.width * 7.0f / 8.0f, size.height * 1.0f / 5.0f, paths[1], size, progress2 * 2);
        v.add(star2);
    }
    if (progress3 > 0) {
        fit(star3, big, size.width * 1.0f / 6.0f, size.height * 2.2f / 5.0f, paths[2], size, progress3 * 2);
        v.add(star3);
    }
    if (progress4 > 0) {
        fit(star4, big, size.width * 3.1f / 6.0f, size.height * 1.2f / 5.0f, paths[0], size, progress4 * 2);
        v.add(star4);
    }
    if (progress5 > 0) {
        fit(star5, big, size.width * 1.9f / 6.0f, size.height * 4.2f / 5.0f, paths[1], size, progress5 * 2);
        v.add(star5);
    }
    if (progress6 > 0) {
        fit(star6, big, size.width * 13.0f / 15.0f, size.height * 4.3f / 5.0f, paths[2], size, progress6 * 2);
        v.add(star6);
    }
    if (progress7 > 0) {
        fit(star7, big, size.width * 2.0f / 5.0f, size.height * 2.4f / 5.0f, paths[0], size, progress7 * 2);
        v.add(star7);
    }
    if (progress8 > 0) {
        fit(star8, big, size.width * 3.0f / 6.0f, size.height * 2.0f / 5.0f, paths[2], size, progress8 * 2);
        v.add(star8);
    }

    Shape[] shapes = v.toArray(new Shape[v.size()]);
    if (type == LEFT) {
        AffineTransform flipHorizontal = TransformUtils.createAffineTransform(0, 0,
                0, size.height,
                size.width, 0,
                size.width, 0,
                size.width, size.height,
                0, 0);
        for (int a = 0; a < shapes.length; a++) {
            if (shapes[a] instanceof GeneralPath) {
                ((GeneralPath) shapes[a]).transform(flipHorizontal);
            } else {
                shapes[a] = flipHorizontal.createTransformedShape(shapes[a]);
            }
        }
    }
    return shapes;
}
 
Example 19
Source File: ContractController.java    From nuls-v2 with MIT License 4 votes vote down vote up
@RpcMethod("contractCreate")
@ApiOperation(description = "发布合约", order = 401)
@Parameters(value = {
        @Parameter(parameterName = "chainId", requestType = @TypeDescriptor(value = int.class), parameterDes = "链id"),
        @Parameter(parameterName = "sender",  parameterDes = "交易创建者账户地址"),
        @Parameter(parameterName = "password",  parameterDes = "账户密码"),
        @Parameter(parameterName = "alias",  parameterDes = "合约别名"),
        @Parameter(parameterName = "gasLimit", requestType = @TypeDescriptor(value = long.class), parameterDes = "GAS限制"),
        @Parameter(parameterName = "price", requestType = @TypeDescriptor(value = long.class), parameterDes = "GAS单价"),
        @Parameter(parameterName = "contractCode",  parameterDes = "智能合约代码(字节码的Hex编码字符串)"),
        @Parameter(parameterName = "args", requestType = @TypeDescriptor(value = Object[].class), parameterDes = "参数列表", canNull = true),
        @Parameter(parameterName = "remark",  parameterDes = "交易备注", canNull = true)
})
@ResponseData(name = "返回值", description = "返回一个Map对象,包含两个属性", responseType = @TypeDescriptor(value = Map.class, mapKeys = {
        @Key(name = "txHash", description = "发布合约的交易hash"),
        @Key(name = "contractAddress", description = "生成的合约地址")
}))
public RpcResult contractCreate(List<Object> params) {
    VerifyUtils.verifyParams(params, 9);
    try {
        int i = 0;
        Integer chainId = (Integer) params.get(i++);
        String sender = (String) params.get(i++);
        String password = (String) params.get(i++);
        String alias = (String) params.get(i++);
        Long gasLimit = Long.parseLong(params.get(i++).toString());
        Long price = Long.parseLong(params.get(i++).toString());
        String contractCode = (String) params.get(i++);
        List argsList = (List) params.get(i++);
        Object[] args = argsList != null ? argsList.toArray() : null;
        String remark = (String) params.get(i++);

        if (!Context.isChainExist(chainId)) {
            return RpcResult.paramError(String.format("chainId [%s] is invalid", chainId));
        }
        if (gasLimit < 0) {
            return RpcResult.paramError(String.format("gasLimit [%s] is invalid", gasLimit));
        }
        if (price < 0) {
            return RpcResult.paramError(String.format("price [%s] is invalid", price));
        }

        if (!AddressTool.validAddress(chainId, sender)) {
            return RpcResult.paramError(String.format("sender [%s] is invalid", sender));
        }

        if(!FormatValidUtils.validAlias(alias)) {
            return RpcResult.paramError(String.format("alias [%s] is invalid", alias));
        }

        if (StringUtils.isBlank(contractCode)) {
            return RpcResult.paramError("contractCode is empty");
        }
        CreateContractReq req = new CreateContractReq();
        req.setChainId(config.getChainId());
        req.setSender(sender);
        req.setPassword(password);
        req.setPrice(price);
        req.setGasLimit(gasLimit);
        req.setContractCode(contractCode);
        req.setAlias(alias);
        req.setArgs(args);
        req.setRemark(remark);
        Result<Map> result = contractProvider.createContract(req);
        return ResultUtil.getJsonRpcResult(result);
    } catch (Exception e) {
        Log.error(e);
        return RpcResult.failed(CommonCodeConstanst.DATA_ERROR, e.getMessage());
    }
}
 
Example 20
Source File: AbstractFileObject.java    From commons-vfs with Apache License 2.0 2 votes vote down vote up
/**
 * Finds the set of matching descendants of this file, in depthwise order.
 *
 * @param selector The FileSelector.
 * @return list of files or null if the base file (this object) do not exist
 * @throws FileSystemException if an error occurs.
 */
@Override
public FileObject[] findFiles(final FileSelector selector) throws FileSystemException {
    final List<FileObject> list = this.listFiles(selector);
    return list == null ? null : list.toArray(new FileObject[list.size()]);
}