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.ibm.iotf.sample.devicemgmt.device.RasPiFirmwareHandlerSample.java

private InstalStatus ParseInstallLog() throws FileNotFoundException {
    try {/*from   ww w.j  av a 2  s.c  om*/
        File file = new File(INSTALL_LOG_FILE);
        Scanner scanner = new Scanner(file);

        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            if (line.contains(DEPENDENCY_ERROR_MSG)) {
                scanner.close();
                return InstalStatus.DEPENDENCY_ERROR;
            } else if (line.contains(ERROR_MSG)) {
                scanner.close();
                return InstalStatus.ERROR;
            }
        }
        scanner.close();
    } catch (FileNotFoundException e) {
        throw e;
    }
    return InstalStatus.SUCCESS;
}

From source file:br.univali.ps.fuzzy.portugolFuzzyCorretor.core.PortugolFuzzyCorretor.java

private int contarNumeroLinhas() {
    int linhas = 0;
    Scanner scanner = new Scanner(this.codigoPortugol); // Para possibilitar a edio do texto dentro do programa
                                                        // Caso no seja necessrio, contabilizar dentro do FileController
    while (scanner.hasNextLine()) {
        linhas++;//from w  ww .j  a  v  a2 s  .c  o m
        scanner.nextLine();
    }
    scanner.close();
    return linhas;
}

From source file:org.apache.activemq.transport.discovery.http.HTTPDiscoveryAgent.java

synchronized private Set<String> doLookup(long freshness) {
    String url = registryURL + "?freshness=" + freshness;
    try {/*www  .  ja  va 2  s.co  m*/
        HttpGet method = new HttpGet(url);
        ResponseHandler<String> handler = new BasicResponseHandler();
        String response = httpClient.execute(method, handler);
        LOG.debug("GET to " + url + " got a " + response);
        Set<String> rc = new HashSet<String>();
        Scanner scanner = new Scanner(response);
        while (scanner.hasNextLine()) {
            String service = scanner.nextLine();
            if (service.trim().length() != 0) {
                rc.add(service);
            }
        }
        scanner.close();
        return rc;
    } catch (Exception e) {
        LOG.debug("GET to " + url + " failed with: " + e);
        return null;
    }
}

From source file:com.rapid.server.RapidServletContextListener.java

public static int loadControls(ServletContext servletContext) throws Exception {

    // assume no controls
    int controlCount = 0;

    // create a list for our controls
    List<JSONObject> jsonControls = new ArrayList<JSONObject>();

    // get the directory in which the control xml files are stored
    File dir = new File(servletContext.getRealPath("/WEB-INF/controls/"));

    // create a filter for finding .control.xml files
    FilenameFilter xmlFilenameFilter = new FilenameFilter() {
        public boolean accept(File dir, String name) {
            return name.toLowerCase().endsWith(".control.xml");
        }//from   w w  w  .  ja v  a  2  s .c  om
    };

    // create a schema object for the xsd
    Schema schema = _schemaFactory
            .newSchema(new File(servletContext.getRealPath("/WEB-INF/schemas/") + "/control.xsd"));
    // create a validator
    Validator validator = schema.newValidator();

    // loop the xml files in the folder
    for (File xmlFile : dir.listFiles(xmlFilenameFilter)) {

        // get a scanner to read the file
        Scanner fileScanner = new Scanner(xmlFile).useDelimiter("\\A");

        // read the xml into a string
        String xml = fileScanner.next();

        // close the scanner (and file)
        fileScanner.close();

        // validate the control xml file against the schema
        validator.validate(new StreamSource(new ByteArrayInputStream(xml.getBytes("UTF-8"))));

        // convert the string into JSON
        JSONObject jsonControlCollection = org.json.XML.toJSONObject(xml).getJSONObject("controls");

        JSONObject jsonControl;
        int index = 0;
        int count = 0;

        if (jsonControlCollection.optJSONArray("control") == null) {
            jsonControl = jsonControlCollection.getJSONObject("control");
        } else {
            jsonControl = jsonControlCollection.getJSONArray("control").getJSONObject(index);
            count = jsonControlCollection.getJSONArray("control").length();
        }

        do {

            // check this type does not already exist
            for (int i = 0; i < jsonControls.size(); i++) {
                if (jsonControl.getString("type").equals(jsonControls.get(i).getString("type")))
                    throw new Exception(" control type is loaded already. Type names must be unique");
            }

            // add the jsonControl to our array
            jsonControls.add(jsonControl);

            // inc the control count
            controlCount++;
            // inc the count of controls in this file
            index++;

            // get the next one
            if (index < count)
                jsonControl = jsonControlCollection.getJSONArray("control").getJSONObject(index);

        } while (index < count);

    }

    // sort the list of controls by name
    Collections.sort(jsonControls, new Comparator<JSONObject>() {
        @Override
        public int compare(JSONObject c1, JSONObject c2) {
            try {
                return Comparators.AsciiCompare(c1.getString("name"), c2.getString("name"), false);
            } catch (JSONException e) {
                return 0;
            }
        }

    });

    // create a JSON Array object which will hold json for all of the available controls
    JSONArray jsonArrayControls = new JSONArray(jsonControls);

    // put the jsonControls in a context attribute (this is available via the getJsonControls method in RapidHttpServlet)
    servletContext.setAttribute("jsonControls", jsonArrayControls);

    _logger.info(controlCount + " controls loaded in .control.xml files");

    return controlCount;

}

