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.houghtonassociates.bamboo.plugins.dao.GerritService.java

private void installVerificationLabel() throws RepositoryException {
    final String targetRevision = "refs/meta/config";
    String filePath = gc.getWorkingDirectoryPath() + File.separator + "MetaConfig";
    String projectConfig = filePath + File.separator + "project.config";
    String url = String.format("ssh://%s@%s:%d/%s", gc.getUsername(), gc.getHost(), gc.getPort(),
            "All-Projects.git");

    boolean verifiedSectionFound = false;

    Scanner scanner = null;
    JGitRepository jgitRepo = new JGitRepository();

    if (verifiedLabelAdded)
        return;//  ww w . j a  v  a  2s  .  c  o  m

    synchronized (GerritService.class) {
        try {
            jgitRepo.setAccessData(gc);

            jgitRepo.open(filePath, true);

            jgitRepo.openSSHTransport(url);

            jgitRepo.fetch(targetRevision);

            jgitRepo.checkout(targetRevision);

            StringBuilder content = new StringBuilder();
            File fConfig = new File(projectConfig);
            scanner = new Scanner(fConfig);

            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                if (line.contains("[label \"Verified\"]")) {
                    verifiedSectionFound = true;
                    break;
                }

                content.append(line).append("\n");

                if (line.contains("[access \"refs/heads/*\"]")) {
                    content.append("\tlabel-Verified = -1..+1 group Administrators\n");
                }
            }

            scanner.close();

            if (verifiedSectionFound) {
                verifiedLabelAdded = true;
                return;
            }

            content.append("[label \"Verified\"]\n");
            content.append("\tfunction = MaxWithBlock\n");
            content.append("\tvalue = -1 Fails\n");
            content.append("\tvalue =  0 No score\n");
            content.append("\tvalue = +1 Verified\n");

            File fConfig2 = new File(projectConfig);

            FileUtils.writeStringToFile(fConfig2, content.toString());

            jgitRepo.add("project.config");

            PushResult r = jgitRepo.commitPush("Enabled verification label.", targetRevision);

            if (r.getMessages().contains("ERROR")) {
                throw new RepositoryException(r.getMessages());
            }

            verifiedLabelAdded = true;
        } catch (org.eclipse.jgit.errors.TransportException e) {
            throw new RepositoryException(e);
        } catch (FileNotFoundException e) {
            throw new RepositoryException(
                    "Could not locate the project.config! Your checkout must have failed.");
        } catch (IOException e) {
            throw new RepositoryException(e);
        } finally {
            jgitRepo.close();
            if (scanner != null)
                scanner.close();
        }
    }
}

From source file:com.amazonaws.auth.profile.internal.ProfilesConfigFileParser.java

/**
 * Loads the credentials from the given input stream.
 *
 * @param is input stream from where the profile details are read.
 * @throws IOException//from  w  w  w .j a v  a  2s  .  c  o m
 */
