Java Code Examples for java.util.regex.PatternSyntaxException

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project chukwa, under directory /src/main/java/org/apache/hadoop/chukwa/datacollection/writer/.

Source file: SocketTeeWriter.java

  20 
vote

/** 
 * initializes the tee.
 */
public void setup(){
  try {
    try {
      sock.setSoTimeout(timeout);
      sock.setKeepAlive(USE_KEEPALIVE);
      in=new BufferedReader(new InputStreamReader(sock.getInputStream()));
      out=new DataOutputStream(sock.getOutputStream());
      String cmd=in.readLine();
      if (!cmd.contains(" ")) {
        throw new PatternSyntaxException("command should be keyword pattern, but no ' ' seen",cmd,-1);
      }
      String uppercased=cmd.substring(0,cmd.indexOf(' ')).toUpperCase();
      if (RAW.equals(uppercased))       fmt=DataFormat.Raw;
 else       if (WRITABLE.equals(uppercased))       fmt=DataFormat.Writable;
 else       if (ASCII_HEADER.equals(uppercased))       fmt=DataFormat.Header;
 else {
        throw new PatternSyntaxException("bad command '" + uppercased + "' -- starts with neither '"+ RAW+ "' nor '"+ WRITABLE+ " nor "+ ASCII_HEADER+ "'.",cmd,-1);
      }
      String cmdAfterSpace=cmd.substring(cmd.indexOf(' ') + 1);
      if (cmdAfterSpace.toLowerCase().equals("all"))       rules=Filter.ALL;
 else       rules=new Filter(cmdAfterSpace);
synchronized (tees) {
        tees.add(this);
      }
      out.write("OK\n".getBytes());
      log.info("tee to " + sock.getInetAddress() + " established");
    }
 catch (    PatternSyntaxException e) {
      out.write(e.toString().getBytes());
      out.writeByte('\n');
      out.close();
      in.close();
      sock.close();
      log.warn(e);
    }
  }
 catch (  IOException e) {
    log.warn(e);
  }
}
 

Example 2

From project HiTune_1, under directory /chukwa-hitune-dist/src/java/org/apache/hadoop/chukwa/datacollection/writer/.

Source file: SocketTeeWriter.java

  20 
vote

/** 
 * initializes the tee.
 */
public void setup(){
  try {
    try {
      sock.setSoTimeout(timeout);
      sock.setKeepAlive(USE_KEEPALIVE);
      in=new BufferedReader(new InputStreamReader(sock.getInputStream()));
      out=new DataOutputStream(sock.getOutputStream());
      String cmd=in.readLine();
      if (!cmd.contains(" ")) {
        throw new PatternSyntaxException("command should be keyword pattern, but no ' ' seen",cmd,-1);
      }
      String uppercased=cmd.substring(0,cmd.indexOf(' ')).toUpperCase();
      if (RAW.equals(uppercased))       fmt=DataFormat.Raw;
 else       if (WRITABLE.equals(uppercased))       fmt=DataFormat.Writable;
 else       if (ASCII_HEADER.equals(uppercased))       fmt=DataFormat.Header;
 else {
        throw new PatternSyntaxException("bad command '" + uppercased + "' -- starts with neither '"+ RAW+ "' nor '"+ WRITABLE+ " nor "+ ASCII_HEADER+ "'.",cmd,-1);
      }
      String cmdAfterSpace=cmd.substring(cmd.indexOf(' ') + 1);
      if (cmdAfterSpace.toLowerCase().equals("all"))       rules=Filter.ALL;
 else       rules=new Filter(cmdAfterSpace);
synchronized (tees) {
        tees.add(this);
      }
      out.write("OK\n".getBytes());
      log.info("tee to " + sock.getInetAddress() + " established");
    }
 catch (    PatternSyntaxException e) {
      out.write(e.toString().getBytes());
      out.writeByte('\n');
      out.close();
      in.close();
      sock.close();
      log.warn(e);
    }
  }
 catch (  IOException e) {
    log.warn(e);
  }
}
 

Example 3

From project james, under directory /data-library/src/main/java/org/apache/james/rrt/lib/.

Source file: RecipientRewriteTableUtil.java

  20 
vote

/** 
 * Processes regex virtual user mapping If a mapped target string begins with the prefix regex:, it must be formatted as regex:<regular-expression>:<parameterized-string>, e.g., regex:(.*)@(.*):${1}@tld
 * @param address the MailAddress to be mapped
 * @param targetString a String specifying the mapping
 * @throws MalformedPatternException
 */
public static String regexMap(MailAddress address,String targetString){
  String result=null;
  int identifierLength=RecipientRewriteTable.REGEX_PREFIX.length();
  int msgPos=targetString.indexOf(':',identifierLength + 1);
  if (msgPos < identifierLength + 1)   throw new PatternSyntaxException("Regex should be formatted as regex:<regular-expression>:<parameterized-string>",targetString,0);
  Pattern pattern=Pattern.compile(targetString.substring(identifierLength,msgPos));
  Matcher match=pattern.matcher(address.toString());
  if (match.matches()) {
    Map<String,String> parameters=new HashMap<String,String>(match.groupCount());
    for (int i=1; i < match.groupCount(); i++) {
      parameters.put(Integer.toString(i),match.group(i));
    }
    result=replaceParameters(targetString.substring(msgPos + 1),parameters);
  }
  return result;
}
 

Example 4

From project SPaTo_Visual_Explorer, under directory /src/net/spato/sve/app/.

Source file: SPaToGUI.java

  20 
vote

public void updateSearchMatches(){
  SPaToDocument doc=app.workspace.doc;
  searchMsg=null;
  searchUniqueMatch=-1;
  if ((doc == null) || !doc.view.hasNodes)   return;
  String searchPhrase=tfSearch.getText();
  if (searchPhrase.length() == 0) {
    searchMatches=null;
    return;
  }
  if (searchMatches == null) {
    searchMatches=new boolean[doc.view.NN];
    searchMatchesChild=new int[doc.view.NN];
  }
  if (btnRegexpSearch.isSelected()) {
    try {
      Pattern p=Pattern.compile(searchPhrase);
      if (p.matcher("").find())       throw new PatternSyntaxException("Expression matches empty string",searchPhrase,-1);
      for (int i=0; i < doc.view.NN; i++)       searchMatches[i]=p.matcher(doc.view.nodes[i].label).find() || p.matcher(doc.view.nodes[i].name).find();
    }
 catch (    PatternSyntaxException e) {
      searchMsg="E" + e.getDescription();
      if (e.getIndex() > -1)       searchMsg+=": " + e.getPattern().substring(0,e.getIndex());
    }
  }
 else {
    boolean caseSensitive=!searchPhrase.equals(searchPhrase.toLowerCase());
    for (int i=0; i < doc.view.NN; i++)     searchMatches[i]=(caseSensitive ? doc.view.nodes[i].label.contains(searchPhrase) : doc.view.nodes[i].label.toLowerCase().contains(searchPhrase)) || (caseSensitive ? doc.view.nodes[i].name.contains(searchPhrase) : doc.view.nodes[i].name.toLowerCase().contains(searchPhrase));
  }
  searchMatchesValid=true;
  for (int i=0; i < doc.view.NN; i++)   if (searchMatches[i])   if (searchUniqueMatch == -1)   searchUniqueMatch=i;
 else {
    searchUniqueMatch=-1;
    break;
  }
  if (searchUniqueMatch > -1)   searchMsg="M" + doc.view.nodes[searchUniqueMatch].name;
}
 

Example 5

From project AdminCmd, under directory /src/main/java/be/Balor/Manager/.

Source file: LocaleManager.java

  19 
vote

private String recursiveReplaceLocale(final String locale,final Map<String,String> values){
  String ResultString=null;
  String result=locale;
  try {
    Matcher regexMatcher=recursiveLocale.matcher(locale);
    while (regexMatcher.find()) {
      ResultString=regexMatcher.group(1);
      final String recLocale=getLocale(ResultString);
      if (recLocale != null) {
        result=regexMatcher.replaceFirst(recLocale);
      }
 else {
        result=regexMatcher.replaceFirst("");
      }
      regexMatcher=recursiveLocale.matcher(result);
    }
    regexMatcher=replaceLocale.matcher(result);
    while (regexMatcher.find()) {
      ResultString=regexMatcher.group(1);
      final String replaceValue=values.get(ResultString);
      if (replaceValue != null) {
        try {
          result=regexMatcher.replaceFirst(Matcher.quoteReplacement(replaceValue));
        }
 catch (        final StringIndexOutOfBoundsException e) {
          result=regexMatcher.replaceFirst(replaceValue.replaceAll("\\W",""));
        }
      }
 else {
        result=regexMatcher.replaceFirst("");
      }
      regexMatcher=replaceLocale.matcher(result);
    }
  }
 catch (  final PatternSyntaxException ex) {
  }
  final Matcher regexMatcher=buggedLocale.matcher(result);
  result=regexMatcher.replaceAll("?$1");
  return result;
}
 

