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

The following examples show how to use org.apache.commons.io.FileUtils#forceMkdir() . 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: NoraUiCommandLineInterface.java    From NoraUi with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * @param verbose
 *            boolean to activate verbose mode (show more traces).
 * @param gson
 *            is singleton json tool.
 * @param noraUiApplicationFile
 *            Object contain a application file from CLI Files.
 */
private void createFileApplicationsNoraUiCliFiles(boolean verbose, Gson gson, NoraUiApplicationFile noraUiApplicationFile) {
    try {
        FileUtils.forceMkdir(new File(CLI_FILES_DIR + File.separator + CLI_APPLICATIONS_FILES_DIR));
        File applicationFile = new File(CLI_FILES_DIR + File.separator + CLI_APPLICATIONS_FILES_DIR + File.separator + noraUiApplicationFile.getName() + JSON);
        if (!applicationFile.exists()) {
            Files.asCharSink(applicationFile, StandardCharsets.UTF_8).write(gson.toJson(noraUiApplicationFile));
            if (verbose) {
                log.info("Applications File [{}.json] created with success.", noraUiApplicationFile.getName());
            }
        } else {
            if (verbose) {
                log.info("Applications File [{}.json] already exist.", noraUiApplicationFile.getName());
            }
        }
    } catch (Exception e) {
        log.error(TECHNICAL_IO_EXCEPTION, e.getMessage(), e);
    }
}
 
Example 2
Source File: SimpleFileIO.java    From unidbg with Apache License 2.0 6 votes vote down vote up
public SimpleFileIO(int oflags, File file, String path) {
    super(oflags);
    this.file = file;
    this.path = path;

    if (file.isDirectory()) {
        throw new IllegalArgumentException("file is directory: " + file);
    }

    try {
        FileUtils.forceMkdir(file.getParentFile());
        if (!file.exists() && !file.createNewFile()) {
            throw new IOException("createNewFile failed: " + file);
        }

        randomAccessFile = new RandomAccessFile(file, "rws");
        onCreate(randomAccessFile);
    } catch (IOException e) {
        throw new IllegalStateException("process file failed: " + file.getAbsolutePath(), e);
    }
}
 