private static Map<String, Profile> loadProfiles(InputStream is) throws IOException {
    Scanner scanner = new Scanner(is);
    AWSCredentials credentials = null;
    String profileName = null;
    String accessKey = null;
    String secretKey = null;
    String line = null;
    boolean accessKeyRead = false;
    boolean secretKeyRead = false;
    ProfileCredentialScannerState scannerState = ProfileCredentialScannerState.READ_CONFIG_NAME;
    HashMap<String, Profile> profilesByName = new HashMap<String, Profile>();

    try {
        while (scanner.hasNextLine()) {
            line = scanner.nextLine();
            line = line.trim();

            if (line.isEmpty())
                continue;

            if (!line.startsWith("[") && !line.startsWith(AWS_ACCESS_KEY_ID)
                    && !line.startsWith(AWS_SECRET_ACCESS_KEY)) {
                LOG.info("Unsupported configuration setting: " + line);
                continue;
            }

            switch (scannerState) {
            case READ_CONFIG_NAME:
                profileName = parseProfileName(line);
                scannerState = ProfileCredentialScannerState.READ_KEY;
                break;
            case READ_KEY:
                if (line.startsWith(AWS_ACCESS_KEY_ID) && !accessKeyRead) {
                    accessKey = parseAccessKey(line);
                    accessKeyRead = true;
                } else if (!secretKeyRead) {
                    secretKey = parseSecretKey(line);
                    secretKeyRead = true;
                } else {
                    throw new AmazonClientException(
                            "Unable to load Amazon AWS Credentials. File not in proper format.");
                }
                break;
            }

            if (accessKeyRead && secretKeyRead) {

                assertParameterNotEmpty(profileName,
                        "Unable to load credentials into profile. ProfileName is empty. " + line);
                assertParameterNotEmpty(accessKey,
                        "Unable to load credentials into profile. AWS Access Key ID is empty. " + line);
                assertParameterNotEmpty(secretKey,
                        "Unable to load credentials into profile. AWS Secret Access Key is empty. " + line);

                credentials = new BasicAWSCredentials(accessKey, secretKey);
                profilesByName.put(profileName, new Profile(credentials));
                scannerState = ProfileCredentialScannerState.READ_CONFIG_NAME;
                accessKeyRead = false;
                secretKeyRead = false;
            }
        }
        if (scannerState != ProfileCredentialScannerState.READ_CONFIG_NAME || accessKeyRead || secretKeyRead) {
            throw new AmazonClientException(
                    "Unable to load credentials into profile. Profile Name or AWS Access Key ID or AWS Secret Access Key missing for a profile.");
        }

    } finally {
        scanner.close();
    }

    return profilesByName;
}

From source file:csns.importer.parser.MFTScoreParser.java

public void parse(MFTScoreImporter importer) {
    Department department = importer.getDepartment();
    Date date = importer.getDate();

    Scanner scanner = new Scanner(importer.getText());
    scanner.useDelimiter("\\s+|\\r\\n|\\r|\\n");
    while (scanner.hasNext()) {
        // last name
        String lastName = scanner.next();
        while (!lastName.endsWith(","))
            lastName += " " + scanner.next();
        lastName = lastName.substring(0, lastName.length() - 1);

        // first name
        String firstName = scanner.next();

        // score/* w  ww .  j  ava  2 s.  co m*/
        Stack<String> stack = new Stack<String>();
        String s = scanner.next();
        while (!isScore(s)) {
            stack.push(s);
            s = scanner.next();
        }
        int value = Integer.parseInt(s);

        // authorization code
        stack.pop();

        // cin
        String cin = null;
        if (!stack.empty() && isCin(stack.peek()))
            cin = stack.pop();

        // user
        User user = null;
        if (cin != null)
            user = userDao.getUserByCin(cin);
        else {
            List<User> users = userDao.getUsers(lastName, firstName);
            if (users.size() == 1)
                user = users.get(0);
        }

        if (user != null) {
            MFTScore score = mftScoreDao.getScore(department, date, user);
            if (score == null) {
                score = new MFTScore();
                score.setDepartment(department);
                score.setDate(date);
                score.setUser(user);
            } else {
                logger.info(user.getId() + ": " + score.getValue() + " => " + value);
            }
            score.setValue(value);
            importer.getScores().add(score);
        } else {
            User failedUser = new User();
            failedUser.setLastName(lastName);
            failedUser.setFirstName(firstName);
            failedUser.setCin(cin);
            importer.getFailedUsers().add(failedUser);
        }

        logger.debug(lastName + "," + firstName + "," + cin + "," + value);
    }

    scanner.close();
}

From source file:carmen.LocationResolver.java

