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

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

Introduction

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

Prototype

public static List readLines(File file) throws IOException 

Source Link

Document

Reads the contents of a file line by line to a List of Strings using the default encoding for the VM.

Usage

From source file:grisu.frontend.view.swing.jobmonitoring.single.appSpecific.Gold.java

protected void calculateCurrentLigandNoAndCpusAndLicenses() {

    if (StringUtils.isBlank(currentStatusPath)) {
        return;// ww w. j a  v  a 2  s. c  o m
    }

    getCpusProgressBar().setString("Updating...");
    getLicensesAllProgressbar().setString("Updating...");
    getLicensesJobProgressBar().setString("Updating...");
    getWalltimeProgressbar().setString("Updating...");
    getProgressBar().setString("Updating...");

    List<String> lines = null;
    Long timestampTemp = -1L;
    try {
        final File currentStatusFile = fm.downloadFile(currentStatusPath);
        lines = FileUtils.readLines(currentStatusFile);
        timestampTemp = fm.getLastModified(currentStatusPath);
    } catch (final Exception e) {
        myLogger.error(e.getLocalizedMessage(), e);
        getCpusProgressBar().setString("n/a");
        getLicensesAllProgressbar().setString("n/a");
        getLicensesJobProgressBar().setString("n/a");
        getWalltimeProgressbar().setString("n/a");
        getProgressBar().setString("n/a");
        return;
    }

    final Long deltaInSeconds = (timestampTemp - startTimestamp) / 1000L;
    getWalltimeProgressbar().setValue(deltaInSeconds.intValue());

    final Long hours = deltaInSeconds / 3600L;
    getWalltimeProgressbar().setString(hours + "  (of " + (walltime / 3600) + ")");

    if (lines.size() != 1) {
        getCpusProgressBar().setString("Error...");
        getLicensesAllProgressbar().setString("Error...");
        getLicensesJobProgressBar().setString("Error...");
        return;
    }

    final String[] tokens = lines.get(0).split(",");

    int cpusTemp = -1;
    try {
        cpusTemp = Integer.parseInt(tokens[1]);
    } catch (final Exception e) {
        myLogger.error(e.getLocalizedMessage(), e);
    }

    int licensesUserTemp = -1;
    try {
        licensesUserTemp = Integer.parseInt(tokens[2]);
    } catch (final Exception e) {
        myLogger.error(e.getLocalizedMessage(), e);
    }

    int licensesAllTemp = -1;
    try {
        licensesAllTemp = Integer.parseInt(tokens[3]);
    } catch (final Exception e) {
        myLogger.error(e.getLocalizedMessage(), e);
    }

    if (cpusTemp <= 0) {
        getCpusProgressBar().setString("n/a");
        getCpusProgressBar().setValue(0);
    } else {
        getCpusProgressBar().setString(cpusTemp + "   (of " + noCpus + ")");
        getCpusProgressBar().setValue(cpusTemp);
    }
    if (licensesUserTemp <= 0) {
        getLicensesJobProgressBar().setString("n/a");
        getLicensesJobProgressBar().setValue(0);
    } else {
        getLicensesJobProgressBar().setString(licensesUserTemp + "   (of " + noCpus + ")");
        getLicensesJobProgressBar().setValue(licensesUserTemp);
    }
    if (licensesAllTemp <= 0) {
        getLicensesAllProgressbar().setString("n/a");
        getLicensesAllProgressbar().setValue(0);
    } else {
        getLicensesAllProgressbar().setString(licensesAllTemp + "   (of " + GOLD_LICENSES + ")");
        getLicensesAllProgressbar().setValue(licensesAllTemp);
    }

    Integer ligands = -1;
    try {
        ligands = Integer.parseInt(tokens[4]);
    } catch (final Exception e) {
        myLogger.error(e.getLocalizedMessage(), e);
        getProgressBar().setString("n/a");
        getProgressBar().setValue(0);
        return;
    }

    getProgressBar().setString(ligands.toString() + "  (of " + noLigands + ")");
    getProgressBar().setValue(ligands);
}

From source file:de.nbi.ontology.test.OntologyMatchTest.java

/**
 * Test, if terms are properly match to concept labels. The a list of terms
 * contains a term in each line./*  ww  w.  ja v a2 s. c o  m*/
 * 
 * @param inFile
 *            a list of terms
 * @throws IOException
 */