Example 3
Source File: Describe.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
private void scan(String directory, String name) {
	try {
		List<JaxrsClass> jaxrsClasses = new ArrayList<>();
		List<Class<?>> classes = this.scanJaxrsClass(name);
		for (Class<?> clz : classes) {
			if (StandardJaxrsAction.class.isAssignableFrom(clz)) {
				jaxrsClasses.add(this.jaxrsClass(clz));
			}
		}
		LinkedHashMap<String, List<?>> map = new LinkedHashMap<>();
		jaxrsClasses = jaxrsClasses.stream().sorted(Comparator.comparing(JaxrsClass::getName))
				.collect(Collectors.toList());
		map.put("jaxrs", jaxrsClasses);
		File dir = new File(directory);
		FileUtils.forceMkdir(dir);
		File file = new File(dir, "describe.json");
		FileUtils.writeStringToFile(file, XGsonBuilder.toJson(map), DefaultCharset.charset);
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 4
Source File: IpaLoader.java    From unidbg with Apache License 2.0 6 votes vote down vote up
protected String[] getEnvs(File rootDir) throws IOException {
        List<String> list = new ArrayList<>();
        list.add("PrintExceptionThrow=YES"); // log backtrace of every objc_exception_throw()
        if (log.isDebugEnabled()) {
            list.add("OBJC_HELP=YES"); // describe available environment variables
//            list.add("OBJC_PRINT_OPTIONS=YES"); // list which options are set
//            list.add("OBJC_PRINT_INITIALIZE_METHODS=YES"); // log calls to class +initialize methods
            list.add("OBJC_PRINT_CLASS_SETUP=YES"); // log progress of class and category setup
            list.add("OBJC_PRINT_PROTOCOL_SETUP=YES"); // log progress of protocol setup
            list.add("OBJC_PRINT_IVAR_SETUP=YES"); // log processing of non-fragile ivars
            list.add("OBJC_PRINT_VTABLE_SETUP=YES"); // log processing of class vtables
        }
        UUID uuid = UUID.nameUUIDFromBytes(DigestUtils.md5(appDir + "_Documents"));
        String homeDir = "/var/mobile/Containers/Data/Application/" + uuid.toString().toUpperCase();
        list.add("CFFIXED_USER_HOME=" + homeDir);
        FileUtils.forceMkdir(new File(rootDir, homeDir));
        return list.toArray(new String[0]);
    }
 
Example 5
Source File: PathUtil.java    From zstack with Apache License 2.0 5 votes vote down vote up
public static void forceCreateDirectory(String path) {
    try {
        FileUtils.forceMkdir(new File(path));
    } catch (IOException ex) {
        logger.warn(String.format("Failed in creating directory: %s: %s", path, ex.getMessage()));
    }
}
 
Example 6
Source File: Storage.java    From secrecy with Apache License 2.0 5 votes vote down vote up
public static File getTempFolder() {
    File tempDir = CustomApp.context.getExternalCacheDir();
    if (tempDir == null)                                                // when all else fails
        tempDir = CustomApp.context.getFilesDir();
    try {
        FileUtils.forceMkdir(tempDir);
    } catch (Exception e) {
        Util.log(e);
    }
    return tempDir;
}
 
Example 7
Source File: DataServerTools.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
public static DataTcpWebServer start(DataServer dataServer) throws Exception {
	File dataBaseDir = new File(Config.base(), "local/repository/data");
	FileUtils.forceMkdir(dataBaseDir);
	Server tcpServer = null;
	Server webServer = null;
	String password = Config.token().getPassword();
	String[] tcps = new String[9];
	tcps[0] = "-tcp";
	tcps[1] = "-tcpAllowOthers";
	tcps[2] = "-tcpPort";
	tcps[3] = dataServer.getTcpPort().toString();
	tcps[4] = "-baseDir";
	tcps[5] = dataBaseDir.getAbsolutePath();
	tcps[6] = "-tcpPassword";
	tcps[7] = password;
	tcps[8] = "-ifNotExists";
	tcpServer = Server.createTcpServer(tcps).start();
	Integer webPort = dataServer.getWebPort();
	if ((null != webPort) && (webPort > 0)) {
		String webs[] = new String[4];
		webs[0] = "-web";
		webs[1] = "-webAllowOthers";
		webs[2] = "-webPort";
		webs[3] = webPort.toString();
		webServer = Server.createWebServer(webs).start();
	}
	System.out.println("****************************************");
	System.out.println("* data server start completed.");
	System.out.println("* port: " + dataServer.getTcpPort() + ".");
	System.out.println("* web console port: " + dataServer.getWebPort() + ".");
	System.out.println("****************************************");
	return new DataTcpWebServer(tcpServer, webServer);
}
 
Example 8
Source File: PipelineTest.java    From wisdom with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws IOException {
    FileUtils.forceMkdir(SOURCES);
    textWatcher = new SpyWatcher(SOURCES, "txt");
    mdWatcher = new SpyWatcher(SOURCES, "md");
    mojo = mock(Mojo.class);
    Log log = mock(Log.class);
    when(mojo.getLog()).thenReturn(log);
    pipeline = new Pipeline(mojo, FAKE, Arrays.asList(textWatcher, mdWatcher), false);
    pipeline.watch();
}
 
Example 9
Source File: MarkdownRenderer.java    From owltools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void tellToIndex() throws IOException {
	String path = directoryPath; 
	FileUtils.forceMkdir(new File(path));
	// todo - make configurable
	io = new PrintStream(
			FileUtils.openOutputStream(new File(path + "/index.md")) 
			);
}
 
Example 10
Source File: AutomationTrainingDocumentExporter.java    From webanno with Apache License 2.0 5 votes vote down vote up
private void exportTrainingDocumentContents(ProjectExportRequest aRequest,
        ProjectExportTaskMonitor aMonitor, ExportedProject aExProject, File aCopyDir)
    throws IOException, ProjectExportException
{
    Project project = aRequest.getProject();
    File trainDocumentDir = new File(aCopyDir + TRAIN_FOLDER);
    FileUtils.forceMkdir(trainDocumentDir);
    // Get all the training documents from the project
    List<TrainingDocument> documents = automationService.listTrainingDocuments(project);
    int i = 1;
    for (TrainingDocument trainingDocument : documents) {
        try {
            FileUtils.copyFileToDirectory(
                    automationService.getTrainingDocumentFile(trainingDocument),
                    trainDocumentDir);
            aMonitor.setProgress((int) Math.ceil(((double) i) / documents.size() * 10.0));
            i++;
            log.info("Imported content for training document [" + trainingDocument.getId()
                    + "] in project [" + project.getName() + "] with id [" + project.getId()
                    + "]");
        }
        catch (FileNotFoundException e) {
            log.error("Source file [{}] related to project couldn't be located in repository",
                    trainingDocument.getName(), ExceptionUtils.getRootCause(e));
            aMonitor.addMessage(LogMessage.error(this,
                    "Source file [%s] related to project couldn't be located in repository",
                    trainingDocument.getName()));
            throw new ProjectExportException(
                    "Couldn't find some source file(s) related to project");
        }
    }
}
 
Example 11
Source File: NoraUiCommandLineInterfaceUT.java    From NoraUi with GNU Affero General Public License v3.0 5 votes vote down vote up
@Before
public void setUp() throws IOException {
    cli = new NoraUiCommandLineInterface();
    // mock Application Object here.
    cli.setApplication(new Application("src" + File.separator + "test"));
    cli.setScenario(new Scenario("src" + File.separator + "test"));
    cli.setModel(new Model("src" + File.separator + "test"));
    FileUtils.forceMkdir(new File(".noraui"));
}
 
Example 12
Source File: StormConfig.java    From jstorm with Apache License 2.0 5 votes vote down vote up
public static String masterInimbus(Map conf) throws IOException {
    String ret = masterLocalDir(conf) + FILE_SEPERATEOR + "ininumbus";
    try {
        FileUtils.forceMkdir(new File(ret));
    } catch (IOException e) {
        LOG.error("Failed to create dir " + ret, e);
        throw e;
    }
    return ret;
}
 
Example 13
Source File: GeneratedFileManager.java    From laozhongyi with MIT License 5 votes vote down vote up
public static void mkdirForHyperParameterConfig() {
    final String homeDir = System.getProperty("user.home");
    final String logDir = "hyper" + new LocalDateTime().toString();
    mHyperParameterConfigDirPath = FilenameUtils.concat(homeDir, logDir);
    try {
        FileUtils.forceMkdir(new File(mHyperParameterConfigDirPath));
    } catch (final IOException e) {
        throw new IllegalStateException(e);
    }
}
 
Example 14
Source File: TestBase.java    From hiped2 with Apache License 2.0 5 votes vote down vote up
@Before
public void before() throws IOException {
    if(TEST_ROOT_DIR.exists()) {
        FileUtils.forceDelete(TEST_ROOT_DIR);
    }
    FileUtils.forceMkdir(TEST_ROOT_DIR);
}
 
Example 15
Source File: RunShaderFamily.java    From graphicsfuzz with Apache License 2.0 4 votes vote down vote up
public static void mainHelper(
    String[] args,
    FuzzerServiceManager.Iface managerOverride)
    throws ShaderDispatchException, InterruptedException, IOException, ArgumentParserException {

  ArgumentParser parser = ArgumentParsers.newArgumentParser("RunShaderFamily")
      .defaultHelp(true)
      .description("Get images for all shaders in a shader set.");

  parser.addArgument("--verbose")
      .action(Arguments.storeTrue())
      .help("Verbose output.");

  parser.addArgument("--server")
      .help(
          "URL of server to use for sending get image requests.")
      .type(String.class);

  parser.addArgument("--worker")
      .help("The name of the worker used for get image requests. Used with --server.")
      .type(String.class);

  parser.addArgument("--output")
      .help("Output directory.")
      .setDefault(new File("."))
      .type(File.class);

  parser.addArgument("shader_family")
      .help("Shader family directory, or prefix of single shader job")
      .type(String.class);

  Namespace ns = parser.parseArgs(args);

  final boolean verbose = ns.get("verbose");
  final String shaderFamily = ns.get("shader_family");
  final String server = ns.get("server");
  final String worker = ns.get("worker");
  final File outputDir = ns.get("output");

  if (managerOverride != null && (server == null || worker == null)) {
    throw new ArgumentParserException(
        "Must supply server (dummy string) and worker name when executing in server process.",
        parser);
  }

  if (server != null) {
    if (worker == null) {
      throw new ArgumentParserException("With --server, must supply --worker name.", parser);
    }
  }

  IShaderDispatcher imageGenerator =
      server == null
          ? new LocalShaderDispatcher(false)
          : new RemoteShaderDispatcher(
              server + "/manageAPI",
              worker,
              managerOverride,
              new AtomicLong());

  FileUtils.forceMkdir(outputDir);

  if (!new File(shaderFamily).isDirectory()) {
    if (!new File(shaderFamily + ".json").exists()) {
      throw new ArgumentParserException(
          "Shader family must be a directory or the prefix of a single shader job.", parser);
    }
    // Special case: run get image on a single shader.
    runShader(outputDir, shaderFamily, imageGenerator,
        Optional.empty());
    return;
  }

  IShaderSet shaderSet = new LocalShaderSet(new File(shaderFamily));

  runShaderFamily(shaderSet, outputDir, imageGenerator);
}
 
Example 16
Source File: Application.java    From NoraUi with GNU Affero General Public License v3.0 4 votes vote down vote up
private void addHomePage(String applicationName, String noraRobotName, Class<?> robotContext, boolean verbose) {
    String pagePath = mainPath + File.separator + "java" + File.separator + robotContext.getCanonicalName().replaceAll("\\.", "/").replace("utils", "application/pages/" + applicationName)
            .replace("/", Matcher.quoteReplacement(File.separator)).replaceAll(robotContext.getSimpleName(), applicationName.toUpperCase().charAt(0) + applicationName.substring(1) + "HomePage")
            + ".java";
    StringBuilder sb = new StringBuilder();
    sb.append(getJavaClassHeaders(noraRobotName)).append(System.lineSeparator());
    sb.append(robotContext.getPackage().toString().replace("utils", "application.pages." + applicationName) + ";").append(System.lineSeparator());
    sb.append(System.lineSeparator());
    sb.append("import static " + robotContext.getCanonicalName() + "." + applicationName.toUpperCase() + SUFFIX_KEY).append(System.lineSeparator());
    sb.append(System.lineSeparator());
    sb.append("import org.openqa.selenium.support.ui.ExpectedConditions;").append(System.lineSeparator());
    sb.append(IMPORT_SLF4J_LOGGER).append(System.lineSeparator());
    sb.append(System.lineSeparator());
    sb.append("import " + robotContext.getCanonicalName() + ";").append(System.lineSeparator());
    sb.append(System.lineSeparator());
    sb.append("import com.github.noraui.application.page.Page;").append(System.lineSeparator());
    sb.append("import com.github.noraui.browser.waits.Wait;").append(System.lineSeparator());
    sb.append("import com.github.noraui.log.annotation.Loggable;").append(System.lineSeparator());
    sb.append("import com.github.noraui.utils.Context;").append(System.lineSeparator());
    sb.append("import com.github.noraui.utils.Utilities;").append(System.lineSeparator());
    sb.append("import com.google.inject.Singleton;").append(System.lineSeparator());
    sb.append(System.lineSeparator());
    sb.append(NORAUI_LOGGABLE_ANNOTATION).append(System.lineSeparator());
    sb.append(GOOGLE_INJECT_SINGLETON_ANNOTATION).append(System.lineSeparator());
    sb.append("public class " + applicationName.toUpperCase().charAt(0) + applicationName.substring(1) + "HomePage extends Page {").append(System.lineSeparator());
    sb.append(System.lineSeparator());
    sb.append("    static Logger log;").append(System.lineSeparator());
    sb.append(System.lineSeparator());
    sb.append("    public final PageElement login = new PageElement(\"-login_field\", \"Login\");").append(System.lineSeparator());
    sb.append("    public final PageElement password = new PageElement(\"-password_field\", \"Password\");").append(System.lineSeparator());
    sb.append("    public final PageElement signInButton = new PageElement(\"-sign_in_button\", \"Sign-in button\");").append(System.lineSeparator());
    sb.append(System.lineSeparator());
    sb.append("    public final PageElement signInError = new PageElement(\"-sign_in_error\", \"Sign-in error\");").append(System.lineSeparator());
    sb.append(System.lineSeparator());
    sb.append("    private static final String TITLE_PAGE = \"" + applicationName.toUpperCase().charAt(0) + applicationName.substring(1) + "\";").append(System.lineSeparator());
    sb.append(System.lineSeparator());
    sb.append("    public " + applicationName.toUpperCase().charAt(0) + applicationName.substring(1) + "HomePage() {").append(System.lineSeparator());
    sb.append("        super();").append(System.lineSeparator());
    sb.append("        this.application = " + applicationName.toUpperCase() + SUFFIX_KEY).append(System.lineSeparator());
    sb.append("        this.pageKey = \"" + applicationName.toUpperCase() + SUFFIX_HOME).append(System.lineSeparator());
    sb.append("        this.callBack = Context.getCallBack(" + noraRobotName + "Context.CLOSE_WINDOW_AND_SWITCH_TO_" + applicationName.toUpperCase() + "_HOME);").append(System.lineSeparator());
    sb.append("    }").append(System.lineSeparator());
    sb.append(System.lineSeparator());
    sb.append("    /**").append(System.lineSeparator());
    sb.append("     * {@inheritDoc}").append(System.lineSeparator());
    sb.append("     */").append(System.lineSeparator());
    sb.append("    @Override").append(System.lineSeparator());
    sb.append("    public boolean checkPage(Object... elements) {").append(System.lineSeparator());
    sb.append("        try {").append(System.lineSeparator());
    sb.append("            Wait.until(ExpectedConditions.not(ExpectedConditions.titleIs(\"\")));").append(System.lineSeparator());
    sb.append("            if (!TITLE_PAGE.equals(getDriver().getTitle())) {").append(System.lineSeparator());
    sb.append("                log.error(\"HTML title is not good\");").append(System.lineSeparator());
    sb.append("                return false;").append(System.lineSeparator());
    sb.append("            }").append(System.lineSeparator());
    sb.append("            // Wait.untilAnd(ExpectedConditions.presenceOfElementLocated(Utilities.getLocator(this.login)))").append(System.lineSeparator());
    sb.append("            //   .wait(() -> ExpectedConditions.presenceOfElementLocated(Utilities.getLocator(this.password)))").append(System.lineSeparator());
    sb.append("            //   .wait(() -> ExpectedConditions.presenceOfElementLocated(Utilities.getLocator(this.signInButton)));").append(System.lineSeparator());
    sb.append("            return true;").append(System.lineSeparator());
    sb.append("        } catch (Exception e) {").append(System.lineSeparator());
    sb.append("            log.error(\"HTML title Exception\", e);").append(System.lineSeparator());
    sb.append("            return false;").append(System.lineSeparator());
    sb.append("        }").append(System.lineSeparator());
    sb.append("    }").append(System.lineSeparator());
    sb.append(System.lineSeparator());
    sb.append("}").append(System.lineSeparator());
    try {
        FileUtils.forceMkdir(new File(pagePath.substring(0, pagePath.lastIndexOf(File.separator))));
        File newSelector = new File(pagePath);
        if (!newSelector.exists()) {
            Files.asCharSink(newSelector, StandardCharsets.UTF_8).write(sb.toString());
            if (verbose) {
                log.info("File [{}] created with success.", pagePath);
            }
        } else {
            if (verbose) {
                log.info("File [{}] already exist.", pagePath);
            }
        }
    } catch (Exception e) {
        log.error(TECHNICAL_IO_EXCEPTION, e.getMessage(), e);
    }
}
 
Example 17
Source File: ImportNewProjectsTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void testImportNewGradleProjects() throws Exception {
	IWorkspaceRoot wsRoot = WorkspaceHelper.getWorkspaceRoot();
	IWorkspace workspace = wsRoot.getWorkspace();
	IProject[] projects = workspace.getRoot().getProjects();
	assertEquals(0, projects.length);


	importProjects("gradle/multi-module");
	waitForJobs();
	projects = workspace.getRoot().getProjects();
	assertEquals(4, projects.length);
	// Add new sub-module
	IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject("multi-module");
	File projectBasePath = project.getLocation().toFile();
	BufferedWriter writer = new BufferedWriter(new FileWriter(new File(projectBasePath, "settings.gradle"), true));
	writer.newLine();
	writer.write("include 'test'");
	writer.close();
	File subModulePath = new File(projectBasePath, "test");
	FileUtils.forceMkdir(subModulePath);
	File buildFile = new File(subModulePath, "build.gradle");
	buildFile.createNewFile();

	// Verify no projects imported
	projects = workspace.getRoot().getProjects();
	assertEquals(4, projects.length);

	// Verify import projects
	projectsManager.setConnection(client);
	projectsManager.importProjects(new NullProgressMonitor());
	waitForJobs();
	IProject newProject = workspace.getRoot().getProject("test");
	assertTrue(newProject.exists());
	projects = workspace.getRoot().getProjects();
	assertEquals(5, projects.length);

	ArgumentCaptor<EventNotification> argument = ArgumentCaptor.forClass(EventNotification.class);
	verify(client, times(1)).sendEventNotification(argument.capture());
	assertEquals(EventType.ProjectsImported, argument.getValue().getType());
	assertEquals(((List<URI>) argument.getValue().getData()).size(), projects.length);
}
 
Example 18
Source File: UnicodeBufferTest.java    From p4ic4idea with Apache License 2.0 4 votes vote down vote up
@Test
public void testUTF16File() throws Exception {

	// Add Source file to depot
	client = server.getCurrentClient();
	IChangelist change = new Changelist();
	change.setDescription("Add UTF16 Unicode file");
	change = client.createChangelist(change);

	// ... copy from resource to workspace
	File utf16 = loadFileFromClassPath(CLASS_PATH_PREFIX + "/ko_utf16.xml");
	File testFile = new File(client.getRoot() + FILE_SEP + "ko_utf16.xml");
	Files.copy(utf16.toPath(), testFile.toPath());

	// ... add to pending change
	List<IFileSpec> fileSpecs = FileSpecBuilder.makeFileSpecList(testFile.getAbsolutePath());
	AddFilesOptions addOpts = new AddFilesOptions();
	addOpts.setChangelistId(change.getId());
	List<IFileSpec> msg = client.addFiles(fileSpecs, addOpts);
	assertNotNull(msg);
	assertEquals(FileSpecOpStatus.VALID, msg.get(0).getOpStatus());
	assertEquals("utf16", msg.get(0).getFileType());

	// ... submit file and validate
	msg = change.submit(false);
	assertNotNull(msg);
	assertEquals(FileSpecOpStatus.VALID, msg.get(0).getOpStatus());
	assertEquals(FileAction.ADD, msg.get(0).getAction());

	// Clean up directory
	String clientRoot = client.getRoot();
	FileUtils.deleteDirectory(new File(clientRoot));
	FileUtils.forceMkdir(new File(clientRoot));

	// Force sync client
	SyncOptions opts = new SyncOptions();
	opts.setForceUpdate(true);
	msg = client.sync(null, opts);
	assertNotNull(msg);
	assertEquals(FileSpecOpStatus.VALID, msg.get(0).getOpStatus());
	assertEquals("//depot/r173/ko_utf16.xml", msg.get(0).getDepotPathString());

	// Verify content
	List<String> original = fileToLines(utf16.getAbsolutePath());
	List<String> revised = fileToLines(msg.get(0).getClientPathString());
	Patch patch = DiffUtils.diff(original, revised);
	List deltas = patch.getDeltas();
	assertTrue(deltas.isEmpty());
}
 
Example 19
Source File: AutomationUtil.java    From webanno with Apache License 2.0 4 votes vote down vote up
public static void addOtherFeatureTrainDocument(MiraTemplate aTemplate,
        AnnotationSchemaService aAnnotationService, AutomationService aAutomationService,
        UserDao aUserDao)
    throws IOException, UIMAException, ClassNotFoundException
{
    File miraDir = aAutomationService.getMiraDir(aTemplate.getTrainFeature());
    if (!miraDir.exists()) {
        FileUtils.forceMkdir(miraDir);
    }

    AutomationStatus status = aAutomationService.getAutomationStatus(aTemplate);
    for (AnnotationFeature feature : aTemplate.getOtherFeatures()) {
        File trainFile = new File(miraDir, feature.getId() + ".train");
        boolean documentChanged = false;
        for (TrainingDocument document : aAutomationService
                .listTrainingDocuments(feature.getProject())) {
            if (!document.isProcessed() && (document.getFeature() != null
                    && document.getFeature().equals(feature))) {
                documentChanged = true;
                break;
            }
        }
        if (!documentChanged && trainFile.exists()) {
            continue;
        }

        BufferedWriter trainOut = new BufferedWriter(new FileWriter(trainFile));
        TypeAdapter adapter = aAnnotationService.getAdapter(feature.getLayer());
        for (TrainingDocument trainingDocument : aAutomationService
                .listTrainingDocuments(feature.getProject())) {
            if ((trainingDocument.getFeature() != null
                    && trainingDocument.getFeature().equals(feature))) {
                CAS cas = aAutomationService.readTrainingAnnotationCas(trainingDocument);
                for (AnnotationFS sentence : selectSentences(cas)) {
                    trainOut.append(getMiraLine(aAnnotationService, sentence, feature, adapter)
                            .toString()).append("\n");
                }
                trainingDocument.setProcessed(false);
                status.setTrainDocs(status.getTrainDocs() - 1);
            }
        }
        trainOut.close();
    }
}
 
Example 20
Source File: DocumentTranslationCLI.java    From mobi with GNU Affero General Public License v3.0 4 votes vote down vote up
private static void validateOutputLocation(File loc) throws IOException {
    FileUtils.forceMkdir(loc);
}