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

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

Introduction

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

Prototype

public static void writeLines(File file, Collection lines, String lineEnding) throws IOException 

Source Link

Document

Writes the toString() value of each item in a collection to the specified File line by line.

Usage

From source file:org.structr.server.Structr.java

/**
 * Start the structr server with the previously specified configuration.
 * //from   ww  w. j  a va  2 s  .c  o  m
 * @throws IOException
 * @throws InterruptedException
 * @throws Exception 
 */
public Server start(boolean waitForExit, boolean isTest) throws IOException, InterruptedException, Exception {

    String sourceJarName = app.getProtectionDomain().getCodeSource().getLocation().toString();

    if (!isTest
            && StringUtils.stripEnd(sourceJarName, System.getProperty("file.separator")).endsWith("classes")) {

        String jarFile = System.getProperty("jarFile");
        if (StringUtils.isEmpty(jarFile)) {
            throw new IllegalArgumentException(app.getName()
                    + " was started in an environment where the classloader cannot determine the JAR file containing the main class.\n"
                    + "Please specify the path to the JAR file in the parameter -DjarFile.\n"
                    + "Example: -DjarFile=${project.build.directory}/${project.artifactId}-${project.version}.jar");
        }
        sourceJarName = jarFile;
    }

    // get current base path
    basePath = System.getProperty("home", basePath);
    if (basePath.isEmpty()) {
        // use cwd and, if that fails, /tmp as a fallback
        basePath = System.getProperty("user.dir", "/tmp");
    }

    // create base directory if it does not exist
    File baseDir = new File(basePath);
    if (!baseDir.exists()) {
        baseDir.mkdirs();
    }

    configuredServices.add(ModuleService.class);
    configuredServices.add(NodeService.class);
    configuredServices.add(AgentService.class);
    configuredServices.add(CronService.class);
    configuredServices.add(LogService.class);

    File confFile = checkStructrConf(basePath, sourceJarName);
    Properties configuration = getConfiguration(confFile);

    checkPrerequisites(configuration);

    Server server = new Server(restPort);
    ContextHandlerCollection contexts = new ContextHandlerCollection();
    contexts.addHandler(new DefaultHandler());

    List<Connector> connectors = new LinkedList<Connector>();

    ServletContextHandler servletContext = new ServletContextHandler(server, contextPath, true, true);

    // create resource collection from base path & source JAR
    servletContext.setBaseResource(new ResourceCollection(Resource.newResource(basePath),
            JarResource.newJarResource(Resource.newResource(sourceJarName))));
    servletContext.setInitParameter("configfile.path", confFile.getAbsolutePath());

    // this is needed for the filters to work on the root context "/"
    servletContext.addServlet("org.eclipse.jetty.servlet.DefaultServlet", "/");
    servletContext.setInitParameter("org.eclipse.jetty.servlet.Default.dirAllowed", "false");

    if (enableGzipCompression) {

        FilterHolder gzipFilter = new FilterHolder(GzipFilter.class);
        gzipFilter.setInitParameter("mimeTypes", "text/html,text/plain,text/css,text/javascript");
        servletContext.addFilter(gzipFilter, "/*", EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD));

    }

    if (enableRewriteFilter) {

        FilterHolder rewriteFilter = new FilterHolder(UrlRewriteFilter.class);
        rewriteFilter.setInitParameter("confPath", "/urlrewrite.xml");
        servletContext.addFilter(rewriteFilter, "/*",
                EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD));
    }

    contexts.addHandler(servletContext);

    // enable request logging
    //if ("true".equals(configuration.getProperty("log.requests", "false"))) {
    if (logRequests) {

        String etcPath = basePath + "/etc";
        File etcDir = new File(etcPath);

        if (!etcDir.exists()) {

            etcDir.mkdir();
        }

        String logbackConfFilePath = basePath + "/etc/logback-access.xml";
        File logbackConfFile = new File(logbackConfFilePath);

        if (!logbackConfFile.exists()) {

            // synthesize a logback accees log config file
            List<String> config = new LinkedList<String>();

            config.add("<configuration>");
            config.add("  <appender name=\"FILE\" class=\"ch.qos.logback.core.rolling.RollingFileAppender\">");
            config.add("    <rollingPolicy class=\"ch.qos.logback.core.rolling.TimeBasedRollingPolicy\">");
            config.add("      <fileNamePattern>logs/" + logPrefix
                    + "-%d{yyyy_MM_dd}.request.log.zip</fileNamePattern>");
            config.add("    </rollingPolicy>");
            config.add("    <encoder>");
            config.add("      <charset>UTF-8</charset>");
            config.add("      <pattern>%h %l %u %t \"%r\" %s %b %n%fullRequest%n%n%fullResponse</pattern>");
            config.add("    </encoder>");
            config.add("  </appender>");
            config.add("  <appender-ref ref=\"FILE\" />");
            config.add("</configuration>");
            logbackConfFile.createNewFile();
            FileUtils.writeLines(logbackConfFile, "UTF-8", config);
        }

        FilterHolder loggingFilter = new FilterHolder(TeeFilter.class);
        servletContext.addFilter(loggingFilter, "/*",
                EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD));
        loggingFilter.setInitParameter("includes", "");

        RequestLogHandler requestLogHandler = new RequestLogHandler();
        String logPath = basePath + "/logs";
        File logDir = new File(logPath);

        // Create logs directory if not existing
        if (!logDir.exists()) {

            logDir.mkdir();

        }

        RequestLogImpl requestLog = new RequestLogImpl();
        requestLogHandler.setRequestLog(requestLog);

        HandlerCollection handlers = new HandlerCollection();
        handlers.setHandlers(new Handler[] { contexts, new DefaultHandler(), requestLogHandler });
        server.setHandler(handlers);

    } else {

        server.setHandler(contexts);

    }

    // add possible resource handler for static resources
    if (!resourceHandler.isEmpty()) {

        for (ContextHandler contextHandler : resourceHandler) {

            contexts.addHandler(contextHandler);

        }

    }

    //contexts.setHandlers(new Handler[] { new DefaultHandler(), contexts });

    ResourceProvider resourceProviderInstance = resourceProvider.newInstance();

    // configure JSON REST servlet
    JsonRestServlet structrRestServlet = new JsonRestServlet(resourceProviderInstance, defaultPropertyView,
            AbstractNode.uuid);
    ServletHolder structrRestServletHolder = new ServletHolder(structrRestServlet);

    servletParams.put("PropertyFormat", "FlatNameValue");
    servletParams.put("Authenticator", authenticator.getName());

    structrRestServletHolder.setInitParameters(servletParams);
    structrRestServletHolder.setInitOrder(0);

    // add to servlets
    servlets.put(restUrl + "/*", structrRestServletHolder);

    // add servlet elements
    int position = 1;
    for (Entry<String, ServletHolder> servlet : servlets.entrySet()) {

        String path = servlet.getKey();
        ServletHolder servletHolder = servlet.getValue();

        servletHolder.setInitOrder(position++);

        logger.log(Level.INFO, "Adding servlet {0} for {1}", new Object[] { servletHolder, path });

        servletContext.addServlet(servletHolder, path);
    }

    // register structr application context listener
    servletContext.addEventListener(new ApplicationContextListener());

    contexts.addHandler(servletContext);

    //server.setHandler(contexts);

    // HTTPs can be disabled
    if (enableHttps) {

        if (httpsPort > -1 && keyStorePath != null && !keyStorePath.isEmpty() && keyStorePassword != null) {

            // setup HTTP connector
            SslSelectChannelConnector httpsConnector = null;
            SslContextFactory factory = new SslContextFactory(keyStorePath);

            factory.setKeyStorePassword(keyStorePassword);

            httpsConnector = new SslSelectChannelConnector(factory);

            httpsConnector.setHost(host);

            httpsConnector.setPort(httpsPort);
            httpsConnector.setMaxIdleTime(maxIdleTime);
            httpsConnector.setRequestHeaderSize(requestHeaderSize);

            connectors.add(httpsConnector);

        } else {

            logger.log(Level.WARNING,
                    "Unable to configure SSL, please make sure that application.https.port, application.keystore.path and application.keystore.password are set correctly in structr.conf.");
        }
    }

    if (host != null && !host.isEmpty() && restPort > -1) {

        SelectChannelConnector httpConnector = new SelectChannelConnector();

        httpConnector.setHost(host);
        httpConnector.setPort(restPort);
        httpConnector.setMaxIdleTime(maxIdleTime);
        httpConnector.setRequestHeaderSize(requestHeaderSize);

        connectors.add(httpConnector);

    } else {

        logger.log(Level.WARNING,
                "Unable to configure REST port, please make sure that application.host, application.rest.port and application.rest.path are set correctly in structr.conf.");
    }

    if (!connectors.isEmpty()) {

        server.setConnectors(connectors.toArray(new Connector[0]));

    } else {

        logger.log(Level.SEVERE, "No connectors configured, aborting.");
        System.exit(0);
    }

    server.setGracefulShutdown(1000);
    server.setStopAtShutdown(true);

    if (!quiet) {

        System.out.println();
        System.out.println("Starting " + applicationName + " (host=" + host + ":" + restPort + ", maxIdleTime="
                + maxIdleTime + ", requestHeaderSize=" + requestHeaderSize + ")");
        System.out.println("Base path " + basePath);
        System.out.println();
        System.out.println(applicationName + " started:        http://" + host + ":" + restPort + restUrl);
        System.out.println();
    }

    server.start();

    // The jsp directory is created by the container, but we don't need it
    removeDir(basePath, "jsp");

    if (!callbacks.isEmpty()) {

        for (Callback callback : callbacks) {

            callback.execute();
        }

    }

    if (waitForExit) {

        server.join();

        if (!quiet) {

            System.out.println();
            System.out.println(applicationName + " stopped.");
            System.out.println();
        }
    }

    return server;
}

