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.WsFtpBookmarkCollection.java

private boolean parse(final ProtocolFactory protocols, final Host current, final String line) {
    final Scanner scanner = new Scanner(line);
    scanner.useDelimiter("=");
    if (!scanner.hasNext()) {
        log.warn("Missing key in line:" + line);
        return false;
    }//from w  w  w .  ja  va2s .c  om
    String name = scanner.next().toLowerCase(Locale.ROOT);
    if (!scanner.hasNext()) {
        log.warn("Missing value in line:" + line);
        return false;
    }
    String value = scanner.next().replaceAll("\"", StringUtils.EMPTY);
    if ("conntype".equals(name)) {
        try {
            switch (Integer.parseInt(value)) {
            case 4:
                current.setProtocol(protocols.forScheme(Scheme.sftp));
                break;
            case 5:
                current.setProtocol(protocols.forScheme(Scheme.ftps));
                break;
            }
            // Reset port to default
            current.setPort(-1);
        } catch (NumberFormatException e) {
            log.warn("Unknown Protocol:" + e.getMessage());
        }
    } else 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 ("dir".equals(name)) {
        current.setDefaultPath(value);
    } else if ("comment".equals(name)) {
        current.setComment(value);
    } else if ("uid".equals(name)) {
        current.getCredentials().setUsername(value);
    }
    return true;
}

From source file:kuona.client.JenkinsHttpClient.java

/**
 * Perform a GET request and parse the response and return a simple string of the content
 *
 * @param path path to request, can be relative or absolute
 * @return the entity text/*from w  ww .  j av  a2s  . c  om*/
 * @throws IOException, HttpResponseException
 */
public String get(String path, String contentType) throws IOException {
    HttpGet getMethod = new HttpGet(api(path));
    HttpResponse response = client.execute(getMethod, localContext);
    try {
        httpResponseValidator.validateResponse(response);
        Scanner s = new Scanner(response.getEntity().getContent());
        s.useDelimiter("\\z");
        StringBuffer sb = new StringBuffer();
        while (s.hasNext()) {
            sb.append(s.next());
        }
        return sb.toString();
    } finally {
        releaseConnection(getMethod);
    }
}

From source file:org.sipfoundry.sipxconfig.freeswitch.api.FreeswitchApiResultParserImpl.java

private ActiveConferenceMember parseConferenceMember(String line, String conferenceName) {
    ActiveConferenceMember member = new ActiveConferenceMember();

    Scanner scan = new Scanner(line);
    scan.useDelimiter(COMMAND_LIST_DELIM);

    member.setId(scan.nextInt());//  w w  w. ja v  a 2  s  .c  o m

    String sipAddress = scan.next().split("/")[2];

    member.setUuid(scan.next());

    String callerIdName = scan.next();
    if (callerIdName.equals(conferenceName)) {
        callerIdName = "";
    }

    String number = scan.next();

    String permissions = scan.next();
    member.setCanHear(permissions.contains("hear"));
    member.setCanSpeak(permissions.contains("speak"));

    member.setNumber(number);

    member.setName(callerIdName + " (" + sipAddress + ")");

    member.setVolumeIn(scan.nextInt());
    member.setVolumeOut(scan.nextInt());
    member.setEnergyLevel(scan.nextInt());
    return member;
}

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

@Override
public List<ImportedUser> parse(String text) {
    Scanner scanner = new Scanner(text);
    scanner.useDelimiter("\\s+|\\r\\n|\\r|\\n");
    String first = scanner.next();
    scanner.close();/*w  ww .j  av a 2  s.c  o m*/

    return first.equals("1") ? parse1(text) : parse2(text);
}

From source file:ch.sdi.core.impl.parser.CsvParser.java

/**
 * Parses the given input stream.// w ww  . j ava 2  s. c  om
 * <p>
 *
 * @param aInputStream
 *        must not be null
 * @param aDelimiter
 *        must not be null
 * @param aEncoding
 *        The encoding to be used. If null or empty, the systems default encoding is used.
 * @return a list which contains a list for each found person. The inner list contains the found
 *         values for this person. The number and the order must correspond to the configured field
 *         name list (see
 *         in each line.
 * @throws SdiException
 */
