Java Code Examples for org.apache.commons.io.FileUtils.forceMkdir()

The following are Jave code examples for showing how to use forceMkdir() of the org.apache.commons.io.FileUtils class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: FunnyCreator   File: FunnyMaven.java   View Source Code Vote up 6 votes
public void prepare() throws Exception {
    this.funnyCreator.info("Extracting maven");
    ZipUtils.unzipResource("/apache-maven-3.5.0.zip", FunnyConstants.MAVEN_DIRECTORY.getPath());

    this.invoker = new DefaultInvoker();
    this.invoker.setMavenHome(FunnyConstants.MAVEN_DIRECTORY);

    if (!FunnyConstants.BUILD_DIRECTORY.exists()) {
        FileUtils.forceMkdir(FunnyConstants.BUILD_DIRECTORY);
    }

    FunnyCreator.getLogger().info("Parse pom.xml");

    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();

    Document doc = dBuilder.parse(new File(FunnyConstants.REPOSITORY_DIRECTORY, "pom.xml"));
    doc.getDocumentElement().normalize();

    this.projectElement = (Element) doc.getElementsByTagName("project").item(0);
}
 
Example 2
Project: osc-core   File: PluginUploader.java   View Source Code Vote up 6 votes
@Override
public OutputStream receiveUpload(String filename, String mimeType) {
    if (filename == null || filename.isEmpty()) {
        return null;
    }
    log.info("Start uploading file: " + filename);
    try {
        if (validateFileExtension(filename)) {
            this.uploadPath = getTemporaryUploadPath();
            File uploadDirectory = new File(this.uploadPath);
            if (!uploadDirectory.exists()) {
                FileUtils.forceMkdir(uploadDirectory);
            }
            this.file = new File(this.uploadPath + filename);
            return new FileOutputStream(this.file);
        }

    } catch (Exception e) {
        log.error("Error opening file: " + filename, e);
        ViewUtil.iscNotification(VmidcMessages.getString(VmidcMessages_.UPLOAD_COMMON_ERROR) + e.getMessage(),
                Notification.Type.ERROR_MESSAGE);
    }
    return null;
}
 
Example 3
Project: cas-5.1.0   File: ChainingMetadataResolverCacheLoader.java   View Source Code Vote up 6 votes
private void resolveUrlBasedMetadataResource(final SamlRegisteredService service,
                                             final List<MetadataResolver> metadataResolvers,
                                             final AbstractResource metadataResource) throws Exception {

    final SamlIdPProperties.Metadata md = casProperties.getAuthn().getSamlIdp().getMetadata();
    final File backupDirectory = new File(md.getLocation().getFile(), "metadata-backups");
    final File backupFile = new File(backupDirectory, metadataResource.getFilename());

    LOGGER.debug("Metadata backup directory is designated to be [{}]", backupDirectory.getCanonicalPath());
    FileUtils.forceMkdir(backupDirectory);

    LOGGER.debug("Metadata backup file will be at [{}]", backupFile.getCanonicalPath());
    FileUtils.forceMkdirParent(backupFile);

    final HttpClientMultithreadedDownloader downloader =
            new HttpClientMultithreadedDownloader(metadataResource, backupFile);

    final FileBackedHTTPMetadataResolver metadataProvider = new FileBackedHTTPMetadataResolver(
            this.httpClient.getWrappedHttpClient(), metadataResource.getURL().toExternalForm(),
            backupFile.getCanonicalPath());
    buildSingleMetadataResolver(metadataProvider, service);
    metadataResolvers.add(metadataProvider);
}
 