@SuppressWarnings("unchecked")
protected void loadLocationFile(String filename) throws JsonParseException, JsonMappingException, IOException {
    ObjectMapper mapper = new ObjectMapper();

    Scanner inputScanner = new Scanner(new FileInputStream(filename));
    while (inputScanner.hasNextLine()) {
        String line = inputScanner.nextLine();
        Map<String, Object> locationObj = mapper.readValue(line, Map.class);
        Location location = Location.parseLocationFromJsonObj(locationObj);

        List<String> aliases = (List<String>) locationObj.get("aliases");
        this.idToLocation.put(location.getId(), location);
        this.locationToId.put(location, location.getId());
        HashSet<String> justAddedAliases = new HashSet<String>();
        if (aliases != null) {
            for (String alias : aliases) {
                if (justAddedAliases.contains(alias))
                    continue;

                if (this.locationNameToLocation.containsKey(alias))
                    logger.warn("Duplicate location name: " + alias);
                else
                    this.locationNameToLocation.put(alias, location);
                justAddedAliases.add(alias);

                // Add entries without punctuation.
                String newEntry = alias.replaceAll("\\p{Punct}", " ").replaceAll("\\s+", " ");
                if (justAddedAliases.contains(newEntry))
                    continue;

                if (!newEntry.equals(alias)) {
                    if (this.locationNameToLocation.containsKey(newEntry))
                        logger.warn("Duplicate location name: " + newEntry);
                    else
                        this.locationNameToLocation.put(newEntry, location);
                }//ww  w . j ava 2 s.c o m

                justAddedAliases.add(newEntry);

            }
        }
    }
    inputScanner.close();
}

From source file:com.aurel.track.dbase.InitDatabase.java

private static void insertPostLoadData(String file) {
    Connection coni = null;//from   www  . j  a v  a 2 s .c  o  m
    Connection cono = null;
    try {
        coni = getConnection();
        cono = getConnection();
        Statement ostmt = cono.createStatement();
        if (isFirstStartEver) {
            LOGGER.info("Filling some post load data...");
            try {

                URL populateURL = ApplicationBean.getInstance().getServletContext().getResource(file);
                InputStream in = populateURL.openStream();
                java.util.Scanner s = new java.util.Scanner(in, "UTF-8");
                s.useDelimiter(";");
                String st = null;
                StringBuilder stb = new StringBuilder();
                int line = 0;

                while (s.hasNext()) {
                    stb.append(s.nextLine().trim());
                    st = stb.toString();
                    ++line;
                    if (!st.isEmpty() && !st.startsWith("--") && !st.startsWith("/*")) {
                        if (st.endsWith(";")) {
                            stb = new StringBuilder(); // clear buffer
                            st = st.substring(0, st.length() - 1); // remove the semicolon
                            try {
                                ostmt.executeUpdate(st);
                                LOGGER.info(st);
                            } catch (Exception exc) {
                                LOGGER.error("Problem inserting post-load data: " + exc.getMessage());
                                LOGGER.error("Line " + line + ": " + st);
                            }
                        } else {
                            stb.append(" ");
                        }
                    } else {
                        stb = new StringBuilder();
                    }
                }
                s.close();
                in.close();

            } catch (Exception e) {
                System.err.println(ExceptionUtils.getStackTrace(e));
            }
            LOGGER.info("Post-load data is okay.");
        }
        ApplicationStarter.getInstance().actualizePercentComplete(
                ApplicationStarter.getInstance().INIT_DB_DATA_STEP, ApplicationStarter.INIT_DB_DATA_TEXT);
    } catch (Exception e) {
        LOGGER.error("Problem inserting post-load objects: " + e.getMessage());
        LOGGER.debug(STACKTRACE, e);
    } finally {
        if (coni != null) {
            try {
                coni.close();
            } catch (SQLException e) {
                LOGGER.info("Closing connection failed with " + e.getMessage());
                LOGGER.debug(ExceptionUtils.getStackTrace(e));
            }
        }
        if (cono != null) {
            try {
                cono.close();
            } catch (SQLException e) {
                LOGGER.info("Closing connection failed with " + e.getMessage());
                LOGGER.debug(ExceptionUtils.getStackTrace(e));
            }
        }
    }
}