public List<List<String>> parse(InputStream aInputStream, String aDelimiter, String aEncoding,
        List<RawDataFilterString> aFilters) throws SdiException {
    if (!StringUtils.hasLength(aDelimiter)) {
        throw new SdiException("Delimiter not set", SdiException.EXIT_CODE_CONFIG_ERROR);
    } // if myDelimiter == null

    try {
        myLog.debug("Using encoding " + aEncoding);

        BufferedReader br = new BufferedReader(
                !StringUtils.hasText(aEncoding) ? new InputStreamReader(aInputStream)
                        : new InputStreamReader(aInputStream, aEncoding));
        List<List<String>> result = new ArrayList<>();
        Collection<String> myLinesFiltered = new ArrayList<>();

        int lineNo = 0;
        String line;
        LineLoop: while ((line = br.readLine()) != null) {
            lineNo++;

            if (aFilters != null) {
                for (RawDataFilterString filter : aFilters) {
                    if (filter.isFiltered(line)) {
                        myLog.debug("Skipping commented line: " + line);
                        myLinesFiltered.add(line);
                        continue LineLoop;
                    }
                }
            }

            myLog.debug("Parsing line " + lineNo + ": " + line);

            List<String> list = new ArrayList<String>();
            Scanner sc = new Scanner(line);
            try {
                sc.useDelimiter(aDelimiter);
                while (sc.hasNext()) {
                    list.add(sc.next());
                }

                // Note: if the line is terminated by the delimiter (last entry not present, the last entry
                // will not appear in the scanned enumeration. Check for this special case:
                if (line.endsWith(aDelimiter)) {
                    list.add("");
                } // if line.endsWith( aDelimiter )
            } finally {
                sc.close();
            }

            result.add(list);
        }

        myLog.info(new ReportMsg(ReportMsg.ReportType.PREPARSE_FILTER, "Filtered lines", myLinesFiltered));

        return result;
    } catch (Throwable t) {
        throw new SdiException("Problems while parsing CSV file", t, SdiException.EXIT_CODE_PARSE_ERROR);
    }
}

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

private void jText1OrJArea1Change(DocumentEvent doc) {
    try {/*from  w  w w .  ja  v  a 2  s  .  c  o m*/
        String complie1 = regexText.getText();
        String complie2 = regexText0.getText();
        String complie = complie1;
        if (StringUtils.isBlank(complie1)) {
            complie = complie2;
        }

        String matcherStr = srcArea.getText();

        if (StringUtils.isBlank(complie)) {
            setTitle("Regex");
            return;
        }
        if (StringUtils.isBlank(matcherStr)) {
            setTitle("content");
            return;
        }

        Pattern pattern = Pattern.compile(complie);
        Matcher matcher = pattern.matcher(matcherStr);

        DefaultComboBoxModel model1 = new DefaultComboBoxModel();
        groupList.setModel(model1);
        while (matcher.find()) {
            model1.addElement("---------------------");
            for (int ii = 0; ii <= matcher.groupCount(); ii++) {
                model1.addElement(ii + " : [" + matcher.group(ii) + "]");
            }
        }

        DefaultComboBoxModel model2 = new DefaultComboBoxModel();
        scannerList.setModel(model2);
        Scanner scanner = new Scanner(matcherStr);
        scanner.useDelimiter(pattern);
        while (scanner.hasNext()) {
            model2.addElement("[" + scanner.next() + "]");
        }
        scanner.close();
        this.setTitle("?");
    } catch (Exception ex) {
        this.setTitle(ex.getMessage());
        ex.printStackTrace();
    }
}

From source file:com.sonicle.webtop.core.versioning.SqlUpgradeScript.java

