Example usage for java.util Scanner close

List of usage examples for java.util Scanner close

Introduction

In this page you can find the example usage for java.util Scanner close.

Prototype

public void close() 

Source Link

Document

Closes this scanner.

Usage

From source file:com.mapr.db.utils.ImportCSV.java

public void readSchema(String path) {

    String schemaLine = "";
    StringTokenizer st;/*  w  ww . j  a  va2 s . c o  m*/
    String column = "", datatype = "";

    countColumnsInSchema = 0;

    try {
        Scanner scan = new Scanner(new FileReader(path));

        while (scan.hasNextLine()) {
            schemaLine = scan.nextLine().trim();
            if (schemaLine.startsWith("#"))
                continue;
            st = new StringTokenizer(schemaLine, " ");
            while (st.hasMoreTokens()) {
                column = st.nextToken();
                datatype = st.nextToken();
                valueTypesInSchema.add(countColumnsInSchema, datatype);
                columnNamesInSchema.add(countColumnsInSchema, column);
            }
            countColumnsInSchema++;
        }
        scan.close();
    } catch (Exception e) {
        System.out.println("Error reading schema: " + schemaLine + "\n(Column Name:" + column + "\tData type:"
                + datatype + ")");
        e.printStackTrace();
        System.exit(-1);
    }
}

From source file:com.conx.logistics.kernel.bpm.impl.jbpm.core.mock.BPMGuvnorUtil.java

private String readFile(InputStream inStream) throws IOException {
    StringBuilder fileContents = new StringBuilder();
    Scanner scanner = new Scanner(inStream);
    String lineSeparator = System.getProperty("line.separator");
    try {//w w  w .  j  ava2 s . c o m
        while (scanner.hasNextLine()) {
            fileContents.append(scanner.nextLine() + lineSeparator);
        }
        return fileContents.toString();
    } finally {
        scanner.close();
    }
}

From source file:ch.kostceco.tools.siardexcerpt.excerption.moduleexcerpt.impl.ExcerptCGrepModuleImpl.java