Example 6

From project any23, under directory /plugins/basic-crawler/src/main/java/org/apache/any23/cli/.

Source file: Crawler.java

  19 
vote

@Override public Pattern convert(String value){
  try {
    return Pattern.compile(value);
  }
 catch (  PatternSyntaxException pse) {
    throw new ParameterException(format("Invalid page filter, '%s' must be a regular expression.",value));
  }
}
 

Example 7

From project autopsy, under directory /KeywordSearch/src/org/sleuthkit/autopsy/keywordsearch/.

Source file: KeywordSearchEditListPanel.java

  19 
vote

private void addWordButtonActionPerformed(java.awt.event.ActionEvent evt){
  String newWord=addWordField.getText().trim();
  boolean isLiteral=!chRegex.isSelected();
  final Keyword keyword=new Keyword(newWord,isLiteral);
  if (!isLiteral) {
    int selI=this.selectorsCombo.getSelectedIndex();
    if (selI < this.selectorsCombo.getItemCount() - 1) {
      BlackboardAttribute.ATTRIBUTE_TYPE selector=BlackboardAttribute.ATTRIBUTE_TYPE.values()[selI];
      keyword.setType(selector);
    }
  }
  if (newWord.equals("")) {
    return;
  }
 else   if (currentKeywordList.hasKeyword(keyword)) {
    KeywordSearchUtil.displayDialog("New Keyword Entry","Keyword already exists in the list.",KeywordSearchUtil.DIALOG_MESSAGE_TYPE.INFO);
    return;
  }
  boolean valid=true;
  try {
    Pattern.compile(newWord);
  }
 catch (  PatternSyntaxException ex1) {
    valid=false;
  }
catch (  IllegalArgumentException ex2) {
    valid=false;
  }
  if (!valid) {
    KeywordSearchUtil.displayDialog("New Keyword Entry","Invalid keyword pattern.  Use words or a correct regex pattern.",KeywordSearchUtil.DIALOG_MESSAGE_TYPE.ERROR);
    return;
  }
  tableModel.addKeyword(keyword);
  KeywordSearchListsXML.getCurrent().addList(currentKeywordList);
  chRegex.setSelected(false);
  addWordField.setText("");
  initButtons();
}
 

Example 8

From project BMach, under directory /src/jsyntaxpane/actions/.

Source file: DocumentSearchData.java

  19 
vote

/** 
 * Sets the pattern from a string and flags
 * @param pat String of pattern
 * @param regex true if the pattern should be a regexp
 * @param ignoreCase true to ignore case
 * @throws java.util.regex.PatternSyntaxException
 */
public void setPattern(String pat,boolean regex,boolean ignoreCase) throws PatternSyntaxException {
  if (pat != null && pat.length() > 0) {
    int flag=(regex) ? 0 : Pattern.LITERAL;
    flag|=(ignoreCase) ? Pattern.CASE_INSENSITIVE : 0;
    setPattern(Pattern.compile(pat,flag));
  }
 else {
    setPattern(null);
  }
}
 

Example 9

From project capedwarf-green, under directory /validation-api/src/main/java/org/jboss/capedwarf/validation/api/.

Source file: PatternConstraintValidator.java

  19 
vote

protected Pattern createPattern(javax.validation.constraints.Pattern parameters){
  javax.validation.constraints.Pattern.Flag flags[]=parameters.flags();
  int intFlag=0;
  for (  javax.validation.constraints.Pattern.Flag flag : flags) {
    intFlag=intFlag | flag.getValue();
  }
  try {
    return java.util.regex.Pattern.compile(parameters.regexp(),intFlag);
  }
 catch (  PatternSyntaxException e) {
    throw new IllegalArgumentException("Invalid regular expression.",e);
  }
}
 

Example 10

From project cdh-mapreduce-ext, under directory /src/main/java/org/apache/hadoop/mapreduce/lib/input/.

Source file: SequenceFileInputFilter.java

  19 
vote

/** 
 * Define the filtering regex and stores it in conf
 * @param conf where the regex is set
 * @param regex regex used as a filter
 */
public static void setPattern(Configuration conf,String regex) throws PatternSyntaxException {
  try {
    Pattern.compile(regex);
  }
 catch (  PatternSyntaxException e) {
    throw new IllegalArgumentException("Invalid pattern: " + regex);
  }
  conf.set(FILTER_REGEX,regex);
}
 

Example 11

From project ceres, under directory /ceres-binding/src/main/java/com/bc/ceres/binding/converters/.

Source file: PatternConverter.java

  19 
vote

@Override public Pattern parse(String text) throws ConversionException {
  if (text.isEmpty()) {
    return null;
  }
  try {
    return Pattern.compile(text);
  }
 catch (  PatternSyntaxException e) {
    throw new ConversionException(e.getMessage(),e);
  }
}
 

Example 12

From project clearcase-plugin, under directory /src/main/java/hudson/plugins/clearcase/.

Source file: ClearCaseSCM.java

  19 
vote

/** 
 * Validates the excludedRegions Regex
 */
public FormValidation doExcludedRegionsCheck(@QueryParameter final String value) throws IOException, ServletException {
  String v=fixEmptyAndTrim(value);
  if (v != null) {
    String[] regions=v.split("[\\r\\n]+");
    for (    String region : regions) {
      try {
        Pattern.compile(region);
      }
 catch (      PatternSyntaxException e) {
        return FormValidation.error("Invalid regular expression. " + e.getMessage());
      }
    }
  }
  return FormValidation.ok();
}
 

Example 13

From project cloudify, under directory /USM/src/main/java/org/cloudifysource/usm/launcher/.

Source file: DefaultProcessLauncher.java

  19 
vote

private List<String> lookUpCommandLineForOS(final Map<String,ExecutableDSLEntry> map,final String os){
  final Set<Entry<String,ExecutableDSLEntry>> entries=map.entrySet();
  for (  final Entry<String,ExecutableDSLEntry> entry : entries) {
    final String key=entry.getKey();
    final ExecutableDSLEntry value=entry.getValue();
    try {
      if (Pattern.matches(key,os)) {
        return getCommandLineFromValue(value);
      }
    }
 catch (    final PatternSyntaxException pse) {
      logger.log(Level.WARNING,"Opeating System regular expression pattern: " + key + " cannot be compiled. It will me compared using basic string matching.",pse);
      if (key.equals(os)) {
        return getCommandLineFromValue(value);
      }
    }
  }
  return null;
}
 

Example 14

From project components, under directory /common/common/src/main/java/org/switchyard/component/common/composer/.

Source file: BaseRegexContextMapper.java

  19 
vote

private void setPatternList(String regexs,List<Pattern> patternList){
  Set<String> regexSet=Strings.uniqueSplitTrimToNull(regexs,",");
  List<Pattern> tmpList=new ArrayList<Pattern>();
  for (  String regex : regexSet) {
    try {
      Pattern pattern=Pattern.compile(regex);
      tmpList.add(pattern);
    }
 catch (    PatternSyntaxException pse) {
      throw new IllegalArgumentException("\"" + regex + "\" is not a valid regex pattern: "+ pse.getMessage());
    }
  }
synchronized (patternList) {
    patternList.clear();
    patternList.addAll(tmpList);
  }
}
 

Example 15

From project cotopaxi-core, under directory /src/main/java/br/octahedron/cotopaxi/controller/converter/.

Source file: StringArrayConverter.java

  19 
vote

@Override public String[] convert(String input){
  try {
    return input.split(this.separator);
  }
 catch (  PatternSyntaxException ex) {
    return null;
  }
}
 

Example 16

From project CsvEngine, under directory /src/main/java/fr/ybonnel/csvengine/validator/.

Source file: ValidatorRegExp.java

  19 
vote

@Override public void addParams(Map<String,String> params) throws InvalidParamException {
  super.addParams(params);
  if (!params.containsKey(PARAM_PATTERN)) {
    throw new InvalidParamException("The parameter \"" + PARAM_PATTERN + "\" is mandatory");
  }
  try {
    pattern=Pattern.compile(params.get(PARAM_PATTERN));
  }
 catch (  PatternSyntaxException exception) {
    throw new InvalidParamException("The parameter \"" + PARAM_PATTERN + "\" hasn't the good format",exception);
  }
}
 

Example 17

From project culvert, under directory /culvert-main/src/main/java/com/bah/culvert/data/index/.

