java.util.regex.Matcher Java Examples

The following examples show how to use java.util.regex.Matcher. 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 Project: netbeans   Author: apache   File: EnvironmentVariableResolver.java    License: Apache License 2.0 6 votes vote down vote up
public String resolve(String string, ClassLoader loader) {
    String parsed = string;
    Matcher matcher = Pattern.compile("(?<!\\\\)\\$E\\{(.*?)\\}").matcher(parsed);
    while (matcher.find()) {
        try {
            String name = matcher.group(1);
            String value = SystemUtils.getEnvironmentVariable(name);
            if(value!=null) {
                parsed = parsed.replace(matcher.group(), value);
            }
        } catch (NativeException e) {
            ErrorManager.notifyDebug(StringUtils.format(
                    ERROR_CANNOT_PARSE_PATTERN, matcher.group()), e);
        }
    }
    return parsed;
}
 
Example #2
Source Project: quaerite   Author: mitre   File: ElevateQueryComparer.java    License: Apache License 2.0 6 votes vote down vote up
private static QuerySet loadQueries(Path file) throws Exception {
    QuerySet querySet = new QuerySet();
    Matcher uc = Pattern.compile("[A-Z]").matcher("");
    try (InputStream is = Files.newInputStream(file)) {
        try (Reader reader = new InputStreamReader(new BOMInputStream(is), "UTF-8")) {
            Iterable<CSVRecord> records = CSVFormat.EXCEL
                    .withFirstRecordAsHeader().parse(reader);
            for (CSVRecord record : records) {
                String q = record.get("query");
                Integer c = Integer.parseInt(record.get("count"));
                if (querySet.queries.containsKey(q)) {
                    LOG.warn("duplicate queries?! >" + q + "<");
                }

                querySet.set(q, c);
            }
        }
    }
    LOG.info("loaded " + querySet.queries.size() + " queries");
    return querySet;
}
 