@Override
public boolean validate(File siardDatei, File outFile, String excerptString) throws ExcerptCGrepException {
    // Ausgabe -> Ersichtlich das SIARDexcerpt arbeitet
    int onWork = 41;

    boolean isValid = true;

    File fGrepExe = new File("resources" + File.separator + "grep" + File.separator + "grep.exe");
    String pathToGrepExe = fGrepExe.getAbsolutePath();
    if (!fGrepExe.exists()) {
        // grep.exe existiert nicht --> Abbruch
        getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C)
                + getTextResourceService().getText(ERROR_XML_C_MISSINGFILE, fGrepExe.getAbsolutePath()));
        return false;
    } else {//from   w w w.  jav a  2s  .  c  o  m
        File fMsys10dll = new File("resources" + File.separator + "grep" + File.separator + "msys-1.0.dll");
        if (!fMsys10dll.exists()) {
            // msys-1.0.dll existiert nicht --> Abbruch
            getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C)
                    + getTextResourceService().getText(ERROR_XML_C_MISSINGFILE, fMsys10dll.getAbsolutePath()));
            return false;
        }
    }

    File tempOutFile = new File(outFile.getAbsolutePath() + ".tmp");
    String content = "";

    // Record aus Maintable herausholen
    try {
        if (tempOutFile.exists()) {
            Util.deleteDir(tempOutFile);
        }

        /* Nicht vergessen in "src/main/resources/config/applicationContext-services.xml" beim
         * entsprechenden Modul die property anzugeben: <property name="configurationService"
         * ref="configurationService" /> */

        String name = getConfigurationService().getMaintableName();
        String folder = getConfigurationService().getMaintableFolder();
        String cell = getConfigurationService().getMaintablePrimarykeyCell();

        File fMaintable = new File(siardDatei.getAbsolutePath() + File.separator + "content" + File.separator
                + "schema0" + File.separator + folder + File.separator + folder + ".xml");

        try {
            // grep "<c11>7561234567890</c11>" table13.xml >> output.txt
            String command = "cmd /c \"" + pathToGrepExe + " \"<" + cell + ">" + excerptString + "</" + cell
                    + ">\" " + fMaintable.getAbsolutePath() + " >> " + tempOutFile.getAbsolutePath() + "\"";
            /* Das redirect Zeichen verunmglicht eine direkte eingabe. mit dem geschachtellten Befehl
             * gehts: cmd /c\"urspruenlicher Befehl\" */

            // System.out.println( command );

            Process proc = null;
            Runtime rt = null;

            getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_ELEMENT_OPEN, name));

            try {
                Util.switchOffConsole();
                rt = Runtime.getRuntime();
                proc = rt.exec(command.toString().split(" "));
                // .split(" ") ist notwendig wenn in einem Pfad ein Doppelleerschlag vorhanden ist!

                // Fehleroutput holen
                StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR");

                // Output holen
                StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT");

                // Threads starten
                errorGobbler.start();
                outputGobbler.start();

                // Warte, bis wget fertig ist
                proc.waitFor();

                Util.switchOnConsole();

            } catch (Exception e) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C)
                        + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage()));
                return false;
            } finally {
                if (proc != null) {
                    closeQuietly(proc.getOutputStream());
                    closeQuietly(proc.getInputStream());
                    closeQuietly(proc.getErrorStream());
                }
            }

            Scanner scanner = new Scanner(tempOutFile);
            content = "";
            try {
                content = scanner.useDelimiter("\\Z").next();
            } catch (Exception e) {
                // Grep ergab kein treffer Content Null
                content = "";
            }
            scanner.close();

            getMessageService()
                    .logError(getTextResourceService().getText(MESSAGE_XML_ELEMENT_CONTENT, content));
            getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_ELEMENT_CLOSE, name));

            if (tempOutFile.exists()) {
                Util.deleteDir(tempOutFile);
            }
            content = "";

            // Ende Grep

        } catch (Exception e) {
            getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C)
                    + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage()));
            return false;
        }

    } catch (Exception e) {
        getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C)
                + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage()));
        return false;
    }

    // Ende MainTable

    // grep der SubTables
    try {
        String name = null;
        String folder = null;
        String cell = null;

        InputStream fin = new FileInputStream(
                new File("configuration" + File.separator + "SIARDexcerpt.conf.xml"));
        SAXBuilder builder = new SAXBuilder();
        Document document = builder.build(fin);
        fin.close();

        /* read the document and for each subTable */
        Namespace ns = Namespace.getNamespace("");

        // select schema elements and loop
        List<Element> subtables = document.getRootElement().getChild("subtables", ns).getChildren("subtable",
                ns);
        for (Element subtable : subtables) {
            name = subtable.getChild("name", ns).getText();
            folder = subtable.getChild("folder", ns).getText();
            cell = subtable.getChild("foreignkeycell", ns).getText();

            // System.out.println( name + " - " + folder + " - " + cell );
            File fSubtable = new File(siardDatei.getAbsolutePath() + File.separator + "content" + File.separator
                    + "schema0" + File.separator + folder + File.separator + folder + ".xml");

            try {
                // grep "<c11>7561234567890</c11>" table13.xml >> output.txt
                String command = "cmd /c \"" + pathToGrepExe + " \"<" + cell + ">" + excerptString + "</" + cell
                        + ">\" " + fSubtable.getAbsolutePath() + " >> " + tempOutFile.getAbsolutePath() + "\"";
                /* Das redirect Zeichen verunmglicht eine direkte eingabe. mit dem geschachtellten Befehl
                 * gehts: cmd /c\"urspruenlicher Befehl\" */

                // System.out.println( command );

                Process proc = null;
                Runtime rt = null;

                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_ELEMENT_OPEN, name));

                try {
                    Util.switchOffConsole();
                    rt = Runtime.getRuntime();
                    proc = rt.exec(command.toString().split(" "));
                    // .split(" ") ist notwendig wenn in einem Pfad ein Doppelleerschlag vorhanden ist!

                    // Fehleroutput holen
                    StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR");

                    // Output holen
                    StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT");

                    // Threads starten
                    errorGobbler.start();
                    outputGobbler.start();

                    // Warte, bis wget fertig ist
                    proc.waitFor();

                    Util.switchOnConsole();

                } catch (Exception e) {
                    getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C)
                            + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage()));
                    return false;
                } finally {
                    if (proc != null) {
                        closeQuietly(proc.getOutputStream());
                        closeQuietly(proc.getInputStream());
                        closeQuietly(proc.getErrorStream());
                    }
                }

                Scanner scanner = new Scanner(tempOutFile);
                content = "";
                try {
                    content = scanner.useDelimiter("\\Z").next();
                } catch (Exception e) {
                    // Grep ergab kein treffer Content Null
                    content = "";
                }
                scanner.close();

                getMessageService()
                        .logError(getTextResourceService().getText(MESSAGE_XML_ELEMENT_CONTENT, content));
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_ELEMENT_CLOSE, name));

                if (tempOutFile.exists()) {
                    Util.deleteDir(tempOutFile);
                }
                content = "";

                // Ende Grep

            } catch (Exception e) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C)
                        + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage()));
                return false;
            }

            // Ende SubTables
            if (onWork == 41) {
                onWork = 2;
                System.out.print("-   ");
                System.out.print("\r");
            } else if (onWork == 11) {
                onWork = 12;
                System.out.print("\\   ");
                System.out.print("\r");
            } else if (onWork == 21) {
                onWork = 22;
                System.out.print("|   ");
                System.out.print("\r");
            } else if (onWork == 31) {
                onWork = 32;
                System.out.print("/   ");
                System.out.print("\r");
            } else {
                onWork = onWork + 1;
            }
        }
        System.out.print("   ");
        System.out.print("\r");
    } catch (Exception e) {
        getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C)
                + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage()));
        return false;
    }

    return isValid;
}