Source file: TermBasedIndex.java

  19 
vote

/** 
 * This will construct the necessary row IDs to be inserted into the index table. Creates terms based on the configuration settings.
 * @param keyValue The CKeyValue to index.
 * @return List of CKeyValues corresponding to the different terms.
 * @throws RuntimeException If the record row ID length takes up more than 4bytes
 */
private List<CKeyValue> createTermList(CKeyValue keyValue) throws RuntimeException {
  boolean toSplit=getSplitable();
  boolean toLower=getToLower();
  String tokenRegex=getTokenRegex();
  String value=new String(keyValue.getValue(),Charset.forName("UTF-8"));
  if (toLower) {
    value=value.toLowerCase();
  }
  ArrayList<CKeyValue> indexKeyValueList=new ArrayList<CKeyValue>();
  byte[] recordTableRowId=keyValue.getRowId();
  if (toSplit) {
    try {
      String[] words=new String(value).split(tokenRegex);
      for (      String word : words) {
        byte[] indexRowId;
        indexRowId=createIndexRowId(Bytes.toBytes(word),recordTableRowId);
        indexKeyValueList.add(new CKeyValue(indexRowId));
      }
    }
 catch (    PatternSyntaxException e) {
      throw new RuntimeException("Invalid token regex for splitting terms.",e);
    }
  }
 else {
    byte[] indexRowId;
    indexRowId=createIndexRowId(Bytes.toBytes(value),recordTableRowId);
    indexKeyValueList.add(new CKeyValue(indexRowId));
  }
  return indexKeyValueList;
}
 

Example 18

From project cvs-plugin, under directory /src/main/java/hudson/scm/.

Source file: ExcludedRegion.java

  19 
vote

/** 
 * Validates the excludeRegions Regex
 */
public FormValidation doCheckPattern(@QueryParameter final String value){
  String v=fixNull(value).trim();
  try {
    Pattern.compile(v);
  }
 catch (  PatternSyntaxException e) {
    return FormValidation.error("Invalid regular expression. " + e.getMessage());
  }
  return FormValidation.ok();
}
 

Example 19

From project dawn-isencia, under directory /com.isencia.passerelle.actor/src/main/java/com/isencia/passerelle/actor/filter/.

Source file: HeaderFilter.java

  19 
vote

/** 
 * Checks whether the given item matches the given regular expression
 * @param item DOCUMENT ME!
 * @param expression DOCUMENT ME!
 * @return DOCUMENT ME!
 */
protected boolean matchesRegExp(String item,String expression){
  try {
    return Pattern.matches(expression,item);
  }
 catch (  PatternSyntaxException e) {
    logger.error("Syntax error in regular expression " + expression,e);
    return false;
  }
}
 

Example 20

From project dawn-isenciaui, under directory /com.isencia.passerelle.workbench.model.editor.ui/src/main/java/com/isencia/passerelle/workbench/model/editor/ui/descriptor/.

Source file: RegularExpressionDescriptor.java

  19 
vote

protected boolean isLegalExpression(String regexOrWildCardPattern){
  if (regexOrWildCardPattern == null || "".equals(regexOrWildCardPattern))   return false;
  if (param.isRegularExpression()) {
    try {
      Pattern.compile(regexOrWildCardPattern);
      return true;
    }
 catch (    PatternSyntaxException ne) {
      return false;
    }
  }
 else {
    return true;
  }
}
 

Example 21

From project Eclipse, under directory /com.mobilesorcery.sdk.capabilities.devices/src/com/mobilesorcery/sdk/capabilities/devices/internal/.

Source file: DeviceCapabilitiesParser.java

  19 
vote

private void addCapabilites(CapabilitiesMap capabilitiesMap,String matchingCriteria,Capabilities capabilities){
  if (matchingCriteria == null) {
    return;
  }
  try {
    if (matchingCriteria.startsWith("profile:")) {
      capabilitiesMap.addProfileCapability(Pattern.compile(matchingCriteria.substring("profile:".length())),capabilities);
    }
 else     if (matchingCriteria.startsWith("runtime:")) {
      capabilitiesMap.addRuntimeCapability(Pattern.compile(matchingCriteria.substring("runtime:".length())),capabilities);
    }
 else {
      capabilitiesMap.addRuntimeCapability(Pattern.compile(matchingCriteria),capabilities);
    }
  }
 catch (  PatternSyntaxException e) {
    CoreMoSyncPlugin.getDefault().log(e);
  }
}
 

Example 22

From project eclipse-integration-gradle, under directory /org.springsource.ide.eclipse.gradle.core/src/org/springsource/ide/eclipse/gradle/core/preferences/.

Source file: GradlePreferences.java

  19 
vote

/** 
 * Sets the WTP deployment exclusions. May throw an exception if the exclusion expression have syntax errors.
 */
public void setDeploymentExclusions(RegexpListDeploymentExclusions exclusions) throws PatternSyntaxException {
  exclusions.verify();
  RegexpListDeploymentExclusions current=getDeploymentExclusions();
  if (!current.equals(exclusions)) {
    putStrings(DEPLOYMENT_EXCLUSIONS,exclusions.getSourceExps());
  }
}
 

Example 23

From project erjang, under directory /src/main/java/erjang/m/re/.

Source file: Native.java

  19 
vote

@BIF static public ETuple2 compile(EObject obj1,EObject obj2){
  ESeq opts=obj2.testSeq();
  Options o=new Options();
  if (!o.init(opts)) {
    throw ERT.badarg(obj1,obj2);
  }
  String pattern=o.decode(obj1);
  try {
    Pattern c=Pattern.compile(pattern,o.flags);
    return new ETuple2(ERT.am_ok,new ECompiledRE(o,c));
  }
 catch (  PatternSyntaxException e) {
    return new ETuple2(ERT.am_error,new ETuple2(EString.fromString(e.getDescription()),ERT.box(e.getIndex())));
  }
}
 

Example 24

From project exo-router, under directory /src/test/java/org/exoplatform/ks/router/.

Source file: RegexTest.java

  19 
vote

public void testCompileFail() throws Exception {
  try {
    Pattern.compile("abc(jhds");
    fail();
  }
 catch (  PatternSyntaxException ex) {
  }
  try {
    Pattern.compile("abc)jhds");
    fail();
  }
 catch (  PatternSyntaxException ex) {
  }
  try {
    Pattern.compile("abc\\)jhds");
  }
 catch (  PatternSyntaxException ex) {
  }
}
 

Example 25

From project gatein-management, under directory /core/src/main/java/org/gatein/management/core/api/.

Source file: PathElement.java

  19 
vote

public static PathElement pathElement(String path) throws PatternSyntaxException {
  String replacedCurlySegment=replaceEnclosedCurlyBraces(path);
  String[] split=TEMPLATE_PARAM_PATTERN.split(replacedCurlySegment);
  Matcher withPathParam=TEMPLATE_PARAM_PATTERN.matcher(replacedCurlySegment);
  int i=0;
  StringBuilder buffer=new StringBuilder();
  if (i < split.length)   buffer.append(split[i++]);
  int groupNumber=1;
  List<Group> groups=new ArrayList<Group>();
  while (withPathParam.find()) {
    String name=withPathParam.group(1);
    buffer.append("(");
    if (withPathParam.group(3) == null) {
      buffer.append(TEMPLATE_PARAM_DEFAULT_REGEX);
      groups.add(new Group(name,groupNumber++));
    }
 else {
      String expr=withPathParam.group(3);
      expr=recoverEnclosedCurlyBraces(expr);
      buffer.append(expr);
      groups.add(new Group(name,groupNumber++));
      groupNumber+=groupCount(expr);
    }
    buffer.append(")");
    if (i < split.length)     buffer.append(split[i++]);
  }
  return new PathElement(path,groups,buffer.toString());
}
 

Example 26

From project gitblit, under directory /src/com/gitblit/utils/.

Source file: StringUtils.java

  19 
vote

/** 
 * Splits the string into a list of string by the specified separator.
 * @param value
 * @param separator
 * @return list of strings
 */
public static List<String> getStringsFromValue(String value,String separator){
  List<String> strings=new ArrayList<String>();
  try {
    String[] chunks=value.split(separator + "(?=([^\"]*\"[^\"]*\")*[^\"]*$)");
    for (    String chunk : chunks) {
      chunk=chunk.trim();
      if (chunk.length() > 0) {
        if (chunk.charAt(0) == '"' && chunk.charAt(chunk.length() - 1) == '"') {
          chunk=chunk.substring(1,chunk.length() - 1).trim();
        }
        strings.add(chunk);
      }
    }
  }
 catch (  PatternSyntaxException e) {
    throw new RuntimeException(e);
  }
  return strings;
}
 

