Java Code Examples for java.util.Scanner#match()

The following examples show how to use java.util.Scanner#match() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BatchResponseParser.java    From cloud-odata-java with Apache License 2.0 6 votes vote down vote up
private String getBoundary(final String contentType) throws BatchException {
  Scanner contentTypeScanner = new Scanner(contentType).useDelimiter(";\\s?");
  if (contentTypeScanner.hasNext(REG_EX_CONTENT_TYPE)) {
    contentTypeScanner.next(REG_EX_CONTENT_TYPE);
  } else {
    contentTypeScanner.close();
    throw new BatchException(BatchException.INVALID_CONTENT_TYPE.addContent(HttpContentType.MULTIPART_MIXED));
  }
  if (contentTypeScanner.hasNext(REG_EX_BOUNDARY_PARAMETER)) {
    contentTypeScanner.next(REG_EX_BOUNDARY_PARAMETER);
    MatchResult result = contentTypeScanner.match();
    contentTypeScanner.close();
    if (result.groupCount() == 1 && result.group(1).trim().matches(REG_EX_BOUNDARY)) {
      return trimQuota(result.group(1).trim());
    } else {
      throw new BatchException(BatchException.INVALID_BOUNDARY);
    }
  } else {
    contentTypeScanner.close();
    throw new BatchException(BatchException.MISSING_PARAMETER_IN_CONTENT_TYPE);
  }
}
 
Example 2
Source File: CustomFormat.java    From mr4c with Apache License 2.0 6 votes vote down vote up
public Map<String,String> parse(String str) {
	if ( !matches(str) ) {
		throw new IllegalArgumentException(String.format("[%s] doesn't match pattern [%s]", str, m_pattern));
	}
	Scanner scanner = new Scanner(str);
	scanner.findWithinHorizon(m_regex, 0);
	MatchResult result = scanner.match();
	Map<String,String> vals = new HashMap<String,String>();
	if ( result.groupCount()!=m_nameList.size() ) {
		// this shouldn't be able to happen
		throw new IllegalStateException(String.format("[%s] doesn't match pattern [%s]; found %d matches, expected %d", str, m_pattern, result.groupCount(), m_nameList.size()));
	}
	for (int i=1; i<=result.groupCount(); i++) {
		String name = m_nameList.get(i-1);
		String val = result.group(i);
		if ( vals.containsKey(name) ) {
			if ( !vals.get(name).equals(val) ) {
				throw new IllegalArgumentException(String.format("[%s]doesnt match pattern [%s]; variable [%s] has values [%s] and [%s]", str, m_pattern, name, val, vals.get(name)));
			}
		}
		vals.put(name,result.group(i));
	}
	return vals;
}
 
Example 3
Source File: BatchRequestParser.java    From cloud-odata-java with Apache License 2.0 6 votes vote down vote up
private String getBoundary(final String contentType) throws BatchException {
  Scanner contentTypeScanner = new Scanner(contentType).useDelimiter(";\\s?");
  if (contentTypeScanner.hasNext(REG_EX_CONTENT_TYPE)) {
    contentTypeScanner.next(REG_EX_CONTENT_TYPE);
  } else {
    contentTypeScanner.close();
    throw new BatchException(BatchException.INVALID_CONTENT_TYPE.addContent(HttpContentType.MULTIPART_MIXED));
  }
  if (contentTypeScanner.hasNext(REG_EX_BOUNDARY_PARAMETER)) {
    contentTypeScanner.next(REG_EX_BOUNDARY_PARAMETER);
    MatchResult result = contentTypeScanner.match();
    contentTypeScanner.close();
    if (result.groupCount() == 1 && result.group(1).trim().matches(REG_EX_BOUNDARY)) {
      return trimQuota(result.group(1).trim());
    } else {
      throw new BatchException(BatchException.INVALID_BOUNDARY);
    }
  } else {
    contentTypeScanner.close();
    throw new BatchException(BatchException.MISSING_PARAMETER_IN_CONTENT_TYPE);
  }
}
 
