Java Code Examples for com.google.common.io.Files#createParentDirs()

The following examples show how to use com.google.common.io.Files#createParentDirs() . 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: TreeShaker.java    From j2objc with Apache License 2.0 6 votes vote down vote up
private File stripIncompatible(List<String> sourceFileNames, Parser parser) throws IOException {
  File strippedDir = null;
  for (int i = 0; i < sourceFileNames.size(); i++) {
    String fileName = sourceFileNames.get(i);
    RegularInputFile file = new RegularInputFile(fileName);
    String source = j2objcOptions.fileUtil().readFile(file);
    if (!source.contains("J2ObjCIncompatible")) {
      continue;
    }
    if (strippedDir == null) {
      strippedDir = Files.createTempDir();
      parser.prependSourcepathEntry(strippedDir.getPath());
    }
    Parser.ParseResult parseResult = parser.parseWithoutBindings(file, source);
    String qualifiedName = parseResult.mainTypeName();
    parseResult.stripIncompatibleSource();
    String relativePath = qualifiedName.replace('.', File.separatorChar) + ".java";
    File strippedFile = new File(strippedDir, relativePath);
    Files.createParentDirs(strippedFile);
    Files.write(
        parseResult.getSource(), strippedFile, j2objcOptions.fileUtil().getCharset());
    sourceFileNames.set(i, strippedFile.getPath());
  }
  return strippedDir;
}
 
Example 2
Source File: FileConfiguration.java    From Kettle with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Saves this {@link FileConfiguration} to the specified location.
 * <p>
 * If the file does not exist, it will be created. If already exists, it
 * will be overwritten. If it cannot be overwritten or created, an
 * exception will be thrown.
 * <p>
 * This method will save using the system default encoding, or possibly
 * using UTF8.
 *
 * @param file File to save to.
 * @throws IOException              Thrown when the given file cannot be written to for
 *                                  any reason.
 * @throws IllegalArgumentException Thrown when file is null.
 */
public void save(File file) throws IOException {
    Validate.notNull(file, "File cannot be null");

    Files.createParentDirs(file);

    String data = saveToString();

    Writer writer = new OutputStreamWriter(new FileOutputStream(file), Charsets.UTF_8);

    try {
        writer.write(data);
    } finally {
        writer.close();
    }
}
 
Example 3
Source File: CycleFinder.java    From j2objc with Apache License 2.0 6 votes vote down vote up
private File stripIncompatible(
    List<String> sourceFileNames, Parser parser) throws IOException {
  File strippedDir = null;
  for (int i = 0; i < sourceFileNames.size(); i++) {
    String fileName = sourceFileNames.get(i);
    RegularInputFile file = new RegularInputFile(fileName);
    String source = j2objcOptions.fileUtil().readFile(file);
    if (!source.contains("J2ObjCIncompatible")) {
      continue;
    }
    if (strippedDir == null) {
      strippedDir = Files.createTempDir();
      parser.prependSourcepathEntry(strippedDir.getPath());
    }
    Parser.ParseResult parseResult = parser.parseWithoutBindings(file, source);
    String qualifiedName = parseResult.mainTypeName();
    parseResult.stripIncompatibleSource();
    String relativePath = qualifiedName.replace('.', File.separatorChar) + ".java";
    File strippedFile = new File(strippedDir, relativePath);
    Files.createParentDirs(strippedFile);
    Files.asCharSink(strippedFile, Charset.forName(options.fileEncoding()))
        .write(parseResult.getSource());
    sourceFileNames.set(i, strippedFile.getPath());
  }
  return strippedDir;
}
 
Example 4
Source File: SoftwareProcessSshDriverIntegrationTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test(groups = "Integration")
public void testCopiesAllFilesInDirectory() throws IOException {
    localhost.config().set(BrooklynConfigKeys.ONBOX_BASE_DIR, tempDataDir.getAbsolutePath());

    Path frogsPath = Paths.get(tempDataDir.getAbsolutePath(), "runtime-files", "frogs.txt");
    Files.createParentDirs(frogsPath.toFile());
    String frogsContent = new ResourceUtils(null).getResourceAsString("classpath://org/apache/brooklyn/entity/software/base/frogs.txt");
    Files.write(frogsContent.getBytes(), frogsPath.toFile());

    EmptySoftwareProcess entity = app.createAndManageChild(EntitySpec.create(EmptySoftwareProcess.class)
            .configure(SoftwareProcess.RUNTIME_FILES, MutableMap.of(frogsPath.getParent().toString(), "custom-runtime-files")));
    app.start(ImmutableList.of(localhost));

    File frogs = new File(entity.getAttribute(SoftwareProcess.RUN_DIR), "custom-runtime-files/frogs.txt");
    assertExcerptFromTheFrogs(frogs);
}
 
