Example usage for org.apache.commons.io FileUtils waitFor

List of usage examples for org.apache.commons.io FileUtils waitFor

Introduction

In this page you can find the example usage for org.apache.commons.io FileUtils waitFor.

Prototype

public static boolean waitFor(File file, int seconds) 

Source Link

Document

Waits for NFS to propagate a file creation, imposing a timeout.

Usage

From source file:org.broadinstitute.sting.jna.lsf.v7_0_6.LibBatPipelineTest.java

@Test
public void testSubmitEcho() throws Exception {
    String queue = "hour";
    File outFile = tryCreateNetworkTempFile("LibBatIntegrationTest.out");

    submit req = new submit();

    for (int i = 0; i < LibLsf.LSF_RLIM_NLIMITS; i++)
        req.rLimits[i] = LibLsf.DEFAULT_RLIMIT;

    req.projectName = "LibBatIntegrationTest";
    req.options |= LibBat.SUB_PROJECT_NAME;

    req.queue = queue;//  w  w  w .ja  v a 2  s  .c  o  m
    req.options |= LibBat.SUB_QUEUE;

    req.outFile = outFile.getPath();
    req.options |= LibBat.SUB_OUT_FILE;

    req.userPriority = 100;
    req.options2 |= LibBat.SUB2_JOB_PRIORITY;

    req.command = "echo \"Hello world.\"";

    String[] argv = { "", "-a", "tv" };
    int setOptionResult = LibBat.setOption_(argv.length, new StringArray(argv), "a:", req, ~0, ~0, ~0, null);
    Assert.assertTrue(setOptionResult != -1, "setOption_ returned -1");

    submitReply reply = new submitReply();
    long jobId = LibBat.lsb_submit(req, reply);

    Assert.assertFalse(jobId < 0, LibBat.lsb_sperror("Error dispatching"));

    System.out.println("Waiting for job to run: " + jobId);
    int jobStatus = LibBat.JOB_STAT_PEND;
    while (Utils.isFlagSet(jobStatus, LibBat.JOB_STAT_PEND)
            || Utils.isFlagSet(jobStatus, LibBat.JOB_STAT_RUN)) {
        Thread.sleep(30 * 1000L);

        int numJobs = LibBat.lsb_openjobinfo(jobId, null, null, null, null, LibBat.ALL_JOB);
        try {
            Assert.assertEquals(numJobs, 1);

            IntByReference more = new IntByReference();

            jobInfoEnt jobInfo = LibBat.lsb_readjobinfo(more);
            Assert.assertNotNull(jobInfo, "Job info is null");
            Assert.assertEquals(more.getValue(), 0, "More job info results than expected");

            jobStatus = jobInfo.status;
        } finally {
            LibBat.lsb_closejobinfo();
        }
    }
    Assert.assertTrue(Utils.isFlagSet(jobStatus, LibBat.JOB_STAT_DONE),
            String.format("Unexpected job status: 0x%02x", jobStatus));

    Assert.assertTrue(FileUtils.waitFor(outFile, 120), "File not found: " + outFile.getAbsolutePath());
    System.out.println("--- output ---");
    System.out.println(FileUtils.readFileToString(outFile));
    System.out.println("--- output ---");
    Assert.assertTrue(outFile.delete(), "Unable to delete " + outFile.getAbsolutePath());
    Assert.assertEquals(reply.queue, req.queue, "LSF reply queue does not match requested queue.");
    System.out.println("Validating that we reached the end of the test without exit.");
}

From source file:org.geoserver.wps.remote.plugin.output.XMPPRawDataOutput.java

/**
 * @param value/*from w ww. j ava 2 s .com*/
 * @param type
 * @param pID
 * @param baseURL
 * @param xmppClient
 * @param publish
 *
 * @throws IOException
 */
