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.ikanow.infinit.e.api.social.sharing.ShareHandler.java

private String getReferenceString(SharePojo share) {
    // FILE:/*from   ww  w .  j a  v  a 2 s.c  om*/
    if (null == share.getDocumentLocation().get_id()) { // local file based reference
        FileInputStream fin = null;
        Scanner s = null;
        try {
            File f = new File(share.getDocumentLocation().getCollection());
            fin = new FileInputStream(f);
            s = new Scanner(fin, "UTF-8");
            return (s.useDelimiter("\n").next());
        } catch (Exception e) {
            return null;
        } finally {
            try {
                if (null != fin)
                    fin.close();
                if (null != s)
                    s.close();
            } catch (Exception e) {
            } // (probably just never opened)               
        }
    }
    // DB:
    // Carry on, this is a database object
    HashSet<String> shareIdStrs = new HashSet<String>();
    for (ShareCommunityPojo commIds : share.getCommunities()) {
        shareIdStrs.add(commIds.get_id().toString());
    }
    String retVal = null;
    BasicDBObject query = new BasicDBObject(DocumentPojo._id_, share.getDocumentLocation().get_id()); // (same for all artifacts)
    String dbName = share.getDocumentLocation().getDatabase();
    String collectionName = share.getDocumentLocation().getCollection();
    BasicDBObject returnVal = (BasicDBObject) MongoDbManager.getCollection(dbName, collectionName)
            .findOne(query);
    try {
        BasicDBList communities = null;
        boolean bCustomJob = dbName.equals("custommr"); // (a bit different)
        boolean bFoundOverlap = false;
        if (!bCustomJob) {
            ObjectId communityId = (ObjectId) returnVal.get(DocumentPojo.communityId_); // (same for other artifacts)
            bFoundOverlap = shareIdStrs.contains(communityId.toString());
        } else {
            communities = (BasicDBList) returnVal.get("communityIds"); // (shared across multiple json types)
            for (Object commIdObj : communities) {
                ObjectId commId = (ObjectId) commIdObj;
                if (shareIdStrs.contains(commId.toString())) {
                    bFoundOverlap = true;
                    break;
                }
            }
        }
        if (!bFoundOverlap) {
            throw new RuntimeException(""); // (turned into the common message below)
        }
        if (!bCustomJob) { // everything but custom jobs
            Date modifiedTime = returnVal.getDate(DocumentPojo.modified_); // (same for other artifacts)
            if (null != modifiedTime) {
                share.setModified(modifiedTime);
            }
            retVal = returnVal.toString();
        } else { // custom jobs
            String database = returnVal.getString(CustomMapReduceJobPojo.outputDatabase_);
            if (null == database) {
                database = dbName;
            }
            Date modifiedTime = returnVal.getDate(CustomMapReduceJobPojo.lastCompletionTime_);
            if (null != modifiedTime) {
                share.setModified(modifiedTime);
            }
            String collection = returnVal.getString(CustomMapReduceJobPojo.outputCollection_);
            BasicDBObject returnVal2 = (BasicDBObject) MongoDbManager.getCollection(database, collection)
                    .findOne();
            retVal = returnVal2.toString();
        }
    } catch (Exception e) {
        throw new RuntimeException("Document not found or permission issue (no overlapping communities)");
    }
    return retVal;
}

From source file:la2launcher.MainFrame.java

private void scanSumFile(File sums, SumHandler handler, boolean full)
        throws FileNotFoundException, IOException {
    FileInputStream fis = new FileInputStream(sums);
    Scanner scn = new Scanner(fis);
    while (scn.hasNextLine()) {
        String line = scn.nextLine();
        if ("#-[Required from required.ini]----------------------------------".equals(line)) {
            break;
        }//w w  w  .  j  a  v a  2s .  com
        int pipe = line.indexOf('|');
        int nextPipe = line.indexOf('|', pipe + 1);
        String sum = line.substring(0, pipe);
        String name = line.substring(pipe + 1, nextPipe);
        if (!full) {
            if (name.toUpperCase().startsWith("\\SYSTEM")) {
                handler.handle(new MDNamePair(name, sum));
            }
        } else {
            handler.handle(new MDNamePair(name, sum));
        }
    }
    scn.close();
    fis.close();
}