Example 5
Source File: TestReliableSpoolingFileEventReader.java    From mt-flume with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() throws IOException, InterruptedException {
  if (!WORK_DIR.isDirectory()) {
    Files.createParentDirs(new File(WORK_DIR, "dummy"));
  }

  // write out a few files
  for (int i = 0; i < 4; i++) {
    File fileName = new File(WORK_DIR, "file"+i);
    StringBuilder sb = new StringBuilder();

    // write as many lines as the index of the file
    for (int j = 0; j < i; j++) {
      sb.append("file" + i + "line" + j + "\n");
    }
    Files.write(sb.toString(), fileName, Charsets.UTF_8);
  }
  Thread.sleep(1500L); // make sure timestamp is later
  Files.write("\n", new File(WORK_DIR, "emptylineFile"), Charsets.UTF_8);
}
 
Example 6
Source File: ATHJUnitRunner.java    From blueocean-plugin with MIT License 5 votes vote down vote up
private void writeScreenShotCause(Throwable t, Object test, FrameworkMethod method) throws IOException {
    WebDriver driver = injector.getInstance(WebDriver.class);
    File file = new File("target/screenshots/"+ test.getClass().getName() + "_" + method.getName() + ".png");

    Throwable cause = t.getCause();
    boolean fromException = false;
    while(cause != null) {
        if(cause instanceof ScreenshotException) {
            ScreenshotException se = ((ScreenshotException) cause);

            byte[] screenshot =  Base64.getMimeDecoder().decode(se.getBase64EncodedScreenshot());

            Files.createParentDirs(file);
            Files.write(screenshot, file);
            logger.info("Wrote screenshot to " + file.getAbsolutePath());
            fromException = true;
            break;
        } else {
            cause = cause.getCause();
        }
    }

    if(!fromException) {
        File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(scrFile, file);
        logger.info("Wrote screenshot to " + file.getAbsolutePath());
    }
}
 
Example 7
Source File: FileScanWriter.java    From emodb with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean writeScanCompleteFile(URI fileUri, byte[] contents)
        throws IOException {
    File file = new File(fileUri.toURL().getFile());
    if (file.exists()) {
        // Complete already marked; take no action
        return false;

    }
    Files.createParentDirs(file);
    Files.write(contents, file);
    return true;
}
 
Example 8
Source File: IoUtil.java    From camunda-bpm-elasticsearch with Apache License 2.0 5 votes vote down vote up
public static void writeToFile(byte[] content, String fileName, boolean createFile) {
  File file = new File(fileName);
  try {
    if (createFile) {
      Files.createParentDirs(file);
      file.createNewFile();
    }

    Files.write(content, file);
  } catch (IOException e) {
    // nop
  }
}
 
Example 9
Source File: ConfigFileBasedClusterMetadataProvider.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public void setClusterMetadata(ClusterMetadata metadata) {
    try {
        File configFile = new File(metadataUrl.replaceFirst("file://", ""));
        Files.createParentDirs(configFile);
        ClusterMetadataPrototype metadataPrototype = toPrototype(metadata);
        mapper.writeValue(configFile, metadataPrototype);
        cachedMetadata.set(fetchMetadata(metadataUrl));
        providerService.clusterMetadataChanged(new Versioned<>(metadata, configFile.lastModified()));
    } catch (IOException e) {
        throw new IllegalArgumentException(e);
    }
}
 
Example 10
Source File: ServerLoadDataInfileHandler.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
private void saveDataToFile(LoadData data,String dnName)
{
    if (data.getFileName() == null)
    {
        String dnPath = tempPath + dnName + ".txt";
        data.setFileName(dnPath);
    }

       File dnFile = new File(data.getFileName());
        try
        {
            if (!dnFile.exists()) {
                                    Files.createParentDirs(dnFile);
                                }
                       	Files.append(joinLine(data.getData(),data), dnFile, Charset.forName(loadData.getCharset()));

        } catch (IOException e)
        {
            throw new RuntimeException(e);
        }finally
        {
            data.setData(null);

        }



}
 
