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

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

Introduction

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

Prototype

public static void touch(File file) throws IOException 

Source Link

Document

Implements the same behaviour as the "touch" utility on Unix.

Usage

From source file:org.apache.oodt.cas.pge.writers.MockDynamicConfigFileWriter.java

@Override
public File generateFile(String filePath, Metadata metadata, Logger logger, Object... customArgs)
        throws IOException {
    File configFile = new File(filePath);
    configFile.getParentFile().mkdirs();
    FileUtils.touch(configFile);
    return configFile;
}

From source file:org.apache.sling.commons.log.logback.integration.ITConfigPrinter.java

@Test
public void includeOnlyLastNFiles() throws Exception {
    waitForPrinter();//from   w  w  w. ja  v a 2  s  . c  om
    Configuration config = ca.getConfiguration(PID, null);
    Dictionary<String, Object> p = new Hashtable<String, Object>();
    p.put(LogConfigManager.PRINTER_MAX_INCLUDED_FILES, 3);
    p.put(LogConfigManager.LOG_LEVEL, "INFO");
    config.update(p);

    delay();

    createLogConfig("error.log", "includeOnlyLastNFiles", "includeOnlyLastNFiles.1");

    //txt mode log should at least have mention of all files
    for (int i = 0; i < 10; i++) {
        FileUtils.touch(new File(logDir, "error.log." + i));
    }

    StringWriter sw = new StringWriter();
    invoke("printConfiguration", new PrintWriter(sw), "txt");
    assertThat(sw.toString(), containsString("error.log"));
    for (int i = 0; i < 10; i++) {
        assertThat(sw.toString(), containsString("error.log." + i));
    }

    //Attachment should only be upto 3
    assertTrue(((URL[]) invoke("getAttachments", "zip")).length > 3);
}

From source file:org.apache.solr.SolrTestCaseJ4Test.java

@BeforeClass
public static void beforeClass() throws Exception {
    // Create a temporary directory that holds a core NOT named "collection1". Use the smallest configuration sets
    // we can so we don't copy that much junk around.
    tmpSolrHome = createTempDir().toFile().getAbsolutePath();

    File subHome = new File(new File(tmpSolrHome, "core0"), "conf");
    assertTrue("Failed to make subdirectory ", subHome.mkdirs());
    String top = SolrTestCaseJ4.TEST_HOME() + "/collection1/conf";
    FileUtils.copyFile(new File(top, "schema-tiny.xml"), new File(subHome, "schema-tiny.xml"));
    FileUtils.copyFile(new File(top, "solrconfig-minimal.xml"), new File(subHome, "solrconfig-minimal.xml"));
    FileUtils.copyFile(new File(top, "solrconfig.snippet.randomindexconfig.xml"),
            new File(subHome, "solrconfig.snippet.randomindexconfig.xml"));

    FileUtils.copyDirectory(new File(tmpSolrHome, "core0"), new File(tmpSolrHome, "core1"));
    // Core discovery will default to the name of the dir the core.properties file is in. So if everything else is
    // OK as defaults, just the _presence_ of this file is sufficient.
    FileUtils.touch(new File(tmpSolrHome, "core0/core.properties"));
    FileUtils.touch(new File(tmpSolrHome, "core1/core.properties"));

    FileUtils.copyFile(getFile("solr/solr.xml"), new File(tmpSolrHome, "solr.xml"));

    initCore("solrconfig-minimal.xml", "schema-tiny.xml", tmpSolrHome, "core1");
}

From source file:org.apache.storm.daemon.worker.Worker.java

