Package it.halfone.parser.token.impl

Source Code of it.halfone.parser.token.impl.RegexReferenceParser

/**
*
*/
package it.halfone.parser.token.impl;

import it.halfone.exception.InvalidDocumentException;
import it.halfone.hava.container.Context;
import it.halfone.parser.token.TokenParser;
import it.halfone.regex.Regex;

import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
* RegexReferenceParser - 03/ott/2011
*
* @author Andrea La Rosa
*/
public class RegexReferenceParser implements TokenParser {

  private static final Pattern pattern = Pattern.compile("^.*?([a-zA-Z]\\w*).*$");

  /*
   * (non-Javadoc)
   *
   * @see it.halfone.parser.token.TokenParser#parseToken(it.halfone.hava.Context)
   */
  @Override
  public boolean parseToken(Context ctx) throws InvalidDocumentException {
    boolean retVal;
    String ruleName = ctx.getValue("ruleName");
    int index = ctx.getValue("index");
    String token = ctx.getValue("token");
    List<Regex> regexList = ctx.getValue("regexList");
    Map<String, Regex> existingRuleMap = ctx.getValue("existingRule");

    Matcher matcher = pattern.matcher(token);
    if (retVal = matcher.find()) {
      token = token.replaceFirst("([a-zA-Z]\\w*)", TokenParser.ID + index);
      if (matcher.group(1).equals(ruleName)) {
        regexList.add(Regex.self());
      } else {
        if (existingRuleMap.get(matcher.group(1)) == null) {
          throw new InvalidDocumentException("No rule with id " + matcher.group(1));
        }
        regexList.add(existingRuleMap.get(matcher.group(1)));
      }
      ctx.setValue("token", token);
      ctx.setValue("index", ++index);
    }

    return retVal;
  }

}
TOP

Related Classes of it.halfone.parser.token.impl.RegexReferenceParser

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.