From source file:org.structr.server.Structr.java

private File checkStructrConf(String basePath, String sourceJarName) throws IOException {

    // create and register config file
    String confPath = basePath + "/structr.conf";
    File confFile = new File(confPath);

    // Create structr.conf if not existing
    if (!confFile.exists()) {

        // synthesize a config file
        List<String> config = new LinkedList<String>();

        config.add("##################################");
        config.add("# structr global config file     #");
        config.add("##################################");
        config.add("");

        if (sourceJarName.endsWith(".jar") || sourceJarName.endsWith(".war")) {

            config.add("# resources");
            config.add("resources = " + sourceJarName);
            config.add("");
        }/*from  w  w  w  .  j  a  va 2 s  .  c o m*/

        config.add("# JSON output nesting depth");
        config.add("json.depth = " + jsonDepth);
        config.add("");
        config.add("# base directory");
        config.add("base.path = " + basePath);
        config.add("");
        config.add("# temp files directory");
        config.add("tmp.path = /tmp");
        config.add("");
        config.add("# database files directory");
        config.add("database.path = " + basePath + "/db");
        config.add("");
        config.add("# binary files directory");
        config.add("files.path = " + basePath + "/files");
        config.add("");
        config.add("# log database file");
        config.add("log.database.path = " + basePath + "/" + logDbName);
        config.add("");
        config.add("# REST server settings");
        config.add("application.host = " + host);
        config.add("application.rest.port = " + restPort);
        config.add("application.rest.path = " + restUrl);
        config.add("");
        config.add("application.https.enabled = " + enableHttps);
        config.add("application.https.port = " + httpsPort);
        config.add("application.keystore.path = " + keyStorePath);
        config.add("application.keystore.password = " + keyStorePassword);
        config.add("");
        config.add("# SMTP settings");
        config.add("smtp.host = " + smtpHost);
        config.add("smtp.port = " + smtpPort);
        config.add("");
        config.add("superuser.username = superadmin");
        config.add("superuser.password = " + RandomStringUtils.randomAlphanumeric(12)); // Intentionally, no default password here

        if (!configuredServices.isEmpty()) {

            config.add("");
            config.add("# services");

            StringBuilder configuredServicesLine = new StringBuilder("configured.services =");

            for (Class<? extends Service> serviceClass : configuredServices) {
                configuredServicesLine.append(" ").append(serviceClass.getSimpleName());
            }

            config.add(configuredServicesLine.toString());

        }

        config.add("");
        config.add("# logging");
        config.add("log.requests = " + logRequests);
        config.add("log.name = structr-yyyy_mm_dd.request.log");

        if (!cronServiceTasks.isEmpty()) {

            config.add("");
            config.add("# cron tasks");
            config.add("CronService.tasks = \\");

            StringBuilder cronServiceTasksLines = new StringBuilder();
            StringBuilder cronExpressions = new StringBuilder();

            for (Entry<String, String> task : cronServiceTasks.entrySet()) {

                String taskClassName = task.getKey();
                String cronExpression = task.getValue();
                cronServiceTasksLines.append(taskClassName).append(" \\\n");
                cronExpressions.append(taskClassName).append(".cronExpression = ").append(cronExpression)
                        .append("\n");

            }

            if (cronServiceTasksLines.length() > 0) {

                config.add(cronServiceTasksLines.substring(0, cronServiceTasksLines.length() - 3));
                config.add(cronExpressions.toString());
            }

        }

        if (!customConfigLines.isEmpty()) {

            config.add("# custom configuration");

            for (String configLine : customConfigLines) {
                config.add(configLine);
            }

        }

        confFile.createNewFile();

        FileUtils.writeLines(confFile, "UTF-8", config);
    }

    return confFile;
}

