Example usage for java.util Scanner useDelimiter

List of usage examples for java.util Scanner useDelimiter

Introduction

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

Prototype

public Scanner useDelimiter(String pattern) 

Source Link

Document

Sets this scanner's delimiting pattern to a pattern constructed from the specified String .

Usage

From source file:ch.cyberduck.core.importer.FireFtpBookmarkCollection.java

private void read(final ProtocolFactory protocols, final String entry) {
    final Host current = new Host(protocols.forScheme(Scheme.ftp));
    current.getCredentials().setUsername(PreferencesFactory.get().getProperty("connection.login.anon.name"));
    for (String attribute : entry.split(", ")) {
        Scanner scanner = new Scanner(attribute);
        scanner.useDelimiter(":");
        if (!scanner.hasNext()) {
            log.warn("Missing key in line:" + attribute);
            continue;
        }//from w  ww .  j av a 2  s . com
        String name = scanner.next().toLowerCase(Locale.ROOT);
        if (!scanner.hasNext()) {
            log.warn("Missing value in line:" + attribute);
            continue;
        }
        String value = scanner.next().replaceAll("\"", StringUtils.EMPTY);
        if ("host".equals(name)) {
            current.setHostname(value);
        } else if ("port".equals(name)) {
            try {
                current.setPort(Integer.parseInt(value));
            } catch (NumberFormatException e) {
                log.warn("Invalid Port:" + e.getMessage());
            }
        } else if ("remotedir".equals(name)) {
            current.setDefaultPath(value);
        } else if ("webhost".equals(name)) {
            current.setWebURL(value);
        } else if ("encoding".equals(name)) {
            current.setEncoding(value);
        } else if ("notes".equals(name)) {
            current.setComment(value);
        } else if ("account".equals(name)) {
            current.setNickname(value);
        } else if ("privatekey".equals(name)) {
            current.getCredentials().setIdentity(LocalFactory.get(value));
        } else if ("pasvmode".equals(name)) {
            if (Boolean.TRUE.toString().equals(value)) {
                current.setFTPConnectMode(FTPConnectMode.passive);
            }
            if (Boolean.FALSE.toString().equals(value)) {
                current.setFTPConnectMode(FTPConnectMode.active);
            }
        } else if ("login".equals(name)) {
            current.getCredentials().setUsername(value);
        } else if ("password".equals(name)) {
            current.getCredentials().setPassword(value);
        } else if ("anonymous".equals(name)) {
            if (Boolean.TRUE.toString().equals(value)) {
                current.getCredentials()
                        .setUsername(PreferencesFactory.get().getProperty("connection.login.anon.name"));
            }
        } else if ("security".equals(name)) {
            if ("authtls".equals(value)) {
                current.setProtocol(protocols.forScheme(Scheme.ftps));
                // Reset port to default
                current.setPort(-1);
            }
            if ("sftp".equals(value)) {
                current.setProtocol(protocols.forScheme(Scheme.sftp));
                // Reset port to default
                current.setPort(-1);
            }
        }
    }
    this.add(current);
}

From source file:me.figo.FigoConnection.java

/***
 * Handle the response of a request by decoding its JSON payload
 * @param stream Stream containing the JSON data
 * @param typeOfT Type of the data to be expected
 * @return Decoded data//from  ww w .  java  2s . com
 */
private <T> T handleResponse(InputStream stream, Type typeOfT) {
    // check whether decoding is actual requested
    if (typeOfT == null)
        return null;

    // read stream body
    Scanner s = new Scanner(stream, "UTF-8");
    s.useDelimiter("\\A");
    String body = s.hasNext() ? s.next() : "";
    s.close();

    // decode JSON payload
    Gson gson = GsonAdapter.createGson();
    return gson.fromJson(body, typeOfT);
}

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

/**
 * This parser handles the format under Self Service -> Faculty Center -> My
 * Schedule on GET. A sample record is as follows:
 * "Doe,John M 302043188 3.00 Engr, Comp Sci, & Tech  CS MS". Again, not all
 * fields may be present./*ww w .  j  a v  a2 s .  co  m*/
 */
private List<ImportedUser> parse2(String text) {
    List<ImportedUser> students = new ArrayList<ImportedUser>();
    Stack<String> stack = new Stack<String>();

    Scanner scanner = new Scanner(text);
    scanner.useDelimiter("\\s+|\\r\\n|\\r|\\n");
    while (scanner.hasNext()) {
        String name = "";
        do {
            String token = scanner.next();
            if (!isName(token))
                stack.push(token);
            else {
                name = token;
                while (!stack.isEmpty() && !isDegree(stack.peek()))
                    name = stack.pop() + " " + name;
                break;
            }
        } while (scanner.hasNext());

        String cin = "";
        boolean cinFound = false;
        while (scanner.hasNext()) {
            cin = scanner.next();
            if (isCin(cin)) {
                cinFound = true;
                break;
            } else
                name += " " + cin;
        }

        if (cinFound) {
            ImportedUser student = new ImportedUser();
            student.setCin(cin);
            student.setName(name);
            students.add(student);
        }
    }
    scanner.close();

    return students;
}

