Java Code Examples for

The following examples show how to use . 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:    From proarc with GNU General Public License v3.0 8 votes vote down vote up
    public void testGetMix() throws Exception {
        File root = temp.getRoot();
        File imageFile = new File(root, "test.tif");
//        FileUtils.copyFile(new File("/tmp/test.jp2"),
//                imageFile, true);
        FileUtils.copyURLToFile(TiffImporterTest.class.getResource("testscan.tiff"), imageFile);
        JHoveOutput output = JhoveUtility.getMix(imageFile, root, null,
                MetsUtils.getCurrentDate(), "testscan.tiff");
        Mix mix = output.getMix();

        String toXml = MixUtils.toXml(mix, true);
//        System.out.println(toXml);
        assertEquals(toXml, "image/tiff", mix.getBasicDigitalObjectInformation()
Example 2
Source File:    From Recaf with MIT License 6 votes vote down vote up
 * @throws IOException
 * 		Throw when the local artifact cannot be found <i>(Does not exist locally and cannot be
 * 		fetched)</i>.
private void findArtifact() throws IOException {
	// Check local maven repo
	Path localArtifact = MavenUtil.getLocalArtifactUrl(groupId, artifactId, version);
	if (Files.exists(localArtifact)) {
		setBacking(new JarResource(localArtifact));
	// Verify artifact is on central
	MavenUtil.verifyArtifactOnCentral(groupId, artifactId, version);
	// Copy artifact to local maven repo
	URL url = MavenUtil.getArtifactUrl(groupId, artifactId, version);
	FileUtils.copyURLToFile(url, localArtifact.toFile());
	setBacking(new JarResource(localArtifact));
	// TODO: Not here, but allow auto-resolving ALL dependencies not just the specified one
Example 3
Source File:    From DiscordSRV with GNU General Public License v3.0 6 votes vote down vote up
@Command(commandNames = { "setpicture" },
        helpMessage = "Sets the picture of the bot on Discord",
        permission = "discordsrv.setpicture",
        usageExample = "setpicture"
public static void execute(CommandSender sender, String[] args) {
    if (args.length == 0) {
        sender.sendMessage(ChatColor.RED + "No URL given");
    } else {
        File pictureFile = new File(DiscordSRV.getPlugin().getDataFolder(), "picture.jpg");
        try {
            FileUtils.copyURLToFile(new URL(args[0]), pictureFile);
            sender.sendMessage(ChatColor.AQUA + "✓");
        } catch (IOException | RuntimeException e) {
            sender.sendMessage(ChatColor.RED + "✗: " + e.getMessage());
Example 4
Source File:    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
private QuickstartTableRequest prepareOfflineTableRequest(File configDir)
    throws IOException {

  _schemaFile = new File(configDir, "airlineStats_schema.json");
  _ingestionJobSpecFile = new File(configDir, "ingestionJobSpec.yaml");
  File tableConfigFile = new File(configDir, "airlineStats_offline_table_config.json");

  ClassLoader classLoader = Quickstart.class.getClassLoader();
  URL resource = classLoader.getResource("examples/batch/airlineStats/airlineStats_schema.json");
  FileUtils.copyURLToFile(resource, _schemaFile);
  resource = classLoader.getResource("examples/batch/airlineStats/ingestionJobSpec.yaml");
  FileUtils.copyURLToFile(resource, _ingestionJobSpecFile);
  resource = classLoader.getResource("examples/batch/airlineStats/airlineStats_offline_table_config.json");
  FileUtils.copyURLToFile(resource, tableConfigFile);

  return new QuickstartTableRequest("airlineStats", _schemaFile, tableConfigFile, _ingestionJobSpecFile,
Example 5
Source File:    From sepia-assist-server with MIT License 5 votes vote down vote up
private boolean callServerProcess(String url, String audioFilePath){
			new URL(url), 
			new File(audioFilePath), 
			7500, 7500
		return true;
	}catch(Exception e){
		Debugger.println("TTS server call FAILED. URL: " + url.replaceFirst("\\?.*", "") + " - Msg.: " + e.getMessage(), 1);
		Debugger.printStackTrace(e, 3);
		return false;
Example 6
Source File:    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static void copyURLToFile(URL source, File destination) {
    try {
        FileUtils.copyURLToFile(source, destination);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
Example 7
Source File:    From bleachhack-1.14 with GNU General Public License v3.0 5 votes vote down vote up
public static void downloadSongs(boolean log) {
	try {
				  new URL(""), 
		ZipFile zip = new ZipFile(BleachFileMang.getDir().resolve("notebot").resolve("").toFile());
		Enumeration<? extends ZipEntry> files = zip.entries();
		int count = 0;
		while (files.hasMoreElements()) {
			ZipEntry file = files.nextElement();
			File outFile = BleachFileMang.getDir().resolve("notebot").resolve(file.getName()).toFile();
			if (file.isDirectory()) outFile.mkdirs();
		    else {
		        InputStream in = zip.getInputStream(file);
		        FileOutputStream out = new FileOutputStream(outFile);
		        IOUtils.copy(in, out);

		if (log) BleachLogger.infoMessage("Downloaded " + count + " Songs");
	} catch (Exception e) { if (log) BleachLogger.warningMessage("Error Downloading Songs... " + e); e.printStackTrace(); }
Example 8
Source File:    From konduit-serving with Apache License 2.0 5 votes vote down vote up
public static File cache(String url, String module, String testName, String fileName) throws IOException {
    File testDir = TestUtils.testResourcesStorageDir();
    File saveDir = new File(testDir, module + "/" + testName);
    File f = new File(saveDir, fileName);

    if (!f.exists()) {"Downloading model: {} -> {}", url, f.getAbsolutePath());
        FileUtils.copyURLToFile(new URL(url), f);"Download complete");
    return f;
Example 9
Source File:    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void copyFrom(URL resource) {
    try {
        FileUtils.copyURLToFile(resource, this);
    } catch (IOException e) {
        throw new RuntimeException(e);
Example 10
Source File:    From konduit-serving with Apache License 2.0 5 votes vote down vote up
public void runFaceDetector(TestContext testContext) throws Exception {
    File imageFile = Paths.get(new ClassPathResource(".").getFile().getAbsolutePath(), "inference/onnx/data/1.jpg").toFile();

    if (!imageFile.exists()) {
        FileUtils.copyURLToFile(new URL(""), imageFile);
    NativeImageLoader nativeImageLoader = new NativeImageLoader(240, 320);
    Image image = nativeImageLoader.asImageMatrix(imageFile);

    INDArray contents = image.getImage();

    byte[] npyContents = Nd4j.toNpyByteArray(contents);

    File inputFile = temporary.newFile();
    FileUtils.writeByteArrayToFile(inputFile, npyContents);

    Response response = given().port(port)
            .multiPart("input", inputFile)

    assertEquals("Response failed", 200, response.getStatusCode());

    JsonObject output = new JsonObject(response.asString());


    INDArray scores = ObjectMappers.fromJson(output.getJsonObject("scores").encode(), NDArrayOutput.class).getNdArray();
    assertEquals(0.9539676, scores.getFloat(0), 1e-6);
    assertArrayEquals(new long[]{1, 8840}, scores.shape());

    INDArray boxes = ObjectMappers.fromJson(output.getJsonObject("boxes").encode(), NDArrayOutput.class).getNdArray();
    assertEquals(0.002913665, boxes.getFloat(0), 1e-6);
    assertArrayEquals(new long[]{1, 17680}, boxes.shape());
Example 11
Source File:    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static void copyURLToFile(URL source, File destination) {
    try {
        FileUtils.copyURLToFile(source, destination);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
Example 12
Source File:    From scheduling with GNU Affero General Public License v3.0 5 votes vote down vote up
 * Fetch the node.jar at the given url and store it to a file
 * Disable ssl handshake if https
 * @param jarUrl url to fetch
 * @param destination local file
 * @throws IOException
private static void fetchUrl(String jarUrl, File destination) throws IOException {
    if (jarUrl.startsWith("https")) {

    FileUtils.copyURLToFile(new URL(jarUrl), destination);
Example 13
Source File:    From inception with Apache License 2.0 5 votes vote down vote up
public File writeFileDownloadToTemporaryFile(String downloadUrl, Object marker) throws
    Path pathName = Paths.get(downloadUrl);
    String fileName = pathName.getFileName().toString();
    File tmpFile = File.createTempFile(INCEPTION_TMP_FILE_PREFIX, fileName);
    log.debug("Creating temporary file for [{}] in [{}]", fileName, tmpFile.getAbsolutePath());
    fileTracker.track(tmpFile, marker);
    FileUtils.copyURLToFile(new URL(downloadUrl), tmpFile);
    return tmpFile;
Example 14
Source File:    From proarc with GNU General Public License v3.0 4 votes vote down vote up
private File createTestFile(String templatePath, File file) throws IOException {
    URL resource = TiffImporterTest.class.getResource(templatePath);
    FileUtils.copyURLToFile(resource, file);
    return file;
Example 15
Source File:    From VersionChecker with GNU Lesser General Public License v3.0 4 votes vote down vote up
public static File downloadFileFromURL(URL url, Update update, ModContainer mod, String fileName) throws IOException {
    File newFile = new File(fileName);
    FileUtils.copyURLToFile(url, newFile);
    return newFile;
Example 16
Source File:    From gocd with Apache License 2.0 4 votes vote down vote up
void copyPluginToThePluginDirectory(File pluginDir,
                                    String destinationFilenameOfPlugin) throws IOException, URISyntaxException {
    URL resource = getClass().getClassLoader().getResource("defaultFiles/descriptor-aware-test-plugin.jar");

    FileUtils.copyURLToFile(resource, new File(pluginDir, destinationFilenameOfPlugin));
Example 17
Source File:    From konduit-serving with Apache License 2.0 4 votes vote down vote up
@Ignore   //To be run manually due to need for webcam and frame output
public void testBBoxFilter() throws Exception {
    //Pretrained model source:

    String fileUrl = "";
    File testDir = TestUtils.testResourcesStorageDir();
    File saveDir = new File(testDir, "konduit-serving-tensorflow/bbox-filter");
    File f = new File(saveDir, "frozen_inference_graph.pb");

    if (!f.exists()) {"Downloading model: {} -> {}", fileUrl, f.getAbsolutePath());
        FileUtils.copyURLToFile(new URL(fileUrl), f);"Download complete");

    GraphBuilder b = new GraphBuilder();
    GraphStep input = b.input();
    //Capture frame from webcam
    GraphStep camera = input.then("camera", new CameraFrameCaptureStep()

    //Convert image to NDArray (can configure size, BGR/RGB, normalization, etc here)
    ImageToNDArrayConfig c = new ImageToNDArrayConfig()
            .height(300)  //
            .width(300)   // size origin

    GraphStep i2n = camera.then("image2NDArray", new ImageToNDArrayStep()
            .outputNames(Arrays.asList("image_tensor")) //TODO varargs builder method

    //Run image in TF model
    GraphStep tf = i2n.then("tf", builder()
            .inputNames(Collections.singletonList("image_tensor"))      //TODO varargs builder method
            .outputNames(Arrays.asList("detection_boxes", "detection_scores", "detection_classes", "num_detections"))

    //Post process SSD outputs to BoundingBox objects
    String[] COCO_LABELS = new String[]{"person", "bicycle", "car", "motorcycle", "airplane", "bus", "train", "truck", "boat", "traffic light", "fire hydrant", "street sign", "stop sign", "parking meter", "bench", "bird", "cat", "dog", "horse", "sheep", "cow", "elephant", "bear", "zebra", "giraffe", "hat", "backpack", "umbrella", "shoe", "eye glasses", "handbag", "tie", "suitcase", "frisbee", "skis", "snowboard", "sports ball", "kite", "baseball bat", "baseball glove", "skateboard", "surfboard", "tennis racket", "bottle", "plate", "wine glass", "cup", "fork", "knife", "spoon", "bowl", "banana", "apple", "sandwich", "orange", "broccoli", "carrot", "hot dog", "pizza", "donut", "cake", "chair", "couch", "potted plant", "bed", "mirror", "dining table", "window", "desk", "toilet", "door", "tv", "laptop", "mouse", "remote", "keyboard", "cell phone", "microwave", "oven", "toaster", "sink", "refrigerator", "blender", "book", "clock", "vase", "scissors", "teddy bear", "hair drier", "toothbrush", "hair brush"};

    GraphStep ssdProc = tf.then("bbox", new SSDToBoundingBoxStep()

    String[] classesToKeep = new String[]{"person", "car"};

    //Post process SSD outputs to BoundingBox objects
    GraphStep bboxFilter = ssdProc.then("filtered_bbox", new BoundingBoxFilterStep()

    //Merge camera image with bounding boxes
    GraphStep merged = camera.mergeWith("img_filtered_bbox", bboxFilter);

    //Draw bounding boxes on the image
    GraphStep drawer = merged.then("drawer", new DrawBoundingBoxStep()
            .imageToNDArrayConfig(c)        //Provide the config to account for the fact that the input image is cropped
            .drawCropRegion(true)           //Draw the region of the camera that is cropped when using ImageToNDArray

    //Show image in Java frame
    GraphStep show = drawer.then("show", new ShowImageStep()
            .displayName("bbox filter")

    GraphPipeline p =;

    PipelineExecutor exec = p.executor();

    Data in = Data.empty();
    for (int i = 0; i < 1000; i++) {

Example 18
Source File:    From deeplearning4j with Apache License 2.0 4 votes vote down vote up
 * Returns a pretrained model for the given dataset, if available.
 * @param pretrainedType
 * @return
 * @throws IOException
public <M extends Model> M initPretrained(PretrainedType pretrainedType) throws IOException {
    String remoteUrl = pretrainedUrl(pretrainedType);
    if (remoteUrl == null)
        throw new UnsupportedOperationException(
                        "Pretrained " + pretrainedType + " weights are not available for this model.");

    String localFilename = new File(remoteUrl).getName();

    File rootCacheDir = DL4JResources.getDirectory(ResourceType.ZOO_MODEL, modelName());
    File cachedFile = new File(rootCacheDir, localFilename);

    if (!cachedFile.exists()) {"Downloading model to " + cachedFile.toString());
        FileUtils.copyURLToFile(new URL(remoteUrl), cachedFile);
    } else {"Using cached model at " + cachedFile.toString());

    long expectedChecksum = pretrainedChecksum(pretrainedType);
    if (expectedChecksum != 0L) {"Verifying download...");
        Checksum adler = new Adler32();
        FileUtils.checksum(cachedFile, adler);
        long localChecksum = adler.getValue();"Checksum local is " + localChecksum + ", expecting " + expectedChecksum);

        if (expectedChecksum != localChecksum) {
            log.error("Checksums do not match. Cleaning up files and failing...");
            throw new IllegalStateException(
                            "Pretrained model file failed checksum. If this error persists, please open an issue at");

    if (modelType() == MultiLayerNetwork.class) {
        return (M) ModelSerializer.restoreMultiLayerNetwork(cachedFile);
    } else if (modelType() == ComputationGraph.class) {
        return (M) ModelSerializer.restoreComputationGraph(cachedFile);
    } else {
        throw new UnsupportedOperationException(
                        "Pretrained models are only supported for MultiLayerNetwork and ComputationGraph.");
Example 19
Source File:    From DataVec with Apache License 2.0 3 votes vote down vote up
public File downloadAndUntar() throws IOException {
    if (fileDir != null) {
        return fileDir;
    // mac gives unique tmp each run and we want to store this persist
    // this data across restarts
    File tmpDir = new File(System.getProperty("user.home"));

    File baseDir = new File(tmpDir, LOCAL_DIR_NAME);
    if (!(baseDir.isDirectory() || baseDir.mkdir())) {
        throw new IOException("Could not mkdir " + baseDir);
    }"Downloading mnist...");
    // getFromOrigin training records
    File tarFile = new File(baseDir, trainingFilesFilename);

    if (!tarFile.isFile()) {
        FileUtils.copyURLToFile(new URL(trainingFilesURL), tarFile);

    ArchiveUtils.unzipFileTo(tarFile.getAbsolutePath(), baseDir.getAbsolutePath());

    // getFromOrigin training records
    File labels = new File(baseDir, trainingFileLabelsFilename);

    if (!labels.isFile()) {
        FileUtils.copyURLToFile(new URL(trainingFileLabelsURL), labels);

    ArchiveUtils.unzipFileTo(labels.getAbsolutePath(), baseDir.getAbsolutePath());

    fileDir = baseDir;
    return fileDir;
Example 20
Source File:    From OneSignal-Java-SDK with Apache License 2.0 2 votes vote down vote up
 * Download a file from {@code url} to the {@code location}.
 * @param url the url of the file to retrieve
 * @param location the path and filename where to save the file
 * @throws IOException if {@code url} cannot be opened
 * @throws IOException if {@code location} is a directory
 * @throws IOException if {@code location} cannot be written
 * @throws IOException if {@code location} needs creating but can't be
 * @throws IOException if an IO error occurs during copying
public static void csvExportFileDownload(URL url, File location) throws IOException {
    FileUtils.copyURLToFile(url, location);