From source file:org.test.LookupSVNUsers.java

/**
 * @param args//from  w w w  .j a  v  a 2 s . com
 * @throws IOException 
 */
public static void main(String[] args) throws IOException {

    if (args.length != 2) {
        log.error("USAGE: <svn users file(input)> <git authors file (output)>");

        System.exit(-1);
    }

    Set<String> unmatchedNameSet = new LinkedHashSet<String>();

    Map<String, GitUser> gitUserMap = new LinkedHashMap<String, GitUser>();

    String svnAuthorsFile = args[0];

    List<String> lines = FileUtils.readLines(new File(svnAuthorsFile));

    for (String line : lines) {

        // intentionally handle both upper and lower case varients of the same name.
        String svnUserName = line.trim();

        if (svnUserName.contains("("))
            continue; // skip over this line as we can't use it on the url

        if (gitUserMap.keySet().contains(svnUserName))
            continue; // skip this duplicate.

        log.info("starting on user = " + svnUserName);

        String gitName = extractFullName(svnUserName);

        if (gitName == null) {

            gitName = extractFullName(svnUserName.toLowerCase());
        }

        if (gitName == null) {
            unmatchedNameSet.add(svnUserName);
        } else {

            gitUserMap.put(svnUserName, new GitUser(svnUserName, gitName));
            log.info("mapped user (" + svnUserName + ") to: " + gitName);

        }

    }

    List<String> mergedList = new ArrayList<String>();

    mergedList.add("# GENERATED ");

    List<String> userNameList = new ArrayList<String>();

    userNameList.addAll(gitUserMap.keySet());

    Collections.sort(userNameList);

    for (String userName : userNameList) {

        GitUser gUser = gitUserMap.get(userName);

        mergedList.add(gUser.getSvnAuthor() + " = " + gUser.getGitUser() + " <" + gUser.getSvnAuthor()
                + "@users.sourceforge.net>");

    }

    for (String username : unmatchedNameSet) {

        log.warn("failed to match SVN User = " + username);

        // add in the unmatched entries as is.
        mergedList.add(username + " = " + username + " <" + username + "@users.sourceforge.net>");
    }

    FileUtils.writeLines(new File(args[1]), "UTF-8", mergedList);

}