Example 11
Source File: AppServiceImpl.java    From axelor-open-suite with GNU Affero General Public License v3.0 5 votes vote down vote up
private void copy(InputStream in, File toDir, String name) throws IOException {
  File dst = FileUtils.getFile(toDir, name);
  Files.createParentDirs(dst);
  FileOutputStream out = new FileOutputStream(dst);
  try {
    ByteStreams.copy(in, out);
  } finally {
    out.close();
  }
}
 
Example 12
Source File: InputFilePreprocessor.java    From j2objc with Apache License 2.0 5 votes vote down vote up
private void processRegularSource(ProcessingContext input) throws IOException {
  InputFile file = input.getFile();
  String source = options.fileUtil().readFile(file);
  boolean shouldMapHeaders = options.getHeaderMap().useSourceDirectories();
  boolean doIncompatibleStripping = source.contains("J2ObjCIncompatible");
  if (!(shouldMapHeaders || doIncompatibleStripping)) {
    // No need to parse.
    return;
  }
  Parser.ParseResult parseResult = parser.parseWithoutBindings(file, source);
  if (parseResult == null) {
    // The parser found and reported one or more errors.
    return;
  }
  String qualifiedName = parseResult.mainTypeName();
  if (shouldMapHeaders) {
    options.getHeaderMap().put(qualifiedName, input.getGenerationUnit().getOutputPath() + ".h");
  }
  if (doIncompatibleStripping) {
    parseResult.stripIncompatibleSource();
    File strippedDir = getCreatedStrippedSourcesDir();
    String relativePath = qualifiedName.replace('.', File.separatorChar) + ".java";
    File strippedFile = new File(strippedDir, relativePath);
    Files.createParentDirs(strippedFile);
    Files.asCharSink(strippedFile, options.fileUtil().getCharset())
        .write(parseResult.getSource());
    input.setFile(new RegularInputFile(strippedFile.getPath(), relativePath));
  }
}
 
Example 13
Source File: FetchingCacheServiceImpl.java    From genie with Apache License 2.0 5 votes vote down vote up
private void createDirectoryStructureIfNotExists(final File dir) throws IOException {
    if (!dir.exists()) {
        try {
            Files.createParentDirs(new File(dir, DUMMY_FILE_NAME));
        } catch (final IOException e) {
            throw new IOException("Failed to create directory: " + dir.getAbsolutePath(), e);
        }
    } else if (!dir.isDirectory()) {
        throw new IOException("This location is not a directory: " + dir.getAbsolutePath());
    }
}
 
Example 14
Source File: FileUtils.java    From metanome-algorithms with Apache License 2.0 5 votes vote down vote up
private boolean create() {
	try {
		Files.createParentDirs(file);
	} catch (IOException e) {
		log.warn("Error creating file", e);
		return false;
	}
	return true;
}
 
Example 15
Source File: OutputWriterFactory.java    From deploymentmanager-autogen with Apache License 2.0 5 votes vote down vote up
@Override
void writeOutput(Message message) throws IOException {
  Map<String, SolutionPackage> solutions;
  if (message instanceof BatchOutput) {
    final BatchOutput batchMessage = (BatchOutput) message;
    ImmutableMap.Builder<String, SolutionPackage> builder = ImmutableMap.builder();
    for (BatchOutput.SolutionOutput solution : batchMessage.getSolutionsList()) {
      builder.put(solution.getPartnerId() + "/" + solution.getSolutionId(),
          solution.getPackage());
    }
    solutions = builder.build();
  } else {
    solutions = ImmutableMap.of("", (SolutionPackage) message);
  }

  for (Map.Entry<String, SolutionPackage> entry : solutions.entrySet()) {
    for (SolutionPackage.File file : entry.getValue().getFilesList()) {
      String filePath =
          Paths.get(this.settings.getOutput(), entry.getKey(), file.getPath()).toString();
      File outputFile = new File(filePath);
      Files.createParentDirs(outputFile);
      if (filePath.endsWith(".png") || filePath.endsWith(".jpg")) {
        Files.write(BaseEncoding.base64().decode(file.getContent()), outputFile);
      } else {
        Files.asCharSink(outputFile, UTF_8).write(file.getContent());
      }
    }
  }
}
 