Example 27

From project Grammar-Kit, under directory /support/org/intellij/grammar/generator/.

Source file: ParserGeneratorUtil.java

  19 
vote

@Nullable public static BnfExpression findAttributeValueNode(BnfAttrs attrs,String attrName,String ruleName){
  if (attrs == null)   return null;
  BnfExpression noPattern=null;
  for (  BnfAttr tree : attrs.getAttrList()) {
    if (attrName.equals(tree.getId().getText())) {
      BnfAttrPattern attrPattern=tree.getAttrPattern();
      BnfExpression attrValue=tree.getExpression();
      if (attrPattern == null) {
        noPattern=attrValue;
        if (ruleName == null)         break;
      }
 else       if (ruleName != null) {
        BnfLiteralExpression pattern=attrPattern.getLiteralExpression();
        try {
          if (pattern != null && Pattern.matches(StringUtil.stripQuotesAroundValue(pattern.getText()),ruleName)) {
            return attrValue;
          }
        }
 catch (        PatternSyntaxException e) {
        }
      }
    }
  }
  return ruleName != null && Pattern.matches(".*(_\\d+)+",ruleName) ? noPattern != null ? NULL_ATTR : null : noPattern;
}
 

Example 28

From project hadoop_framework, under directory /match/src/main/java/org/sleuthkit/hadoop/.

Source file: GrepMapper.java

  19 
vote

@Override public void setup(Context ctx){
  String[] regexlist=ctx.getConfiguration().get("mapred.mapper.regex").split("\n");
  for (  String item : regexlist) {
    if ("".equals(item))     continue;
    try {
      patterns.add(Pattern.compile(item));
    }
 catch (    PatternSyntaxException ex) {
      patterns.add(Pattern.compile("xxxINVALID_PATTERNxxx"));
      LOG.error("Bad regular expression: " + item,ex);
    }
  }
  super.setup(ctx);
}
 

Example 29

From project hibernate-validator, under directory /engine/src/main/java/org/hibernate/validator/internal/constraintvalidators/.

Source file: PatternValidator.java

  19 
vote

public void initialize(Pattern parameters){
  Pattern.Flag flags[]=parameters.flags();
  int intFlag=0;
  for (  Pattern.Flag flag : flags) {
    intFlag=intFlag | flag.getValue();
  }
  try {
    pattern=java.util.regex.Pattern.compile(parameters.regexp(),intFlag);
  }
 catch (  PatternSyntaxException e) {
    throw log.getInvalidRegularExpressionException(e);
  }
}
 

Example 30

From project ios-driver, under directory /server/src/main/java/org/uiautomation/ios/server/application/.

Source file: LanguageDictionary.java

  19 
vote

public boolean match(String content,String originalText){
  String normalizedContent=Normalizer.normalize(content,norme);
  String normalizedOriginalText=Normalizer.normalize(originalText,norme);
  String pattern=getRegexPattern(normalizedOriginalText);
  try {
    boolean regex=normalizedContent.matches(pattern);
    return regex;
  }
 catch (  PatternSyntaxException e) {
  }
  return false;
}
 

Example 31

From project ISAconfigurator, under directory /src/main/java/org/isatools/isacreatorconfigurator/configui/.

Source file: CheckRegExGUI.java

  19 
vote

public void mousePressed(MouseEvent event){
  if (event.getSource() == test) {
    try {
      Pattern pattern=Pattern.compile(regExp.getText());
      Matcher matcher=pattern.matcher(testCase.getText());
      if (matcher.matches()) {
        result.setText("Passed Regular Expression Test!");
        result.setForeground(UIHelper.DARK_GREEN_COLOR);
      }
 else {
        result.setText("Failed Regular Expression Test!");
        result.setForeground(Color.RED);
      }
    }
 catch (    PatternSyntaxException pse) {
      result.setText("Invalid pattern!!");
      result.setForeground(Color.RED);
    }
  }
}
 

Example 32

From project ISAcreator, under directory /src/main/java/org/isatools/isacreator/common/.

Source file: RegExFormatter.java

  19 
vote

public RegExFormatter(String pattern,JFormattedTextField dce,boolean discardOnInvalid,Color foreground,Color warningForeground,Color background,Color warningBackground) throws PatternSyntaxException {
  this(pattern);
  this.dce=dce;
  this.discardOnInvalid=discardOnInvalid;
  this.foreground=foreground;
  this.warningForeground=warningForeground;
  this.backgound=background;
  this.warningBackground=warningBackground;
}
 

Example 33

From project jackrabbit-oak, under directory /oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/nodetype/constraint/.

Source file: StringConstraint.java

  19 
vote

public StringConstraint(String definition){
  Pattern p;
  try {
    p=Pattern.compile(definition);
  }
 catch (  PatternSyntaxException pse) {
    String msg='\'' + definition + "' is not valid regular expression syntax";
    log.warn(msg);
    p=null;
  }
  pattern=p;
}
 

Example 34

From project jboss-jsf-api_spec, under directory /src/main/java/javax/faces/validator/.

Source file: RegexValidator.java

  19 
vote

/** 
 * </p>Validate a String against a regular expression pattern.  The full regex pattern must be matched in order to pass the validation.</p>
 * @param context {@inheritDoc}
 * @param component {@inheritDoc}
 * @param value {@inheritDoc}
 * @throws NullPointerException {@inheritDoc}
 * @throws ValidatorException   {@inheritDoc}
 */
public void validate(FacesContext context,UIComponent component,Object value){
  if (context == null) {
    throw new NullPointerException();
  }
  if (component == null) {
    throw new NullPointerException();
  }
  if (value == null) {
    return;
  }
  FacesMessage fmsg;
  Locale locale=context.getViewRoot().getLocale();
  if (regex == null || regex.length() == 0) {
    fmsg=MessageFactory.getMessage(locale,PATTERN_NOT_SET_MESSAGE_ID,(Object)null);
    throw new ValidatorException(fmsg);
  }
  try {
    Pattern pattern=Pattern.compile(regex);
    Matcher matcher=pattern.matcher((String)value);
    if (!matcher.matches()) {
      Object[] params={regex};
      fmsg=MessageFactory.getMessage(locale,NOT_MATCHED_MESSAGE_ID,params);
      throw new ValidatorException(fmsg);
    }
  }
 catch (  PatternSyntaxException pse) {
    fmsg=MessageFactory.getMessage(locale,MATCH_EXCEPTION_MESSAGE_ID,(Object)null);
    throw new ValidatorException(fmsg,pse);
  }
}
 

Example 35

From project jftp, under directory /src/main/java/com/myjavaworld/jftp/.

Source file: LocalFileFilterDlg.java

  19 
vote

private boolean validateInput(){
  String error=null;
  Component errorComponent=null;
  try {
    getRegexFilter();
    getDateFilter();
  }
 catch (  PatternSyntaxException exp) {
    MessageFormat mf=new MessageFormat(resources.getString("error.pattern.invalid"));
    error=mf.format(new Object[]{exp.getMessage()});
    errorComponent=tfRegexFilter;
  }
catch (  ParseException exp) {
    MessageFormat mf=new MessageFormat(resources.getString("error.date.invalid"));
    error=mf.format(new Object[]{exp.getMessage()});
    errorComponent=tfStartDate;
  }
  if (error != null) {
    GUIUtil.showError(this,error);
    if (errorComponent != null) {
      errorComponent.requestFocusInWindow();
    }
    return false;
  }
  return true;
}
 

Example 36

From project jira-hudson-integration, under directory /hudson-apiv2-plugin/src/main/java/com/marvelution/hudson/plugins/apiv2/.

Source file: APIv2Plugin.java

  19 
vote

/** 
 * Web Method to validate a given  {@link Pattern}
 * @param value the {@link Pattern} to validate
 * @return validation result
 * @throws IOException in case of errors
 * @throws ServletException in case of errors
 */
public FormValidation doCheckPattern(@QueryParameter final String value) throws IOException, ServletException {
  if (!Hudson.getInstance().hasPermission(Hudson.ADMINISTER) || StringUtils.isBlank(value)) {
    return FormValidation.ok();
  }
  try {
    Pattern.compile(value);
    return FormValidation.ok();
  }
 catch (  PatternSyntaxException e) {
    StringBuilder builder=new StringBuilder(e.getDescription());
    if (e.getIndex() >= 0) {
      builder.append(" near index ").append(e.getIndex());
    }
    builder.append("<pre>");
    builder.append(e.getPattern()).append(System.getProperty("line.separator"));
    if (e.getIndex() >= 0) {
      for (int i=0; i < e.getIndex(); ++i) {
        builder.append(' ');
      }
      builder.append('^');
    }
    builder.append("</pre>");
    return FormValidation.errorWithMarkup(builder.toString());
  }
}
 