From source file:pcgen.io.PCGIOHandler.java

public static void write(File partyFile, List<File> characterFiles) {
    String versionLine = "VERSION:" + PCGenPropBundle.getVersionNumber();
    String[] files = new String[characterFiles.size()];
    for (int i = 0; i < files.length; i++) {
        files[i] = FileHelper.findRelativePath(partyFile, characterFiles.get(i));
    }//from  w w  w  . j  av a  2 s  .com
    String filesLine = StringUtils.join(files, ',');
    try {
        FileUtils.writeLines(partyFile, "UTF-8", Arrays.asList(versionLine, filesLine));
    } catch (IOException ex) {
        Logging.errorPrint("Could not save the party file: " + partyFile.getAbsolutePath(), ex);
    }
}

From source file:playground.meisterk.org.matsim.run.facilities.ShopsOf2005ToFacilities.java

private static void shopsToTXT(Config config) {

    ScenarioImpl scenario = (ScenarioImpl) ScenarioUtils.createScenario(ConfigUtils.createConfig());
    ActivityFacilities shopsOf2005 = scenario.getActivityFacilities();
    shopsOf2005.setName("shopsOf2005");
    ArrayList<String> txtLines = new ArrayList<String>();
    ShopId shopId = null;/*  www.j av a2s .  c o  m*/
    String aShopLine = null;
    String facilityId = null;

    Day[] days = Day.values();
    OpeningTimeImpl opentime = null;

    // write header line
    aShopLine = "retailer" + ShopsOf2005ToFacilities.FIELD_DELIM + "businessRegion"
            + ShopsOf2005ToFacilities.FIELD_DELIM + "shopType" + ShopsOf2005ToFacilities.FIELD_DELIM
            + "shopDescription" + ShopsOf2005ToFacilities.FIELD_DELIM + "street"
            + ShopsOf2005ToFacilities.FIELD_DELIM + "postcode" + ShopsOf2005ToFacilities.FIELD_DELIM + "city"
            + ShopsOf2005ToFacilities.FIELD_DELIM + "CH1903_X" + ShopsOf2005ToFacilities.FIELD_DELIM
            + "CH1903_Y";

    for (Day day : days) {

        aShopLine += ShopsOf2005ToFacilities.FIELD_DELIM;
        aShopLine += day.getAbbrevEnglish();
        for (int ii = 1; ii <= 3; ii++) {
            aShopLine += ShopsOf2005ToFacilities.FIELD_DELIM;
        }
    }

    txtLines.add(aShopLine);

    System.out.println("Reading facilities xml file... ");
    FacilitiesReaderMatsimV1 facilities_reader = new FacilitiesReaderMatsimV1(scenario);
    facilities_reader.readFile(config.facilities().getInputFile());
    System.out.println("Reading facilities xml file...done.");

    Iterator<? extends ActivityFacility> facilityIterator = shopsOf2005.getFacilities().values().iterator();

    while (facilityIterator.hasNext()) {

        ActivityFacilityImpl facility = (ActivityFacilityImpl) facilityIterator.next();
        facilityId = facility.getId().toString();
        System.out.println(facilityId);

        try {
            shopId = new ShopId(facility.getId().toString());
        } catch (ArrayIndexOutOfBoundsException e) {
            continue;
        }

        // name, coordinates etc. (fixed length)
        aShopLine = shopId.getRetailer() + ShopsOf2005ToFacilities.FIELD_DELIM + shopId.getBusinessRegion()
                + ShopsOf2005ToFacilities.FIELD_DELIM + shopId.getShopType()
                + ShopsOf2005ToFacilities.FIELD_DELIM + shopId.getShopDescription()
                + ShopsOf2005ToFacilities.FIELD_DELIM + shopId.getStreet() + ShopsOf2005ToFacilities.FIELD_DELIM
                + shopId.getPostcode() + ShopsOf2005ToFacilities.FIELD_DELIM + shopId.getCity()
                + ShopsOf2005ToFacilities.FIELD_DELIM + (int) facility.getCoord().getY()
                + ShopsOf2005ToFacilities.FIELD_DELIM + (int) facility.getCoord().getX();
        ;

        ActivityOptionImpl shopping = (ActivityOptionImpl) facility.getActivityOptions()
                .get(ACTIVITY_TYPE_SHOP);
        if (shopping != null) {

            // open times (variable length)

            Set<OpeningTime> dailyOpentime = shopping.getOpeningTimes();

            if (dailyOpentime != null) {

                // what crappy code is that...but I had to get finished :-)
                opentime = (OpeningTimeImpl) ((TreeSet) dailyOpentime).last();
                aShopLine += ShopsOf2005ToFacilities.FIELD_DELIM;
                aShopLine += Time.writeTime(opentime.getStartTime());
                aShopLine += ShopsOf2005ToFacilities.FIELD_DELIM;
                aShopLine += Time.writeTime(opentime.getEndTime());
                if (dailyOpentime.size() == 2) {
                    opentime = (OpeningTimeImpl) ((TreeSet) dailyOpentime).first();
                    aShopLine += ShopsOf2005ToFacilities.FIELD_DELIM;
                    aShopLine += Time.writeTime(opentime.getStartTime());
                    aShopLine += ShopsOf2005ToFacilities.FIELD_DELIM;
                    aShopLine += Time.writeTime(opentime.getEndTime());
                } else if (dailyOpentime.size() == 1) {
                    aShopLine += ShopsOf2005ToFacilities.FIELD_DELIM;
                    aShopLine += ShopsOf2005ToFacilities.FIELD_DELIM;
                }

            }

        }
        txtLines.add(aShopLine);

    }

    System.out.println("Writing txt file...");
    try {
        FileUtils.writeLines(new File((String) null /* filename not specified */), "UTF-8", txtLines);
    } catch (IOException e) {
        e.printStackTrace();
    }
    System.out.println("Writing txt file...done.");

}