@SuppressWarnings("unchecked")
@Test(dataProviderClass = TestFileProvider.class, dataProvider = "childTestFiles", groups = { "functest" })
public void children(File inFile) throws IOException {
    log.info("Processing " + inFile.getName());
    String basename = FilenameUtils.removeExtension(inFile.getAbsolutePath());
    File outFile = new File(basename + ".out");
    File resFile = new File(basename + ".res");

    List<String> terms = FileUtils.readLines(inFile);
    PrintWriter w = new PrintWriter(new FileWriter(outFile));
    for (String term : terms) {
        log.trace("** matching " + term);
        OntClass clazz = index.getModel().getOntClass(term);
        w.println(index.getChildren(clazz));
    }
    w.flush();
    w.close();

    Assert.assertTrue(FileUtils.contentEquals(outFile, resFile));
}

From source file:grisu.frontend.view.swing.files.preview.fileViewers.JobStatusGridFileViewer.java

private synchronized void generateGraph() {

    cpusSeries.clear();/*from  w w w.  ja v a 2 s  .  c o m*/
    licensesUserSeries.clear();
    licensesAllSeries.clear();
    ligandsSeries.clear();

    List<String> lines;
    try {
        lines = FileUtils.readLines(this.csvFile);
    } catch (final IOException e) {
        myLogger.error(e.getLocalizedMessage(), e);
        return;
    }

    for (int i = 0; i < lines.size(); i++) {

        final String[] tokens = lines.get(i).split(",");
        final Date date = new Date(Long.parseLong(tokens[0]) * 1000);
        int cpus = Integer.parseInt(tokens[1]);
        if (cpus < 0) {
            cpus = 0;
        }
        int licensesUser = Integer.parseInt(tokens[2]);
        if (licensesUser < 0) {
            licensesUser = 0;
        }
        int licensesAll = Integer.parseInt(tokens[3]);
        if (licensesAll < 0) {
            licensesAll = 0;
        }
        final int ligands = Integer.parseInt(tokens[4]);

        RegularTimePeriod p = null;
        if (showMinutes) {
            p = new Minute(date);
        } else {
            p = new Hour(date);
        }

        cpusSeries.addOrUpdate(p, cpus);
        licensesUserSeries.addOrUpdate(p, licensesUser);
        licensesAllSeries.addOrUpdate(p, licensesAll);
        ligandsSeries.addOrUpdate(p, ligands);

    }

}

From source file:eu.europeana.sounds.vocabulary.genres.music.OnbMimoMappingTest.java

/**
 * This method extracts mapping IDs in form <EuropeanaId_matchLink> for given input CSV file. 
 * @param filePath//w  w  w.  j av  a  2s .c  o m
 * @param enrichedIds
 * @param mapIdToLine
 * @return header line
 * @throws IOException
 */
private String extractMappingIds(String filePath, List<String> enrichedIds, Map<String, String> mapIdToLine)
        throws IOException {

    File enrichedFile = new File(filePath);
    List<String> instrumentLines = FileUtils.readLines(enrichedFile);
    for (String instrumentLine : instrumentLines.subList(1, instrumentLines.size())) {
        String[] instrumentsArr = instrumentLine.split(CSV_LINE_DELIMITER);
        noteEnrichedId(instrumentsArr, instrumentLine, enrichedIds, mapIdToLine, EUROPEANA_ID_COL_POS,
                EXACT_MATCH_COL_POS);
        noteEnrichedId(instrumentsArr, instrumentLine, enrichedIds, mapIdToLine, EUROPEANA_ID_COL_POS,
                BROAD_MATCH_COL_POS);
    }
    return instrumentLines.get(0);
}

From source file:com.seleniumtests.util.logging.SeleniumRobotLogger.java

/**
 * Parses log file and store logs of each test in testLogs variable
 * @return//from  w  ww  .  j  a v  a 2s  .  c  o  m
 * @throws IOException 
 */