From source file:io.realm.Realm.java

/**
 * Tries to update a list of existing objects identified by their primary key with new JSON data. If an existing
 * object could not be found in the Realm, a new object will be created. This must happen within a transaction.
 *
 * @param clazz Type of {@link io.realm.RealmObject} to create or update. It must have a primary key defined.
 * @param in    InputStream with a list of object data in JSON format.
 *
 * @throws java.lang.IllegalArgumentException if trying to update a class without a
 * {@link io.realm.annotations.PrimaryKey}.
 * @see #createOrUpdateAllFromJson(Class, java.io.InputStream)
 *//*from w w  w . j a v  a  2s .  c o  m*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public <E extends RealmObject> void createOrUpdateAllFromJson(Class<E> clazz, InputStream in)
        throws IOException {
    if (clazz == null || in == null) {
        return;
    }
    checkHasPrimaryKey(clazz);

    // As we need the primary key value we have to first parse the entire input stream as in the general
    // case that value might be the last property :(
    Scanner scanner = null;
    try {
        scanner = getFullStringScanner(in);
        JSONArray json = new JSONArray(scanner.next());
        for (int i = 0; i < json.length(); i++) {
            configuration.getSchemaMediator().createOrUpdateUsingJsonObject(clazz, this, json.getJSONObject(i),
                    true);
        }
    } catch (JSONException e) {
        throw new RealmException("Failed to read JSON", e);
    } finally {
        if (scanner != null) {
            scanner.close();
        }
    }
}

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

public void subsetFile(InputStream in, String outfile, List<Integer> columns, Long numCases, String delimiter) {
    try {/* www . jav a 2 s .c o m*/
        Scanner scanner = new Scanner(in);
        scanner.useDelimiter("\\n");

        BufferedWriter out = new BufferedWriter(new FileWriter(outfile));
        for (long caseIndex = 0; caseIndex < numCases; caseIndex++) {
            if (scanner.hasNext()) {
                String[] line = (scanner.next()).split(delimiter, -1);
                List<String> ln = new ArrayList<String>();
                for (Integer i : columns) {
                    ln.add(line[i]);
                }
                out.write(StringUtils.join(ln, "\t") + "\n");
            } else {
                throw new RuntimeException("Tab file has fewer rows than the determined number of cases.");
            }
        }

        while (scanner.hasNext()) {
            if (!"".equals(scanner.next())) {
                throw new RuntimeException(
                        "Tab file has extra nonempty rows than the determined number of cases.");

            }
        }

        scanner.close();
        out.close();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:com.networknt.light.server.handler.loader.FormLoader.java

private static void loadFormFile(String host, File file) {
    Scanner scan = null;
    try {/*  ww  w  . ja va 2 s.  c  o  m*/
        scan = new Scanner(file, Loader.encoding);
        // the content is only the data portion.
        String content = scan.useDelimiter("\\Z").next();
        // convert to map
        Map<String, Object> newMap = ServiceLocator.getInstance().getMapper().readValue(content,
                new TypeReference<HashMap<String, Object>>() {
                });
        String formId = (String) newMap.get("formId");
        Map<String, Object> oldMap = (Map<String, Object>) formMap.get(formId);
        boolean changed = false;
        if (oldMap == null) {
            // never loaded before.
            changed = true;
        } else {
            if (newMap.get("action") != null && !newMap.get("action").equals(oldMap.get("action"))) {
                changed = true;
            }
            if (!changed && newMap.get("schema") != null
                    && !newMap.get("schema").equals(oldMap.get("schema"))) {
                changed = true;
            }
            if (!changed && newMap.get("form") != null && !newMap.get("form").equals(oldMap.get("form"))) {
                changed = true;
            }
            if (!changed && newMap.get("modelData") != null
                    && !newMap.get("modelData").equals(oldMap.get("modelData"))) {
                changed = true;
            }
        }
        if (changed) {
            Map<String, Object> inputMap = new HashMap<String, Object>();
            inputMap.put("category", "form");
            inputMap.put("name", "impForm");
            inputMap.put("readOnly", false);

            Map<String, Object> data = new HashMap<String, Object>();
            data.put("content", content);
            inputMap.put("data", data);
            HttpPost httpPost = new HttpPost(host + "/api/rs");
            httpPost.addHeader("Authorization", "Bearer " + jwt);
            StringEntity input = new StringEntity(
                    ServiceLocator.getInstance().getMapper().writeValueAsString(inputMap));
            input.setContentType("application/json");
            httpPost.setEntity(input);
            CloseableHttpResponse response = httpclient.execute(httpPost);

            try {
                System.out.println("Form: " + file.getAbsolutePath() + " is loaded with status "
                        + response.getStatusLine());
                HttpEntity entity = response.getEntity();
                BufferedReader rd = new BufferedReader(new InputStreamReader(entity.getContent()));
                String json = "";
                String line = "";
                while ((line = rd.readLine()) != null) {
                    json = json + line;
                }
                //System.out.println("json = " + json);
                EntityUtils.consume(entity);
            } finally {
                response.close();
            }
        }
    } catch (IOException ioe) {
        ioe.printStackTrace();
    } finally {
        if (scan != null)
            scan.close();
    }
}