private Object encodeAsPlainRawData(Object value, String type, String pID, String baseURL,
        XMPPClient xmppClient, boolean publish, String name, String title, String description,
        String defaultStyle, String targetWorkspace, String metadata) throws IOException {
    final String extension = ((String) ((Object[]) XMPPClient.PRIMITIVE_NAME_TYPE_MAP.get(type))[4]);
    final String fileName = "wps-remote-str-rawdata_" + pID + extension;
    final File outputFile = getOutputFile(xmppClient, (String) value);
    final String content = FileUtils.readFileToString(outputFile);

    LOGGER.finest("[XMPP Raw Data Output - ProduceOutput] encodeAsPlainRawData:" + fileName);

    value = new StringRawData(content,
            ((String) ((Object[]) XMPPClient.PRIMITIVE_NAME_TYPE_MAP.get(type))[3]).split(",")[0]);
    if (publish) {
        final File tempFile = new File(FileUtils.getTempDirectory(), fileName);

        LOGGER.finest(
                "[XMPP Raw Data Output - ProduceOutput] encodeAsPlainRawData:" + tempFile.getAbsolutePath());

        FileUtils.writeStringToFile(tempFile, ((StringRawData) value).getData());
        FileUtils.waitFor(tempFile, 5);

        String wsName = xmppClient.getGeoServer().getCatalog().getDefaultWorkspace().getName();
        DataStoreInfo h2DataStore = xmppClient.createH2DataStore(wsName, FilenameUtils.getBaseName(fileName));

        try {
            xmppClient.importLayer(tempFile, type, h2DataStore, name + "_" + pID, title, description,
                    defaultStyle, targetWorkspace, metadata);
        } catch (Exception e) {
            LOGGER.log(Level.WARNING,
                    "There was an issue while trying to automatically publish the Layer into the Catalog!", e);
        }
    }
    return value;
}

From source file:org.mobicents.servlet.restcomm.amazonS3.S3AccessTool.java

public URI uploadFile(final String fileToUpload) {
    AWSCredentials credentials = new BasicAWSCredentials(accessKey, securityKey);
    AmazonS3 s3client = new AmazonS3Client(credentials);
    s3client.setRegion(Region.getRegion(Regions.fromName(bucketRegion)));
    if (logger.isInfoEnabled()) {
        logger.info("S3 Region: " + bucketRegion.toString());
    }// w ww.  j ava 2s.  c  om
    try {
        StringBuffer bucket = new StringBuffer();
        bucket.append(bucketName);
        if (folder != null && !folder.isEmpty())
            bucket.append("/").append(folder);
        URI fileUri = URI.create(fileToUpload);
        if (logger.isInfoEnabled()) {
            logger.info("File to upload to S3: " + fileUri.toString());
        }
        File file = new File(fileUri);
        //            while (!file.exists()){}
        //            logger.info("File exist: "+file.exists());
        //First generate the Presigned URL, buy some time for the file to be written on the disk
        Date date = new Date();
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        if (daysToRetainPublicUrl > 0) {
            cal.add(Calendar.DATE, daysToRetainPublicUrl);
        } else {
            //By default the Public URL will be valid for 180 days
            cal.add(Calendar.DATE, 180);
        }
        date = cal.getTime();
        GeneratePresignedUrlRequest generatePresignedUrlRequestGET = new GeneratePresignedUrlRequest(
                bucket.toString(), file.getName());
        generatePresignedUrlRequestGET.setMethod(HttpMethod.GET);
        generatePresignedUrlRequestGET.setExpiration(date);

        URL downloadUrl = s3client.generatePresignedUrl(generatePresignedUrlRequestGET);

        //Second upload the file to S3
        //            while (!file.exists()){}
        while (!FileUtils.waitFor(file, 30)) {
        }
        if (file.exists()) {
            PutObjectRequest putRequest = new PutObjectRequest(bucket.toString(), file.getName(), file);
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentType(new MimetypesFileTypeMap().getContentType(file));
            putRequest.setMetadata(metadata);
            if (reducedRedundancy)
                putRequest.setStorageClass(StorageClass.ReducedRedundancy);
            s3client.putObject(putRequest);

            if (removeOriginalFile) {
                removeLocalFile(file);
            }
            return downloadUrl.toURI();
        } else {
            logger.error("Timeout waiting for the recording file: " + file.getAbsolutePath());
            return null;
        }
    } catch (AmazonServiceException ase) {
        logger.error("Caught an AmazonServiceException");
        logger.error("Error Message:    " + ase.getMessage());
        logger.error("HTTP Status Code: " + ase.getStatusCode());
        logger.error("AWS Error Code:   " + ase.getErrorCode());
        logger.error("Error Type:       " + ase.getErrorType());
        logger.error("Request ID:       " + ase.getRequestId());
        return null;
    } catch (AmazonClientException ace) {
        logger.error("Caught an AmazonClientException, which ");
        logger.error("Error Message: " + ace.getMessage());
        return null;
    } catch (URISyntaxException e) {
        logger.error("URISyntaxException: " + e.getMessage());
        return null;
    }
}

