Example usage for org.apache.commons.lang SystemUtils getJavaIoTmpDir

List of usage examples for org.apache.commons.lang SystemUtils getJavaIoTmpDir

Introduction

In this page you can find the example usage for org.apache.commons.lang SystemUtils getJavaIoTmpDir.

Prototype

public static File getJavaIoTmpDir() 

Source Link

Document

Gets the Java IO temporary directory as a File.

Usage

From source file:com.enonic.cms.core.boot.HomeResolverTest.java

@Before
public void setUp() throws Exception {
    this.tmpDir = new File(SystemUtils.getJavaIoTmpDir(), "tmp-" + UUID.randomUUID().toString());
    this.defaultHomeDir = new File(this.tmpDir, "cms.home").getCanonicalFile();
    this.invalidHomeDir = new File(this.tmpDir, "invalid.home").getCanonicalFile();
    this.validHomeDir = new File(this.tmpDir, "valid.home").getCanonicalFile();
    this.notCreatedHomeDir = new File(this.tmpDir, "not.created.home").getCanonicalFile();

    this.defaultHomeDir.mkdirs();
    this.validHomeDir.mkdirs();
    FileUtils.touch(this.invalidHomeDir);
}

From source file:com.enonic.cms.core.boot.ConfigBuilderTest.java

@Before
public void setUp() throws Exception {
    this.homeDir = new File(SystemUtils.getJavaIoTmpDir(), "tmp-" + UUID.randomUUID().toString());

    this.classLoader = Mockito.mock(ClassLoader.class);

    this.builder = new ConfigBuilder(this.homeDir);
    this.builder.setSystemProperties(new Properties());
    this.builder.setClassLoader(this.classLoader);
}

From source file:com.github.neoio.net.message.staging.file.FileMessageStagingFactory.java

public FileMessageStagingFactory() throws NetIOException {
    this(SystemUtils.getJavaIoTmpDir());
}

From source file:com.gs.obevo.db.impl.platforms.h2.H2JdbcDataSourceFactory.java

public static String getUrlUncached(String dbName, boolean persistToFile) {
    Validate.notNull(dbName, "dbName parameter must be specified");
    String url;//ww  w .  j av  a  2 s  .co m
    if (persistToFile) {
        // In order to allow access to the db from multiple processes, the FILE_LOCK=NO setting is needed.
        // This however, does not prevent concurrency issues from multiple writers.
        // Other options found in the docs that we are not using: MVCC=TRUE;FILE_LOCK=SERIALIZED
        String dbFileName = new File(SystemUtils.getJavaIoTmpDir(), dbName).getAbsolutePath();
        LOG.info("writing db to file:{}", dbFileName);
        url = String.format("jdbc:h2:file:%s;FILE_LOCK=NO", dbFileName);
    } else {
        // use DB_CLOSE_DELAY=-1 to keep the DB open for the duration of the JVM
        url = String.format("jdbc:h2:mem:%s;DB_CLOSE_DELAY=-1", dbName);
    }
    LOG.info("setting up in memory db: {}", url);
    return url;
}

From source file:mitm.test.TestUtils.java

public static int getTempFileCount(final String prefix, final String postfix) {
    String[] files = SystemUtils.getJavaIoTmpDir().list(new FilenameFilter() {
        @Override/* ww w.j a v  a 2 s  .c  o m*/
        public boolean accept(File file, String s) {
            return StringUtils.startsWith(s, prefix) && StringUtils.endsWith(s, postfix);
        }
    });

    return files != null ? files.length : 0;
}

From source file:at.molindo.esi4j.rebuild.scrutineer.ScrutineerRebuildProcessor.java