Example 4
Source File: TzdbZoneRulesCompiler.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
private int parseYear(Scanner s, int defaultYear) {
    if (s.hasNext(YEAR)) {
        s.next(YEAR);
        MatchResult mr = s.match();
        if (mr.group(1) != null) {
            return 1900;  // systemv has min
        } else if (mr.group(2) != null) {
            return YEAR_MAX_VALUE;
        } else if (mr.group(3) != null) {
            return defaultYear;
        }
        return Integer.parseInt(mr.group(4));
        /*
        if (mr.group("min") != null) {
            //return YEAR_MIN_VALUE;
            return 1900;  // systemv has min
        } else if (mr.group("max") != null) {
            return YEAR_MAX_VALUE;
        } else if (mr.group("only") != null) {
            return defaultYear;
        }
        return Integer.parseInt(mr.group("year"));
        */
    }
    throw new IllegalArgumentException("Unknown year: " + s.next());
}
 
Example 5
Source File: BatchResponseParser.java    From cloud-odata-java with Apache License 2.0 6 votes vote down vote up
private Map<String, String> parseMimeHeaders(final Scanner scanner) throws BatchException {
  Map<String, String> headers = new HashMap<String, String>();
  while (scanner.hasNext() && !(scanner.hasNext(REG_EX_BLANK_LINE))) {
    if (scanner.hasNext(REG_EX_HEADER)) {
      scanner.next(REG_EX_HEADER);
      currentLineNumber++;
      MatchResult result = scanner.match();
      if (result.groupCount() == 2) {
        String headerName = result.group(1).trim().toLowerCase(Locale.ENGLISH);
        String headerValue = result.group(2).trim();
        headers.put(headerName, headerValue);
      }
    } else {
      throw new BatchException(BatchException.INVALID_HEADER.addContent(scanner.next()));
    }
  }
  return headers;
}
 
Example 6
Source File: TzdbZoneRulesCompiler.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
private int parseYear(Scanner s, int defaultYear) {
    if (s.hasNext(YEAR)) {
        s.next(YEAR);
        MatchResult mr = s.match();
        if (mr.group(1) != null) {
            return 1900;  // systemv has min
        } else if (mr.group(2) != null) {
            return YEAR_MAX_VALUE;
        } else if (mr.group(3) != null) {
            return defaultYear;
        }
        return Integer.parseInt(mr.group(4));
        /*
        if (mr.group("min") != null) {
            //return YEAR_MIN_VALUE;
            return 1900;  // systemv has min
        } else if (mr.group("max") != null) {
            return YEAR_MAX_VALUE;
        } else if (mr.group("only") != null) {
            return defaultYear;
        }
        return Integer.parseInt(mr.group("year"));
        */
    }
    throw new IllegalArgumentException("Unknown year: " + s.next());
}
 
Example 7
Source File: TzdbZoneRulesCompiler.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
private int parseYear(Scanner s, int defaultYear) {
    if (s.hasNext(YEAR)) {
        s.next(YEAR);
        MatchResult mr = s.match();
        if (mr.group(1) != null) {
            return 1900;  // systemv has min
        } else if (mr.group(2) != null) {
            return YEAR_MAX_VALUE;
        } else if (mr.group(3) != null) {
            return defaultYear;
        }
        return Integer.parseInt(mr.group(4));
        /*
        if (mr.group("min") != null) {
            //return YEAR_MIN_VALUE;
            return 1900;  // systemv has min
        } else if (mr.group("max") != null) {
            return YEAR_MAX_VALUE;
        } else if (mr.group("only") != null) {
            return defaultYear;
        }
        return Integer.parseInt(mr.group("year"));
        */
    }
    throw new IllegalArgumentException("Unknown year: " + s.next());
}
 
Example 8
Source File: PluginMessagesCLIResult.java    From thym with Eclipse Public License 1.0 6 votes vote down vote up
private void parseMessage(){
	
	Scanner scanner = new Scanner(getMessage());
	
	while(scanner.hasNextLine()){
		//check of --variable APP_ID=value is needed
		if( scanner.findInLine("(?:\\s\\-\\-variable\\s(\\w*)=value)") != null ){
			MatchResult mr = scanner.match();
			StringBuilder missingVars = new StringBuilder();
			for(int i = 0; i<mr.groupCount();i++){
				if(i>0){
					missingVars.append(",");
				}
				missingVars.append(mr.group());
			}
			pluginStatus = new HybridMobileStatus(IStatus.ERROR, HybridCore.PLUGIN_ID, CordovaCLIErrors.ERROR_MISSING_PLUGIN_VARIABLE,
					NLS.bind("This plugin requires {0} to be defined",missingVars), null);
		
		}
		scanner.nextLine();
	}
	scanner.close();
	
}
 