Example 4
Project: invesdwin-context-matlab   File: MFileToSciScriptTask.java   View Source Code Vote up 6 votes
@Override
public void executeScript(final IScriptTaskEngine engine) {
    try {
        final String folderName = UNIQUE_NAME_GENERATOR.get("conversion");
        final File folder = new File(BASE_FOLDER, folderName);
        FileUtils.forceMkdir(folder);
        final File inputFile = new File(folder, "input.m");
        final FileOutputStream fis = new FileOutputStream(inputFile);
        IOUtils.copy(mfileIn, fis);
        fis.close();
        engine.eval("mfile2sci(\"" + inputFile.getAbsolutePath() + "\", \"" + folder.getAbsolutePath()
                + "\", %f, %T, 1, %T)");
        final File outputFile = new File(folder, "input.sci");
        outputStr = FileUtils.readFileToString(outputFile, Charset.defaultCharset());
        FileUtils.deleteQuietly(folder);
    } catch (final IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 5
Project: x-job   File: ClassLoaderHandler.java   View Source Code Vote up 6 votes
/**
 * Write java string to file , Preparing to compile
 *
 * @param java
 * @return
 * @throws IOException
 */
private File generateFile(String fileName, String java) throws IOException {
    logger.info("Step 2:Write java string to file...");
    String floder = TARGETCLASSDIR + FileSeparator + "tmp";
    File destFile = new File(floder);
    FileUtils.forceMkdir(destFile);
    File file = new File(floder + FileSeparator + fileName + ".java");
    try {
        OutputStream outputStream = new FileOutputStream(file);
        outputStream.write(java.getBytes());
        outputStream.flush();
        outputStream.close();
    } catch (IOException e) {
        logger.error(
                "Write java strng to file fail.....message is {}",
                e.getMessage()
        );
        e.printStackTrace();
    }
    return file;
}
 
Example 6
Project: invesdwin-context-matlab   File: JavasciScriptTaskEngineMatlab.java   View Source Code Vote up 6 votes
public JavasciScriptTaskEngineMatlab(final Scilab scilab) {
    this.scilab = scilab;
    this.inputs = new JavasciScriptTaskInputsMatlab(this);
    this.results = new JavasciScriptTaskResultsMatlab(this);
    if (IScriptTaskRunnerMatlab.LOG.isDebugEnabled()) {
        expressionEnding = ";";
    } else {
        expressionEnding = "";
    }
    try {
        FileUtils.forceMkdir(FOLDER);
    } catch (final IOException e) {
        throw new RuntimeException(e);
    }
    this.scriptFile = new File(FOLDER, UNIQUE_NAME_GENERATOR.get("script") + ".sce");
}
 
Example 7
Project: generator-jhipster-storage   File: _StorageService.java   View Source Code Vote up 6 votes
@Autowired
public StorageService(AmazonS3 s3Client) throws IOException {
    isLocalFileSystem = s3Client == null;

    if (isLocalFileSystem) {
        this.s3Client = null;
        this.buckets = null;
        localFileSystemDirectory =
                new File(String.format("%s/%s", new File("build").getAbsolutePath(), "storage"));
        FileUtils.forceMkdir(localFileSystemDirectory);
    } else {
        this.s3Client = s3Client;
        this.buckets = new ConcurrentHashMap<>();
        this.s3Client.listBuckets().forEach(bucket -> buckets.put(bucket.getName(), bucket));
    }
}
 
Example 8
Project: momo-2   File: Listeners.java   View Source Code Vote up 6 votes
private static void checkFiles(Guild g) {
	File f;
	if (!(f = new File("resources/guilds/" + g.getId() +"/")).exists()) {
		try {
			FileUtils.forceMkdir(f);
			FileUtils.copyFile(new File("resources/guilds/template.properties"), 
					new File("resources/guilds/" + g.getId() + "/GuildProperties.properties"));
			FileUtils.copyFile(new File("resources/guilds/template.db"), 
					new File("resources/guilds/" + g.getId() + "/Data.db"));
			FileUtils.copyFile(new File("resources/guilds/template.json"), 
					new File("resources/guilds/" + g.getId() + "/IdlePlaylist.json"));
			log.info("Guild file initialized: {}", g.getId());
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	}
}
 
Example 9
Project: otter-G   File: FileSystemClassScanner.java   View Source Code Vote up 5 votes
public void setExtendsDir(String extendsDir) {
    this.extendsDir = extendsDir;

    File dir = new File(extendsDir);
    if (!dir.exists()) {
        try {
            FileUtils.forceMkdir(dir);
        } catch (IOException e) {
            logger.error("##ERROR", e);
        }
    }
}
 
Example 10
Project: jwala   File: JvmServiceImplTest.java   View Source Code Vote up 5 votes
@Before
public void setup() throws IOException {
    initMocks(this);
    FileUtils.forceMkdir(new File(ApplicationProperties.get(PropertyKeys.PATHS_GENERATED_RESOURCE_DIR) + "/" + JUNIT_JVM));

    reset(Config.mockJvmPersistenceService, Config.mockGroupService, Config.mockApplicationService, Config.mockHistoryFacadeService,
            Config.mockMessagingTemplate, Config.mockGroupStateNotificationService, Config.mockResourceService,
            Config.mockClientFactoryHelper, Config.mockJvmControlService, Config.mockBinaryDistributionService,
            Config.mockBinaryDistributionLockManager, Config.mockJvmStateService, Config.mockWebServerPersistenceService, Config.mockGroupPersistenceService);
}
 
Example 11
Project: calendar-based-microsim   File: HardcodedData.java   View Source Code Vote up 5 votes
public static void initOutPutPath(String outputPath) {
	HardcodedData.outputTablesPath = outputPath;
	try {
		FileUtils.forceMkdir(new File(HardcodedData.outputTablesPath));
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}
 
Example 12
Project: leaf-snowflake   File: Utils.java   View Source Code Vote up 5 votes
public static String createPid( String pidDir) throws Exception
{
	if ( !PathUtils.exists_file(pidDir) )
	{
		FileUtils.forceMkdir(new File(pidDir));
	}
	if (! new File(pidDir).isDirectory() )
	{
		throw new RuntimeException("pid dir: " + pidDir + "is not directory.");
	}
	List<String> existPids = PathUtils.read_dir_contents(pidDir);
	//获得当前进程ID
	String pid = process_pid();
	String pidPath = pidDir + Config.FILE_SEPERATEOR + pid;
	PathUtils.touch(pidPath);
	LOG.info("Successfully touch pid: " + pidPath );

	for (String existPid : existPids)
	{
		try
		{
			kill(Integer.valueOf(existPid));
			PathUtils.rmpath(pidDir + Config.FILE_SEPERATEOR + existPid);
		} catch (Exception e)
		{
			LOG.warn(e.getMessage(),e);
		}
	}
	return pidPath;

}
 
Example 13
Project: aliyun-maxcompute-data-collectors   File: DataDrivenImportJob.java   View Source Code Vote up 5 votes
private void writeAvroSchema(final Schema schema) throws IOException {
  // Generate schema in JAR output directory.
  final File schemaFile = new File(options.getJarOutputDir(), schema.getName() + ".avsc");

  LOG.info("Writing Avro schema file: " + schemaFile);
  FileUtils.forceMkdir(schemaFile.getParentFile());
  FileUtils.writeStringToFile(schemaFile, schema.toString(true));

  // Copy schema to code output directory.
  try {
    FileUtils.moveFileToDirectory(schemaFile, new File(options.getCodeOutputDir()), true);
  } catch (final IOException e) {
    LOG.debug("Could not move Avro schema file to code output directory.", e);
  }
}
 
Example 14
Project: openrouteservice   File: FileUtility.java   View Source Code Vote up 5 votes
public static void makeDirectory(String directory) throws Exception {
	File dir = new File(directory);
	if (!dir.exists()) {
		try {
			FileUtils.forceMkdir(dir);
		} catch (SecurityException se) {
			// handle it
		}

		if (!dir.exists())
			throw new Exception("Unable to create directory - " + directory);
	}
}
 
Example 15
Project: JuniperBotJ   File: BlurImageController.java   View Source Code Vote up 5 votes
private File getCache() throws IOException {
    if (StringUtils.isEmpty(cacheFolder)) {
        return null;
    }
    File cacheDirectory = new File(cacheFolder);
    FileUtils.forceMkdir(cacheDirectory);
    return cacheDirectory;
}
 
Example 16
Project: spring2ts   File: BaseClientBuilder.java   View Source Code Vote up 5 votes
protected File createProjectDirectory() throws IOException {
    //File result = Files.createTempDir();
    //result.deleteOnExit();
    File result = new File("./" + System.currentTimeMillis());
    FileUtils.forceMkdir(result);
    return result;
}
 
Example 17
Project: raml-java-tools   File: RamlToPojoMojo.java   View Source Code Vote up 4 votes
@Override
public void execute() throws MojoExecutionException, MojoFailureException {

    getLog().error("GAAAAAA!");
    if (skip) {
        getLog().info("Skipping execution...");
        return;
    }

    if (ramlFile == null) {
        throw new MojoExecutionException("ramlFile is not defined");
    }

    try {
        FileUtils.forceMkdir(outputDirectory);
    } catch (final IOException ioe) {
        throw new MojoExecutionException("Failed to create directory: " + outputDirectory, ioe);
    }

    try {
        project.addCompileSourceRoot(outputDirectory.getPath());

        RamlModelResult ramlModelResult =
                new RamlModelBuilder().buildApi(
                        new FileReader(ramlFile),
                        ".");
        if (ramlModelResult.hasErrors()) {
            for (ValidationResult validationResult : ramlModelResult.getValidationResults()) {
                System.err.println(validationResult.getMessage());
            }
            throw new MojoExecutionException("invalid raml " + ramlFile);
        }

        final Api api = ramlModelResult.getApiV10();
        RamlToPojo ramlToPojo = RamlToPojoBuilder.builder(api)
                .inPackage(defaultPackage)
                .fetchTypes(fromAnywhere())
                .findTypes(everyWhere()).build();

        ramlToPojo.buildPojos().createAllTypes(outputDirectory.getAbsolutePath());

    } catch (IOException e) {

        throw new MojoExecutionException("execution exception", e);
    }
}
 
Example 18
Project: karate   File: UploadController.java   View Source Code Vote up 4 votes
public UploadController() throws Exception {
    File file = new File(FILES_BASE);
    FileUtils.forceMkdir(file);
    logger.info("created directory: {}", file);
}
 
Example 19
Project: otter-G   File: NioUtils.java   View Source Code Vote up 4 votes
/**
 * 尝试多次创建
 */
public static boolean create(File dest, final boolean isFile, final int retryTimes) {
    if (dest == null) {
        return false;
    }

    int totalRetry = retryTimes;

    if (retryTimes < 0) {
        totalRetry = 1;
    }

    int retry = 0;
    while (retry++ < totalRetry) {
        try {
            if (true == isFile) {
                if ((true == dest.exists()) || (true == dest.createNewFile())) {
                    return true;
                }
            } else {
                FileUtils.forceMkdir(dest);
                return true;
            }
        } catch (Exception ex) {
            // 本次等待时间
            int wait = (int) Math.pow(retry, retry) * timeWait;
            wait = (wait < timeWait) ? timeWait : wait;

            // 尝试等待
            if (retry == totalRetry) {
                return false;
            } else {

                // 记录日志
                logger.warn(String.format("[%s] create() - retry %s failed : wait [%s] ms , caused by %s",
                                          dest.getAbsolutePath(), retry, wait, ex.getMessage()));
                try {
                    Thread.sleep(wait);
                } catch (InterruptedException e) {
                    return false;
                }
            }
        }
    }

    return false;
}
 
Example 20
Project: plugin-prov   File: TerraformResourceTest.java   View Source Code Vote up 4 votes
@After
@Before
public void cleanupFiles() throws IOException {
	FileUtils.deleteDirectory(MOCK_PATH);
	FileUtils.forceMkdir(MOCK_PATH);
}