Example 37

From project JoshEdit, under directory /org/lateralgm/joshedit/.

Source file: QuickFind.java

  19 
vote

/** 
 * @see org.lateralgm.joshedit.FindDialog.FindNavigator#findNext()	 
 */
@Override public void findNext(){
  String ftext=tFind.getText();
  if (ftext.length() == 0)   return;
  if (FindDialog.regex.isSelected()) {
    Pattern p;
    try {
      p=Pattern.compile(ftext,Pattern.CASE_INSENSITIVE);
    }
 catch (    PatternSyntaxException pse) {
      System.out.println("Shit man, your expression sucks");
      return;
    }
    lastResult=joshText.code.findNext(p,joshText.caret.row,joshText.caret.col + (joshText.sel.isEmpty() ? 0 : 1));
    if (lastResult != null)     selectFind(lastResult);
    return;
  }
  String[] findme=ftext.split("\r?\n");
  lastResult=joshText.code.findNext(findme,joshText.caret.row,joshText.caret.col + (joshText.sel.isEmpty() ? 0 : 1));
  if (lastResult != null)   selectFind(lastResult);
  return;
}
 

Example 38

From project Jota-Text-Editor, under directory /src/jp/sblo/pandora/jota/.

Source file: Search.java

  19 
vote

public Search(Activity parent,String query,CharSequence text,boolean regexp,boolean ignoreCase,OnSearchFinishedListener listener){
  mData=new ArrayList<Record>();
  mQuery=query;
  mParent=parent;
  mText=text;
  mListener=listener;
  if (query != null && query.length() > 0) {
    String patternText=query;
    if (!regexp) {
      patternText=escapeMetaChar(patternText);
    }
    try {
      if (ignoreCase) {
        mPattern=Pattern.compile(patternText,Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE | Pattern.MULTILINE);
      }
 else {
        mPattern=Pattern.compile(patternText);
      }
      mTask=new SearchTask();
      mTask.execute();
    }
 catch (    PatternSyntaxException e) {
      Toast.makeText(parent,R.string.toast_syntax_error,Toast.LENGTH_LONG).show();
    }
  }
}
 

Example 39

From project jupload, under directory /src/wjhk/jupload2/policies/.

Source file: DefaultUploadPolicy.java

  19 
vote

/** 
 * @param stringUploadError the stringUploadError to set
 * @throws JUploadException
 */
protected void setStringUploadError(String stringUploadError) throws JUploadException {
  this.stringUploadError=stringUploadError;
  if (stringUploadError != null) {
    try {
      this.patternError=Pattern.compile(stringUploadError);
    }
 catch (    PatternSyntaxException e) {
      throw new JUploadException("Invalid regex in parameter stringUploadError");
    }
  }
}
 

Example 40

From project juzu, under directory /core/src/test/java/juzu/impl/router/regex/.

Source file: RegExpParserTestCase.java

  19 
vote

void parse(String s,boolean javaFail,boolean javaccFail){
  try {
    Pattern.compile(s);
    if (javaFail) {
      throw new AssertionFailedError("Was expecting " + s + " to not be compilable");
    }
  }
 catch (  PatternSyntaxException e) {
    if (!javaFail) {
      AssertionFailedError afe=new AssertionFailedError("Was expecting " + s + " to be compilable");
      afe.initCause(e);
      throw afe;
    }
  }
  try {
    CharStream stream=new CharStream(s);
    Lexer lexer=new Lexer(stream);
    REParser parser=new REParser(lexer);
    parser.parse();
    assertEquals(s.length(),stream.getIndex());
    if (lexer.hasNext()) {
      throw new SyntaxException();
    }
    if (javaccFail) {
      throw new AssertionFailedError("Was expecting " + s + " to not be compilable");
    }
  }
 catch (  SyntaxException e) {
    if (!javaccFail) {
      AssertionFailedError afe=new AssertionFailedError("Was expecting " + s + " to be compilable");
      afe.initCause(e);
      throw afe;
    }
  }
}
 

Example 41

From project kawala, under directory /kawala-testing/src/main/java/com/kaching/platform/testing/.

Source file: BadCodeSnippetsRunner.java

  19 
vote

private Map<Snippet,Set<File>> snippetsToExceptions(Snippet[] snippets){
  Map<Snippet,Set<File>> patternsToExceptions=newHashMap();
  for (  Snippet snippet : snippets) {
    try {
      Set<File> files=newHashSet();
      for (int i=0; i < snippet.exceptions().length; i++) {
        files.add(new File(snippet.exceptions()[i]));
      }
      patternsToExceptions.put(snippet,files);
    }
 catch (    PatternSyntaxException e) {
      throw new AssertionError(e.getMessage());
    }
  }
  return patternsToExceptions;
}
 

Example 42

From project kernel_1, under directory /exo.kernel.container/src/main/java/org/exoplatform/container/client/http/.

Source file: ClientTypeMap.java

  19 
vote

public HttpClientType findClient(String userAgent){
  if (userAgent == null)   return clientList_.get(0);
  if (userAgent.equals(""))   return clientList_.get(0);
  HttpClientType client;
  for (int i=0; i < clientList_.size(); i++) {
    client=clientList_.get(i);
    String userAgentPattern=client.getUserAgentPattern();
    if (userAgentPattern != null) {
      try {
        if (userAgent.matches(userAgentPattern))         return client;
      }
 catch (      PatternSyntaxException e) {
        LOG.error(e.getLocalizedMessage(),e);
        return clientList_.get(0);
      }
    }
  }
  return clientList_.get(0);
}
 

Example 43

From project license-maven-plugin, under directory /src/main/java/org/codehaus/mojo/license/.

Source file: DefaultDependenciesTool.java

  19 
vote

protected boolean isIncludable(Artifact project,Pattern includedGroupPattern,Pattern includedArtifactPattern){
  Logger log=getLogger();
  if (includedGroupPattern != null) {
    try {
      Matcher matchGroupId=includedGroupPattern.matcher(project.getGroupId());
      if (matchGroupId.find()) {
        if (log.isDebugEnabled()) {
          log.debug("Include " + project.getGroupId());
        }
        return true;
      }
    }
 catch (    PatternSyntaxException e) {
      log.warn(String.format(INVALID_PATTERN_MESSAGE,includedGroupPattern.pattern()));
    }
  }
  if (includedArtifactPattern != null) {
    try {
      Matcher matchGroupId=includedArtifactPattern.matcher(project.getArtifactId());
      if (matchGroupId.find()) {
        if (log.isDebugEnabled()) {
          log.debug("Include " + project.getArtifactId());
        }
        return true;
      }
    }
 catch (    PatternSyntaxException e) {
      log.warn(String.format(INVALID_PATTERN_MESSAGE,includedArtifactPattern.pattern()));
    }
  }
  return false;
}
 

Example 44

From project logback, under directory /logback-core/src/main/java/ch/qos/logback/core/boolex/.

Source file: Matcher.java

  19 
vote

public void start(){
  if (name == null) {
    addError("All Matcher objects must be named");
    return;
  }
  try {
    int code=0;
    if (!caseSensitive) {
      code|=Pattern.CASE_INSENSITIVE;
    }
    if (canonEq) {
      code|=Pattern.CANON_EQ;
    }
    if (unicodeCase) {
      code|=Pattern.UNICODE_CASE;
    }
    pattern=Pattern.compile(regex,code);
    start=true;
  }
 catch (  PatternSyntaxException pse) {
    addError("Failed to compile regex [" + regex + "]",pse);
  }
}
 

Example 45

From project logsaw-app, under directory /net.sf.logsaw.dialect.pattern/src/net/sf/logsaw/dialect/pattern/.

Source file: APatternDialect.java

  19 
vote

@Override public <T>void validate(IConfigOption<T> option,T value) throws CoreException {
  option.visit(new IConfigOptionVisitor(){
    @Override public void visit(    StringConfigOption opt,    String value) throws CoreException {
      if (OPTION_PATTERN.equals(opt)) {
        Assert.isNotNull(value,"externalPattern");
        getLogger().info("Validating conversion pattern " + value);
        IConversionPatternTranslator translator=doCreatePatternTranslator();
        Assert.isNotNull(translator,"patternTranslator");
        value=translator.prepare(value);
        Assert.isNotNull(value,"externalPattern");
        List<ConversionRule> rules=translator.extractRules(value);
        Assert.isNotNull(rules,"rules");
        if (rules.isEmpty()) {
          throw new CoreException(new Status(IStatus.ERROR,PatternDialectPlugin.PLUGIN_ID,Messages.APatternDialect_error_invalidPattern));
        }
        for (        ConversionRule rule : rules) {
          translator.applyDefaults(rule,APatternDialect.this);
          translator.rewrite(rule,APatternDialect.this);
        }
        try {
          Pattern internalPattern=Pattern.compile(toRegexPattern(value,translator,rules));
          getLogger().debug("Internal Pattern: " + internalPattern.pattern());
        }
 catch (        PatternSyntaxException e) {
          throw new CoreException(new Status(IStatus.ERROR,PatternDialectPlugin.PLUGIN_ID,NLS.bind(Messages.APatternDialect_error_failedToTranslateToRegex,value)));
        }
      }
    }
  }
,value);
  super.validate(option,value);
}
 