Example 9
Source File: TzdbZoneRulesCompiler.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
private int parseYear(Scanner s, int defaultYear) {
    if (s.hasNext(YEAR)) {
        s.next(YEAR);
        MatchResult mr = s.match();
        if (mr.group(1) != null) {
            return 1900;  // systemv has min
        } else if (mr.group(2) != null) {
            return YEAR_MAX_VALUE;
        } else if (mr.group(3) != null) {
            return defaultYear;
        }
        return Integer.parseInt(mr.group(4));
        /*
        if (mr.group("min") != null) {
            //return YEAR_MIN_VALUE;
            return 1900;  // systemv has min
        } else if (mr.group("max") != null) {
            return YEAR_MAX_VALUE;
        } else if (mr.group("only") != null) {
            return defaultYear;
        }
        return Integer.parseInt(mr.group("year"));
        */
    }
    throw new IllegalArgumentException("Unknown year: " + s.next());
}
 
Example 10
Source File: BatchRequestParser.java    From cloud-odata-java with Apache License 2.0 6 votes vote down vote up
private Map<String, String> parseHeaders(final Scanner scanner) throws BatchException {
  Map<String, String> headers = new HashMap<String, String>();
  while (scanner.hasNext() && !(scanner.hasNext(REG_EX_BLANK_LINE))) {
    if (scanner.hasNext(REG_EX_HEADER)) {
      scanner.next(REG_EX_HEADER);
      currentLineNumber++;
      MatchResult result = scanner.match();
      if (result.groupCount() == 2) {
        String headerName = result.group(1).trim().toLowerCase(Locale.ENGLISH);
        String headerValue = result.group(2).trim();
        headers.put(headerName, headerValue);
      }
    } else {
      throw new BatchException(BatchException.INVALID_HEADER.addContent(scanner.next()));
    }
  }
  return headers;
}
 
Example 11
Source File: DefaultFormat.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
protected ThreadStack parseThreadInfo(String threadInfo) {
    Scanner s = new Scanner(threadInfo);
    ThreadStack result = new ThreadStack();

    // parsing thread info
    s.findInLine(threadInfoPattern());
    MatchResult res = s.match();

    result.setThreadName(res.group(1));

    result.setType(res.group(3));

    result.setPriority(res.group(4));
    result.setTid(res.group(7));
    result.setNid(res.group(8));
    result.setStatus(res.group(9));

    s.close();
    return result;
}
 
Example 12
Source File: SystemUtils.java    From 30-android-libraries-in-30-days with Apache License 2.0 6 votes vote down vote up
private static MatchResult matchSystemFile(final String pSystemFile, final String pPattern, final int pHorizon) throws SystemUtilsException {
	InputStream in = null;
	try {
		final Process process = new ProcessBuilder(new String[] { "/system/bin/cat", pSystemFile }).start();

		in = process.getInputStream();
		final Scanner scanner = new Scanner(in);

		final boolean matchFound = scanner.findWithinHorizon(pPattern, pHorizon) != null;
		if(matchFound) {
			return scanner.match();
		} else {
			throw new SystemUtilsException();
		}
	} catch (final IOException e) {
		throw new SystemUtilsException(e);
	} finally {
		StreamUtils.close(in);
	}
}
 
Example 13
Source File: TzdbZoneRulesCompiler.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
private int parseYear(Scanner s, int defaultYear) {
    if (s.hasNext(YEAR)) {
        s.next(YEAR);
        MatchResult mr = s.match();
        if (mr.group(1) != null) {
            return 1900;  // systemv has min
        } else if (mr.group(2) != null) {
            return YEAR_MAX_VALUE;
        } else if (mr.group(3) != null) {
            return defaultYear;
        }
        return Integer.parseInt(mr.group(4));
        /*
        if (mr.group("min") != null) {
            //return YEAR_MIN_VALUE;
            return 1900;  // systemv has min
        } else if (mr.group("max") != null) {
            return YEAR_MAX_VALUE;
        } else if (mr.group("only") != null) {
            return defaultYear;
        }
        return Integer.parseInt(mr.group("year"));
        */
    }
    throw new IllegalArgumentException("Unknown year: " + s.next());
}
 