From source file:com.blackducksoftware.tools.appuseradjuster.add.AddUser.java

private List<String> getFileContents() {
    List<String> contents = new ArrayList<String>();

    FileInputStream fis = null;/*ww  w  .ja  v a2  s.  co m*/

    try {
        fis = new FileInputStream(userAppRoleMappingFilePath);
    } catch (FileNotFoundException e) {
        logger.error("Unable to read in the Application/User mapping file: {}", userAppRoleMappingFilePath);
        e.printStackTrace();
    }

    Scanner scanner = new Scanner(fis);

    logger.info("Reading file for Application/User+role mapping ({})", userAppRoleMappingFilePath);

    while (scanner.hasNextLine()) {
        contents.add(scanner.nextLine());
    }

    scanner.close();

    return contents;
}

From source file:org.apache.uima.ruta.resource.TreeWordList.java

/**
 * Creates a new Tree in the existing treeWordList from a file with path pathname
 * //from w w w  .j a  v a  2s . c  o  m
 * @param stream
 *          Open InputStream containing the word for the treeWordList, this method will close the
 *          stream.
 */
public void buildNewTree(InputStream stream) throws IOException {
    Scanner scan = new Scanner(stream, "UTF-8");
    // creating a new tree
    this.root = new TextNode();
    while (scan.hasNextLine()) {
        String s = scan.nextLine().trim();
        // HOTFIX for old formats
        if (s.endsWith("=")) {
            s = s.substring(0, s.length() - 1);
            s = s.trim();
        }
        addWord(s);
    }
    scan.close();
}

From source file:edu.harvard.med.iccbl.screensaver.io.screens.ScreenPrivacyExpirationUpdater.java

/**
 * Return the subject first and the message second.
 * Message://w  w  w.ja  v a2  s.  c  o  m
 * {0} Screen Number
 * {1} Screen Title
 * {2} timeToNotify (tbd, formatting)
 * 
 * @throws MessagingException
 */
private Pair<String, String> getScreenExpireNotificationSubjectMessage() throws MessagingException {
    InputStream in = null;
    if (isCommandLineFlagSet(EXPIRATION_EMAIL_MESSAGE_LOCATION[SHORT_OPTION_INDEX])) {
        try {
            in = new FileInputStream(
                    new File(getCommandLineOptionValue(EXPIRATION_EMAIL_MESSAGE_LOCATION[SHORT_OPTION_INDEX])));
        } catch (FileNotFoundException e) {
            sendErrorMail(
                    "Operation not completed for ScreenPrivacyExpirationUpdater, could not locate expiration message",
                    toString(), e);
            throw new DAOTransactionRollbackException(e);
        }
    } else {
        in = this.getClass().getResourceAsStream(EXPIRATION_MESSAGE_TXT_LOCATION);
    }
    Scanner scanner = new Scanner(in);
    try {
        StringBuilder builder = new StringBuilder();
        String subject = scanner.nextLine(); // first line is the subject
        while (scanner.hasNextLine()) {
            builder.append(scanner.nextLine()).append("\n");
        }
        return Pair.newPair(subject, builder.toString());
    } finally {
        scanner.close();
    }
}

From source file:de.ingrid.interfaces.csw.server.cswt.impl.GenericServerCSWT.java

/**
 * Get a Document from a class path location. The actual name of the file is
 * retrieved from the config.properties file.
 *
 * With variant a specific variant (like a localization) can be retrieved.
 * The file name is extended by the variant in the form
 * [name]_[variant].[extension].//from www . j  a  v a 2  s . c om
 *
 * If the variant could not be retrieved, the base file is returned as a
 * fall back.
 *
 * The content is cached. The cache can be controlled by the
 * config.properties entry 'cache.enable'.
 *
 * @param key
 *            One of the keys config.properties, defining the actual
 *            filename to be retrieved.
 * @param variant
 *            The variant of the file.
 * @return The Document instance
 */