public void start() throws Exception {
    LOG.info("Launching worker for {} on {}:{} with id {} and conf {}", topologyId, assignmentId, port,
            workerId, conf);/* w  ww  .  j a  va2  s. c  o m*/
    // because in local mode, its not a separate
    // process. supervisor will register it in this case
    // if ConfigUtils.isLocalMode(conf) returns false then it is in distributed mode.
    if (!ConfigUtils.isLocalMode(conf)) {
        // Distributed mode
        SysOutOverSLF4J.sendSystemOutAndErrToSLF4J();
        String pid = Utils.processPid();
        FileUtils.touch(new File(ConfigUtils.workerPidPath(conf, workerId, pid)));
        FileUtils.writeStringToFile(new File(ConfigUtils.workerArtifactsPidPath(conf, topologyId, port)), pid,
                Charset.forName("UTF-8"));
    }
    final Map<String, Object> topologyConf = ConfigUtils
            .overrideLoginConfigWithSystemProperty(ConfigUtils.readSupervisorStormConf(conf, topologyId));
    List<ACL> acls = Utils.getWorkerACL(topologyConf);
    IStateStorage stateStorage = ClusterUtils.mkStateStorage(conf, topologyConf, acls,
            new ClusterStateContext(DaemonType.WORKER));
    IStormClusterState stormClusterState = ClusterUtils.mkStormClusterState(stateStorage, acls,
            new ClusterStateContext());
    Credentials initialCredentials = stormClusterState.credentials(topologyId, null);
    Map<String, String> initCreds = new HashMap<>();
    if (initialCredentials != null) {
        initCreds.putAll(initialCredentials.get_creds());
    }
    autoCreds = AuthUtils.GetAutoCredentials(topologyConf);
    subject = AuthUtils.populateSubject(null, autoCreds, initCreds);
    backpressureZnodeTimeoutMs = ObjectReader.getInt(topologyConf.get(Config.BACKPRESSURE_ZNODE_TIMEOUT_SECS))
            * 1000;

    Subject.doAs(subject, new PrivilegedExceptionAction<Object>() {
        @Override
        public Object run() throws Exception {
            workerState = new WorkerState(conf, context, topologyId, assignmentId, port, workerId, topologyConf,
                    stateStorage, stormClusterState);

            // Heartbeat here so that worker process dies if this fails
            // it's important that worker heartbeat to supervisor ASAP so that supervisor knows
            // that worker is running and moves on
            doHeartBeat();

            executorsAtom = new AtomicReference<>(null);

            // launch heartbeat threads immediately so that slow-loading tasks don't cause the worker to timeout
            // to the supervisor
            workerState.heartbeatTimer.scheduleRecurring(0,
                    (Integer) conf.get(Config.WORKER_HEARTBEAT_FREQUENCY_SECS), () -> {
                        try {
                            doHeartBeat();
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    });

            workerState.executorHeartbeatTimer.scheduleRecurring(0,
                    (Integer) conf.get(Config.WORKER_HEARTBEAT_FREQUENCY_SECS),
                    Worker.this::doExecutorHeartbeats);

            workerState.registerCallbacks();

            workerState.refreshConnections(null);

            workerState.activateWorkerWhenAllConnectionsReady();

            workerState.refreshStormActive(null);

            workerState.runWorkerStartHooks();

            List<IRunningExecutor> newExecutors = new ArrayList<IRunningExecutor>();
            for (List<Long> e : workerState.getExecutors()) {
                if (ConfigUtils.isLocalMode(topologyConf)) {
                    newExecutors.add(LocalExecutor.mkExecutor(workerState, e, initCreds).execute());
                } else {
                    newExecutors.add(Executor.mkExecutor(workerState, e, initCreds).execute());
                }
            }
            executorsAtom.set(newExecutors);

            EventHandler<Object> tupleHandler = (packets, seqId, batchEnd) -> workerState
                    .sendTuplesToRemoteWorker((HashMap<Integer, ArrayList<TaskMessage>>) packets, seqId,
                            batchEnd);

            // This thread will publish the messages destined for remote tasks to remote connections
            transferThread = Utils.asyncLoop(() -> {
                workerState.transferQueue.consumeBatchWhenAvailable(tupleHandler);
                return 0L;
            });

            DisruptorBackpressureCallback disruptorBackpressureHandler = mkDisruptorBackpressureHandler(
                    workerState);
            workerState.transferQueue.registerBackpressureCallback(disruptorBackpressureHandler);
            workerState.transferQueue
                    .setEnableBackpressure((Boolean) topologyConf.get(Config.TOPOLOGY_BACKPRESSURE_ENABLE));
            workerState.transferQueue.setHighWaterMark(
                    ObjectReader.getDouble(topologyConf.get(Config.BACKPRESSURE_DISRUPTOR_HIGH_WATERMARK)));
            workerState.transferQueue.setLowWaterMark(
                    ObjectReader.getDouble(topologyConf.get(Config.BACKPRESSURE_DISRUPTOR_LOW_WATERMARK)));

            WorkerBackpressureCallback backpressureCallback = mkBackpressureHandler(topologyConf);
            backpressureThread = new WorkerBackpressureThread(workerState.backpressureTrigger, workerState,
                    backpressureCallback);
            if ((Boolean) topologyConf.get(Config.TOPOLOGY_BACKPRESSURE_ENABLE)) {
                backpressureThread.start();
                stormClusterState.topologyBackpressure(topologyId, backpressureZnodeTimeoutMs,
                        workerState::refreshThrottle);

                int pollingSecs = ObjectReader.getInt(topologyConf.get(Config.TASK_BACKPRESSURE_POLL_SECS));
                workerState.refreshBackpressureTimer.scheduleRecurring(0, pollingSecs,
                        workerState::refreshThrottle);
            }

            credentialsAtom = new AtomicReference<Credentials>(initialCredentials);

            establishLogSettingCallback();

            workerState.stormClusterState.credentials(topologyId, Worker.this::checkCredentialsChanged);

            workerState.refreshCredentialsTimer.scheduleRecurring(0,
                    (Integer) conf.get(Config.TASK_CREDENTIALS_POLL_SECS), new Runnable() {
                        @Override
                        public void run() {
                            checkCredentialsChanged();
                            if ((Boolean) topologyConf.get(Config.TOPOLOGY_BACKPRESSURE_ENABLE)) {
                                checkThrottleChanged();
                            }
                        }
                    });

            workerState.checkForUpdatedBlobsTimer.scheduleRecurring(0,
                    (Integer) conf.getOrDefault(Config.WORKER_BLOB_UPDATE_POLL_INTERVAL_SECS, 10),
                    new Runnable() {
                        @Override
                        public void run() {
                            try {
                                LOG.debug("Checking if blobs have updated");
                                updateBlobUpdates();
                            } catch (IOException e) {
                                // IOException from reading the version files to be ignored
                                LOG.error(e.getStackTrace().toString());
                            }
                        }
                    });

            // The jitter allows the clients to get the data at different times, and avoids thundering herd
            if (!(Boolean) topologyConf.get(Config.TOPOLOGY_DISABLE_LOADAWARE_MESSAGING)) {
                workerState.refreshLoadTimer.scheduleRecurringWithJitter(0, 1, 500, Worker.this::doRefreshLoad);
            }

            workerState.refreshConnectionsTimer.scheduleRecurring(0,
                    (Integer) conf.get(Config.TASK_REFRESH_POLL_SECS), workerState::refreshConnections);

            workerState.resetLogLevelsTimer.scheduleRecurring(0,
                    (Integer) conf.get(Config.WORKER_LOG_LEVEL_RESET_POLL_SECS),
                    logConfigManager::resetLogLevels);

            workerState.refreshActiveTimer.scheduleRecurring(0,
                    (Integer) conf.get(Config.TASK_REFRESH_POLL_SECS), workerState::refreshStormActive);

            LOG.info("Worker has topology config {}",
                    Utils.redactValue(topologyConf, Config.STORM_ZOOKEEPER_TOPOLOGY_AUTH_PAYLOAD));
            LOG.info("Worker {} for storm {} on {}:{}  has finished loading", workerId, topologyId,
                    assignmentId, port);
            return this;
        };
    });

}

From source file:org.apache.taverna.raven.plugins.ui.CheckForNoticeStartupHook.java

public boolean startup() {

    if (GraphicsEnvironment.isHeadless()) {
        return true; // if we are running headlessly just return
    }/*  w  w w.  j ava 2  s  .  co  m*/

    long noticeTime = -1;
    long lastCheckedTime = -1;

    HttpClient client = new HttpClient();
    client.setConnectionTimeout(TIMEOUT);
    client.setTimeout(TIMEOUT);
    PluginManager.setProxy(client);
    String message = null;

    try {
        URI noticeURI = new URI(BASE_URL + "/" + version + "/" + SUFFIX);
        HttpMethod method = new GetMethod(noticeURI.toString());
        int statusCode = client.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            logger.warn("HTTP status " + statusCode + " while getting " + noticeURI);
            return true;
        }
        String noticeTimeString = null;
        Header h = method.getResponseHeader("Last-Modified");
        message = method.getResponseBodyAsString();
        if (h != null) {
            noticeTimeString = h.getValue();
            noticeTime = format.parse(noticeTimeString).getTime();
            logger.info("NoticeTime is " + noticeTime);
        }

    } catch (URISyntaxException e) {
        logger.error("URI problem", e);
        return true;
    } catch (IOException e) {
        logger.info("Could not read notice", e);
    } catch (ParseException e) {
        logger.error("Could not parse last-modified time", e);
    }

    if (lastNoticeCheckFile.exists()) {
        lastCheckedTime = lastNoticeCheckFile.lastModified();
    }

    if ((message != null) && (noticeTime != -1)) {
        if (noticeTime > lastCheckedTime) {
            // Show the notice dialog
            JOptionPane.showMessageDialog(null, message, "Taverna notice", JOptionPane.INFORMATION_MESSAGE,
                    WorkbenchIcons.tavernaCogs64x64Icon);
            try {
                FileUtils.touch(lastNoticeCheckFile);
            } catch (IOException e) {
                logger.error("Unable to touch file", e);
            }
        }
    }
    return true;
}