Example 14
Source File: TzdbZoneRulesCompiler.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
private int parseYear(Scanner s, int defaultYear) {
    if (s.hasNext(YEAR)) {
        s.next(YEAR);
        MatchResult mr = s.match();
        if (mr.group(1) != null) {
            return 1900;  // systemv has min
        } else if (mr.group(2) != null) {
            return YEAR_MAX_VALUE;
        } else if (mr.group(3) != null) {
            return defaultYear;
        }
        return Integer.parseInt(mr.group(4));
        /*
        if (mr.group("min") != null) {
            //return YEAR_MIN_VALUE;
            return 1900;  // systemv has min
        } else if (mr.group("max") != null) {
            return YEAR_MAX_VALUE;
        } else if (mr.group("only") != null) {
            return defaultYear;
        }
        return Integer.parseInt(mr.group("year"));
        */
    }
    throw new IllegalArgumentException("Unknown year: " + s.next());
}
 
Example 15
Source File: ReferenceSequenceFromSeekable.java    From cramtools with Apache License 2.0 5 votes vote down vote up
private static Map<String, FastaSequenceIndexEntry> buildIndex(InputStream is) {
	Scanner scanner = new Scanner(is);

	int sequenceIndex = 0;
	Map<String, FastaSequenceIndexEntry> index = new HashMap<String, FastaSequenceIndexEntry>();
	while (scanner.hasNext()) {
		// Tokenize and validate the index line.
		String result = scanner.findInLine("(.+)\\t+(\\d+)\\s+(\\d+)\\s+(\\d+)\\s+(\\d+)");
		if (result == null)
			throw new RuntimeException("Found invalid line in index file:" + scanner.nextLine());
		MatchResult tokens = scanner.match();
		if (tokens.groupCount() != 5)
			throw new RuntimeException("Found invalid line in index file:" + scanner.nextLine());

		// Skip past the line separator
		scanner.nextLine();

		// Parse the index line.
		String contig = tokens.group(1);
		long size = Long.valueOf(tokens.group(2));
		long location = Long.valueOf(tokens.group(3));
		int basesPerLine = Integer.valueOf(tokens.group(4));
		int bytesPerLine = Integer.valueOf(tokens.group(5));

		contig = SAMSequenceRecord.truncateSequenceName(contig);
		// Build sequence structure
		index.put(contig, new FastaSequenceIndexEntry(contig, location, size, basesPerLine, bytesPerLine,
				sequenceIndex++));
	}
	scanner.close();
	return index;
}
 
Example 16
Source File: JsEmbeddingProvider.java    From netbeans with Apache License 2.0 5 votes vote down vote up
protected static List<EmbeddingPosition> extractJsEmbeddings(String text, int sourceStart) {
    List<EmbeddingPosition> embeddings = new LinkedList<EmbeddingPosition>();
    // beggining comment around the script
    int start = 0;
    for (; start < text.length(); start++) {
        char c = text.charAt(start);
        if (!Character.isWhitespace(c)) {
            break;
        }
    }
    if (start < text.length() && text.startsWith("<!--", start)) { //NOI18N
        int lineEnd = text.indexOf('\n', start); //NOI18N
        if (isHtmlCommentStartToSkip(text, start, lineEnd)) {
            if (start > 0) {
                embeddings.add(new EmbeddingPosition(sourceStart, start));
            }
            lineEnd++; //skip the \n
            sourceStart += lineEnd;
            text = text.substring(lineEnd);
        }
    }

    // inline comments inside script
    Scanner scanner = new Scanner(text).useDelimiter("(<!--).*(-->)"); //NOI18N
    while (scanner.hasNext()) {
        scanner.next();
        MatchResult match = scanner.match();
        embeddings.add(new EmbeddingPosition(sourceStart + match.start(), match.group().length()));
    }
    return embeddings;
}
 
Example 17
Source File: CustomFormat.java    From mr4c with Apache License 2.0 5 votes vote down vote up
private static List<String> extractNames(String pattern) {
	List<String> names = new ArrayList<String>();
	Scanner scanner = new Scanner(pattern);
	while ( scanner.findWithinHorizon(VAR_REGEX, 0) !=null ) {
		MatchResult result = scanner.match();
		String val = result.group(1);
		names.add(val);
	}
	return names;
}
 