@Override
public void rebuild(InternalIndex index, final Esi4JRebuildSession rebuildSession) {
    index.updateMapping(rebuildSession.getType());

    index.execute(new Esi4JOperation<Void>() {

        @Override//from ww  w  .  j av a  2 s  .  c  om
        public Void execute(Client client, String indexName, Esi4JOperation.OperationContext context) {

            final TypeMapping mapping = context.findTypeMapping(rebuildSession.getType());

            ModuleIdAndVersionStream moduleStream = new ModuleIdAndVersionStream(rebuildSession,
                    DEFAULT_BATCH_SIZE, mapping);

            IdAndVersionFactory factory = new MappedObjectIdAndVersionFactory(mapping);

            ElasticSearchSorter elasticSearchSorter = new ElasticSearchSorter(createSorter(factory));
            IteratorFactory iteratorFactory = new IteratorFactory(factory);
            String workingDirectory = SystemUtils.getJavaIoTmpDir().getAbsolutePath();

            ElasticSearchIdAndVersionStream esStream = new ElasticSearchIdAndVersionStream(
                    new ElasticSearchDownloader(client, indexName, "_type:" + mapping.getTypeAlias(), factory),
                    elasticSearchSorter, iteratorFactory, workingDirectory);

            long start = System.currentTimeMillis();

            BulkIndexHelper h = new BulkIndexHelper().setMaxRunning(2);
            h.setResponseHandler(new BulkIndexHelper.IResponseHandler() {

                @Override
                public void handle(String id, String type) {
                    if ("delete".equals(type)) {
                        onDelete(mapping.getTypeClass(), mapping.toId(id));
                    } else {
                        onIndex(mapping.getTypeClass(), mapping.toId(id));
                    }
                }

            });

            VerifierListener listener = new VerifierListener(client, indexName, context, mapping, h,
                    DEFAULT_BATCH_SIZE);

            try {
                verify(moduleStream, esStream, listener);
            } finally {
                /*
                 * TODO let IdAndVersionStreamVerifier do that as it does
                 * with streams
                 */
                listener.close();
            }

            try {
                h.await();

                long seconds = (System.currentTimeMillis() - start) / 1000;

                // logging
                StringBuilder logMsg = new StringBuilder("finished indexing of ").append(h.getSucceeded())
                        .append(" objects of type ").append(rebuildSession.getType().getName()).append(" in ")
                        .append(seconds).append(" seconds");

                if (h.getFailed() > 0) {
                    logMsg.append(" (").append(h.getFailed()).append(" failed)");
                    log.warn(logMsg.toString());
                } else {
                    log.info(logMsg.toString());
                }

            } catch (InterruptedException e) {
                log.error("awaiting completion of indexing has been interrupted", e);
            }

            return null;
        }
    });
}

From source file:edu.kit.dama.staging.util.StagingUtils.java

/**
 * Get the temporary directory of the transfer associated with the provided
 * transfer container. This directory is located in the user home directory
 * under ~/.lsdf/&lt;TID&gt;, where &lt;TID&gt; stands for the transfer ID of this
 * transfer. To avoid problems with invalid pathnames, the TID gets UTF-8
 * URL-encoded. Within the temporary directory the transfer can store status
 * information or checkpoint data to be able to resume failed transfers.
 *
 * @param pContainer The transfer container for which the temp dir should be
 * returned.//from w w w .j a  v  a2s . co m
 *
 * @return The transfer's temporary directory
 *
 * @throws IOException If there was not set any TID for this transfer or if
 * there are problems getting the users home directory
 */
public static String getTempDir(TransferTaskContainer pContainer) throws IOException {
    if (pContainer != null) {
        LOGGER.debug("Determining transfer tmp directory.");
        File userHome = SystemUtils.getUserHome();
        if (!isAccessibleDirectory(userHome)) {
            //user home not usable (maybe no home directory available). Try system temp dir...
            userHome = SystemUtils.getJavaIoTmpDir();
            if (!isAccessibleDirectory(userHome)) {
                throw new IOException("Failed to obtain valid temp directory. UserHome ("
                        + SystemUtils.getUserHome() + ") and TmpDir (" + userHome + ") are not usable.");
            } else {
                LOGGER.debug("Using tmp directory.");
            }
        } else {
            LOGGER.debug("Using user home directory.");
        }

        return FilenameUtils.concat(FilenameUtils.concat(userHome.getCanonicalPath(), ".lsdf"),
                URLEncoder.encode(pContainer.getUniqueTransferIdentifier(), "UTF-8"));
    } else {
        throw new IOException(
                "Failed to obtain temporary transfer directory. Transfer container must not be 'null'");
    }
}

From source file:fr.mby.portal.coreimpl.configuration.PropertiesConfigurationManager.java

@Override
public void afterPropertiesSet() throws Exception {
    if (!StringUtils.hasText(this.configFileDirectory)) {
        // Init directory
        this.configFileDirectory = SystemUtils.getJavaIoTmpDir().getPath();
    }/*from   w ww. j a va2s .  c o  m*/

    // Test if the direcotry exists
    final File dir = new File(this.configFileDirectory);
    if (!dir.isDirectory()) {
        this.configFileDirectory = SystemUtils.getJavaIoTmpDir().getPath();
    }
}