From source file:org.apache.taverna.security.credentialmanager.impl.CredentialManagerImpl.java

public void deleteRevokedCertificates() {

    if (truststore != null) {
        // Delete the old revoked or unnecessary BioCatalogue,
        // BiodiversityCatalogue and heater's certificates, if present

        if (certificatesRevokedIndicatorFile == null) {
            certificatesRevokedIndicatorFile = new File(credentialManagerDirectory,
                    CERTIFICATES_REVOKED_INDICATOR_FILE_NAME);
        }/*from w w  w  . ja va2s  .  c o m*/

        if (!certificatesRevokedIndicatorFile.exists()) {

            List<URL> certURLsToDelete = new ArrayList<>();
            Class<?> c = CredentialManager.class;
            //certURLsToDelete.add(c.getResource("/trusted-certificates/www.biocatalogue.org-revoked.pem"));
            //certURLsToDelete.add(c.getResource("/trusted-certificates/www.biodiversitycatalogue.org-revoked.pem"));
            //certURLsToDelete.add(c.getResource("/trusted-certificates/heater.cs.man.ac.uk-not-needed.pem"));

            for (URL certURLToDelete : certURLsToDelete) {
                try (InputStream certStreamToDelete = certURLToDelete.openStream()) {
                    // We know there will be only one cert in the chain
                    CertificateFactory cf = CertificateFactory.getInstance("X.509");
                    Certificate certToDelete = cf.generateCertificates(certStreamToDelete)
                            .toArray(new Certificate[0])[0];
                    String aliasToDelete = truststore.getCertificateAlias(certToDelete);
                    if (aliasToDelete != null) {
                        truststore.deleteEntry(aliasToDelete);
                        logger.warn("Deleting revoked/unnecessary certificate " + aliasToDelete);
                    }
                } catch (Exception ex) {
                    logger.info("Can't delete revoked certificate " + certURLToDelete, ex);
                }
            }

            // Touch the file
            try {
                FileUtils.touch(certificatesRevokedIndicatorFile);
            } catch (IOException ioex) {
                // Hmmm, ignore this?
                logger.error("Failed to touch " + certificatesRevokedIndicatorFile.getAbsolutePath(), ioex);
            }
        }

        //Save changes
        try {
            FileOutputStream fos = new FileOutputStream(truststoreFile);
            truststore.store(fos, masterPassword.toCharArray());
        } catch (Exception ex) {
            String exMessage = "Failed to save Truststore after deleting revoked certificates.";
            logger.error(exMessage, ex);
        }
    }
}