From source file:org.restcomm.connect.commons.amazonS3.S3AccessTool.java

public URI uploadFile(final String fileToUpload) {
    if (s3client == null) {
        s3client = getS3client();//ww w . j a v a 2s .c  o  m
    }
    if (logger.isInfoEnabled()) {
        logger.info("S3 Region: " + bucketRegion.toString());
    }
    try {
        if (testing && (!testingUrl.isEmpty() || !testingUrl.equals(""))) {
            //                s3client.setEndpoint(testingUrl);
            //                s3client.setS3ClientOptions(new S3ClientOptions().withPathStyleAccess(true));
            FileUtils.touch(new File(URI.create(fileToUpload)));
        }
        StringBuffer bucket = new StringBuffer();
        bucket.append(bucketName);
        if (folder != null && !folder.isEmpty())
            bucket.append("/").append(folder);
        URI fileUri = URI.create(fileToUpload);
        if (logger.isInfoEnabled()) {
            logger.info("File to upload to S3: " + fileUri.toString());
        }
        File file = new File(fileUri);

        while (!FileUtils.waitFor(file, 30)) {
        }
        if (file.exists()) {
            PutObjectRequest putRequest = new PutObjectRequest(bucket.toString(), file.getName(), file);
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentType(new MimetypesFileTypeMap().getContentType(file));
            putRequest.setMetadata(metadata);
            if (reducedRedundancy)
                putRequest.setStorageClass(StorageClass.ReducedRedundancy);
            s3client.putObject(putRequest);

            if (removeOriginalFile) {
                removeLocalFile(file);
            }
            URI recordingS3Uri = s3client.getUrl(bucket.toString(), file.getName()).toURI();
            return recordingS3Uri;
            //                return downloadUrl.toURI();
        } else {
            logger.error("Timeout waiting for the recording file: " + file.getAbsolutePath());
            return null;
        }
    } catch (AmazonServiceException ase) {
        logger.error("Caught an AmazonServiceException");
        logger.error("Error Message:    " + ase.getMessage());
        logger.error("HTTP Status Code: " + ase.getStatusCode());
        logger.error("AWS Error Code:   " + ase.getErrorCode());
        logger.error("Error Type:       " + ase.getErrorType());
        logger.error("Request ID:       " + ase.getRequestId());
        return null;
    } catch (AmazonClientException ace) {
        logger.error("Caught an AmazonClientException ");
        logger.error("Error Message: " + ace.getMessage());
        return null;
    } catch (URISyntaxException e) {
        logger.error("URISyntaxException: " + e.getMessage());
        return null;
    } catch (IOException e) {
        logger.error("Problem while trying to touch recording file for testing", e);
        return null;
    }
}

From source file:org.silverpeas.core.process.io.file.FileHandler.java

/**
 * @see FileUtils// w  w  w . j a  v  a  2 s  .c  o m
 */
protected boolean waitFor(final FileBasePath basePath, final File file, final int seconds) {
    verify(basePath, file);
    return FileUtils.waitFor(getExistingFile(basePath, file), seconds);
}