From source file:ml.shifu.shifu.core.processor.EvalModelProcessor.java

private double[] locateMaxMinScoreFromFile(SourceType sourceType, String maxMinScoreFolder) throws IOException {
    List<Scanner> scanners = null;
    double maxScore = Double.MIN_VALUE;
    double minScore = Double.MAX_VALUE;
    try {//from  w  w  w  . ja  v  a 2  s .  c  om
        // here only works for 1 reducer
        scanners = ShifuFileUtils.getDataScanners(maxMinScoreFolder, sourceType);
        for (Scanner scanner : scanners) {
            if (scanner.hasNext()) {
                String line = scanner.nextLine().trim();
                String[] splits = line.split(",");
                if (splits.length >= 2) {
                    double localMaxScore = Double.parseDouble(splits[0]);
                    if (maxScore < localMaxScore) {
                        maxScore = localMaxScore;
                    }

                    Double localMinScore = Double.parseDouble(splits[1]);
                    if (minScore > localMinScore) {
                        minScore = localMinScore;
                    }
                }
            }
        }
    } finally {
        if (scanners != null) {
            for (Scanner scanner : scanners) {
                if (scanner != null) {
                    scanner.close();
                }
            }
        }
    }
    return new double[] { maxScore, minScore };
}

From source file:com.mythesis.userbehaviouranalysis.Utils.java

/**
 * a method that reads a txt file with the necessary parameters
 * @param input the file that includes the necessary parameters
 *///from  w w w .  j  a v a 2  s  . c  om