public static synchronized void parseLogFile() {
    Appender fileLoggerAppender = Logger.getRootLogger().getAppender(FILE_APPENDER_NAME);
    if (fileLoggerAppender == null) {
        return;
    }

    // read the file from appender directly
    List<String> logLines;
    try {
        logLines = FileUtils.readLines(new File(((FileAppender) fileLoggerAppender).getFile()));
    } catch (IOException e) {
        getLogger(SeleniumRobotLogger.class).error("cannot read log file", e);
        return;
    }

    // clean before reading file. correction of issue #100
    SeleniumRobotLogger.testLogs.clear();

    //store the name of the thread for each test
    Map<String, String> testPerThread = new HashMap<>();

    for (String line : logLines) {
        Matcher matcher = SeleniumRobotLogger.LOG_FILE_PATTERN.matcher(line);
        if (matcher.matches()) {
            String thread = matcher.group(1);
            String content = matcher.group(2);

            if (content.contains(SeleniumRobotLogger.START_TEST_PATTERN)) {
                String testName = content.split(SeleniumRobotLogger.START_TEST_PATTERN)[1].trim();
                testPerThread.put(thread, testName);

                // do not refresh content of logs in case test is retried
                if (!SeleniumRobotLogger.testLogs.containsKey(testName)) {
                    SeleniumRobotLogger.testLogs.put(testName, "");
                }
            }
            if (testPerThread.get(thread) != null) {
                String testName = testPerThread.get(thread);
                SeleniumRobotLogger.testLogs.put(testName,
                        SeleniumRobotLogger.testLogs.get(testName).concat(line + "\n"));
            }
        }
    }
}

From source file:com.amazonaws.eclipse.android.sdk.newproject.NewAndroidProjectWizard.java

@Override
@SuppressWarnings("restriction")
public boolean performFinish() {
    if (getContainer() instanceof WizardDialog) {
        setRunnableContext((WizardDialog) getContainer());
    }/*from w  w w  . j av a 2 s  .  c om*/

    try {
        NewProjectWizardState newProjectWizardState = new NewProjectWizardState(Mode.ANY);
        newProjectWizardState.projectName = dataModel.getProjectName();
        newProjectWizardState.applicationName = "AWS Android Application";
        newProjectWizardState.packageName = dataModel.getPackageName();
        newProjectWizardState.target = dataModel.getAndroidTarget();
        newProjectWizardState.createActivity = false;

        new NewProjectCreator(newProjectWizardState, runnableContext).createAndroidProjects();
        IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(dataModel.getProjectName());

        IJavaProject javaProject = JavaCore.create(project);
        AndroidSdkInstall awsAndroidSdk = AndroidSdkManager.getInstance().getDefaultSdkInstall();
        awsAndroidSdk.writeMetadataToProject(javaProject);
        AwsAndroidSdkClasspathUtils.addAwsAndroidSdkToProjectClasspath(javaProject, awsAndroidSdk);

        AndroidManifestFile androidManifestFile = new AndroidManifestFile(project);
        androidManifestFile.initialize();
        copyProguardPropertiesFile(project);

        if (dataModel.isSampleCodeIncluded()) {
            // copy sample code files over
            Bundle bundle = Platform.getBundle(AndroidSDKPlugin.PLUGIN_ID);
            URL url = FileLocator.find(bundle, new Path("resources/S3_Uploader/"), null);
            try {
                File sourceFile = new File(FileLocator.resolve(url).toURI());
                File projectFolder = project.getLocation().toFile();
                File projectSourceFolder = new File(projectFolder, "src");

                for (File file : sourceFile.listFiles()) {
                    File destinationFile = new File(project.getLocation().toFile(), file.getName());
                    if (file.isDirectory())
                        FileUtils.copyDirectory(file, destinationFile);
                    else
                        FileUtils.copyFile(file, destinationFile);
                }

                // move *.java files to new src dir
                String s = dataModel.getPackageName().replace(".", File.separator) + File.separator;
                for (File file : projectSourceFolder.listFiles()) {
                    if (file.isDirectory())
                        continue;
                    File destinationFile = new File(projectSourceFolder, s + file.getName());
                    FileUtils.moveFile(file, destinationFile);

                    // update package lines with regex
                    // replace "com.amazonaws.demo.s3uploader" with dataModel.getPackageName()
                    List<String> lines = FileUtils.readLines(destinationFile);
                    ArrayList<String> outLines = new ArrayList<String>();
                    for (String line : lines) {
                        outLines.add(line.replace("com.amazonaws.demo.s3uploader", dataModel.getPackageName()));
                    }
                    FileUtils.writeLines(destinationFile, outLines);
                }

                // update android manifest file
                androidManifestFile.addSampleActivity();
            } catch (Exception e) {
                IStatus status = new Status(IStatus.ERROR, AndroidSDKPlugin.PLUGIN_ID,
                        "Unable to update AWS SDK with sample app for Android project setup", e);
                StatusManager.getManager().handle(status, StatusManager.SHOW | StatusManager.LOG);
            }
        }

        // refresh the workspace to pick up the changes we just made
        project.refreshLocal(IResource.DEPTH_INFINITE, null);
    } catch (Exception e) {
        IStatus status = new Status(IStatus.ERROR, AndroidSDKPlugin.PLUGIN_ID,
                "Unable to create new AWS Android project", e);
        StatusManager.getManager().handle(status, StatusManager.SHOW | StatusManager.LOG);
        return false;
    }

    return true;
}