From source file:com.joshlong.esb.springintegration.modules.net.sftp.config.SFTPMessageSourceFactoryBean.java

@Override
protected SFTPMessageSource createInstance() throws Exception {
    try {//from   w  ww  . ja v  a  2  s  .  c  o m
        if ((localWorkingDirectory == null) || StringUtils.isEmpty(localWorkingDirectory)) {
            File tmp = SystemUtils.getJavaIoTmpDir();
            File sftpTmp = new File(tmp, "sftpInbound");
            this.localWorkingDirectory = "file://" + sftpTmp.getAbsolutePath();
        }
        assert !StringUtils
                .isEmpty(this.localWorkingDirectory) : "the local working directory mustn't be null!";

        // resource for local directory
        ResourceEditor editor = new ResourceEditor(this.resourceLoader);
        editor.setAsText(this.localWorkingDirectory);
        this.localDirectoryResource = (Resource) editor.getValue();

        fileReadingMessageSource = new FileReadingMessageSource();

        synchronizer = new SFTPInboundSynchronizer();

        if (null == taskScheduler) {
            Map<String, TaskScheduler> tss = null;

            if ((tss = applicationContext.getBeansOfType(TaskScheduler.class)).keySet().size() != 0) {
                taskScheduler = tss.get(tss.keySet().iterator().next());
            }
        }

        if (null == taskScheduler) {
            ThreadPoolTaskScheduler ts = new ThreadPoolTaskScheduler();
            ts.setPoolSize(10);
            ts.setErrorHandler(new ErrorHandler() {
                public void handleError(Throwable t) {
                    // todo make this forward a message onto the error channel (how does that work?)
                    logger.debug("error! ", t);
                }
            });

            ts.setWaitForTasksToCompleteOnShutdown(true);
            ts.initialize();
            this.taskScheduler = ts;
        }

        SFTPSessionFactory sessionFactory = SFTPSessionUtils.buildSftpSessionFactory(this.getHost(),
                this.getPassword(), this.getUsername(), this.getKeyFile(), this.getKeyFilePassword(),
                this.getPort());

        QueuedSFTPSessionPool pool = new QueuedSFTPSessionPool(15, sessionFactory);
        pool.afterPropertiesSet();
        synchronizer.setRemotePath(this.getRemoteDirectory());
        synchronizer.setPool(pool);
        synchronizer.setAutoCreatePath(this.isAutoCreateDirectories());
        synchronizer.setShouldDeleteDownloadedRemoteFiles(this.isAutoDeleteRemoteFilesOnSync());

        SFTPMessageSource sftpMessageSource = new SFTPMessageSource(fileReadingMessageSource, synchronizer);

        sftpMessageSource.setTaskScheduler(taskScheduler);

        if (null != this.trigger) {
            sftpMessageSource.setTrigger(trigger);
        }

        sftpMessageSource.setLocalDirectory(this.localDirectoryResource);
        sftpMessageSource.afterPropertiesSet();
        sftpMessageSource.start();

        return sftpMessageSource;
    } catch (Throwable thr) {
        logger.debug("error occurred when trying to configure SFTPmessageSource ", thr);
    }

    return null;
}

From source file:edu.cornell.med.icb.goby.config.GobyConfiguration.java

/**
 * Any default configuration item values if required should defined here.
 *
 * @return The default configuration to use.
 *///from   w w  w .  jav  a 2  s. c o m
private Configuration getDefaultConfiguration() {
    final Configuration defaultConfiguration = new BaseConfiguration();
    defaultConfiguration.addProperty(EXECUTABLE_PATH_LASTAG, "");
    defaultConfiguration.addProperty(EXECUTABLE_PATH_LAST, "");
    defaultConfiguration.addProperty(EXECUTABLE_PATH_BWA, "");
    defaultConfiguration.addProperty(EXECUTABLE_PATH_GSNAP, "");
    defaultConfiguration.addProperty(DATABASE_DIRECTORY, ".");
    defaultConfiguration.addProperty(WORK_DIRECTORY, SystemUtils.getJavaIoTmpDir().toString());
    return defaultConfiguration;
}