Example 16
Source File: LocalMsInstFileService.java    From tac with MIT License 5 votes vote down vote up
@Override
public Boolean saveInstanceFile(TacInst tacInst, byte[] data) {

    // 文件存在删除

    try {
        Long instId = tacInst.getId();

        File zipOutFile = new File(tacFileService.getLoadClassFilePath(instId));

        if (zipOutFile.exists()) {
            boolean deleteResult = zipOutFile.delete();
            LOGGER.debug("TacInstanceLoader.loadTacHandler,instId:{} exists,delete result {}", instId,
                deleteResult);
        } else {
            final String saveFileName = tacFileService.getLoadClassFilePath(instId);
            LOGGER.debug("TacInstanceLoader.loadTacHandler,saveFileName:{} ", saveFileName);
            Files.createParentDirs(new File(saveFileName));
            LOGGER.debug("TacInstanceLoader.loadTacHandler,createParentDirs success");
        }
        zipOutFile.createNewFile();
        LOGGER.debug("TacInstanceLoader.loadTacHandler,createNewFile success " + zipOutFile.getAbsolutePath());
        FileCopyUtils.copy(data, zipOutFile);
        LOGGER.debug("TacInstanceLoader.loadTacHandler,createNewFile copy success");

        return true;
    } catch (Exception e) {

        throw new IllegalStateException(e.getMessage(), e);
    }

}
 
Example 17
Source File: FileScanWriter.java    From emodb with Apache License 2.0 5 votes vote down vote up
@Override
protected ListenableFuture<?> transfer(TransferKey transferKey, URI uri, File file){
    _activeFiles.put(transferKey, file);
    try {
        File dest = new File(uri.toURL().getFile());
        Files.createParentDirs(dest);
        Files.copy(file, dest);
        return Futures.immediateFuture(null);
    } catch (Exception e) {
        return Futures.immediateFailedFuture(e);
    } finally {
        _activeFiles.remove(transferKey);
    }

}
 
Example 18
Source File: DirectoryWriter.java    From EasyRouter with Apache License 2.0 5 votes vote down vote up
public void write(File relativeRoot, String relativePath, byte[] bytes) throws IOException {
    if (bytes != null) {
        File target = toSystemDependentFile(relativeRoot, relativePath);
        Files.createParentDirs(target);
        Files.write(bytes, target);
    }

}
 
Example 19
Source File: StandardProcessOperations.java    From exhibitor with Apache License 2.0 4 votes vote down vote up
private void prepConfigFile(Details details) throws IOException
{
    UsState                 usState = new UsState(exhibitor);

    File                    idFile = new File(details.dataDirectory, "myid");
    if ( usState.getUs() != null )
    {
        Files.createParentDirs(idFile);
        String                  id = String.format("%d\n", usState.getUs().getServerId());
        Files.write(id.getBytes(), idFile);
    }
    else
    {
        exhibitor.getLog().add(ActivityLog.Type.INFO, "Starting in standalone mode");
        if ( idFile.exists() && !idFile.delete() )
        {
            exhibitor.getLog().add(ActivityLog.Type.ERROR, "Could not delete ID file: " + idFile);
        }
    }

    Properties      localProperties = new Properties();
    localProperties.putAll(details.properties);

    localProperties.setProperty("clientPort", Integer.toString(usState.getConfig().getInt(IntConfigs.CLIENT_PORT)));

    String          portSpec = String.format(":%d:%d", usState.getConfig().getInt(IntConfigs.CONNECT_PORT), usState.getConfig().getInt(IntConfigs.ELECTION_PORT));
    for ( ServerSpec spec : usState.getServerList().getSpecs() )
    {
        localProperties.setProperty("server." + spec.getServerId(), spec.getHostname() + portSpec + spec.getServerType().getZookeeperConfigValue());
    }

    if ( (usState.getUs() != null) && (usState.getUs().getServerType() == ServerType.OBSERVER) )
    {
        localProperties.setProperty("peerType", "observer");
    }

    File            configFile = new File(details.configDirectory, "zoo.cfg");
    OutputStream out = new BufferedOutputStream(new FileOutputStream(configFile));
    try
    {
        localProperties.store(out, "Auto-generated by Exhibitor - " + new Date());
    }
    finally
    {
        CloseableUtils.closeQuietly(out);
    }
}
 
Example 20
Source File: FileUtil.java    From j360-dubbo-app-all with Apache License 2.0 2 votes vote down vote up
/**
 * 确保父目录及其父目录直到根目录都已经创建.
 * 
 * @see Files#createParentDirs(File)
 */
public static void makesureParentDirExists(File file) throws IOException {
	Files.createParentDirs(file);
}