From source file:de.unisb.cs.st.javalanche.mutation.runtime.testDriver.MutationTestDriver.java

public MutationTestDriver() {
    File dir = configuration.getOutputDir();
    lastId = 0l;//from   www  . j  a va2 s .co  m
    try {
        String s;
        File mutationIdFile = configuration.getMutationIdFile();
        if (mutationIdFile != null) {
            s = mutationIdFile.getName();
        } else {
            s = "default";
        }
        controlFile = new File(dir, s + "-mutation-id-control-file");
        logger.info("Control file: " + controlFile + " " + Util.getStackTraceString());
        if (controlFile.exists()) {
            List<String> readLines;
            readLines = FileUtils.readLines(controlFile);
            logger.info("Control file has " + readLines.size() + " entries.");
            if (readLines.size() > 0) {
                String lastLine = (String) readLines.get(readLines.size() - 1);
                logger.info("Last id: " + lastLine);
                lastId = Long.valueOf(lastLine);
            }
        }
        controlFileWriter = new FileWriter(controlFile);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:it.drwolf.ridire.session.async.WordCounter.java

public Integer countWordsFromPoSTagResource(File posTagResourceFile) throws IOException {
    List<String> lines = FileUtils.readLines(posTagResourceFile);
    Integer count = 0;//from  ww w  .  ja  va2  s  . com
    StrTokenizer tokenizer = StrTokenizer.getTSVInstance();
    for (String l : lines) {
        tokenizer.reset(l);
        String[] tokens = tokenizer.getTokenArray();
        if (tokens.length == 3) {
            if (this.isValidPos(tokens[1].trim())) {
                ++count;
            }
        }
    }
    return count;
}

From source file:au.org.ala.delta.intkey.ui.WebSearchDialog.java

private void loadSearchEngines(File file, JComboBox cmb) {

    List<SearchEngineDescriptor> engines = new ArrayList<WebSearchDialog.SearchEngineDescriptor>();
    try {/*  w  w w. j a  va 2  s  .  c o m*/
        List<String> lines = FileUtils.readLines(file);
        for (String line : lines) {
            SearchEngineDescriptor desc = parseSearchEngineDescriptor(line);
            if (desc != null) {
                engines.add(desc);
            } else {
                Logger.log("Could not parse search engine descriptor: " + line);
            }
        }

        ComboBoxModel model = new DefaultComboBoxModel(engines.toArray());
        cmb.setModel(model);
        if (model.getSize() > 0) {
            model.setSelectedItem(model.getElementAt(0));
        }

    } catch (IOException ioex) {
        throw new RuntimeException(ioex);
    }
}

From source file:edu.ku.brc.specify.config.DebugLoggerDialog.java

/**
 * /*from   ww  w  .  j  av a 2  s.c om*/
 */
@SuppressWarnings("unchecked")
public boolean configureLoggersInternal() {
    boolean loggersNotLoaded = false;

    if (debugLogFile.exists()) {
        try {
            for (String line : (List<String>) FileUtils.readLines(debugLogFile)) {
                String[] toks = StringUtils.split(line, "=");
                Logger logger = loggers.get(toks[0]);
                if (logger != null) {
                    logger.setLevel(Boolean.parseBoolean(toks[1]) ? Level.DEBUG : Level.OFF);

                } else {
                    //System.err.println("Logger["+toks[0]+"] not found.");
                    loggersNotLoaded = true;
                    try {
                        @SuppressWarnings("unused")
                        Class<?> cls = Class.forName(toks[0]);

                    } catch (Exception ex) {
                        //edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
                        //edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(DebugLoggerDialog.class, ex);
                    }
                }
            }

        } catch (IOException ex) {
            ex.printStackTrace();
            edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
            edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(DebugLoggerDialog.class, ex);
        }
    } else {
        System.out.println("Nothing to Configure.");
    }

    return loggersNotLoaded;
}