From source file:gtu._work.ui.JSFMakerUI.java

void resetPasteClipboardHtmlToJtable() {
    String content = ClipboardUtil.getInstance().getContents();
    Pattern tdStartPattern = Pattern.compile("<[tT][dDhH][^>]*>");
    Pattern tdEndPattern = Pattern.compile("</[tT][dDhH]>");
    Pattern innerPattern_HasTag = Pattern.compile("<[\\w:]+\\s[^>]*value=\"([^\"]*)\"[^>]*>",
            Pattern.MULTILINE);/*from  w ww.  ja va  2  s. c o m*/
    Matcher innerMatcher = null;
    Scanner scan = new Scanner(content);
    Scanner tdScan = null;
    String currentContent = null;
    String tdContent = null;
    StringBuilder sb = new StringBuilder();
    scan.useDelimiter("<tr>");
    for (; scan.hasNext();) {
        boolean anyMatcher = false;

        tdScan = new Scanner(scan.next());
        tdScan.useDelimiter(tdStartPattern);
        while (tdScan.hasNext()) {
            tdScan.useDelimiter(tdEndPattern);
            if (tdScan.hasNext()) {
                tdContent = tdScan.next().replaceAll(tdStartPattern.pattern(), "");
                {
                    innerMatcher = innerPattern_HasTag.matcher(tdContent.toString());
                    if (innerMatcher.find()) {
                        currentContent = StringUtils.defaultIfEmpty(innerMatcher.group(1), "&nbsp;");
                        //                            System.out.format("1[%s]\n", currentContent);
                        sb.append(currentContent + "\t");
                        continue;
                    }
                    currentContent = tdContent.toString().replaceAll("<[\\w:=,.#;/'?\"\\s\\{\\}\\(\\)\\[\\]]+>",
                            "");
                    currentContent = currentContent.replaceAll("[\\s\t\n]", "");
                    currentContent = StringUtils.defaultIfEmpty(currentContent, "&nbsp;");
                    //                        System.out.format("2[%s]\n", currentContent);
                    sb.append(currentContent + "\t");
                    anyMatcher = true;
                }
            }
            tdScan.useDelimiter(tdStartPattern);
        }
        if (anyMatcher) {
            sb.append("\n");
        }
    }
    scan.close();
    ClipboardUtil.getInstance().setContents(sb);
    System.out.println("####################################");
    System.out.println(sb);
    System.out.println("####################################");
}

From source file:gdsc.smlm.ij.plugins.pcpalm.PCPALMFitting.java