Example 46

From project lor-jamwiki, under directory /jamwiki-core/src/main/java/org/jamwiki/utils/.

Source file: SpamFilter.java

  19 
vote

/** 
 */
private static void initialize() throws DataAccessException {
  File file=null;
  try {
    file=Utilities.getClassLoaderFile(SPAM_BLACKLIST_FILE);
  }
 catch (  IOException e) {
    throw new DataAccessException("I/O exception while initlaizing spam blacklist",e);
  }
  String regex="";
  String regexText=null;
  try {
    regexText=FileUtils.readFileToString(file,"UTF-8").trim();
  }
 catch (  IOException e) {
    throw new DataAccessException("I/O exception while initlaizing spam blacklist",e);
  }
  String[] tokens=regexText.split("\n");
  for (int i=0; i < tokens.length; i++) {
    String token=tokens[i];
    if (StringUtils.isBlank(token)) {
      continue;
    }
    if (i > 0) {
      regex+="|";
    }
    regex+=token.trim();
  }
  try {
    spamRegexPattern=Pattern.compile(regex,Pattern.CASE_INSENSITIVE);
  }
 catch (  PatternSyntaxException e) {
    throw new DataAccessException("Failure while parsing spam regular expression list",e);
  }
  logger.info("Loading spam filter regular expression:" + regex);
}
 

Example 47

From project maven-cxx-plugin, under directory /src/main/java/org/wayoda/ang/project/.

Source file: Sketch.java

  19 
vote

/** 
 * Returns the index of the first character that is not a whitespace char or a pre-processor directive.
 * @param in the String to be processed
 * @return int the postion where the prototypes need to be filled in
 */
private int getPrototypeLocation(String in){
  Pattern pattern=null;
  Matcher matcher=null;
  try {
    String whiteSpacePattern="(\\G\\s+)";
    String preProcessorDirective="(\\G#(?:\\\\\\n|.)*)";
    String patternString=whiteSpacePattern + "|" + preProcessorDirective;
    pattern=Pattern.compile(patternString,Pattern.MULTILINE);
  }
 catch (  PatternSyntaxException pse) {
    throw new RuntimeException("Internal error in firstStatement()",pse);
  }
  matcher=pattern.matcher(in);
  int position=0;
  while (matcher.find()) {
    position=matcher.end();
  }
  return position;
}
 

Example 48

From project moho, under directory /moho-impl/src/main/java/com/voxeo/moho/sip/.

Source file: SIPHelper.java

  19 
vote

public static SipServletRequest createSipInitnalRequest(final SipFactory factory,final String method,final Address from,final Address to,final Map<String,String> headers,SipApplicationSession applicationSession){
  final SipServletRequest req=factory.createRequest(applicationSession != null ? applicationSession : factory.createApplicationSession(),method,from,to);
  URI ruri=req.getRequestURI();
  if (ruri instanceof SipURI) {
    SipURI sruri=(SipURI)ruri;
    if (sruri.getUserParam() == null) {
      sruri.setUserParam("phone");
      req.setRequestURI(sruri);
    }
  }
  if (headers != null) {
    for (    final Map.Entry<String,String> e : headers.entrySet()) {
      if (e.getKey().equalsIgnoreCase("Route")) {
        try {
          String[] values=e.getValue().split("\\|\\|\\|");
          int length=values.length;
          for (int i=length - 1; i >= 0; i--) {
            LOG.debug("route[" + i + "]: "+ values[i]);
            try {
              req.pushRoute(factory.createAddress(values[i]));
            }
 catch (            ServletParseException ex) {
              LOG.error("Invalid Route Header: " + values[i]);
            }
          }
        }
 catch (        PatternSyntaxException ex) {
          LOG.error(ex);
        }
      }
    }
    headers.remove("Route");
    headers.remove("route");
  }
  SIPHelper.addHeaders(req,headers);
  return req;
}
 

Example 49

From project mvel, under directory /src/main/java/org/mvel2/ast/.

Source file: RegExMatch.java

  19 
vote

public RegExMatch(char[] expr,int start,int offset,int fields,int patternStart,int patternOffset,ParserContext pCtx){
  super(pCtx);
  this.expr=expr;
  this.start=start;
  this.offset=offset;
  this.patternStart=patternStart;
  this.patternOffset=patternOffset;
  if ((fields & COMPILE_IMMEDIATE) != 0) {
    this.stmt=(ExecutableStatement)subCompileExpression(expr,start,offset);
    if ((this.patternStmt=(ExecutableStatement)subCompileExpression(expr,patternStart,patternOffset,pCtx)) instanceof ExecutableLiteral) {
      try {
        p=compile(valueOf(patternStmt.getValue(null,null)));
      }
 catch (      PatternSyntaxException e) {
        throw new CompileException("bad regular expression",expr,patternStart,e);
      }
    }
  }
}
 

Example 50

From project nutch, under directory /src/plugin/urlnormalizer-regex/src/java/org/apache/nutch/net/urlnormalizer/regex/.

Source file: RegexURLNormalizer.java

  19 
vote

/** 
 * Constructor which can be passed the file name, so it doesn't look in the configuration files for it.
 */
public RegexURLNormalizer(Configuration conf,String filename) throws IOException, PatternSyntaxException {
  super(conf);
  List<Rule> rules=readConfigurationFile(filename);
  if (rules != null) {
    defaultRules=rules;
  }
}
 

Example 51

From project openengsb-framework, under directory /components/ekb/transformation-wonderland/src/main/java/org/openengsb/core/ekb/transformation/wonderland/internal/operation/.

Source file: AbstractStandardTransformationOperation.java

  19 
vote

/** 
 * Generates a matcher for the given valueString with the given regular expression.
 */
protected Matcher generateMatcher(String regex,String valueString) throws TransformationOperationException {
  if (regex == null) {
    throw new TransformationOperationException("No regex defined. The step will be skipped.");
  }
  try {
    Pattern pattern=Pattern.compile(regex);
    return pattern.matcher(valueString);
  }
 catch (  PatternSyntaxException e) {
    String message=String.format("Given regex string %s can't be compiled. The step will be skipped.",regex);
    logger.warn(message);
    throw new TransformationOperationException(message);
  }
}
 

Example 52

From project OWASP-WebScarab, under directory /src/org/owasp/webscarab/plugin/.

Source file: Framework.java

  19 
vote

/** 
 * Creates a new instance of Framework
 */
public Framework(){
  _model=new FrameworkModel();
  _wrapper=new FrameworkModelWrapper(_model);
  _scriptManager=new ScriptManager(this);
  _allowAddConversation=new AddConversationHook();
  _analyseConversation=new AnalyseConversationHook();
  _scriptManager.registerHooks("Framework",new Hook[]{_allowAddConversation,_analyseConversation});
  extractVersionFromManifest();
  _credentialManager=new CredentialManager();
  configureHTTPClient();
  String dropRegex=Preferences.getPreference("WebScarab.dropRegex",null);
  try {
    setDropPattern(dropRegex);
  }
 catch (  PatternSyntaxException pse) {
    _logger.warning("Got an invalid regular expression for conversations to ignore: " + dropRegex + " results in "+ pse.toString());
  }
  String whitelistRegex=Preferences.getPreference("WebScarab.whitelistRegex",null);
  try {
    setWhitelistPattern(whitelistRegex);
  }
 catch (  PatternSyntaxException pse) {
    _logger.warning("Got an invalid regular expression for conversations to whitelist: " + whitelistRegex + " results in "+ pse.toString());
  }
  _qp=new Framework.QueueProcessor();
  _queueThread=new Thread(_qp,"QueueProcessor");
  _queueThread.setDaemon(true);
  _queueThread.setPriority(Thread.MIN_PRIORITY);
  _queueThread.start();
}
 

Example 53

From project PhysicalShop, under directory /src/main/java/com/wolvereness/util/.

Source file: Config.java

  19 
vote

/** 
 * @param section Section to retrieve pattern from
 * @param node Node to read from
 * @return A compiled pattern.
 */