From source file:playground.meisterk.org.matsim.run.westumfahrung.CompareScenarios.java

private void writeResults() {

    File scenarioComparisonFile = new File(this.scenarioComparisonFilename);
    File routeSwitchersFile = new File(this.routeSwitchersListFilename);
    try {/*from www  .j  av  a 2  s  .com*/
        FileUtils.writeLines(scenarioComparisonFile, "UTF-8", this.scenarioComparisonLines);
        FileUtils.writeLines(routeSwitchersFile, "UTF-8", this.routeSwitchersLines);
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:pt.ua.tm.neji.web.server.Server.java

/**
 * Remove a dictionary. The dictionary file is deleted at dictionaries directory
 * and is removed from the server context.
 *
 * @param id dictionary id/*  w w w . j  a  va  2 s . com*/
 * @throws NejiException
 */
public void removeDictionary(int id) throws NejiException {

    // Get dicitionary
    Dictionary dictionary;
    try {
        dictionary = db.getDictionary(id);
    } catch (NejiException ex) {
        throw new NejiException("There was a problem removing the dictionary.\n" + "Please try again later.",
                ex);
    }

    // Verify if there are services or models that use this dicitionary
    if (!dictionary.getServices().isEmpty()) {
        throw new NejiException("Can't remove the dicitionay '" + dictionary.getName()
                + "' because it is being used by one or more services.");
    } else if (!dictionary.getModels().isEmpty()) {
        throw new NejiException("Can't remove the dicitionay '" + dictionary.getName()
                + "' because it is being used by one or more models.");
    }

    try {
        // Delete dicitionary from database
        db.removeDictionary(id);

        // Delete dicitionary from _priority file.
        File priorityFile = new File(DICTIONARIES_PRIORITY_PATH);
        List<String> lines = FileUtils.readLines(priorityFile);
        lines.remove(dictionary.getFile());
        FileUtils.writeLines(priorityFile, lines, false);

        // Remove dictionary from server context
        context.removeDictionary(dictionary.getFile());

        // Delete dicitionary file
        File dictionaryFile = new File(DICTIONARIES_PATH + dictionary.getFile());
        dictionaryFile.delete();

    } catch (NejiException | IOException ex) {
        throw new NejiException("There was a problem removing the dictionary.\n" + "Please try again later.",
                ex);
    }
}

From source file:pt.ua.tm.neji.web.server.Server.java

/**
 * Add new model to server. The model file is saved at models directory
 * and is added to the server context./*w  w w .ja v  a  2 s . c  o  m*/
 *
 * @param model                 model
 * @param file                  model file
 * @param configurationFile     configuration file
 * @param configurationFileName configuration file name
 * @param propertiesFile        properties file
 * @param propertiesFileName    properties file name
 * @throws NejiException
 */
public void addModel(Model model, InputStream file, InputStream configurationFile, String configurationFileName,
        InputStream propertiesFile, String propertiesFileName) throws NejiException {

    // Validate the model
    validateModel(model, configurationFileName, propertiesFileName, true);

    // Create model directory
    File modelDir = new File(MODELS_PATH + model.getName() + File.separator);
    File normalizationModelDir = new File(MODELS_PATH + model.getName() + File.separator + "normalization");
    modelDir.mkdir();
    normalizationModelDir.mkdir();

    // Save model into models folder
    try {
        IOUtils.copy(file, new FileOutputStream(modelDir.getAbsolutePath() + File.separator + model.getFile()));
    } catch (IOException ex) {
        throw new NejiException("There was a problem adding the model.\n" + "Please try again later.", ex);
    }

    // Save configuration file
    try {
        String configurationFilePath = modelDir.getAbsolutePath() + File.separator + configurationFileName;
        IOUtils.copy(configurationFile, new FileOutputStream(configurationFilePath));
    } catch (IOException ex) {

        // Delete dir
        try {
            FileUtils.deleteDirectory(modelDir);
        } catch (IOException ex2) {
        }

        throw new NejiException("There was a problem adding the model.\n" + "Please try again later.", ex);
    }

    // Save properties file
    String propertiesFilePath = modelDir.getAbsolutePath() + File.separator + propertiesFileName;
    File propFile = new File(propertiesFilePath);
    try {
        IOUtils.copy(propertiesFile, new FileOutputStream(propFile));

        // Add normalization line
        List<String> lines = FileUtils.readLines(propFile);
        int i = 0;
        for (String line : lines) {
            if (line.startsWith("dictionaries=")) {
                break;
            }
            i++;
        }

        if (i < lines.size()) {
            lines.remove(i);
        }

        lines.add("dictionaries=normalization" + File.separator);

        FileUtils.writeLines(propFile, lines, false);

    } catch (IOException ex) {

        // Delete dir
        try {
            FileUtils.deleteDirectory(modelDir);
        } catch (IOException ex2) {
        }

        throw new NejiException("There was a problem adding the model.\n" + "Please try again later.", ex);
    }

    // Save normalization info
    try {

        // Get normalization dictionaries
        List<String> lines = new ArrayList<>();
        for (String dictionaryName : model.getDictionaries()) {
            lines.add("../../../dictionaries/" + db.getDictionaryFile(dictionaryName));
        }

        // Write normalization _priority file
        File normalizationPriorityFile = new File(
                normalizationModelDir.getAbsoluteFile() + File.separator + "_priority");
        FileUtils.writeLines(normalizationPriorityFile, lines);

    } catch (IOException ex) {

        // Delete dir
        try {
            FileUtils.deleteDirectory(modelDir);
        } catch (IOException ex2) {
        }

        throw new NejiException("There was a problem adding the model.\n" + "Please try again later.", ex);
    }

    // Add model to current server context  
    try {
        MLModel ml = new MLModel(model.getName(), new File(propertiesFilePath));
        context.addNewModel(ml.getModelName(), ml);
    } catch (Exception ex) {

        // Delete dir
        try {
            FileUtils.deleteDirectory(modelDir);
        } catch (IOException ex2) {
        }

        throw new NejiException("The model file '" + model.getFile()
                + "' is not in the correct format.\nIt needs to be in GZIP format, "
                + "generated by Neji training features..");
    }

    // Save model details in database
    try {
        // Extract group from model
        String group = context.getModel(model.getName()).getSemanticGroup();
        model.setGroup(group);

        db.addModel(model);
    } catch (NejiException ex) {

        ex.printStackTrace();

        // Delete dir
        try {
            FileUtils.deleteDirectory(modelDir);
        } catch (IOException ex2) {
        }

        // Remove model from server context
        context.removeModel(model.getName());

        throw new NejiException("There was a problem adding the model.\n" + "Please try again later.", ex);
    }

    // Update _priority file
    try {

        FileWriter fw = new FileWriter(MODELS_PATH + "_priority", true);
        fw.write(model.getName() + File.separator + propertiesFileName + "\n");
        fw.close();
    } catch (IOException ex) {

        ex.printStackTrace();

        // Delete dir
        try {
            FileUtils.deleteDirectory(modelDir);
        } catch (IOException ex2) {
        }

        // Remove model from server context
        context.removeModel(model.getName());

        // Delete model data from database
        // ....

        throw new NejiException("There was a problem adding the model.\n" + "Please try again later.", ex);
    }
}

From source file:pt.ua.tm.neji.web.server.Server.java

/**
 * Remove a model. The model files are deleted at models directory
 * and it is removed from the server context.
 *
 * @param id model id/*from ww  w. j av a 2  s .c  om*/
 * @throws NejiException
 */
public void removeModel(int id) throws NejiException {

    // Get model
    Model model;
    try {
        model = db.getModel(id);
    } catch (NejiException ex) {
        throw new NejiException("There was a problem removing the model.\n" + "Please try again later.", ex);
    }

    // Verify if there are services that use this model
    if (!model.getServices().isEmpty()) {
        throw new NejiException("Can't remove the dicitionay '" + model.getName()
                + "' because it is being used by one or more services.");
    }

    try {
        // Delete model from database
        db.removeModel(id);

        // Delete model from _priority file.
        File priorityFile = new File(MODELS_PATH + "_priority");
        List<String> lines = FileUtils.readLines(priorityFile);
        int i = 0;
        for (String line : lines) {
            if (line.startsWith(model.getName() + File.separator)) {
                break;
            }
            i++;
        }
        lines.remove(i);
        FileUtils.writeLines(priorityFile, lines, false);

        // Remove model from server context
        context.removeModel(model.getName());

        // Delete model files
        File modelDir = new File(MODELS_PATH + model.getName() + File.separator);
        FileUtils.deleteDirectory(modelDir);

    } catch (NejiException | IOException ex) {
        throw new NejiException("There was a problem removing the model.\n" + "Please try again later.", ex);
    }
}

From source file:se.trixon.toolbox.checksum.ChecksumTopComponent.java

private void saveFile(File file) {
    Calendar calendar = Calendar.getInstance();

    String header = String.format("#Created by %s@%s on %s with TT Checksum, www.trixon.se/toolbox\n",
            System.getProperty("user.name"), SystemHelper.getHostname(), calendar.getTime());
    try {//www.  j a  va  2 s.c o  m
        FileUtils.write(file, header);
        FileUtils.writeLines(file, mChecksumRows, true);
        FileUtils.writeStringToFile(file, "\n", true);
    } catch (IOException ex) {
        Message.error(Dict.IO_ERROR_TITLE.getString(),
                String.format(Dict.FILE_ERROR_WRITE_MESSAGE.getString(), file.getAbsolutePath()));
    }
}