private void readFile(InputStreamReader readable, boolean flatNewLines) throws IOException {
    this.statements = new ArrayList<>();
    StringBuilder sb = null, sbsql = null;
    String lines[] = null;//w w  w  .j  a v  a  2 s.c  o m

    Scanner s = new Scanner(readable);
    s.useDelimiter("(;( )?(\r)?\n)");
    //s.useDelimiter("(;( )?(\r)?\n)|(--\n)");
    while (s.hasNext()) {
        String block = s.next();
        block = StringUtils.replace(block, "\r", "");
        if (!StringUtils.isEmpty(block)) {
            // Remove remaining ; at the end of the block (only if this block is the last one)
            if (!s.hasNext() && StringUtils.endsWith(block, ";"))
                block = StringUtils.left(block, block.length() - 1);

            sb = new StringBuilder();
            sbsql = new StringBuilder();
            lines = StringUtils.split(block, "\n");
            for (String line : lines) {
                if (AnnotationLine.matches(line)) {
                    if (DataSourceAnnotationLine.matches(line)) {
                        statements.add(new DataSourceAnnotationLine(line));
                    } else if (IgnoreErrorsAnnotationLine.matches(line)) {
                        statements.add(new IgnoreErrorsAnnotationLine(line));
                    } else if (RequireAdminAnnotationLine.matches(line)) {
                        statements.add(new RequireAdminAnnotationLine(line));
                    } else {
                        throw new IOException("Bad line: " + line);
                    }
                } else if (CommentLine.matches(line)) {
                    sb.append(line);
                    sb.append("\n");
                } else {
                    sbsql.append(StringUtils.trim(line));
                    sbsql.append(" ");
                    if (!flatNewLines)
                        sbsql.append("\n");
                }
            }
            if (sb.length() > 0)
                statements.add(new CommentLine(StringUtils.removeEnd(sb.toString(), "\n")));
            if (sbsql.length() > 0)
                statements.add(new SqlLine(StringUtils.removeEnd(sbsql.toString(), "\n")));
        }
    }
}

From source file:ddf.catalog.transformer.csv.common.CsvTransformerTest.java

@Test
public void writeSearchResultsToCsv() throws CatalogTransformerException {
    List<AttributeDescriptor> requestedAttributes = new ArrayList<>();
    requestedAttributes.add(buildAttributeDescriptor("attribute1", BasicTypes.STRING_TYPE));

    Appendable csvText = CsvTransformer.writeMetacardsToCsv(metacardList, requestedAttributes,
            Collections.emptyMap());

    Scanner scanner = new Scanner(csvText.toString());
    scanner.useDelimiter(CSV_ITEM_SEPARATOR_REGEX);

    String[] expectedHeaders = { "attribute1" };
    validate(scanner, expectedHeaders);//from ww w .  jav a  2s . c om

    String[] expectedValues = { "", "value1" };

    for (int i = 0; i < METACARD_COUNT; i++) {
        validate(scanner, expectedValues);
    }

    // final new line causes an extra "" value at end of file
    assertThat(scanner.hasNext(), is(true));
    assertThat(scanner.next(), is(""));
    assertThat(scanner.hasNext(), is(false));
}

From source file:ddf.catalog.transformer.csv.common.CsvTransformerTest.java

@Test
public void writeSearchResultsToCsvWithAliasMap() throws CatalogTransformerException {
    List<AttributeDescriptor> requestedAttributes = new ArrayList<>();
    requestedAttributes.add(buildAttributeDescriptor("attribute1", BasicTypes.STRING_TYPE));

    Map<String, String> aliasMap = ImmutableMap.of("attribute1", "column1");

    Appendable csvText = CsvTransformer.writeMetacardsToCsv(metacardList, requestedAttributes, aliasMap);

    Scanner scanner = new Scanner(csvText.toString());
    scanner.useDelimiter(CSV_ITEM_SEPARATOR_REGEX);

    String[] expectedHeaders = { "column1" };
    validate(scanner, expectedHeaders);//  w w  w  .  j  av a2 s.c  o m

    String[] expectedValues = { "", "value1" };

    for (int i = 0; i < METACARD_COUNT; i++) {
        validate(scanner, expectedValues);
    }

    // final new line causes an extra "" value at end of file
    assertThat(scanner.hasNext(), is(true));
    assertThat(scanner.next(), is(""));
    assertThat(scanner.hasNext(), is(false));
}

From source file:org.colombbus.tangara.core.Version.java

private void doExtractFieldsFromText(String textVersion) throws Exception {
    Scanner scanner = new Scanner(textVersion);
    scanner.useDelimiter("\\."); //$NON-NLS-1$
    major = scanner.nextInt();//  ww  w . j  a  v  a 2  s  .  com
    if (scanner.hasNext())
        minor = scanner.nextInt();
    if (scanner.hasNext())
        fix = scanner.nextInt();
    if (scanner.hasNext())
        qualifier = scanner.next();
    if (scanner.hasNext()) {
        throw new Exception("Too many fields"); //$NON-NLS-1$
    }
    scanner.close();
}