Example #3
Source Project: Tok-Android   Author: InsightIM   File: MsgTextView.java    License: GNU General Public License v3.0 6 votes vote down vote up
public CharSequence buildOrderLink(CharSequence content) {
    String c = content.toString();
    SpannableString sp = new SpannableString(c);
    if (enableOrderLink) {
        Matcher orderMatcher = PatternUtil.getOrderMatcher(c);
        while (orderMatcher.find()) {
            sp.setSpan(new OrderLinkSpan(c.substring(orderMatcher.start(), orderMatcher.end())),
                orderMatcher.start(), orderMatcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
    }

    Matcher pkMatcher = PatternUtil.getPkMatcher(c);
    while (pkMatcher.find()) {
        sp.setSpan(new TokIdLinkSpan(c.substring(pkMatcher.start(), pkMatcher.end())),
            pkMatcher.start(), pkMatcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
    setText(sp);
    setMovementMethod(LinkMovementMethod.getInstance());
    return sp;
}
 
Example #4
Source Project: LGoodDatePicker   Author: LGoodDatePicker   File: FormSpecParser.java    License: MIT License 6 votes vote down vote up
private Multiplier multiplier(String expression, int offset) {
    Matcher matcher = MULTIPLIER_PREFIX_PATTERN.matcher(expression);
    if (!matcher.find()) {
        return null;
    }
    if (matcher.start() > 0) {
        fail(offset + matcher.start(), "illegal multiplier position");
    }
    Matcher digitMatcher = DIGIT_PATTERN.matcher(expression);
    if (!digitMatcher.find()) {
        return null;
    }
    String digitStr = expression.substring(0, digitMatcher.end());
    int number = 0;
    try {
        number = Integer.parseInt(digitStr);
    } catch (NumberFormatException e) {
        fail(offset, e);
    }
    if (number <= 0) {
        fail(offset, "illegal 0 multiplier");
    }
    String subexpression = expression.substring(matcher.end(), expression.length() - 1);
    return new Multiplier(number, subexpression, matcher.end());
}
 
Example #5
Source Project: Zebra   Author: Meituan-Dianping   File: GroovyRuleEngine.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("resource")
private static final GroovyObject getGroovyObject(String rule)
		throws IllegalAccessException, InstantiationException {
	if (!RULE_CLASS_CACHE.containsKey(rule)) {
		synchronized (GroovyRuleEngine.class) {
			if (!RULE_CLASS_CACHE.containsKey(rule)) {
				Matcher matcher = DimensionRule.RULE_COLUMN_PATTERN.matcher(rule);
				StringBuilder engineClazzImpl = new StringBuilder(200)
						.append("class RuleEngineBaseImpl extends " + RuleEngineBase.class.getName() + "{")
						.append("Object execute(Map context) {").append(matcher.replaceAll("context.get(\"$1\")"))
						.append("}").append("}");
				GroovyClassLoader loader = new GroovyClassLoader(AbstractDimensionRule.class.getClassLoader());
				Class<?> engineClazz = loader.parseClass(engineClazzImpl.toString());
				RULE_CLASS_CACHE.put(rule, engineClazz);
			}
		}
	}
	return (GroovyObject) RULE_CLASS_CACHE.get(rule).newInstance();
}
 
Example #6
Source Project: Shop-for-JavaWeb   Author: EleTeam   File: ValidateUtils.java    License: MIT License 6 votes vote down vote up
/**
 * 密码验证
 *
 * @param  str
 * @return boolean 验证通过返回true
 */
public static boolean isPassword(String str) {
	StringUtils.trim(str);
	Pattern p = null;
	Matcher m = null;
	boolean b = false;
	if (str == null || str.length() < 6) {
		errMsg = "密码必须为6位以上";
		b = false;
	} else {
		b = true;
		errMsg = "";
	}

	return b;
}
 
Example #7
Source Project: Criteria2Query   Author: OHDSI   File: NumericConvert.java    License: Apache License 2.0 6 votes vote down vote up
public static List<Double[]> extractNumberPositions(String a) {
	//System.out.println("to be matched-->"+a);
	List<Double[]> numberlist=new ArrayList<Double[]>();
	Pattern pattern = Pattern.compile("[\\d\\.]+");
	Matcher matcher = pattern.matcher(a);
	while (matcher.find()) {
		Double[] numpos=new Double[3];
		//System.out.println(matcher.group()); // 打印
		if(matcher.group().equals(".")){
			continue;
		}
		//System.out.println("matcher="+matcher.group()+"startindex="+matcher.start()+",endindex="+matcher.end());	
		try{
			numpos[0]=Double.valueOf(matcher.group());
			numpos[1]=(double) matcher.start();
			numpos[2]=(double) matcher.end();
			numberlist.add(numpos);
		}catch (Exception ex){
			return null;
		}
	}
	return numberlist;
	
}
 
Example #8
Source Project: phoenix-omid   Author: apache   File: StateMachineLogParser.java    License: Apache License 2.0 6 votes vote down vote up
static Map<String, List<String>> getFsmEventMap(BufferedReader f) throws IOException {
    String s = f.readLine();
    Map<String, List<String>> map = new HashMap<String, List<String>>();
    while (s != null) {
        Matcher m = fsmPattern.matcher(s);
        if (m.find()) {
            String key = m.group(1);
            if (!map.containsKey(key)) {
                map.put(key, new ArrayList<String>());
            }
            map.get(key).add(s);
        }
        s = f.readLine();
    }
    return map;
}
 
Example #9
Source Project: wisdom   Author: wisdom-framework   File: LessCompilerMojo.java    License: Apache License 2.0 6 votes vote down vote up
private WatchingException buildWatchingException(String stream, File file, MojoExecutionException e) {
    String[] lines = stream.split("\n");
    for (String l : lines) {
        if (!Strings.isNullOrEmpty(l)) {
            stream = l.trim();
            break;
        }
    }
    final Matcher matcher = LESS_ERROR_PATTERN.matcher(stream);
    if (matcher.matches()) {
        String line = matcher.group(2);
        String character = matcher.group(3);
        String reason = matcher.group(1);
        return new WatchingException("Less Compilation Error", reason, file,
                Integer.valueOf(line), Integer.valueOf(character), null);
    } else {
        return new WatchingException("Less Compilation Error", stream, file, e.getCause());
    }
}
 
Example #10
Source Project: jmonkeyengine   Author: jMonkeyEngine   File: J3mdTechniqueDefWriter.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private String formatCondition(String condition, Collection<MatParam> matParams){
    //condition = condition.replaceAll("defined\\(","");

    String res = condition;
    Pattern pattern = Pattern.compile("defined\\(([A-Z0-9]*)\\)");
    Matcher m = pattern.matcher(condition);

    while(m.find()){
        String match = m.group(0);
        String defineName = m.group(1).toLowerCase();
        for (MatParam matParam : matParams) {
            if(matParam.getName().toLowerCase().equals(defineName)){
                res = res.replace(match, matParam.getName());
            }
        }
    }

    return res;
}
 
Example #11
Source Project: gocd   Author: gocd   File: AccessTokenAuthenticationFilter.java    License: Apache License 2.0 6 votes vote down vote up
private AccessTokenCredential extractAuthTokenCredential(String authorizationHeader) {
    final Pattern BEARER_AUTH_EXTRACTOR_PATTERN = Pattern.compile("bearer (.*)", Pattern.CASE_INSENSITIVE);

    if (isBlank(authorizationHeader)) {
        return null;
    }

    final Matcher matcher = BEARER_AUTH_EXTRACTOR_PATTERN.matcher(authorizationHeader);
    if (matcher.matches()) {
        String token = matcher.group(1);
        AccessToken accessToken = accessTokenService.findByAccessToken(token);
        return new AccessTokenCredential(accessToken);
    }

    return null;
}
 
Example #12
Source Project: baleen   Author: dstl   File: Custom.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void doProcessTextBlock(TextBlock block) throws AnalysisEngineProcessException {
  String text = block.getCoveredText();

  Matcher m = p.matcher(text);
  while (m.find()) {
    Entity ret;
    try {
      ret = block.newAnnotation(et, m.start(), m.end());
    } catch (Exception e) {
      throw new AnalysisEngineProcessException(e);
    }

    ret.setValue(m.group(patternGroup));

    ret.setConfidence(confidence);
    if (!Strings.isNullOrEmpty(subType)) {
      ret.setSubType(subType);
    }

    addToJCasIndex(ret);
  }
}
 
Example #13
Source Project: Much-Assembly-Required   Author: simon987   File: Assembler.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Check for labels in a line and save it
 *
 * @param line          Line to check
 * @param result        Current assembly result
 * @param currentOffset Current offset in bytes
 */
private static void checkForLabel(String line, AssemblyResult result, char currentOffset) {

    line = removeComment(line);

    //Check for labels
    Pattern pattern = Pattern.compile(labelPattern);
    Matcher matcher = pattern.matcher(line);

    if (matcher.find()) {
        String label = matcher.group(0).substring(0, matcher.group(0).length() - 1).trim();

        LogManager.LOGGER.fine("DEBUG: Label " + label + " @ " + (result.origin + currentOffset));
        result.labels.put(label, (char) (result.origin + currentOffset));
    }
}
 
Example #14
Source Project: amazon-mws-orders   Author: integration-technology   File: MwsUtl.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Replace a pattern in a string.
 * <p>
 * Do not do recursive replacement. Return the original string if no changes
 * are required.
 * 
 * @param s
 *            The string to search.
 * 
 * @param p
 *            The pattern to search for.
 * 
 * @param r
 *            The string to replace occurrences with.
 * 
 * @return The new string.
 */
static String replaceAll(String s, Pattern p, String r) {
    int n = s == null ? 0 : s.length();
    if (n == 0) {
        return s;
    }
    Matcher m = p.matcher(s);
    if (!m.find()) {
        return s;
    }
    StringBuilder buf = new StringBuilder(n + 12);
    int k = 0;
    do {
        buf.append(s, k, m.start());
        buf.append(r);
        k = m.end();
    } while (m.find());
    if (k < n) {
        buf.append(s, k, n);
    }
    return buf.toString();
}
 
Example #15
Source Project: spork   Author: sigmoidanalytics   File: RegExLoader.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Tuple getNext() throws IOException {
  Pattern pattern = getPattern();
  Matcher matcher = pattern.matcher("");
  TupleFactory mTupleFactory = DefaultTupleFactory.getInstance();
  String line;
  
  while (in.nextKeyValue()) {
 Text val = in.getCurrentValue();
    line = val.toString();
    if (line.length() > 0 && line.charAt(line.length() - 1) == '\r') {
      line = line.substring(0, line.length() - 1);
    }
    matcher = matcher.reset(line);
    ArrayList<DataByteArray> list = new ArrayList<DataByteArray>();
    if (matcher.find()) {
      for (int i = 1; i <= matcher.groupCount(); i++) {
        list.add(new DataByteArray(matcher.group(i)));
      }
      return mTupleFactory.newTuple(list);  
    }
  }
  return null;
}
 
Example #16
Source Project: xdm   Author: subhra74   File: UpdateChecker.java    License: GNU General Public License v2.0 6 votes vote down vote up
private static boolean isNewerVersion(StringBuilder text, String v2) {
	try {
		// System.out.println(text);
		Matcher matcher = PATTERN_TAG.matcher(text);
		if (matcher.find()) {
			String v1 = matcher.group(1);
			System.out.println(v1 + " " + v2);
			if (v1.indexOf(".") > 0 && v2.indexOf(".") > 0) {
				String[] arr1 = v1.split("\\.");
				String[] arr2 = v2.split("\\.");
				for (int i = 0; i < Math.min(arr1.length,
						arr2.length); i++) {
					int ia = Integer.parseInt(arr1[i]);
					int ib = Integer.parseInt(arr2[i]);
					if (ia > ib) {
						return true;
					}
				}
			}
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
	return false;
}
 
Example #17
Source Project: signal-bot   Author: aaronetz   File: HebrewDiceRollResponder.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public String getResponse(String messageText) {
    Matcher matcher = DICE_ROLL_PATTERN.matcher(messageText);
    if (matcher.matches()) {
        int numDice = Math.min(Integer.parseInt(matcher.group("dice")), MAX_DICE);
        int numSides = Math.min(Integer.parseInt(matcher.group("sides")), MAX_SIDES);
        String flag = matcher.group("flag");
        boolean sorted = flag != null && flag.equalsIgnoreCase("מ");
        IntStream randoms = RANDOM.ints(numDice, 1, numSides + 1);
        if (sorted) {
            randoms = randoms.sorted();
        }
        String randomString = randoms.mapToObj(String::valueOf).collect(Collectors.joining(", ", "[", "]"));
        return String.format("%dק%d: %s", numDice, numSides, randomString);
    }
    return null;
}
 
Example #18
Source Project: MHViewer   Author: axlecho   File: GalleryPageUrlParser.java    License: Apache License 2.0 6 votes vote down vote up
@Nullable
public static Result parse(String url, boolean strict) {
    if (url == null) {
        return null;
    }

    Pattern pattern = strict ? URL_STRICT_PATTERN : URL_PATTERN;
    Matcher m = pattern.matcher(url);
    if (m.find()) {
        Result result = new Result();
        result.gid = NumberUtils.parseLongSafely(m.group(2), -1L);
        result.pToken = m.group(1);
        result.page = NumberUtils.parseIntSafely(m.group(3), 0) - 1;
        if (result.gid < 0 || result.page < 0) {
            return null;
        }
        return result;
    } else {
        return null;
    }
}
 
Example #19
Source Project: school_shop   Author: Owater   File: SmileUtils.java    License: MIT License 6 votes vote down vote up
/**
 * replace existing spannable with smiles
 * @param context
 * @param spannable
 * @return
 */
public static boolean addSmiles(Context context, Spannable spannable) {
    boolean hasChanges = false;
    for (Entry<Pattern, Integer> entry : emoticons.entrySet()) {
        Matcher matcher = entry.getKey().matcher(spannable);
        while (matcher.find()) {
            boolean set = true;
            for (ImageSpan span : spannable.getSpans(matcher.start(),
                    matcher.end(), ImageSpan.class))
                if (spannable.getSpanStart(span) >= matcher.start()
                        && spannable.getSpanEnd(span) <= matcher.end())
                    spannable.removeSpan(span);
                else {
                    set = false;
                    break;
                }
            if (set) {
                hasChanges = true;
                spannable.setSpan(new ImageSpan(context, entry.getValue()),
                        matcher.start(), matcher.end(),
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
    }
    return hasChanges;
}
 
Example #20
Source Project: gecco   Author: xtuhcy   File: UrlMatcher.java    License: MIT License 6 votes vote down vote up
public static String replaceRegexs(String srcUrl, String regex, Map<String, String> params) {
	if(params == null) {
		return srcUrl;
	}
	StringBuffer sb = new StringBuffer();
	Pattern pattern = Pattern.compile(regex);
	Matcher matcher = pattern.matcher(srcUrl);
	while(matcher.find()) {
		String name = matcher.group(1);
		String value = params.get(name);
		if(StringUtils.isNotEmpty(value)) {
			matcher.appendReplacement(sb, value);
		}
	}
	matcher.appendTail(sb);
	return sb.toString();
}
 
Example #21
Source Project: hop   Author: project-hop   File: ActionEvalFilesMetrics.java    License: Apache License 2.0 6 votes vote down vote up
/**********************************************************
 *
 * @param selectedfile
 * @param wildcard
 * @return True if the selectedfile matches the wildcard
 **********************************************************/
private boolean GetFileWildcard( String selectedfile, String wildcard ) {
  Pattern pattern = null;
  boolean getIt = true;

  if ( !Utils.isEmpty( wildcard ) ) {
    pattern = Pattern.compile( wildcard );
    // First see if the file matches the regular expression!
    if ( pattern != null ) {
      Matcher matcher = pattern.matcher( selectedfile );
      getIt = matcher.matches();
    }
  }

  return getIt;
}
 
Example #22
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: RunExamples.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
void showFile(Example e, File f) {
    out.println("--- " + f);
    String text;
    try {
        text = read(f);
    } catch (IOException ex) {
        text = "Error reading " + f + "; " + ex;
    }
    Matcher m = copyrightHeaderPat.matcher(text);
    if (m.matches()) {
        out.println("(Copyright)");
        writeLines(m.group(2));
    } else {
        writeLines(text);
    }
    out.println();
}
 
Example #23
Source Project: Mobike   Author: yiwent   File: CommonUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 判断电话号码是否有效
 *
 * @param phoneNumber
 * @return true 有效 / false 无效
 */
public static boolean isPhoneNumberValid(String phoneNumber) {

    boolean isValid = false;

    String expression = "((^(13|15|18)[0-9]{9}$)|(^0[1,2]{1}\\d{1}-?\\d{8}$)|(^0[3-9] {1}\\d{2}-?\\d{7,8}$)|(^0[1,2]{1}\\d{1}-?\\d{8}-(\\d{1,4})$)|(^0[3-9]{1}\\d{2}-? \\d{7,8}-(\\d{1,4})$))";
    CharSequence inputStr = phoneNumber;

    Pattern pattern = Pattern.compile(expression);
    Matcher matcher = pattern.matcher(inputStr);

    if (matcher.matches()) {
        isValid = true;
    }
    return isValid;
}
 
Example #24
Source Project: quarkus   Author: quarkusio   File: CertificateHelper.java    License: Apache License 2.0 6 votes vote down vote up
public static TrustManager[] createTrustManagers(String cacert) throws GeneralSecurityException, IOException {

        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");

        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null);

        String certBundle = new String(Files.readAllBytes(Paths.get(cacert)), StandardCharsets.UTF_8);
        int start = 0;
        int count = 0;
        Matcher matcher = certBundlePattern.matcher(certBundle);

        while (matcher.find(start)) {
            ByteArrayInputStream inStream = new ByteArrayInputStream(matcher.group().getBytes(StandardCharsets.UTF_8));
            X509Certificate certificate = (X509Certificate) certificateFactory.generateCertificate(inStream);
            keyStore.setCertificateEntry("cert_" + count++, certificate);
            start = matcher.end();
        }

        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(getDefaultAlgorithm());
        trustManagerFactory.init(keyStore);
        return trustManagerFactory.getTrustManagers();
    }
 
Example #25
Source Project: roboconf-platform   Author: roboconf   File: ModelUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Gets and splits exported variables separated by a comma.
 * <p>
 * Variable names are not prefixed by the type's name.<br />
 * Variable values may also be surrounded by quotes.
 * </p>
 *
 * @param exportedVariablesDecl the declaration to parse
 * @param sourceFile the source file
 * @param lineNumber the line number
 * @return a non-null map (key = exported variable name, value = the exported variable)
 */
public static Map<String,ExportedVariable> findExportedVariables( String exportedVariablesDecl, File sourceFile, int lineNumber ) {

	Map<String,ExportedVariable> result = new HashMap<> ();
	Pattern pattern = Pattern.compile( ParsingConstants.PROPERTY_GRAPH_RANDOM_PATTERN, Pattern.CASE_INSENSITIVE );
	ExportedVariablesParser exportsParser = new ExportedVariablesParser();
	exportsParser.parse( exportedVariablesDecl, sourceFile, lineNumber );

	for( Map.Entry<String,String> entry : exportsParser.rawNameToVariables.entrySet()) {
		ExportedVariable var = new ExportedVariable();
		String variableName = entry.getKey();

		Matcher m = pattern.matcher( variableName );
		if( m.matches()) {
			var.setRandom( true );
			var.setRawKind( m.group( 1 ));
			variableName = m.group( 2 ).trim();
		}

		var.setName( variableName );
		var.setValue( entry.getValue());
		result.put( var.getName(), var );
	}

	return result;
}
 
Example #26
Source Project: buck   Author: facebook   File: AndroidBinaryRDotJavaIntegrationTest.java    License: Apache License 2.0 6 votes vote down vote up
private void verifyTrimmedRDotJava(ImmutableSet<String> expected) throws IOException {
  List<String> lines =
      filesystem.readLines(
          BuildTargetPaths.getGenPath(
                  filesystem,
                  BuildTargetFactory.newInstance("//apps/multidex:disassemble_app_r_dot_java"),
                  "%s")
              .resolve("all_r_fields.smali"));

  ImmutableSet.Builder<String> found = ImmutableSet.builder();
  for (String line : lines) {
    Matcher m = SMALI_STATIC_FINAL_INT_PATTERN.matcher(line);
    assertTrue("Could not match line: " + line, m.matches());
    assertThat(m.group(1), IsIn.in(expected));
    found.add(m.group(1));
  }
  assertEquals(expected, found.build());
}
 
Example #27
Source Project: ripme   Author: RipMeApp   File: BcfakesRipper.java    License: MIT License 6 votes vote down vote up
@Override
public String getGID(URL url) throws MalformedURLException {
    Pattern p;
    Matcher m;

    p = Pattern.compile("^https?://[wm.]*bcfakes.com/celebritylist/([a-zA-Z0-9\\-_]+).*$");
    m = p.matcher(url.toExternalForm());
    if (m.matches()) {
        return m.group(1);
    }

    throw new MalformedURLException(
            "Expected bcfakes gallery format: "
                    + "http://www.bcfakes.com/celebritylist/name"
                    + " Got: " + url);
}
 
Example #28
Source Project: datacollector   Author: streamsets   File: YARNStatusParser.java    License: Apache License 2.0 6 votes vote down vote up
public String parseStatus(Collection<String> lines) {
  for (String line : lines) {
    for (Pattern pattern : PATTERNS) {
      Matcher matcher = pattern.matcher(line);
      if (matcher.matches()) {
        String input = matcher.group(1);
        String output = Strings.nullToEmpty(STATE_MAP.get(input));
        if (!output.isEmpty()) {
          return output;
        }
      }
    }
  }
  String msg = "Could not match any YARN status";
  LOG.error(msg + ":" + Joiner.on("\n").join(lines));
  throw new IllegalStateException(msg + ". See logs.");
}
 
Example #29
Source Project: unitime   Author: UniTime   File: EventsExportEventsToJSON.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void print(ExportHelper helper, EventLookupRpcRequest request, List<EventInterface> events, int eventCookieFlags, EventMeetingSortBy sort, boolean asc) throws IOException {
	helper.setup("application/json", reference(), false);
	
   	Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new JsonSerializer<Date>() {
		@Override
		public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
			return new JsonPrimitive(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(src));
		}
	})
	.setFieldNamingStrategy(new FieldNamingStrategy() {
		Pattern iPattern = Pattern.compile("i([A-Z])(.*)");
		@Override
		public String translateName(Field f) {
			Matcher matcher = iPattern.matcher(f.getName());
			if (matcher.matches())
				return matcher.group(1).toLowerCase() + matcher.group(2);
			else
				return f.getName();
		}
	})
	.setPrettyPrinting().create();
   	
   	helper.getWriter().write(gson.toJson(events));
}
 
Example #30
Source Project: journaldev   Author: journaldev   File: RegexExamples.java    License: MIT License 6 votes vote down vote up
public static void main(String[] args) {
	// using pattern with flags
	Pattern pattern = Pattern.compile("ab", Pattern.CASE_INSENSITIVE);
	Matcher matcher = pattern.matcher("ABcabdAb");
	// using Matcher find(), group(), start() and end() methods
	while (matcher.find()) {
		System.out.println("Found the text \"" + matcher.group()
				+ "\" starting at " + matcher.start()
				+ " index and ending at index " + matcher.end());
	}

	// using Pattern split() method
	pattern = Pattern.compile("\\W");
	String[] words = pattern.split("[email protected]#three:four$five");
	for (String s : words) {
		System.out.println("Split using Pattern.split(): " + s);
	}

	// using Matcher.replaceFirst() and replaceAll() methods
	pattern = Pattern.compile("1*2");
	matcher = pattern.matcher("11234512678");
	System.out.println("Using replaceAll: " + matcher.replaceAll("_"));
	System.out.println("Using replaceFirst: " + matcher.replaceFirst("_"));
	System.out.println(Pattern.quote("^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"));
}