From source file:com.alibaba.dubbo.qos.textui.TKv.java

private String filterEmptyLine(String content) {
    final StringBuilder sb = new StringBuilder();
    Scanner scanner = null;
    try {/*from  ww w . j av a2  s. c  o  m*/
        scanner = new Scanner(content);
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            if (line != null) {
                // remove extra space at line's end
                line = StringUtils.stripEnd(line, " ");
                if (line.isEmpty()) {
                    line = " ";
                }
            }
            sb.append(line).append('\n');
        }
    } finally {
        if (null != scanner) {
            scanner.close();
        }
    }

    return sb.toString();
}

From source file:edu.harvard.med.iccbl.screensaver.io.users.UserAgreementExpirationUpdater.java

/**
 * Return the subject first and the message second.
 * Message:/*from  www  .  ja v a  2 s . com*/
 * {0} Expiration Date
 * 
 * @throws MessagingException
 */
private Pair<String, String> getExpireNotificationSubjectMessage() 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 UserAgreementExpirationUpdater, 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();
        while (scanner.hasNextLine()) {
            builder.append(scanner.nextLine()).append("\n");
        }
        return Pair.newPair(subject, builder.toString());
    } finally {
        scanner.close();
    }
}

From source file:com.rapid.server.RapidServletContextListener.java

public static int loadActions(ServletContext servletContext) throws Exception {

    // assume no actions
    int actionCount = 0;

    // create a list of json actions which we will sort later
    List<JSONObject> jsonActions = new ArrayList<JSONObject>();

    // retain our class constructors in a hashtable - this speeds up initialisation
    HashMap<String, Constructor> actionConstructors = new HashMap<String, Constructor>();

    // build a collection of classes so we can re-initilise the JAXB context to recognise our injectable classes
    ArrayList<Action> actions = new ArrayList<Action>();

    // get the directory in which the control xml files are stored
    File dir = new File(servletContext.getRealPath("/WEB-INF/actions/"));

    // create a filter for finding .control.xml files
    FilenameFilter xmlFilenameFilter = new FilenameFilter() {
        public boolean accept(File dir, String name) {
            return name.toLowerCase().endsWith(".action.xml");
        }//from w ww.  jav  a2 s  .c  o  m
    };

    // create a schema object for the xsd
    Schema schema = _schemaFactory
            .newSchema(new File(servletContext.getRealPath("/WEB-INF/schemas/") + "/action.xsd"));
    // create a validator
    Validator validator = schema.newValidator();

    // loop the xml files in the folder
    for (File xmlFile : dir.listFiles(xmlFilenameFilter)) {

        // get a scanner to read the file
        Scanner fileScanner = new Scanner(xmlFile).useDelimiter("\\A");

        // read the xml into a string
        String xml = fileScanner.next();

        // close the scanner (and file)
        fileScanner.close();

        // validate the control xml file against the schema
        validator.validate(new StreamSource(new ByteArrayInputStream(xml.getBytes("UTF-8"))));

        // convert the string into JSON
        JSONObject jsonActionCollection = org.json.XML.toJSONObject(xml).getJSONObject("actions");

        JSONObject jsonAction;
        int index = 0;
        int count = 0;

        // the JSON library will add a single key of there is a single class, otherwise an array
        if (jsonActionCollection.optJSONArray("action") == null) {
            jsonAction = jsonActionCollection.getJSONObject("action");
        } else {
            jsonAction = jsonActionCollection.getJSONArray("action").getJSONObject(index);
            count = jsonActionCollection.getJSONArray("action").length();
        }

        do {

            // check this type does not already exist
            for (int i = 0; i < jsonActions.size(); i++) {
                if (jsonAction.getString("type").equals(jsonActions.get(i).getString("type")))
                    throw new Exception(" action type is loaded already. Type names must be unique");
            }

            // add the jsonControl to our array
            jsonActions.add(jsonAction);
            // get the named type from the json
            String type = jsonAction.getString("type");
            // get the class name from the json
            String className = jsonAction.getString("class");
            // get the class 
            Class classClass = Class.forName(className);
            // check the class extends com.rapid.Action
            if (!Classes.extendsClass(classClass, com.rapid.core.Action.class))
                throw new Exception(type + " action class " + classClass.getCanonicalName()
                        + " must extend com.rapid.core.Action.");
            // check this type is unique
            if (actionConstructors.get(type) != null)
                throw new Exception(type + " action already loaded. Type names must be unique.");
            // add to constructors hashmap referenced by type
            actionConstructors.put(type, classClass.getConstructor(RapidHttpServlet.class, JSONObject.class));
            // add to our jaxb classes collection            
            _jaxbClasses.add(classClass);
            // inc the control count
            actionCount++;
            // inc the count of controls in this file
            index++;

            // get the next one
            if (index < count)
                jsonAction = jsonActionCollection.getJSONArray("control").getJSONObject(index);

        } while (index < count);

    }

    // sort the list of actions by name
    Collections.sort(jsonActions, new Comparator<JSONObject>() {
        @Override
        public int compare(JSONObject c1, JSONObject c2) {
            try {
                return Comparators.AsciiCompare(c1.getString("name"), c2.getString("name"), false);
            } catch (JSONException e) {
                return 0;
            }
        }

    });

    // create a JSON Array object which will hold json for all of the available controls
    JSONArray jsonArrayActions = new JSONArray(jsonActions);

    // put the jsonControls in a context attribute (this is available via the getJsonActions method in RapidHttpServlet)
    servletContext.setAttribute("jsonActions", jsonArrayActions);

    // put the constructors hashmapin a context attribute (this is available via the getContructor method in RapidHttpServlet)
    servletContext.setAttribute("actionConstructors", actionConstructors);

    _logger.info(actionCount + " actions loaded in .action.xml files");

    return actionCount;

}