protected Pattern getPattern(final ConfigurationSection section,final String node){
  final Object pattern=section.get(node);
  try {
    if (pattern != null)     return Pattern.compile(pattern.toString());
    throw new NullPointerException(section.getCurrentPath() + "." + node+ " is null");
  }
 catch (  final PatternSyntaxException e) {
    logWarning(section.getCurrentPath() + "." + node+ " \""+ pattern+ "\" is not valid");
    throw e;
  }
}
 

Example 54

From project Red5, under directory /src/org/red5/server/script/rhino/.

Source file: RhinoScriptUtils.java

  19 
vote

/** 
 * Uses a regex to get the first "function" name, this name is used to create an instance of the javascript object.
 * @param scriptSource
 * @return
 */
private static String getFunctionName(String scriptSource){
  String ret="undefined";
  try {
    ret=scriptSource.replaceAll("[\\S\\w\\s]*?function ([\\w]+)\\(\\)[\\S\\w\\s]+","$1");
    if (ret.equals("undefined") || ret.length() > 64) {
      ret=scriptSource.replaceAll("[\\S\\w\\s]*?var ([\\w]+)[\\S\\w\\s]+","$1");
    }
  }
 catch (  PatternSyntaxException ex) {
    log.error("Syntax error in the regular expression");
  }
catch (  IllegalArgumentException ex) {
    log.error("Syntax error in the replacement text (unescaped $ signs?)");
  }
catch (  IndexOutOfBoundsException ex) {
    log.error("Non-existent backreference used the replacement text");
  }
  log.debug("Got a function name: " + ret);
  return ret;
}
 

Example 55

From project red5-server, under directory /src/org/red5/server/script/rhino/.

Source file: RhinoScriptUtils.java

  19 
vote

/** 
 * Uses a regex to get the first "function" name, this name is used to create an instance of the javascript object.
 * @param scriptSource
 * @return
 */
private static String getFunctionName(String scriptSource){
  String ret="undefined";
  try {
    ret=scriptSource.replaceAll("[\\S\\w\\s]*?function ([\\w]+)\\(\\)[\\S\\w\\s]+","$1");
    if (ret.equals("undefined") || ret.length() > 64) {
      ret=scriptSource.replaceAll("[\\S\\w\\s]*?var ([\\w]+)[\\S\\w\\s]+","$1");
    }
  }
 catch (  PatternSyntaxException ex) {
    log.error("Syntax error in the regular expression");
  }
catch (  IllegalArgumentException ex) {
    log.error("Syntax error in the replacement text (unescaped $ signs?)");
  }
catch (  IndexOutOfBoundsException ex) {
    log.error("Non-existent backreference used the replacement text");
  }
  log.debug("Got a function name: " + ret);
  return ret;
}
 

Example 56

From project rest-fixture, under directory /RestFixture/src/main/java/smartrics/rest/fitnesse/fixture/support/.

Source file: Tools.java

  19 
vote

public static boolean regex(String text,String expr){
  try {
    Pattern p=Pattern.compile(expr);
    boolean find=p.matcher(text).find();
    return find;
  }
 catch (  PatternSyntaxException e) {
    throw new IllegalArgumentException("Invalid regex " + expr);
  }
}
 

Example 57

From project RestFixture, under directory /src/main/java/smartrics/rest/fitnesse/fixture/support/.

Source file: TextBodyTypeAdapter.java

  19 
vote

@Override public boolean equals(Object exp,Object act){
  if (exp == null || act == null) {
    return false;
  }
  String expected=exp.toString();
  if (exp instanceof Parse) {
    expected=((Parse)exp).text();
  }
  String actual=(String)act;
  try {
    Pattern p=Pattern.compile(expected);
    Matcher m=p.matcher(actual);
    if (!m.matches() && !m.find()) {
      addError("no regex match: " + expected);
    }
  }
 catch (  PatternSyntaxException e) {
    if (!expected.equals(actual)) {
      addError("no string match found: " + expected);
    }
  }
  return getErrors().size() == 0;
}
 

Example 58

From project rundeck, under directory /core/src/main/java/com/dtolabs/rundeck/core/authorization/providers/.

Source file: YamlPolicy.java

  19 
vote

public boolean matches(final Set<Attribute> environment){
  Set<URI> matchedSet=new HashSet<URI>();
  for (  final Attribute attribute : environment) {
    final String matchValue=matcher.get(attribute.property);
    if (null != matchValue) {
      Pattern compile;
      try {
        compile=Pattern.compile(matchValue);
      }
 catch (      PatternSyntaxException e) {
        compile=null;
      }
      if (null != compile) {
        final RegexPredicate regexPredicate=new RegexPredicate(compile);
        if (regexPredicate.evaluate(attribute.value)) {
          matchedSet.add(attribute.property);
        }
      }
 else {
        if (matchValue.equals(attribute.value)) {
          matchedSet.add(attribute.property);
        }
      }
    }
  }
  return valid && matchedSet.size() == matcher.keySet().size();
}
 

Example 59

From project skalli, under directory /org.eclipse.skalli.api/src/main/java/org/eclipse/skalli/services/search/.

Source file: SearchQuery.java

  19 
vote

public void setPattern(String pattern,boolean ignoreCase) throws QueryParseException {
  if (StringUtils.isNotBlank(pattern)) {
    try {
      int flags=Pattern.DOTALL;
      if (ignoreCase) {
        flags=flags | Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE;
      }
      setPattern(Pattern.compile(pattern,flags));
    }
 catch (    PatternSyntaxException e) {
      throw new QueryParseException("Pattern has a syntax error",e);
    }
  }
}
 

Example 60

From project Solbase-Solr, under directory /src/java/org/apache/solr/analysis/.

Source file: PatternReplaceFilterFactory.java

  19 
vote

@Override public void init(Map<String,String> args){
  super.init(args);
  try {
    p=Pattern.compile(args.get("pattern"));
  }
 catch (  PatternSyntaxException e) {
    throw new RuntimeException("Configuration Error: 'pattern' can not be parsed in " + this.getClass().getName(),e);
  }
  replacement=args.get("replacement");
  String r=args.get("replace");
  if (null != r) {
    if (r.equals("all")) {
      all=true;
    }
 else {
      if (r.equals("first")) {
        all=false;
      }
 else {
        throw new RuntimeException("Configuration Error: 'replace' must be 'first' or 'all' in " + this.getClass().getName());
      }
    }
  }
}
 

Example 61

From project SpoutTrade_1, under directory /src/main/java/net/ark3l/SpoutTrade/Updater/.

Source file: UpdateChecker.java

  19 
vote

private static BukkitDevDownload getBukkitDevDownload(String plugin) throws Exception {
  URL yahoo=new URL("http://dev.bukkit.org/server-mods/" + plugin + "/files/");
  BufferedReader in=new BufferedReader(new InputStreamReader(yahoo.openStream()));
  String inputLine;
  while ((inputLine=in.readLine()) != null) {
    inputLine=inputLine.trim();
    if (inputLine.startsWith("<td") && inputLine.contains("<a href=\"/server-mods/" + "spouttrade" + "/files")) {
      String result="";
      try {
        Pattern regex=Pattern.compile("/[^\"]*" + "spouttrade" + "[^\"]*",Pattern.MULTILINE);
        Matcher regexMatcher=regex.matcher(inputLine);
        if (regexMatcher.find()) {
          result="http://dev.bukkit.org" + regexMatcher.group();
        }
      }
 catch (      PatternSyntaxException ex) {
      }
      String version="";
      try {
        Pattern regex=Pattern.compile("(?<=\">)[^<]*(?=</a>)",Pattern.MULTILINE);
        Matcher regexMatcher=regex.matcher(inputLine);
        if (regexMatcher.find()) {
          version=regexMatcher.group();
        }
      }
 catch (      PatternSyntaxException ex) {
        ex.printStackTrace();
      }
      in.close();
      return new BukkitDevDownload(version,result);
    }
  }
  in.close();
  return null;
}
 

Example 62

From project Springjutsu-Validation, under directory /validation/src/test/java/org/springjutsu/validation/util/.

Source file: RequestUtilsTest.java

  19 
vote

@Test public void testRegexPatternBreakingControllerPathPath(){
  String[] candidateViewNames=new String[]{"any/path/will/do=/success/view"};
  String[] controllerPaths=new String[]{"{recordId}"};
  HttpServletRequest request=mockRequestWithPattern("{recordId}/any/path/will/do");
  try {
    String matchingRestPath=RequestUtils.findMatchingRestPath(candidateViewNames,controllerPaths,request);
    assertEquals("/success/view",matchingRestPath);
  }
 catch (  PatternSyntaxException pse) {
    fail(pse.getMessage());
    pse.printStackTrace();
  }
}
 