From source file:org.asqatasun.referential.creator.FileGenerator.java

public void createI18NFiles(Set<String> langs) throws IOException {
    FileUtils.touch(getI18nDefaultFile("theme"));
    FileUtils.touch(getI18nDefaultFile("criterion"));
    FileUtils.touch(getI18nDefaultFile("rule"));
    FileUtils.touch(getI18nDefaultFile("rule-remark"));
    FileUtils.touch(getI18nDefaultFile("referential"));
    for (String lang : langs) {
        FileUtils.touch(getI18nFile(lang, "theme"));
        FileUtils.touch(getI18nFile(lang, "criterion"));
        FileUtils.touch(getI18nFile(lang, "rule"));
        FileUtils.touch(getI18nFile(lang, "rule-remark"));
        FileUtils.touch(getI18nFile(lang, "referential"));
    }//from ww  w.  j  ava 2s .c  o  m
}

From source file:org.asqatasun.referential.creator.FileGenerator.java

public void createSqlReference() throws IOException {
    FileUtils.touch(getSqlFile());
    StringBuilder strb = new StringBuilder();
    strb.append(//from w  ww  . j av a 2 s. co m
            "INSERT IGNORE INTO `REFERENCE` (`Cd_Reference`, `Description`, `Label`, `Url`, `Rank`, `Id_Default_Level`) VALUES\n");
    strb.append("(\'").append(vpc.getReferential().replace(".", "")).append("\', NULL, \'")
            .append(vpc.getReferentialLabel()).append("\', \'\', 2000, 1);\n\n");
    strb.append("INSERT IGNORE INTO `TGSI_REFERENTIAL` (`Code`, `Label`) VALUES\n");
    strb.append("(\'").append(vpc.getReferential().replace(".", "")).append("\', \'")
            .append(vpc.getReferentialLabel()).append("\');\n\n");
    FileUtils.writeStringToFile(FileUtils.getFile(getSqlFile()), strb.toString(), true);
}