protected Document getDocument(String key, String variant) {

    // fetch the document from the file system if it is not cached
    String filename = ApplicationProperties.getMandatory(key);
    String filenameVariant = filename;
    if (variant != null && variant.length() > 0) {
        if (filename.contains(FilenameUtils.EXTENSION_SEPARATOR_STR)) {
            filenameVariant = FilenameUtils.getBaseName(filename) + "_" + variant
                    + FilenameUtils.EXTENSION_SEPARATOR_STR + FilenameUtils.getExtension(filename);
        } else {
            filenameVariant = FilenameUtils.getBaseName(filename) + "_" + variant;
        }
    }
    Document doc = null;
    Scanner scanner = null;
    try {
        URL resource = this.getClass().getClassLoader().getResource(filenameVariant);
        if (resource == null) {
            log.warn("Document '" + filenameVariant + "' could not be found in class path.");
            resource = this.getClass().getClassLoader().getResource(filename);
        }
        String path = resource.getPath().replaceAll("%20", " ");
        File file = new File(path);
        scanner = new Scanner(file);
        scanner.useDelimiter("\\A");
        String content = scanner.next();
        scanner.close();
        doc = StringUtils.stringToDocument(content);

    } catch (Exception e) {
        log.error("Error reading document configured in configuration key '" + key + "': " + filename + ", "
                + variant, e);
        throw new RuntimeException("Error reading document configured in configuration key '" + key + "': "
                + filename + ", " + variant, e);
    } finally {
        if (scanner != null) {
            scanner.close();
        }
    }
    return doc;
}

From source file:eu.cassandra.training.entities.Appliance.java

/**
 * This function is the parser of the consumption model provided by the user.
 * /* w  w w  .  j av a 2  s.c o m*/
 * @param filename
 *          The file name of the consumption model
 * @throws IOException
 */
public void parseConsumptionModel(String filename) throws IOException {

    File file = new File(filename);

    String model = "";

    String extension = filename.substring(filename.length() - 3, filename.length());

    Scanner scanner = new Scanner(file);
    switch (extension) {

    case "son":

        while (scanner.hasNext())
            model = model + scanner.nextLine();
        break;
    default:

        while (scanner.hasNext())
            model = model + scanner.nextLine();

        model.replace(" ", "");
    }
    scanner.close();

    activeConsumptionModelString = model;
    DBObject dbo = (DBObject) JSON.parse(activeConsumptionModelString);
    activeConsumptionModel.init(dbo);

    reactiveConsumptionModelString = activeConsumptionModelString.replace("p", "q");
    reactiveConsumptionModelString = reactiveConsumptionModelString.replace("qara", "para");
    System.out.println(reactiveConsumptionModelString);
    dbo = (DBObject) JSON.parse(reactiveConsumptionModelString);
    reactiveConsumptionModel.init(dbo);

}

From source file:edu.clemson.cs.nestbed.server.management.instrumentation.ProgramWeaverManagerImpl.java

public String findComponentFromMakefile(File makefile) throws RemoteException {
    String component = null;//  www .  j  a v  a2 s  . c o m
    Scanner scanner = null;

    try {
        log.debug("Makefile:  " + makefile);
        scanner = new Scanner(makefile);

        while (scanner.hasNext() && component == null) {
            String line = scanner.nextLine();
            String regExp = "^COMPONENT=(\\S+)";
            Pattern pattern = Pattern.compile(regExp);
            Matcher matcher = pattern.matcher(line);

            if (matcher.find()) {
                component = matcher.group(1);
            }
        }
    } catch (FileNotFoundException fnfe) {
        throw new RemoteException("FileNotFoundException", fnfe);
    } finally {
        try {
            scanner.close();
        } catch (Exception ex) {
            /* empty */ }
    }

    if (component == null) {
        // FIXME:  Shouldn't be throwing generic Exceptions
        throw new RemoteException("No main component found in Makefile.");
    }

    return component;
}

From source file:edu.harvard.iq.dataverse.dataaccess.TabularSubsetGenerator.java

public static Long[] subsetLongVector(InputStream in, int column, int numCases) {
    Long[] retVector = new Long[numCases];
    Scanner scanner = new Scanner(in);
    scanner.useDelimiter("\\n");

    for (int caseIndex = 0; caseIndex < numCases; caseIndex++) {
        if (scanner.hasNext()) {
            String[] line = (scanner.next()).split("\t", -1);
            try {
                retVector[caseIndex] = new Long(line[column]);
            } catch (NumberFormatException ex) {
                retVector[caseIndex] = null; // assume missing value
            }/*from   ww w  .j  a  v a  2 s .c o  m*/
        } else {
            scanner.close();
            throw new RuntimeException("Tab file has fewer rows than the stored number of cases!");
        }
    }

    int tailIndex = numCases;
    while (scanner.hasNext()) {
        String nextLine = scanner.next();
        if (!"".equals(nextLine)) {
            scanner.close();
            throw new RuntimeException(
                    "Column " + column + ": tab file has more nonempty rows than the stored number of cases ("
                            + numCases + ")! current index: " + tailIndex + ", line: " + nextLine);
        }
        tailIndex++;
    }

    scanner.close();
    return retVector;

}