From source file:edu.harvard.iq.dvn.ingest.dsb.impl.DvnJavaFieldCutter.java

public void subsetFile(InputStream in, String outfile, Set<Integer> columns, Long numCases, String delimiter) {
    try {//from   w ww. j  a  v a  2 s  .c o m
        Scanner scanner = new Scanner(in);

        dbgLog.fine("outfile=" + outfile);

        BufferedWriter out = new BufferedWriter(new FileWriter(outfile));
        scanner.useDelimiter("\\n");

        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:eu.project.ttc.resources.FixedExpressionResource.java

public void load(DataResource data) throws ResourceInitializationException {
    InputStream inputStream = null;
    try {// w w w .j  av a 2  s  .c om
        inputStream = data.getInputStream();
        Scanner scanner = null;
        try {
            String fixedExpression, line;
            String[] str;
            scanner = new Scanner(inputStream, "UTF-8");
            scanner.useDelimiter(TermSuiteConstants.LINE_BREAK);
            while (scanner.hasNext()) {
                line = scanner.next().split(TermSuiteConstants.DIESE)[0].trim();
                str = line.split(TermSuiteConstants.TAB);
                fixedExpression = str[0];

                fixedExpressionLemmas.add(fixedExpression);
            }
        } catch (Exception e) {
            throw new ResourceInitializationException(e);
        } finally {
            IOUtils.closeQuietly(scanner);
        }
    } catch (IOException e) {
        LOGGER.error("Could not load file {}", data.getUrl());
        throw new ResourceInitializationException(e);
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
}

From source file:coral.reef.web.ReefController.java

@RequestMapping("/admin/edit")
public String edit(@RequestParam(value = "name") String name,
        @RequestParam(value = "properties", required = false) String properties,
        @RequestParam(value = "basepath", required = false) String basepath, Map<String, Object> model) {

    CoralBean cb = coralBeanRepository.findOne(name);

    if (cb == null) {
        cb = new CoralBean();
        String content;//from ww  w .j  av  a2s  .com
        try {
            Scanner scan = new Scanner(new ClassPathResource("reef.default.properties").getInputStream());
            scan.useDelimiter("\\Z");
            content = scan.next();
            cb.setProperties(content);
        } catch (IOException e) {
            content = e.getMessage();
        }
        cb.setName(name);
    }

    if (properties != null) {
        cb.setProperties(properties);
    }

    if (basepath != null) {
        String prop = cb.getProperties();
        prop = prop.replaceFirst("[#]?(\\s*?)exp.basepath = (.*?)\n", "# exp.basepath = " + basepath + "\n");
        cb.setProperties(prop);
    }

    coralBeanRepository.save(cb);

    model.put("coral", cb);

    return "edit";
}

From source file:ru.histone.staticrender.StaticRender.java

public void renderSite(final Path srcDir, final Path dstDir) {
    log.info("Running StaticRender for srcDir={}, dstDir={}", srcDir.toString(), dstDir.toString());
    Path contentDir = srcDir.resolve("content/");
    final Path layoutDir = srcDir.resolve("layouts/");

    FileVisitor<Path> layoutVisitor = new SimpleFileVisitor<Path>() {
        @Override//from  www.j  a v  a 2 s  .  c  om
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            if (file.toString().endsWith("." + TEMPLATE_FILE_EXTENSION)) {
                ArrayNode ast = null;
                try {
                    ast = histone.parseTemplateToAST(new FileReader(file.toFile()));
                } catch (HistoneException e) {
                    throw new RuntimeException("Error parsing histone template:" + e.getMessage(), e);
                }

                final String fileName = file.getFileName().toString();
                String layoutId = fileName.substring(0,
                        fileName.length() - TEMPLATE_FILE_EXTENSION.length() - 1);
                layouts.put(layoutId, ast);
                if (log.isDebugEnabled()) {
                    log.debug("Layout found id='{}', file={}", layoutId, file);
                } else {
                    log.info("Layout found id='{}'", layoutId);
                }
            } else {
                final Path relativeFileName = srcDir.resolve("layouts").relativize(Paths.get(file.toUri()));
                final Path resolvedFile = dstDir.resolve(relativeFileName);
                if (!resolvedFile.getParent().toFile().exists()) {
                    Files.createDirectories(resolvedFile.getParent());
                }
                Files.copy(Paths.get(file.toUri()), resolvedFile, StandardCopyOption.REPLACE_EXISTING,
                        LinkOption.NOFOLLOW_LINKS);
            }
            return FileVisitResult.CONTINUE;
        }
    };

    FileVisitor<Path> contentVisitor = new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {

            Scanner scanner = new Scanner(file, "UTF-8");
            scanner.useDelimiter("-----");

            String meta = null;
            StringBuilder content = new StringBuilder();

            if (!scanner.hasNext()) {
                throw new RuntimeException("Wrong format #1:" + file.toString());
            }

            if (scanner.hasNext()) {
                meta = scanner.next();
            }

            if (scanner.hasNext()) {
                content.append(scanner.next());
                scanner.useDelimiter("\n");
            }

            while (scanner.hasNext()) {
                final String next = scanner.next();
                content.append(next);

                if (scanner.hasNext()) {
                    content.append("\n");
                }
            }

            Map<String, String> metaYaml = (Map<String, String>) yaml.load(meta);

            String layoutId = metaYaml.get("layout");

            if (!layouts.containsKey(layoutId)) {
                throw new RuntimeException(MessageFormat.format("No layout with id='{0}' found", layoutId));
            }

            final Path relativeFileName = srcDir.resolve("content").relativize(Paths.get(file.toUri()));
            final Path resolvedFile = dstDir.resolve(relativeFileName);
            if (!resolvedFile.getParent().toFile().exists()) {
                Files.createDirectories(resolvedFile.getParent());
            }
            Writer output = new FileWriter(resolvedFile.toFile());
            ObjectNode context = jackson.createObjectNode();
            ObjectNode metaNode = jackson.createObjectNode();
            context.put("content", content.toString());
            context.put("meta", metaNode);
            for (String key : metaYaml.keySet()) {
                if (!key.equalsIgnoreCase("content")) {
                    metaNode.put(key, metaYaml.get(key));
                }
            }

            try {
                histone.evaluateAST(layoutDir.toUri().toString(), layouts.get(layoutId), context, output);
                output.flush();
            } catch (HistoneException e) {
                throw new RuntimeException("Error evaluating content: " + e.getMessage(), e);
            } finally {
                output.close();
            }

            return FileVisitResult.CONTINUE;
        }
    };

    try {
        Files.walkFileTree(layoutDir, layoutVisitor);
        Files.walkFileTree(contentDir, contentVisitor);
    } catch (Exception e) {
        throw new RuntimeException("Error during site render", e);
    }
}

From source file:edu.harvard.hul.ois.fits.junit.VideoStdSchemaTestXmlUnit_NoMD5.java

@Test
public void testVideoXmlUnitFitsOutput_AVC_NO_MD5() throws Exception {

    Fits fits = new Fits();

    // First generate the FITS output
    File input = new File("testfiles/FITS-SAMPLE-44_1_1_4_4_4_6_1_1_2_3_1.mp4");
    FitsOutput fitsOut = fits.examine(input);

    XMLOutputter serializer = new XMLOutputter(Format.getPrettyFormat());
    String actualXmlStr = serializer.outputString(fitsOut.getFitsXml());

    // Read in the expected XML file
    Scanner scan = new Scanner(
            new File("testfiles/output/FITS-SAMPLE-44_1_1_4_4_4_6_1_1_2_3_1_mp4_FITS_NO_MD5.xml"));
    String expectedXmlStr = scan.useDelimiter("\\Z").next();
    scan.close();// ww w  .jav a2  s .co  m

    // Set up XMLUnit
    XMLUnit.setIgnoreWhitespace(true);
    XMLUnit.setNormalizeWhitespace(true);

    Diff diff = new Diff(expectedXmlStr, actualXmlStr);

    // Initialize attributes or elements to ignore for difference checking
    diff.overrideDifferenceListener(new IgnoreNamedElementsDifferenceListener("version", "toolversion",
            "dateModified", "fslastmodified", "startDate", "startTime", "timestamp", "fitsExecutionTime",
            "executionTime", "filepath", "location"));

    DetailedDiff detailedDiff = new DetailedDiff(diff);

    // Display any Differences
    List<Difference> diffs = detailedDiff.getAllDifferences();
    if (!diff.identical()) {
        StringBuffer differenceDescription = new StringBuffer();
        differenceDescription.append(diffs.size()).append(" differences");

        System.out.println(differenceDescription.toString());
        for (Difference difference : diffs) {
            System.out.println(difference.toString());
        }

    }

    assertTrue("Differences in XML", diff.identical());
}

From source file:phonegraph.PhoneGraph.java

public void CreatedphoneOnly(String filename) {
    try {// w  w w . ja  v  a  2 s .  c  o  m
        phonemaps = new HashMap<String, Integer>(400000);
        FileReader fileReader = new FileReader(filename);
        // Always wrap FileReader in BufferedReader.
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        String line;
        int count = 0;
        bufferedReader.readLine();
        while ((line = bufferedReader.readLine()) != null) {
            Scanner sc = new Scanner(line);
            sc.useDelimiter("\t");
            Integer id = sc.nextInt();
            String phone = sc.next();
            phonemaps.put(phone, id);
            count++;
            //                if(count%100==0){
            //                    System.out.println(count);
            //                }
        }
        bufferedReader.close();
    } catch (IOException ex) {
        Logger.getLogger(PhoneGraph.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.springframework.cloud.lattice.connector.AbstractServiceInfoCreatorTests.java

protected String readTestDataFile(String fileName) {
    Scanner scanner = null;
    try {/*w  w w.j  av  a2 s.c  om*/
        Reader fileReader = new InputStreamReader(getClass().getResourceAsStream(fileName));
        scanner = new Scanner(fileReader);
        return scanner.useDelimiter("\\Z").next();
    } finally {
        if (scanner != null) {
            scanner.close();
        }
    }
}