From source file:gemlite.core.util.CommandBase.java

/***
 * false,?//from  ww  w. j a  v  a2s  . c  om
 * 
 * @return
 * @throws CmdLineException
 */
protected boolean waitUserInput(String[] args, String msg) {
    Scanner reader = new Scanner(System.in);

    boolean hasInitInput = args != null && args.length > 0;
    if (!hasInitInput)
        System.out.println(msg);
    do//while (hasInitInput && reader.hasNextLine())
    {
        String line = null;
        String[] newArgs = null;
        if (hasInitInput) {
            newArgs = args;
        } else {
            line = reader.nextLine();
            if (line.equalsIgnoreCase("X")) {
                reader.close();
                return false;
            }
            newArgs = line.split(" ");
        }
        try {
            if (newArgs.length > 0 && !newArgs[0].isEmpty())
                parser.parseArgument(newArgs);
            else
                System.err.println("please input your args!");
            printValue();
        } catch (CmdLineException e) {
            e.printStackTrace();
            System.out.println("Error, last Input:[" + line + "]\nInput:");
            continue;
        }
        break;
    } while (true);
    reader.close();
    return true;
}

From source file:net.devietti.ArchConfMapServlet.java

/** Parse a URL (presumed to be pointing at an HTML page) into a Jsoup Document */
private Document getURL(String url) {
    Scanner s = null;
    try {/*from   w ww .j a v a 2 s .  c o  m*/

        s = new Scanner(new URL(url).openStream(), "UTF-8");
        return Jsoup.parse(s.useDelimiter("\\A").next());

    } catch (MalformedURLException e) {
        error(e.getMessage());
    } catch (IOException e) {
        error(e.getMessage());
    } finally {
        if (s != null)
            s.close();
    }
    throw new IllegalStateException("error parsing URL " + url);
}

From source file:com.joliciel.csvLearner.EventCombinationGenerator.java

public void readDesiredCounts(File file) {
    try {/*from   www  .ja  va2s. co m*/
        this.desiredCountPerOutcome = new LinkedHashMap<String, Integer>();
        Scanner scanner = new Scanner(new FileInputStream(file), "UTF-8");
        try {
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                List<String> cells = CSVFormatter.getCSVCells(line);
                String outcome = cells.get(0);
                int count = Integer.parseInt(cells.get(1));
                this.desiredCountPerOutcome.put(outcome, count);
            }
        } finally {
            scanner.close();
        }
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }
}