From source file:org.asqatasun.referentiel.creator.FileGenerator.java

public void createSqlReference() throws IOException {
    FileUtils.touch(getSqlFile());
    StringBuilder strb = new StringBuilder();
    strb.append(//www  .j  a  v  a2  s .c  o  m
            "INSERT IGNORE INTO `REFERENCE` (`Cd_Reference`, `Description`, `Label`, `Url`, `Rank`, `Id_Default_Level`) VALUES\n");
    strb.append("(\'").append(vpc.getReferentiel().replace(".", "")).append("\', NULL, \'")
            .append(vpc.getReferentielLabel()).append("\', \'\', 2000, 1);\n\n");
    strb.append("INSERT IGNORE INTO `TGSI_REFERENTIAL` (`Code`, `Label`) VALUES\n");
    strb.append("(\'").append(vpc.getReferentiel().replace(".", "")).append("\', \'")
            .append(vpc.getReferentielLabel()).append("\');\n\n");
    FileUtils.writeStringToFile(FileUtils.getFile(getSqlFile()), strb.toString(), true);
}

From source file:org.betaconceptframework.astroboa.engine.jcr.io.SerializationBean.java

private File createSerializationFile(String serializationPath, String filename) throws Exception {
    //Filename of zip file
    //File will be store inside repository's home directory
    String repositoryHomeDir = clientContext.getRepositoryContext().getCmsRepository()
            .getRepositoryHomeDirectory();

    StringBuilder serializationFilePath = new StringBuilder();

    serializationFilePath.append(repositoryHomeDir).append(File.separator)
            .append(CmsConstants.SERIALIZATION_DIR_NAME).append(File.separator)
            .append(serializationPath.replaceAll("/", File.separator)).append(File.separator).append(filename)
            .append(ZIP);/*from   w  w  w. j av  a  2s.  co  m*/

    File zipFile = new File(serializationFilePath.toString());

    if (!zipFile.exists()) {
        FileUtils.touch(zipFile);
    }

    return zipFile;
}