Example 63

From project subversion-plugin, under directory /src/main/java/hudson/scm/listtagsparameter/.

Source file: ListSubversionTagsParameterDefinition.java

  19 
vote

public FormValidation doCheckTagsFilter(@QueryParameter String value){
  if (value != null && value.length() == 0) {
    try {
      Pattern.compile(value);
    }
 catch (    PatternSyntaxException pse) {
      FormValidation.error(ResourceBundleHolder.get(ListSubversionTagsParameterDefinition.class).format("NotValidRegex"));
    }
  }
  return FormValidation.ok();
}
 

Example 64

From project subversion-plugin_1, under directory /src/main/java/hudson/scm/.

Source file: SubversionSCM.java

  19 
vote

/** 
 * Validates the excludeRegions Regex.
 * @param value value to validate.
 * @return {@link FormValidation}.
 * @throws java.io.IOException            IOException.
 * @throws javax.servlet.ServletException ServletException.
 */
public FormValidation doCheckExcludedRegions(@QueryParameter String value) throws IOException, ServletException {
  for (  String region : Util.fixNull(value).trim().split("[\\r\\n]+")) {
    try {
      Pattern.compile(region);
    }
 catch (    PatternSyntaxException e) {
      return FormValidation.error("Invalid regular expression. " + e.getMessage());
    }
  }
  return FormValidation.ok();
}
 

Example 65

From project sveditor, under directory /sveditor/plugins/net.sf.sveditor.core/src/net/sf/sveditor/core/fileset/.

Source file: AbstractSVFileMatcher.java

  19 
vote

protected void update_patterns(){
  fIncludePatterns.clear();
  fExcludePatterns.clear();
  for (  SVFileSet fs : fFileSets) {
    for (    String inc : fs.getIncludes()) {
      try {
        fIncludePatterns.add(create_pattern(fs.getBase(),inc));
      }
 catch (      PatternSyntaxException e) {
        fLog.error("Failed to compile base=" + fs.getBase() + " incl="+ inc,e);
      }
    }
    for (    String exc : fs.getExcludes()) {
      try {
        FilePattern p=create_pattern(fs.getBase(),exc);
        fExcludePatterns.add(p);
      }
 catch (      PatternSyntaxException e) {
        fLog.error("Failed to compile base=" + fs.getBase() + " excl="+ exc,e);
      }
    }
  }
}
 

Example 66

From project tedis, under directory /tedis-replicator/src/main/java/com/taobao/common/tedis/replicator/filter/.

Source file: DatabaseFilter.java

  19 
vote

@Override public void prepare(PluginContext context) throws ReplicatorException, InterruptedException {
  try {
    pattern=Pattern.compile(schema);
    matcher=pattern.matcher("");
  }
 catch (  PatternSyntaxException e) {
    throw new ReplicatorException("Replicator fromRegex is invalid:  expression=" + schema,e);
  }
}
 

Example 67

From project utils_1, under directory /src/main/java/net/pterodactylus/util/text/.

Source file: RegularExpressionNumberFormat.java

  19 
vote

/** 
 * Creates a new regular expression number format.
 * @param expression The expression to parse for patterns and values
 * @param separator The separator between patterns and values
 * @param patternSeparator The separator between entries
 * @throws PatternSyntaxException if the regular expressions can not be parsed
 */
public RegularExpressionNumberFormat(String expression,char separator,char patternSeparator) throws PatternSyntaxException {
  String defaultValue=null;
  for (  String pattern : expression.split(String.valueOf(patternSeparator))) {
    if (pattern.indexOf(separator) < 0) {
      defaultValue=pattern;
      break;
    }
    String regularExpression=pattern.substring(0,pattern.indexOf(separator));
    String value=pattern.substring(pattern.indexOf(separator) + 1);
    if (value.startsWith(String.valueOf(separator))) {
      value=value.substring(1);
      defaultValue=value;
    }
    patterns.add(new Pair<Pattern,String>(Pattern.compile(regularExpression),value));
  }
  this.defaultValue=defaultValue;
}
 

Example 68

From project Vega, under directory /platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/conditions/match/.

Source file: RegexMatchAction.java

  19 
vote

private Pattern createRegexPattern(String str){
  try {
    return Pattern.compile(str);
  }
 catch (  PatternSyntaxException e) {
    return null;
  }
}
 

Example 69

From project verdandi, under directory /src/main/java/verdandi/ui/.

Source file: ProjectViewingPanel.java

  19 
vote

protected void searchFieldUpdated(){
  String sText=searchField.getText();
  try {
    searchField.setForeground(Color.BLACK);
    searchField.setToolTipText(RB.getString("projectviewer.searchfield.tooltip"));
    if (sText.startsWith("#")) {
    }
 else {
    }
  }
 catch (  PatternSyntaxException uncompletedRegexp) {
    searchField.setForeground(Color.RED);
    String errTooltip=RB.getString("projectviewer.searchfield.tooltip.invalidregexp");
    errTooltip=errTooltip.replace("{1}",uncompletedRegexp.getLocalizedMessage());
    searchField.setToolTipText(errTooltip);
  }
}
 

Example 70

From project warlock2, under directory /core/cc.warlock.core/src/main/cc/warlock/core/client/settings/internal/.

Source file: HighlightConfigurationProvider.java

  19 
vote

@Override protected void parseChild(Element child){
  if (child.getName().equals("highlight")) {
    IWarlockStyle style=null;
    if (child.elements().size() > 0 && child.element("style") != null) {
      Element sElement=child.element("style");
      style=createStyle(sElement);
    }
    try {
      HighlightString string=new HighlightString(this,null,style);
      fillSetting(string,child);
      highlights.add(string);
    }
 catch (    PatternSyntaxException e) {
      e.printStackTrace();
    }
  }
 else   if (child.getName().equals("style")) {
    IWarlockStyle style=createStyle(child);
    namedStyles.put(style.getName(),style);
  }
}
 

Example 71

From project wip, under directory /src/main/java/fr/ippon/wip/http/request/.

Source file: IgnoreHttpRequestFilter.java

  19 
vote

/** 
 * Check if the script from the given URL has to be deleted
 * @param url the script URL
 * @return a boolean indicating if the script has to be deleted
 */
private boolean isDeletedScript(WIPConfiguration configuration,String url){
  for (  String regex : configuration.getScriptsToDelete()) {
    try {
      Pattern p=Pattern.compile(regex);
      Matcher m=p.matcher(url);
      if (m.find())       return true;
    }
 catch (    PatternSyntaxException e) {
      throw e;
    }
  }
  return false;
}
 

Example 72

From project XACML-Policy-Analysis-Tool, under directory /PolicyAnalysisTool/src/com/sun/xacml/attr/.

Source file: YearMonthDurationAttribute.java

  19 
vote

/** 
 * Returns a new <code>YearMonthDurationAttribute</code> that represents the xf:yearMonthDuration value indicated by the string provided.
 * @param value a string representing the desired value
 * @return a new <code>YearMonthDurationAttribute</code> representing thedesired value
 * @throws ParsingException if any problems occurred while parsing
 */
public static YearMonthDurationAttribute getInstance(String value) throws ParsingException {
  boolean negative=false;
  long years=0;
  long months=0;
  if (pattern == null) {
    try {
      pattern=Pattern.compile(patternString);
    }
 catch (    PatternSyntaxException e) {
      throw new ParsingException("unexpected pattern syntax error");
    }
  }
  Matcher matcher=pattern.matcher(value);
  boolean matches=matcher.matches();
  if (!matches) {
    throw new ParsingException("Syntax error in yearMonthDuration");
  }
  if (matcher.start(GROUP_SIGN) != -1)   negative=true;
  try {
    years=parseGroup(matcher,GROUP_YEARS);
    months=parseGroup(matcher,GROUP_MONTHS);
  }
 catch (  NumberFormatException e) {
    throw new ParsingException("Unable to handle number size");
  }
  return new YearMonthDurationAttribute(negative,years,months);
}
 

Example 73

From project xwiki-commons, under directory /xwiki-commons-core/xwiki-commons-velocity/src/main/java/org/xwiki/velocity/tools/.

Source file: RegexTool.java

  19 
vote

/** 
 * Compiles a regular expression into a java  {@code Pattern} object.
 * @param regex the textual representation of the regular expression
 * @return the {@code Pattern} object corresponding to the regular expression, or {@code null} if the expression isinvalid
 * @since 2.3M1
 */
public Pattern compile(String regex){
  try {
    return Pattern.compile(regex);
  }
 catch (  PatternSyntaxException ex) {
    return null;
  }
}