public void readInput(File input) {
    FileInputStream inputStream = null;
    Scanner sc = null;
    wordvectors = new HashMap<>();
    crawlerOutputPaths = new HashMap<>();

    HashMap<String, String> wordvectorsPaths = new HashMap<>();
    try {
        inputStream = new FileInputStream(input);
        sc = new Scanner(inputStream);

        if (sc.hasNextLine()) {
            int numProfiles = Integer.parseInt(sc.nextLine().split(";")[1].trim().toLowerCase());

            int j = 0;
            while (j < numProfiles) {
                String profile = "";
                if (sc.hasNextLine()) {
                    profile = sc.nextLine().split(";")[1].trim();
                }
                if (sc.hasNextLine()) {
                    String path = sc.nextLine().split(";")[1].trim();
                    crawlerOutputPaths.put(profile, path);
                }
                if (sc.hasNextLine()) {
                    String path = sc.nextLine().split(";")[1].trim();
                    wordvectorsPaths.put(profile, path);
                }
                j++;
            }
        }

        for (String profile : wordvectorsPaths.keySet()) {
            File file = new File(wordvectorsPaths.get(profile));
            try {
                List<String> wordvector = FileUtils.readLines(file);
                wordvectors.put(profile, (ArrayList<String>) wordvector);
            } catch (IOException ex) {
                Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    } catch (FileNotFoundException ex) {
        Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException ex) {
                Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        if (sc != null) {
            sc.close();
        }
    }

}

From source file:com.partypoker.poker.engagement.reach.EngagementReachAgent.java

/**
 * Scan reach database and notify the first content that match the current U.I context
 * @param replaySystemNotifications true iff system notifications must be replayed.
 *//*w w w.  ja  va2 s . co m*/
private void scanContent(boolean replaySystemNotifications) {
    /* Change state */
    mScanning = true;

    /* For all database rows */
    Scanner scanner = mDB.getScanner();
    for (ContentValues values : scanner) {
        /* Parsing may fail */
        EngagementReachContent content = null;
        try {
            /* Parse content */
            content = parseContentFromStorage(values);

            /* Possibly generate a notification */
            notifyContent(content, replaySystemNotifications);
        } catch (Exception e) {
            /*
             * If the content was parsed but an error occurred while notifying, send "dropped" feedback
             * and delete
             */
            if (content != null)
                content.dropContent(mContext);

            /* Otherwise we just delete */
            else
                deleteContent(values.getAsLong(OID), values.getAsLong(DOWNLOAD_ID));

            /* In any case we continue parsing */
        }
    }

    /* Close scanner */
    scanner.close();

    /* Scan finished */
    mScanning = false;
}

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

public void readAndImportCSV(String path, String delimiter) {

    String dataLine = "";
    String[] dataList;//from www.j a  va2 s  .c o  m
    String data = "";

    ArrayList<Object> values = new ArrayList<>();
    int countColumnsInData = 0;

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

        while (scan.hasNextLine()) {
            countColumnsInData = 0;
            dataLine = scan.nextLine().trim();
            //System.out.println(dataLine);
            if (dataLine.endsWith(delimiter)) {
                dataLine = dataLine.substring(0, dataLine.length() - 1);
            }
            dataList = StringUtils.splitPreserveAllTokens(dataLine, delimiter);

            for (int i = 0; i < dataList.length; i++) {

                data = dataList[i];
                if (data.isEmpty()) {
                    if (valueTypesInSchema.get(i) == "String") {
                        data = "null";
                    } else {
                        data = "0";
                    }
                }

                switch (valueTypesInSchema.get(i).toLowerCase()) {
                case "int":
                case "integer":
                case "bigint":
                case "long":
                    values.add(countColumnsInData, Long.valueOf(data));
                    break;
                case "float":
                case "double":
                    values.add(countColumnsInData, Double.valueOf(data));
                    break;
                case "date":
                    values.add(countColumnsInData, Date.valueOf(data));
                    break;
                default:
                    values.add(countColumnsInData, String.valueOf(data));
                    break;
                }

                //System.out.println("Inserting " + values.get(countColumnsInData)
                //        + " into column " + columnNamesInSchema.get(countColumnsInData));

                countColumnsInData++;
            }
            insertDocument(values, countColumnsInData, maprdbTable, maprdbTablePath);
        }
        scan.close();
    } catch (Exception e) {
        System.out.println("Error importing text:\n\t" + dataLine + "\ninto\n\t" + maprdbTablePath);
        e.printStackTrace();
        System.exit(-1);
    }
}

From source file:gdsc.smlm.ij.plugins.DriftCalculator.java

/**
 * Read the drift file storing the T,X,Y into the class level calculatedTimepoints, lastdx and lastdy
 * arrays. Ignore any records where T is outside the limits.
 * //from  w w w.ja v a2s .  c o m
 * @param limits
 * @return The number of records read
 */
private int readDriftFile(int[] limits) {
    int ok = 0;
    BufferedReader input = null;
    try {
        FileInputStream fis = new FileInputStream(driftFilename);
        input = new BufferedReader(new UnicodeReader(fis, null));

        String line;
        Pattern pattern = Pattern.compile("[\t, ]+");
        while ((line = input.readLine()) != null) {
            if (line.length() == 0)
                continue;
            if (Character.isDigit(line.charAt(0))) {
                try {
                    Scanner scanner = new Scanner(line);
                    scanner.useDelimiter(pattern);
                    scanner.useLocale(Locale.US);
                    final int t = scanner.nextInt();
                    if (t < limits[0] || t > limits[1])
                        continue;
                    final double x = scanner.nextDouble();
                    final double y = scanner.nextDouble();
                    calculatedTimepoints[t] = ++ok;
                    lastdx[t] = x;
                    lastdy[t] = y;
                    scanner.close();
                } catch (InputMismatchException e) {
                } catch (NoSuchElementException e) {
                }
            }
        }
    } catch (IOException e) {
        // ignore
    } finally {
        try {
            if (input != null)
                input.close();
        } catch (IOException e) {
            // Ignore
        }
    }
    return ok;
}

From source file:csns.importer.parser.csula.RosterParserImpl.java

/**
 * This parser handles the format under CSULA Baseline -> CSULA Student
 * Records -> Class Roster on GET. A sample record is as follows:
 * "1 123456789 Doe,John M 3.00 ETG CS MS G1". Note that some fields like
 * middle name and units may not be present, and some people's last name has
 * space in it./*ww w.  j av a  2s  . c o m*/
 */
private List<ImportedUser> parse1(String text) {
    List<ImportedUser> students = new ArrayList<ImportedUser>();

    Scanner scanner = new Scanner(text);
    scanner.useDelimiter("\\s+|\\r\\n|\\r|\\n");
    while (scanner.hasNext()) {
        String cin = scanner.next();
        if (!isCin(cin))
            continue;

        String name = "";
        boolean nameFound = false;
        while (scanner.hasNext()) {
            String token = scanner.next();
            name += token + " ";
            if (token.matches(".+,.*")) {
                if (token.endsWith(",") && scanner.hasNext())
                    name += scanner.next();
                nameFound = true;
                break;
            }
        }

        String grade = null;
        boolean gradeFound = false;
        boolean unitsFound = false;
        while (nameFound && scanner.hasNext()) {
            String token = scanner.next();
            if (isUnits(token)) {
                unitsFound = true;
                continue;
            }
            if (isGrade(token)) {
                if (unitsFound) // this must be a grade
                {
                    grade = token;
                    gradeFound = true;
                    break;
                } else
                // this could be a grade or a middle name
                {
                    grade = token;
                    continue;
                }
            }
            if (isProgram(token)) {
                if (grade != null)
                    gradeFound = true;
                break;
            }

            name += token + " ";
        }

        if (nameFound) {
            ImportedUser student = new ImportedUser();
            student.setCin(cin);
            student.setName(name);
            if (gradeFound)
                student.setGrade(grade);
            students.add(student);
        }
    }
    scanner.close();

    return students;
}

From source file:com.houghtonassociates.bamboo.plugins.dao.GerritService.java

private void grantDatabaseAccess() 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 accessDBFound = false;

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

    if (dbAccessGranted)
        return;/*from   w ww. j a  v  a 2 s  .com*/

    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("accessDatabase = group Administrators")) {
                    accessDBFound = true;
                    break;
                }

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

                if (line.contains("[capability]")) {
                    content.append("\taccessDatabase = group Administrators\n");
                }
            }

            scanner.close();

            if (accessDBFound) {
                dbAccessGranted = true;
                return;
            }

            File fConfig2 = new File(projectConfig);

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

            jgitRepo.add("project.config");

            PushResult r = jgitRepo.commitPush("Grant Database Access.", targetRevision);

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

            dbAccessGranted = 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:io.realm.Realm.java

/**
 * Tries to update an existing object defined by its primary key with new JSON data. If no existing object could be
 * found a new object will be saved in the Realm. 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    {@link InputStream} with object data in JSON format.
 * @return Created or updated {@link io.realm.RealmObject}.
 * @throws java.lang.IllegalArgumentException if trying to update a class without a
 * {@link io.realm.annotations.PrimaryKey}.
 * @see #createObjectFromJson(Class, java.io.InputStream)
 *//*from ww w  . java  2s  . c om*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public <E extends RealmObject> E createOrUpdateObjectFromJson(Class<E> clazz, InputStream in)
        throws IOException {
    if (clazz == null || in == null) {
        return null;
    }
    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);
        JSONObject json = new JSONObject(scanner.next());
        return configuration.getSchemaMediator().createOrUpdateUsingJsonObject(clazz, this, json, true);
    } catch (JSONException e) {
        throw new RealmException("Failed to read JSON", e);
    } finally {
        if (scanner != null) {
            scanner.close();
        }
    }
}