Example 18
Source File: BatchResponseParser.java    From cloud-odata-java with Apache License 2.0 5 votes vote down vote up
private BatchSingleResponseImpl parseResponse(final Scanner scanner, final boolean isChangeSet) throws BatchException {
  BatchSingleResponseImpl response = new BatchSingleResponseImpl();
  if (scanner.hasNext(REG_EX_STATUS_LINE)) {
    scanner.next(REG_EX_STATUS_LINE);
    currentLineNumber++;
    final String statusCode;
    final String statusInfo;
    MatchResult result = scanner.match();
    if (result.groupCount() == 2) {
      statusCode = result.group(1);
      statusInfo = result.group(2);
    } else {
      currentLineNumber++;
      throw new BatchException(BatchException.INVALID_STATUS_LINE.addContent(scanner.next()).addContent(currentLineNumber));
    }

    Map<String, String> headers = parseResponseHeaders(scanner);
    parseNewLine(scanner);
    String contentLengthHeader = getHeaderValue(headers, HttpHeaders.CONTENT_LENGTH);
    String body = (contentLengthHeader != null) ? parseBody(scanner, Integer.parseInt(contentLengthHeader)) : parseBody(scanner);
    response.setStatusCode(statusCode);
    response.setStatusInfo(statusInfo);
    response.setHeaders(headers);
    response.setContentId(currentContentId);
    response.setBody(body);
  } else {
    currentLineNumber++;
    throw new BatchException(BatchException.INVALID_STATUS_LINE.addContent(scanner.next()).addContent(currentLineNumber));
  }
  return response;
}
 
Example 19
Source File: JGoogleAnalyticsTracker.java    From Hook-Manager with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Define the proxy to use for all GA tracking requests.
 * <p>
 * Call this static method early (before creating any tracking requests).
 *
 * @param proxyAddr
 *            "addr:port" of the proxy to use; may also be given as URL
 *            ("http://addr:port/").
 */
public static void setProxy(String proxyAddr)
{
	if(proxyAddr != null)
	{
		Scanner s = new Scanner(proxyAddr);
		
		// Split into "proxyAddr:proxyPort".
		proxyAddr = null;
		int proxyPort = 8080;
		try
		{
			s.findInLine("(http://|)([^:/]+)(:|)([0-9]*)(/|)");
			MatchResult m = s.match();
			
			if(m.groupCount() >= 2)
				proxyAddr = m.group(2);
			
			if(m.groupCount() >= 4 && !(m.group(4).length() == 0))
				proxyPort = Integer.parseInt(m.group(4));
		}finally
		{
			s.close();
		}
		
		if(proxyAddr != null)
		{
			SocketAddress sa = new InetSocketAddress(proxyAddr, proxyPort);
			setProxy(new Proxy(Type.HTTP, sa));
		}
	}
}
 
Example 20
Source File: JsEmbeddingProvider.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private List<EmbeddingPosition> extractJsEmbeddings(String text, int sourceStart) {
    List<EmbeddingPosition> embeddings = new LinkedList<>();
    // beginning comment around the script
    int start = 0;
    for (; start < text.length(); start++) {
        char c = text.charAt(start);
        if (!Character.isWhitespace(c)) {
            break;
        }
    }
    if (start < text.length() && text.startsWith("<!--", start)) { //NOI18N
        int lineEnd = text.indexOf('\n', start); //NOI18N
        if (isHtmlCommentStartToSkip(text, start, lineEnd)) {
            if (start > 0) {
                embeddings.add(new EmbeddingPosition(sourceStart, start));
            }
            lineEnd++; //skip the \n
            sourceStart += lineEnd;
            text = text.substring(lineEnd);
            // need to look at the end of the text, whether there is no -->
            int end = text.length() - 1;
            while(end > -1 && Character.isWhitespace(text.charAt(end))) {
                end--;
            }
            if (end > 4) {
                int index = text.indexOf("-->", end - 4);
                if (index != -1) { //NOI18N
                    String helpText = text.substring(0, index);
                    if (helpText.lastIndexOf("<!--") <= helpText.lastIndexOf("-->")) { //NOI18N
                        text = helpText;
                    }
                }
            }
        }
    }
    // inline comments inside script
    Scanner scanner = new Scanner(text).useDelimiter("(<!--).*(-->)"); //NOI18N
    while (scanner.hasNext()) {
        scanner.next();
        MatchResult match = scanner.match();
        embeddings.add(new EmbeddingPosition(sourceStart + match.start(), match.group().length()));
    }
    return embeddings;
}