/**
 * Load a correlation curve from file. Will set the global gr, peakDensity and spatialDomain variables. If the data
 * fails to be loaded then the method will return false.
 * /*from   w w w  . j a va  2s .c  om*/
 * @return True if loaded
 */
private boolean loadCorrelationCurve() {
    inputFilename = Utils.getFilename("Input_Correlation_File", inputFilename);
    if (inputFilename == null)
        return false;

    // Set the analysis variables
    boolean spatialDomainSet = false;
    boolean peakDensitySet = false;

    BufferedReader input = null;
    try {
        FileInputStream fis = new FileInputStream(inputFilename);
        input = new BufferedReader(new UnicodeReader(fis, null));

        String line;
        int count = 0;

        Pattern pattern = Pattern.compile("#([^=]+) = ([^ ]+)");

        // Read the header
        while ((line = input.readLine()) != null) {
            count++;

            if (line.length() == 0)
                continue;
            if (line.charAt(0) != '#') {
                // This is the first record
                break;
            }

            // This is a header line. Extract the key-value pair
            Matcher match = pattern.matcher(line);
            if (match.find()) {
                if (match.group(1).equals(HEADER_SPATIAL_DOMAIN)) {
                    // Do not use Boolean.parseBoolean because this will not fail if the field is 
                    // neither true/false - it only return true for a match to true
                    spatialDomainSet = true;
                    if (match.group(2).equalsIgnoreCase("true"))
                        spatialDomain = true;
                    else if (match.group(2).equalsIgnoreCase("false"))
                        spatialDomain = false;
                    else
                        // We want to know if the field is not true/false
                        spatialDomainSet = false;
                } else if (match.group(1).equals(HEADER_PEAK_DENSITY)) {
                    try {
                        peakDensity = Double.parseDouble(match.group(2));
                        peakDensitySet = true;
                    } catch (NumberFormatException e) {
                        // Ignore this.
                    }
                }
            }
        }

        if (!peakDensitySet) {
            IJ.error(TITLE, "No valid " + HEADER_PEAK_DENSITY + " record in file " + inputFilename);
            return false;
        }
        if (!spatialDomainSet) {
            IJ.error(TITLE, "No valid " + HEADER_SPATIAL_DOMAIN + " record in file " + inputFilename);
            return false;
        }

        // Read the data: gr[0][i], gr[1][i], gr[2][i]
        ArrayList<double[]> data = new ArrayList<double[]>();
        while (line != null) {
            if (line.length() == 0)
                continue;
            if (line.charAt(0) == '#')
                continue;

            // Extract the first 3 fields
            Scanner scanner = new Scanner(line);
            scanner.useDelimiter("[\t ,]+");

            double r, g;
            try {
                r = scanner.nextDouble();
                g = scanner.nextDouble();
            } catch (InputMismatchException e) {
                IJ.error(TITLE, "Incorrect fields on line " + count);
                scanner.close();
                return false;
            } catch (NoSuchElementException e) {
                IJ.error(TITLE, "Incorrect fields on line " + count);
                scanner.close();
                return false;
            }
            // Allow the file to be missing the curve error. This is only used for plotting anyway.
            double error = 0;
            try {
                error = scanner.nextDouble();
            } catch (InputMismatchException e) {
            } catch (NoSuchElementException e) {
            }
            scanner.close();
            data.add(new double[] { r, g, error });

            // Read the next line
            line = input.readLine();
            count++;
        }

        if (data.isEmpty()) {
            IJ.error(TITLE, "No data in file " + inputFilename);
            return false;
        }

        gr = new double[3][data.size()];
        for (int i = 0; i < data.size(); i++) {
            final double[] d = data.get(i);
            gr[0][i] = d[0];
            gr[1][i] = d[1];
            gr[2][i] = d[2];
        }

    } catch (IOException e) {
        IJ.error(TITLE, "Unable to read from file " + inputFilename);
        return false;
    } finally {
        try {
            if (input != null)
                input.close();
        } catch (IOException e) {
            // Ignore
        }
    }

    return true;
}