Java Code Examples for java.util.regex.Pattern

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 ACLS-protocol-library, under directory /aclslib/src/main/java/au/edu/uq/cmm/aclslib/message/.

Source file: AbstractReader.java

  20 
vote

private String nextWithAltDelimiter(Scanner source,Pattern altDelimiter){
  Pattern delimiter=source.delimiter();
  try {
    source.useDelimiter(altDelimiter);
    return source.next();
  }
  finally {
    source.useDelimiter(delimiter);
  }
}
 

Example 2

From project activejdbc, under directory /activejdbc/src/main/java/org/javalite/activejdbc/validation/.

Source file: RegexpValidator.java

  20 
vote

public void validate(Model m){
  if (m.get(attribute) == null) {
    m.addValidator(this,attribute);
    return;
  }
  Object value=m.get(attribute);
  if (!value.getClass().equals(String.class))   throw new IllegalArgumentException("attribute " + attribute + " is not String");
  Pattern pattern=Pattern.compile(rule,Pattern.CASE_INSENSITIVE);
  Matcher matcher=pattern.matcher(value.toString());
  if (!matcher.matches()) {
    m.addValidator(this,attribute);
  }
}
 

Example 3

From project aether-core, under directory /aether-api/src/main/java/org/eclipse/aether/artifact/.

Source file: DefaultArtifact.java

  18 
vote

/** 
 * Creates a new artifact with the specified coordinates and properties. If not specified in the artifact coordinates, the artifact's extension defaults to  {@code jar} and classifier to an empty string.
 * @param coords The artifact coordinates in the format{@code <groupId>:<artifactId>[:<extension>[:<classifier>]]:<version>}, must not be  {@code null}.
 * @param properties The artifact properties, may be {@code null}.
 */
public DefaultArtifact(String coords,Map<String,String> properties){
  Pattern p=Pattern.compile("([^: ]+):([^: ]+)(:([^: ]*)(:([^: ]+))?)?:([^: ]+)");
  Matcher m=p.matcher(coords);
  if (!m.matches()) {
    throw new IllegalArgumentException("Bad artifact coordinates " + coords + ", expected format is <groupId>:<artifactId>[:<extension>[:<classifier>]]:<version>");
  }
  groupId=m.group(1);
  artifactId=m.group(2);
  extension=get(m.group(4),"jar");
  classifier=get(m.group(6),"");
  version=m.group(7);
  file=null;
  this.properties=copyProperties(properties);
}
 

Example 4

From project aim3-tu-berlin, under directory /seminar/exercises/datamining/core/src/test/java/de/tuberlin/dima/aim/exercises/one/.

Source file: AverageTemperaturePerMonthTest.java

  18 
vote

private Map<YearAndMonth,Double> readResults(File outputFile) throws IOException {
  Pattern separator=Pattern.compile("\t");
  Map<YearAndMonth,Double> averageTemperatures=Maps.newHashMap();
  for (  String line : new FileLineIterable(outputFile)) {
    String[] tokens=separator.split(line);
    int year=Integer.parseInt(tokens[0]);
    int month=Integer.parseInt(tokens[1]);
    double temperature=Double.parseDouble(tokens[2]);
    averageTemperatures.put(new YearAndMonth(year,month),temperature);
  }
  return averageTemperatures;
}
 

Example 5

From project alg-vis, under directory /src/algvis/core/.

Source file: WordGenerator.java

  18 
vote

public static Vector<String> parseString(String ss){
  Vector<String> ll=new Vector<String>(Arrays.asList(ss.replaceAll("'"," ").split("(\\s|,)+")));
  Vector<String> result=new Vector<String>();
  Pattern p=Pattern.compile("[\\p{InCombiningDiacriticalMarks}\\p{IsLm}\\p{IsSk}]+");
  for (  String s : ll) {
    s=Normalizer.normalize(s,Normalizer.Form.NFD);
    s=p.matcher(s).replaceAll("");
    s=s.toUpperCase(Locale.ENGLISH);
    s=s.replaceAll("[^A-Z]","");
    result.add(s + "$");
  }
  return result;
}
 

Example 6

From project Amantech, under directory /Android/CloudAppStudioAndroid/src/com/cloudappstudio/data/.

Source file: ColumnValue.java

  18 
vote

public boolean IsImageUrl(){
  try {
    String regex="(https?:\\/\\/.*\\.(?:png|jpg|gif|jpeg|bmp))";
    Pattern patt=Pattern.compile(regex);
    Matcher matcher=patt.matcher(mValue);
    return matcher.matches();
  }
 catch (  RuntimeException e) {
    return false;
  }
}
 

Example 7

From project Amoeba-for-Aladdin, under directory /src/java/com/meidusa/amoeba/util/.

Source file: IPRule.java

  18 
vote

static boolean IsMatch(String ip,String ipRegexString){
  Pattern pattern=ipPattern.get(ipRegexString);
  if (pattern == null) {
    pattern=Pattern.compile(ipRegexString);
    ipPattern.put(ipRegexString,pattern);
  }
  Matcher m=pattern.matcher(ip);
  return m.matches();
}
 

Example 8

From project amplafi-sworddance, under directory /src/main/java/com/sworddance/util/.

Source file: UriParser.java

  18 
vote

public ExtendedMatchResult partsOnly(String uriStr){
  Pattern pattern=this.uriOnly;
  Matcher matcher=pattern.matcher(uriStr);
  if (matcher.find()) {
    return new ExtendedMatchResultImpl(matcher.toMatchResult());
  }
 else {
    return null;
  }
}
 

Example 9

From project amsterdam, under directory /src/main/java/com/unicodecollective/amsterdam/.

Source file: CallSpecs.java

  18 
vote

public static CallSpec methodMatching(String regex){
  final Pattern methodPattern=Pattern.compile(regex);
  return new CallSpec(){
    @Override public boolean matches(    Method method,    Object[] args){
      return methodPattern.matcher(method.getName()).find();
    }
  }
;
}
 

Example 10

From project and-bible, under directory /AndBackendTest/src/net/bible/service/format/osistohtml/.

Source file: ReferenceHandlerTest.java

  18 
vote

public void testReferenceRegExp(){
  Pattern p=Pattern.compile("(sword://)?[A-za-z_]*[/:]{1}[A-Za-z0-9_]*");
  Matcher m1=p.matcher("sword://StrongsRealGreek/01909");
  assertTrue(m1.matches());
  Matcher m2=p.matcher("StrongsHebrew:00411");
  assertTrue(m2.matches());
  Matcher m3=p.matcher("Matt 13:4");
  assertTrue(!m3.matches());
}
 

Example 11

From project Android-DB-Editor, under directory /src/com/troido/dbeditor/.

Source file: ADBConnector.java

  18 
vote

public static ArrayList<String> devices(){
  String devices=runADBCommand(null,"devices");
  ArrayList<String> deviceList=new ArrayList<String>();
  String split[]=devices.split("\n");
  Pattern p=Pattern.compile("(.*?)\\s*device$");
  for (  String s : split) {
    Matcher m=p.matcher(s);
    if (m.find())     deviceList.add(m.group(1));
  }
  return deviceList;
}
 

Example 12

From project android-rackspacecloud, under directory /src/com/rackspacecloud/android/.

Source file: AddAccessRuleActivity.java

  18 
vote

private static boolean validAddress(String address){
  if (address != null && !address.trim().equals("")) {
    Pattern pattern=Pattern.compile("[a-zA-Z0-9.:/, ]+");
    Matcher match=pattern.matcher(address);
    return match.matches();
  }
 else {
    return false;
  }
}
 

Example 13

From project Android-Simple-Social-Sharing, under directory /SimpleSocialSharing/src/com/nostra13/socialsharing/twitter/.

Source file: TwitterDialog.java

  18 
vote

private String findExpression(String text,String regExp){
  Pattern p=Pattern.compile(regExp);
  Matcher m=p.matcher(text);
  if (m.find()) {
    return m.group(0);
  }
 else {
    return null;
  }
}
 

Example 14

From project android-xbmcremote, under directory /src/org/xbmc/android/util/.

Source file: YoutubeURLParser.java

  18 
vote

public static String parseYoutubeURL(Uri playuri){
  if (playuri.getHost().endsWith("youtube.com") || playuri.getHost().endsWith("youtu.be")) {
    final Pattern pattern=Pattern.compile("^http(:?s)?:\\/\\/(?:www\\.)?(?:youtube\\.com|youtu\\.be)\\/watch\\?(?=.*v=([\\w-]+))(?:\\S+)?$",Pattern.CASE_INSENSITIVE);
    final Matcher matcher=pattern.matcher(playuri.toString());
    if (matcher.matches()) {
      return matcher.group(2);
    }
  }
  return null;
}
 

Example 15

From project androidquery, under directory /demo/src/com/androidquery/test/.

Source file: PatternUtility.java

  18 
vote

public static String match(String html,String match){
  Pattern p=Pattern.compile(match);
  Matcher m=p.matcher(html);
  if (m.find()) {
    return m.group();
  }
  return null;
}
 

Example 16

From project android_external_libphonenumber, under directory /java/src/com/android/i18n/phonenumbers/.

Source file: AsYouTypeFormatter.java

  18 
vote

private void narrowDownPossibleFormats(String leadingDigits){
  int indexOfLeadingDigitsPattern=leadingDigits.length() - MIN_LEADING_DIGITS_LENGTH;
  Iterator<NumberFormat> it=possibleFormats.iterator();
  while (it.hasNext()) {
    NumberFormat format=it.next();
    if (format.leadingDigitsPatternSize() > indexOfLeadingDigitsPattern) {
      Pattern leadingDigitsPattern=regexCache.getPatternForRegex(format.getLeadingDigitsPattern(indexOfLeadingDigitsPattern));
      Matcher m=leadingDigitsPattern.matcher(leadingDigits);
      if (!m.lookingAt()) {
        it.remove();
      }
    }
  }
}
 

Example 17

From project ant4eclipse, under directory /org.ant4eclipse.ant.pde/src/org/ant4eclipse/ant/pde/.

Source file: ExecutePdeJunitLauncherTask.java

  18 
vote

/** 
 * <p> </p>
 * @param bundleList
 * @param takeBundlesFromWorkspace
 */
private void computeBundles(String bundleList,boolean takeBundlesFromWorkspace){
  String[] workspacePlugins=bundleList.split(",");
  for (  String workspacePlugin : workspacePlugins) {
    Pattern pattern=Pattern.compile("(.*)@(.*):(.*)");
    Matcher matcher=pattern.matcher(workspacePlugin);
    matcher.matches();
    handle(matcher.group(1),matcher.group(2),matcher.group(3),takeBundlesFromWorkspace);
  }
}
 

Example 18

From project any23, under directory /core/src/test/java/org/apache/any23/extractor/rdfa/.

Source file: XSLTStylesheetTest.java

  18 
vote

private String[] checkPageBaseHandling(String testFile) throws IOException, XSLTStylesheetException {
  final TagSoupParser tagSoupParser=new TagSoupParser(this.getClass().getResourceAsStream(testFile),"http://test/document/uri");
  final StringWriter sw=new StringWriter();
  RDFaExtractor.getXSLT().applyTo(tagSoupParser.getDOM(),sw);
  final String content=sw.toString();
  logger.debug(content);
  final Pattern pattern=Pattern.compile("<!--this_location: '(.+)' this_root: '(.+)' html_base: '(.+)'-->");
  final Matcher matcher=pattern.matcher(content);
  Assert.assertTrue("Cannot find comment matching within generated output.",matcher.find());
  return new String[]{matcher.group(1),matcher.group(2),matcher.group(3)};
}
 

Example 19

From project apb, under directory /modules/apb-base/src/apb/utils/.

Source file: Filter.java

  18 
vote

/** 
 * This filter replaces each substring of the input that matches the given <a href="../util/regex/Pattern.html#sum">regular expression</a> with the given replacement.
 * @param regex the regular expression to which this string is to be matched
 * @throws java.util.regex.PatternSyntaxException if the regular expression's syntax is invalid
 * @see java.util.regex.Pattern
 */
public static Filter replaceAll(String regex,final String replacement){
  final Pattern pattern=Pattern.compile(regex);
  return new Filter(){
    public String filter(    String str){
      return pattern.matcher(str).replaceAll(replacement);
    }
    public String toString(){
      return "Replacing " + pattern + " by "+ replacement;
    }
  }
;
}
 

Example 20

From project arquillian-container-tomcat, under directory /tomcat-common/src/main/java/org/jboss/arquillian/container/tomcat/.

Source file: AdditionalJavaOptionsParser.java

  18 
vote

/** 
 * Parse additional java options. Options are separated by whitespace. In case some option value contains whitespace, the whole key-value pair has to be quoted. For instance string 'opt0 opt1=val1 "opt2=val2 with space"' results in three key-value pairs (opt0 option has an empty value).
 * @param additionaOptions - options to parse
 * @return List of parsed options, returns empty list rather that null value
 */
public static List<String> parse(String additionalOptions){
  List<String> options=new ArrayList<String>();
  if (additionalOptions != null) {
    Pattern p=Pattern.compile(OPTION,Pattern.DOTALL);
    Matcher m=p.matcher(additionalOptions);
    while (m.find()) {
      if (!(m.group().trim().equals(""))) {
        options.add(Pattern.compile(QUOTED_CONTENT,Pattern.DOTALL).matcher(m.group().trim()).replaceAll("$1"));
      }
    }
  }
  return options;
}
 

Example 21

From project arquillian-rusheye, under directory /rusheye-impl/src/main/java/org/jboss/rusheye/oneoff/.

Source file: XmlWriter.java

  18 
vote

private String replacePlaceholders(ComparisonResult cr,File newDir,String line){
  StringBuffer out=new StringBuffer();
  Pattern pattern=Pattern.compile("\\$\\{(.*?)\\}",Pattern.CASE_INSENSITIVE);
  Matcher matcher=pattern.matcher(line);
  while (matcher.find()) {
    matcher.appendReplacement(out,getPlaceholderValue(cr,matcher.group(1)));
  }
  matcher.appendTail(out);
  return out.toString() + "\n";
}
 

Example 22

From project as3-commons-jasblocks, under directory /src/main/java/org/as3commons/asblocks/impl/.

Source file: DocumentationUtils.java

  18 
vote

public static IDocTag findParam(IDocComment doc,String name){
  Iterator<IDocTag> params=doc.getTags("param");
  Pattern p=Pattern.compile("\\s*\\Q" + name + "\\E\\b");
  while (params.hasNext()) {
    IDocTag param=(IDocTag)params.next();
    if (p.matcher(param.getBody()).lookingAt()) {
      return param;
    }
  }
  return null;
}
 

Example 23

From project ATHENA, under directory /core/util/src/main/java/org/fracturedatlas/athena/util/.

Source file: Scrubber.java

  18 
vote

/** 
 * Scrub a JSON string.  For every field in fieldsToScrub, replace the value with SCRUBBED. Both double quoted and single quoted JSON strings are supported Regarding RegEx, for fieldName = foo, this pattern will match: foo":"some_value" and group like so (foo":")(some_value)(")
 * @param stringToScrub the string to scrub
 * @param fieldsToScrub a List of fields in this JSON.  Their values will be replaced with SCRUBBED
 * @return the scrubbed string.
 */
public static String scrubJson(String stringToScrub,List<String> fieldsToScrub){
  if (stringToScrub == null || fieldsToScrub == null || fieldsToScrub.size() == 0) {
    return stringToScrub;
  }
  for (  String fieldName : fieldsToScrub) {
    Pattern pattern=Pattern.compile("(" + fieldName + "[\\\\]*[\"|'][\\s]*:[\\s]*[\\\\]*[\"|'])([^\"|^\\\\]*)([\\\\]*[\"|'])");
    Matcher matcher=pattern.matcher(stringToScrub);
    stringToScrub=matcher.replaceAll("$1" + SCRUBBED + "$3");
  }
  return stringToScrub;
}
 

Example 24

From project atlas, under directory /src/main/java/com/ning/atlas/space/.

Source file: QueryParser.java

  18 
vote

private Predicate<String> regex(String s){
  final Pattern p=Pattern.compile(s.substring(1,s.length() - 1));
  return new Predicate<String>(){
    @Override public boolean apply(    @Nullable String input){
      return p.matcher(input).matches();
    }
  }
;
}
 

Example 25

From project AuthDB, under directory /src/main/java/com/authdb/.

Source file: AuthDB.java

  18 
vote

public static boolean checkEmail(String email){
  Util.logging.Debug("Validating email: " + email);
  Pattern p=Pattern.compile("[email protected]+\\.[a-z]+");
  Matcher m=p.matcher(email);
  boolean Matches=m.matches();
  if (Matches) {
    Util.logging.Debug("Email validation: passed!");
    return true;
  }
 else {
    Util.logging.Debug("Email validation: failed!");
    return false;
  }
}
 

Example 26

From project AuToBI, under directory /src/edu/cuny/qc/speech/AuToBI/core/.

Source file: AuToBIParameters.java

  18 
vote

/** 
 * Parses command line arguments into parameters. <p/> parameters are of the form -parameter_name=parameter_value <p/> or for boolean parameters -boolean_parameter_name
 * @param args command line parameters
 */
public void readParameters(String[] args){
  Pattern boolean_pattern=Pattern.compile("-(\\w*)");
  Pattern parameter_pattern=Pattern.compile("-(\\w*)=(.*)");
  for (  String param : args) {
    Matcher boolean_matcher=boolean_pattern.matcher(param);
    Matcher parameter_matcher=parameter_pattern.matcher(param);
    if (boolean_matcher.matches()) {
      parameters.put(boolean_matcher.group(1),"true");
    }
    if (parameter_matcher.matches()) {
      parameters.put(parameter_matcher.group(1),parameter_matcher.group(2));
    }
  }
}
 

Example 27

From project autopatch, under directory /src/main/java/com/tacitknowledge/util/migration/jdbc/util/.

Source file: SybaseUtil.java

  18 
vote

/** 
 * Determines whether the statement (typically some sql) contains one of the sql commands that are not allowed in a multi-statement transaction.
 * @param statement the text to check
 * @return true if one of the illegal commands is found in the statement.
 * @see <a href="http://manuals.sybase.com/onlinebooks/group-as/asg1250e/svrtsg/Generic__BookTextView/13155;pt=13085">
     *      Sybase Troubleshooting and Error Messages Guide</a>
 */
public static boolean containsIllegalMultiStatementTransactionCommand(String statement){
  boolean contains=false;
  for (Iterator iter=ILLEGAL_MULTISTATEMENT_TRANSACTION_COMMANDS.iterator(); iter.hasNext(); ) {
    Pattern pattern=(Pattern)iter.next();
    Matcher matcher=pattern.matcher(statement);
    if (matcher.matches()) {
      contains=true;
      break;
    }
  }
  return contains;
}
 

Example 28

From project autopsy, under directory /RecentActivity/src/org/sleuthkit/autopsy/recentactivity/.

Source file: Util.java

  18 
vote

public static String getFileName(String value){
  String filename="";
  String filematch="^([a-zA-Z]\\:)(\\\\[^\\\\/:*?<>\"|]*(?<!\\[ \\]))*(\\.[a-zA-Z]{2,6})$";
  Pattern p=Pattern.compile(filematch,Pattern.CASE_INSENSITIVE | Pattern.DOTALL | Pattern.COMMENTS);
  Matcher m=p.matcher(value);
  if (m.find()) {
    filename=m.group(1);
  }
  int lastPos=value.lastIndexOf('\\');
  filename=(lastPos < 0) ? value : value.substring(lastPos + 1);
  return filename.toString();
}
 

Example 29

From project aws-tasks, under directory /src/main/java/datameer/awstasks/util/.

Source file: ExceptionUtil.java

  18 
vote

public static Map<Thread,StackTraceElement[]> getThreadsWithName(String namePatternString){
  Pattern namePattern=Pattern.compile(namePatternString);
  Map<Thread,StackTraceElement[]> threadsToStacktraceMap=Thread.getAllStackTraces();
  Set<Thread> keySet=threadsToStacktraceMap.keySet();
  for (Iterator<Thread> iterator=keySet.iterator(); iterator.hasNext(); ) {
    Thread thread=iterator.next();
    if (!namePattern.matcher(thread.getName()).matches()) {
      iterator.remove();
    }
  }
  return threadsToStacktraceMap;
}
 

Example 30

From project b3log-latke, under directory /latke/src/main/java/org/b3log/latke/util/.

Source file: Strings.java

  18 
vote

/** 
 * Checks whether the specified string is numeric.
 * @param string the specified string
 * @return {@code true} if the specified string is numeric, returns returns  {@code false} otherwise
 */
public static boolean isNumeric(final String string){
  if (isEmptyOrNull(string)) {
    return false;
  }
  final Pattern pattern=Pattern.compile("[0-9]*");
  final Matcher matcher=pattern.matcher(string);
  if (!matcher.matches()) {
    return false;
  }
  return true;
}
 

Example 31

From project banshun, under directory /banshun/core/src/main/java/com/griddynamics/banshun/.

Source file: LookupTargetSource.java

  18 
vote

public LookupTargetSource(ApplicationContext context,String targetBeanName,Class<?> targetClass){
  this.context=context;
  this.targetBeanName=targetBeanName;
  this.targetClass=targetClass;
  final Pattern pattern=Pattern.compile("(.*)" + ContextParentBean.TARGET_SOURCE_SUFFIX);
  Matcher matcher=pattern.matcher(targetBeanName);
  matcher.matches();
  this.actualBeanName=matcher.group(1);
}
 

Example 32

From project bbb-java, under directory /src/main/java/org/mconf/bbb/api/.

Source file: JoinServiceBase.java

  18 
vote

public void setServer(String serverUrl){
  Pattern pattern=Pattern.compile("(.*):(\\d*)");
  Matcher matcher=pattern.matcher(serverUrl);
  if (matcher.matches()) {
    this.serverUrl=matcher.group(1);
    this.serverPort=Integer.parseInt(matcher.group(2));
  }
 else {
    this.serverUrl=serverUrl;
    this.serverPort=80;
  }
}
 

Example 33

From project bdd-security, under directory /src/main/java/net/continuumsecurity/web/steps/.

Source file: WebApplicationSteps.java

  18 
vote

@Then("the session cookies should have the httpOnly flag set") public void sessionCookiesHttpOnlyFlag(){
  Config.instance();
  int numCookies=Config.getSessionIDs().size();
  int cookieCount=0;
  for (  HttpMessage message : burp.getProxyHistory()) {
    for (    String name : Config.getSessionIDs()) {
      Pattern pattern=Pattern.compile(name + "=.*httponly",Pattern.CASE_INSENSITIVE);
      if (pattern.matcher(message.getResponseAsString()).find()) {
        cookieCount++;
      }
    }
  }
  Assert.assertThat(cookieCount,equalTo(numCookies));
}
 

Example 34

From project bel-editor, under directory /org.openbel.editor.core/src/org/openbel/editor/core/common/.

Source file: BELUtilities.java

  18 
vote

/** 
 * Returns true if a string contains one or more alphanumeric (i.e., the {@code Alnum} character class) characters and nothing else.
 * @param s {@link String}
 * @return boolean
 */
public static boolean isAlphanumeric(String s){
  if (!hasLength(s)) {
    return false;
  }
  Pattern p=Pattern.compile("\\p{Alnum}+");
  Matcher m=p.matcher(s);
  return m.matches();
}
 

Example 35

From project bitcask-java, under directory /src/main/java/com/trifork/bitcask/.

Source file: OS.java

  18 
vote

/** 
 * from http://golesny.de/wiki/code:javahowtogetpid; that site has more suggestions if this fails...
 */
private static Integer tryPattern1(String processName){
  Integer result=null;
  Pattern pattern=Pattern.compile("^([0-9]+)@.+$",Pattern.CASE_INSENSITIVE);
  Matcher matcher=pattern.matcher(processName);
  if (matcher.matches()) {
    result=Integer.valueOf(Integer.parseInt(matcher.group(1)));
  }
  return result;
}
 

Example 36

From project Blitz, under directory /src/com/laxser/blitz/web/impl/mapping/.

Source file: RegexMapping.java

  18 
vote

public static void main(String[] args){
  Pattern p=Pattern.compile("^[0-9]+");
  Matcher matcher=p.matcher("56789/asd");
  System.out.println(matcher.find());
  String value=matcher.group();
  while (value.length() > 0 && value.charAt(value.length() - 1) == '/') {
    value=value.substring(0,value.length() - 1);
  }
  System.out.println("value=" + value);
}
 

Example 37

From project blog_1, under directory /stat4j/src/net/sourceforge/stat4j/filter/.

Source file: RegExpScraper.java

  18 
vote

public final Pattern getPattern(String regexp){
  Pattern pattern=(Pattern)patterns.get(regexp);
  if (pattern == null) {
    pattern=Pattern.compile(regexp);
    patterns.put(regexp,pattern);
  }
  return pattern;
}
 

Example 38

From project Aardvark, under directory /aardvark-interactive/src/test/java/gw/vark/.

Source file: InteractiveShellTest.java

  17 
vote

@Test public void testNewProgramInstanceWhenAndOnlyWhenVarkFileIsRefreshed() throws Exception {
  Pattern pattern=Pattern.compile("show-startup-time  show-startup-time: (\\d+)  BUILD SUCCESSFUL.*");
  writeToFile(_varkFile,VARK_FILE_0);
  writeToFile(_userClass,USER_CLASS_0);
  String read=writeToProcessAndRead("show-startup-time" + LINE_SEPARATOR).replace(LINE_SEPARATOR," ");
  assertThat(read).matches(pattern.pattern());
  Matcher matcher=pattern.matcher(read);
  assertThat(matcher.matches()).isTrue();
  long time=Long.parseLong(matcher.group(1));
  read=writeToProcessAndRead("show-startup-time" + LINE_SEPARATOR).replace(LINE_SEPARATOR," ");
  assertThat(read).matches(pattern.pattern());
  matcher=pattern.matcher(read);
  assertThat(matcher.matches()).isTrue();
  long time2=Long.parseLong(matcher.group(1));
  assertThat(time2).isEqualTo(time);
  writeToFile(_varkFile,VARK_FILE_1);
  read=writeToProcessAndRead("show-startup-time" + LINE_SEPARATOR).replace(LINE_SEPARATOR," ");
  assertThat(read).matches(pattern.pattern());
  matcher=pattern.matcher(read);
  assertThat(matcher.matches()).isTrue();
  time2=Long.parseLong(matcher.group(1));
  assertThat(time2).isNotEqualTo(time);
}
 

Example 39

From project acceleo-webapp-generator, under directory /plugins/org.eclipse.acceleo.tutorial/src/org/eclipse/acceleo/tutorial/wizard/.

Source file: EclipseConWizard.java

  17 
vote

/** 
 * Tries and find an encoding value on the very first line of the file contents.
 * @param fileContent The content from which to read an encoding value.
 * @return The charset name if it exists and is supported, <code>null</code> otherwise
 */
private static String getCharset(String fileContent){
  String trimmedContent=fileContent.trim();
  String charsetName=null;
  if (trimmedContent.length() > 0) {
    BufferedReader reader=new BufferedReader(new StringReader(trimmedContent));
    String firstLine=trimmedContent;
    try {
      firstLine=reader.readLine();
    }
 catch (    IOException e) {
    }
    Pattern encodingPattern=Pattern.compile("encoding\\s*=\\s*(\"|\')?([-a-zA-Z0-9]+)\1?");
    Matcher matcher=encodingPattern.matcher(firstLine);
    if (matcher.find()) {
      charsetName=matcher.group(2);
    }
  }
  if (charsetName != null && Charset.isSupported(charsetName)) {
    return charsetName;
  }
  return null;
}
 

Example 40

From project accesointeligente, under directory /src/org/accesointeligente/server/robots/.

Source file: SGS.java

  17 
vote

public void detectCharacterEncoding(){
  HttpGet get;
  HttpResponse response;
  Header contentType;
  Pattern pattern;
  Matcher matcher;
  try {
    get=new HttpGet(baseUrl + homeAction);
    response=client.execute(get);
    contentType=response.getFirstHeader("Content-Type");
    EntityUtils.consume(response.getEntity());
    if (contentType == null || contentType.getValue() == null) {
      characterEncoding="ISO-8859-1";
    }
    pattern=Pattern.compile(".*charset=(.+)");
    matcher=pattern.matcher(contentType.getValue());
    if (!matcher.matches()) {
      characterEncoding="ISO-8859-1";
    }
    characterEncoding=matcher.group(1);
  }
 catch (  Exception e) {
    characterEncoding="ISO-8859-1";
  }
}
 

Example 41

From project addis, under directory /application/src/main/java/org/drugis/addis/util/jaxb/.

Source file: JAXBHandler.java

  17 
vote

public static XmlFormatType determineXmlType(InputStream is) throws IOException {
  is.mark(1024);
  byte[] buffer=new byte[1024];
  int bytesRead=is.read(buffer);
  if (bytesRead < 0) {
    return new XmlFormatType(XmlFormatType.INVALID);
  }
  String str=new String(buffer,0,bytesRead);
  Pattern addisPattern=Pattern.compile("^(<\\?xml[^\\?]*\\?>[\\s]*)?<addis-data[^>]*>");
  Matcher addisMatcher=addisPattern.matcher(str);
  if (!addisMatcher.find()) {
    return new XmlFormatType(XmlFormatType.INVALID);
  }
  Pattern versionPattern=Pattern.compile("http://drugis.org/files/addis-([0-9]*).xsd");
  Matcher versionMatcher=versionPattern.matcher(str);
  XmlFormatType type=null;
  if (versionMatcher.find()) {
    type=new XmlFormatType(Integer.parseInt(versionMatcher.group(1)));
  }
 else {
    type=new XmlFormatType(XmlFormatType.LEGACY_VERSION);
  }
  is.reset();
  return type;
}
 

Example 42

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

Source file: PermissionsEx.java

  17 
vote

private String limitSearcher(final String limit,final Set<String> perms){
  final Pattern regex=Pattern.compile("admincmd\\." + limit.toLowerCase() + "\\.[0-9]+");
  int max=Integer.MIN_VALUE;
  for (  final String perm : perms) {
    final Matcher regexMatcher=regex.matcher(perm.toLowerCase());
    if (!regexMatcher.find()) {
      continue;
    }
    final int current=Integer.parseInt(perm.split("\\.")[2]);
    if (current < max) {
      continue;
    }
    max=current;
  }
  if (max != Integer.MIN_VALUE) {
    return String.valueOf(max);
  }
  return null;
}
 

Example 43

From project aether-ant, under directory /src/main/java/org/eclipse/aether/ant/types/.

Source file: Dependency.java

  17 
vote

public void setCoords(String coords){
  checkAttributesAllowed();
  if (groupId != null || artifactId != null || version != null || type != null || classifier != null || scope != null) {
    throw ambiguousCoords();
  }
  Pattern p=Pattern.compile("([^: ]+):([^: ]+):([^: ]+)((:([^: ]+)(:([^: ]+))?)?:([^: ]+))?");
  Matcher m=p.matcher(coords);
  if (!m.matches()) {
    throw new BuildException("Bad dependency coordinates" + ", expected format is <groupId>:<artifactId>:<version>[[:<type>[:<classifier>]]:<scope>]");
  }
  groupId=m.group(1);
  artifactId=m.group(2);
  version=m.group(3);
  type=m.group(6);
  if (type == null || type.length() <= 0) {
    type="jar";
  }
  classifier=m.group(8);
  if (classifier == null) {
    classifier="";
  }
  scope=m.group(9);
}
 

Example 44

From project agileBase, under directory /gtpb_server/src/com/gtwm/pb/model/manageData/.

Source file: DataManagement.java

  17 
vote

private static String anonymiseNote(List<String> capitalisedWords,String note){
  String[] alphabet={"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
  Pattern numeralPattern=Pattern.compile("[123456789]");
  Pattern capitalWordsPattern=Pattern.compile("[A-Z][a-z0-9]+");
  String newNote=note;
  Matcher capitalWordMatcher=capitalWordsPattern.matcher(note);
  Random randomGenerator=new Random();
  while (capitalWordMatcher.find()) {
    int capitalWordIndex=randomGenerator.nextInt(capitalisedWords.size());
    String capitalWord=capitalisedWords.get(capitalWordIndex);
    newNote=newNote.replace(capitalWordMatcher.group(),capitalWord);
  }
  Matcher numeralMatcher=numeralPattern.matcher(newNote);
  char[] keyChars=newNote.toCharArray();
  while (numeralMatcher.find()) {
    int position=numeralMatcher.start();
    keyChars[position]=alphabet[randomGenerator.nextInt(26)].charAt(0);
  }
  return String.valueOf(keyChars);
}
 

Example 45

From project akela, under directory /src/main/java/com/mozilla/pig/filter/map/.

Source file: RegexContainsKey.java

  17 
vote

@SuppressWarnings("unchecked") @Override public Boolean exec(Tuple input) throws IOException {
  if (input == null || input.size() < 2) {
    return false;
  }
  Map<String,Object> map=(Map<String,Object>)input.get(0);
  String keyPatternStr=(String)input.get(1);
  Pattern p=Pattern.compile(keyPatternStr);
  boolean found=false;
  for (  String k : map.keySet()) {
    if (p.matcher(k).find()) {
      found=true;
      break;
    }
  }
  return found;
}
 

Example 46

From project Alerte-voirie-android, under directory /src/com/fabernovel/alertevoirie/.

Source file: SelectPositionActivity.java

  17 
vote

@Override protected String[] doInBackground(Double... params){
  String[] result=new String[4];
  try {
    List<Address> addr;
    if (!search) {
      addr=geo.getFromLocation(params[0],params[1],1);
    }
 else {
      String address=((TextView)findViewById(R.id.EditText_address_number)).getText().toString() + " " + ((TextView)findViewById(R.id.EditText_address_street)).getText().toString()+ " , "+ ((TextView)findViewById(R.id.EditText_address_town)).getText().toString();
      addr=geo.getFromLocationName(address,1);
      if (addr.size() > 0) {
        geopoint=new GeoPoint((int)(addr.get(0).getLatitude() * 1E6),(int)(addr.get(0).getLongitude() * 1E6));
      }
    }
    if (addr.size() > 0) {
      result[0]=addr.get(0).getAddressLine(0);
      result[3]=addr.get(0).getLocality();
      result[2]=addr.get(0).getPostalCode();
      Pattern p=Pattern.compile("^[\\d\\-]+");
      Matcher m=p.matcher(result[0]);
      if (m.find()) {
        result[1]=m.group();
        result[0]=result[0].replace(result[1],"");
      }
    }
  }
 catch (  IOException e) {
    Log.e(Constants.PROJECT_TAG,"Address error",e);
  }
  return result;
}
 

Example 47

From project anadix, under directory /domains/anadix-html/src/main/java/org/anadix/html/.

Source file: Attributes.java

  17 
vote

/** 
 * Parses the style into list of key - value pairs
 * @param style String representation of style
 * @return list of key - value pairs
 */
public static Properties parseStyle(String style){
  Properties result=new Properties();
  style=style.replace("\r","").replace("\n","").replace("\t","");
  Pattern p=Pattern.compile("[^:;]+:([^;\"]|\"[^\"]+\")*;?");
  Matcher m=p.matcher(style);
  while (m.find()) {
    String prop=m.group().trim();
    if (prop.endsWith(";")) {
      prop=prop.substring(0,prop.length() - 1);
    }
    String[] split=prop.split(":");
    if (split.length < 2) {
      LoggerFactory.getLogger(Attributes.class).warn("CSS property without value: '{}'",prop);
      continue;
    }
    result.setProperty(split[0].trim(),split[1].trim());
  }
  return result;
}
 

Example 48

From project Android-automation, under directory /Tmts_Java/src/com/taobao/tmts/framework/utils/.

Source file: ClickUtils.java

  17 
vote

/** 
 * Clicks on a specific  {@link TextView} displaying a given text.
 * @param regex the text that should be clicked on. The parameter <strong>will</strong> be interpreted as a regular expression.
 * @param longClick {@code true} if the click should be a long click
 * @param match the regex match that should be clicked on
 * @param scroll whether to scroll to find the regex
 * @param time the amount of time to long click
 * @throws InterruptedException 
 */
public void clickOnText(String regex,boolean longClick,int match,boolean scroll,int time) throws InterruptedException {
  final Pattern pattern=Pattern.compile(regex);
  TextView textToClick=null;
  ArrayList<TextView> textViewList=viewUtils.getCurrentViews(TextView.class);
  textViewList=ViewUtils.removeInvisibleViews(textViewList);
  if (match == 0) {
    match=1;
  }
  for (  TextView textView : textViewList) {
    if (pattern.matcher(textView.getText().toString()).find()) {
      matchCounter.addMatchToCount();
    }
    if (matchCounter.getTotalCount() == match) {
      matchCounter.resetCount();
      textToClick=textView;
      break;
    }
  }
  if (textToClick != null) {
    clickOnScreen(this.inst,textToClick,longClick);
  }
 else   if (scroll && scrollUtils.scroll(ScrollUtils.DOWN)) {
    clickOnText(regex,longClick,match,scroll,time);
  }
 else {
    if (matchCounter.getTotalCount() > 0)     Assert.assertTrue("There are only " + matchCounter.getTotalCount() + " matches of "+ regex,false);
 else {
      for (      TextView textView : textViewList) {
        Log.d(LOG_TAG,regex + " not found. Have found: " + textView.getText());
      }
      Assert.assertTrue("The text: " + regex + " is not found!",false);
    }
    matchCounter.resetCount();
  }
}
 

Example 49

From project android-bankdroid, under directory /src/com/liato/bankdroid/banking/banks/.

Source file: Chalmrest.java

  17 
vote

@Override public void update() throws BankException, LoginException, BankChoiceException {
  super.update();
  if (username == null || username.length() == 0)   throw new LoginException(res.getText(R.string.invalid_username_password).toString());
  try {
    String cardNr=username;
    HttpClient httpclient=new DefaultHttpClient();
    HttpGet httpget=new HttpGet("http://kortladdning.chalmerskonferens.se/bgw.aspx?type=getCardAndArticles&card=" + cardNr);
    HttpResponse response=httpclient.execute(httpget);
    HttpEntity entity=response.getEntity();
    if (entity == null)     throw new BankException("Couldn't connect!");
    String s1=EntityUtils.toString(entity);
    Pattern pattern=Pattern.compile("<ExtendedInfo Name=\"Kortvarde\" Type=\"System.Double\" >(.*?)</ExtendedInfo>");
    Matcher matcher=pattern.matcher(s1);
    if (!matcher.find())     throw new BankException("Couldn't parse value!");
    String value=matcher.group(1);
    StringBuilder sb=new StringBuilder();
    int last=0;
    Matcher match=Pattern.compile("_x([0-9A-Fa-f]{4})_").matcher(value);
    while (match.find()) {
      sb.append(value.substring(last,Math.max(match.start() - 1,0)));
      int i=Integer.parseInt(match.group(1),16);
      sb.append((char)i);
      last=match.end();
    }
    sb.append(value.substring(last));
    value=sb.toString();
    matcher=Pattern.compile("<CardInfo id=\"" + cardNr + "\" Name=\"(.*?)\"").matcher(s1);
    if (!matcher.find())     throw new BankException("Coldn't parse name!");
    String name=matcher.group(1);
    accounts.add(new Account(name,BigDecimal.valueOf(Double.parseDouble(value)),"1"));
  }
 catch (  Exception e) {
    throw new BankException(e.getMessage());
  }
 finally {
    super.updateComplete();
  }
}
 

Example 50

From project android_aosp_packages_apps_Settings, under directory /src/com/android/settings/.

Source file: DeviceInfoSettings.java

  17 
vote

private String getFormattedKernelVersion(){
  String procVersionStr;
  try {
    BufferedReader reader=new BufferedReader(new FileReader("/proc/version"),256);
    try {
      procVersionStr=reader.readLine();
    }
  finally {
      reader.close();
    }
    final String PROC_VERSION_REGEX="\\w+\\s+" + "\\w+\\s+" + "([^\\s]+)\\s+"+ "\\(([^\\[email protected]]+(?:@[^\\s.]+)?)[^)]*\\)\\s+"+ "\\((?:[^(]*\\([^)]*\\))?[^)]*\\)\\s+"+ "([^\\s]+)\\s+"+ "(?:PREEMPT\\s+)?"+ "(.+)";
    Pattern p=Pattern.compile(PROC_VERSION_REGEX);
    Matcher m=p.matcher(procVersionStr);
    if (!m.matches()) {
      Log.e(TAG,"Regex did not match on /proc/version: " + procVersionStr);
      return "Unavailable";
    }
 else     if (m.groupCount() < 4) {
      Log.e(TAG,"Regex match on /proc/version only returned " + m.groupCount() + " groups");
      return "Unavailable";
    }
 else {
      return (new StringBuilder(m.group(1)).append("\n").append(m.group(2)).append(" ").append(m.group(3)).append("\n").append(m.group(4))).toString();
    }
  }
 catch (  IOException e) {
    Log.e(TAG,"IO Exception when getting kernel version for Device Info screen",e);
    return "Unavailable";
  }
}
 

Example 51

From project andstatus, under directory /src/org/andstatus/app/util/.

Source file: I18n.java

  17 
vote

/** 
 * The function enables to have different localized message formats (actually, any number of them) for different quantities of something. E.g. in Russian we need at least three different messages notifying User  about the number of new tweets: 1 ????  (same for 21, 31, ...) 2 ????? ( same for 3, 4, 22, ... ) 5 ?????? (same for 5, ... 11, 12, 20 ...) ... see /res/values-ru/arrays.xml (R.array.appwidget_tweet_patterns)
 * @author yvolk (Yuri Volkov), http://yurivolkov.com
 */
public static String formatQuantityMessage(Context context,int messageFormat,int quantityOfSomething,int array_patterns,int array_formats){
  String submessage="";
  String message="";
  String toMatch=new Integer(quantityOfSomething).toString();
  String[] p=context.getResources().getStringArray(array_patterns);
  String[] f=context.getResources().getStringArray(array_formats);
  String subformat="{0} ???";
  for (int i=0; i < p.length; i++) {
    Pattern pattern=Pattern.compile(p[i]);
    Matcher m=pattern.matcher(toMatch);
    if (m.matches()) {
      subformat=f[i];
      break;
    }
  }
  MessageFormat msf=new MessageFormat(subformat);
  submessage=msf.format(new Object[]{quantityOfSomething});
  if (messageFormat == 0) {
    message=submessage;
  }
 else {
    MessageFormat mf=new MessageFormat(context.getText(messageFormat).toString());
    message=mf.format(new Object[]{submessage});
  }
  if (MyLog.isLoggable(TAG,Log.VERBOSE)) {
    Log.v(TAG,"formatMessage, num=" + toMatch + "; subformat="+ subformat+ "; submessage="+ submessage+ "; message="+ message);
  }
  return message;
}
 

Example 52

From project andtweet, under directory /src/com/xorcode/andtweet/util/.

Source file: I18n.java

  17 
vote

/** 
 * The function enables to have different localized message formats (actually, any number of them) for different quantities of something. E.g. in Russian we need at least three different messages notifying User  about the number of new tweets: 1 ????  (same for 21, 31, ...) 2 ????? ( same for 3, 4, 22, ... ) 5 ?????? (same for 5, ... 11, 12, 20 ...) ... see /res/values-ru/arrays.xml (R.array.appwidget_tweet_patterns)
 * @author yvolk (Yuri Volkov), http://yurivolkov.com
 */
public static String formatQuantityMessage(Context context,int messageFormat,int quantityOfSomething,int array_patterns,int array_formats){
  String submessage="";
  String message="";
  String toMatch=new Integer(quantityOfSomething).toString();
  String[] p=context.getResources().getStringArray(array_patterns);
  String[] f=context.getResources().getStringArray(array_formats);
  String subformat="{0} ???";
  for (int i=0; i < p.length; i++) {
    Pattern pattern=Pattern.compile(p[i]);
    Matcher m=pattern.matcher(toMatch);
    if (m.matches()) {
      subformat=f[i];
      break;
    }
  }
  MessageFormat msf=new MessageFormat(subformat);
  submessage=msf.format(new Object[]{quantityOfSomething});
  if (messageFormat == 0) {
    message=submessage;
  }
 else {
    MessageFormat mf=new MessageFormat(context.getText(messageFormat).toString());
    message=mf.format(new Object[]{submessage});
  }
  if (Log.isLoggable(AndTweetService.APPTAG,Log.VERBOSE)) {
    Log.v(TAG,"formatMessage, num=" + toMatch + "; subformat="+ subformat+ "; submessage="+ submessage+ "; message="+ message);
  }
  return message;
}
 

Example 53

From project apg, under directory /src/org/thialfihar/android/apg/ui/widget/.

Source file: UserIdEditor.java

  17 
vote

public void setValue(String userId){
  mName.setText("");
  mComment.setText("");
  mEmail.setText("");
  Pattern withComment=Pattern.compile("^(.*) [(](.*)[)] <(.*)>$");
  Matcher matcher=withComment.matcher(userId);
  if (matcher.matches()) {
    mName.setText(matcher.group(1));
    mComment.setText(matcher.group(2));
    mEmail.setText(matcher.group(3));
    return;
  }
  Pattern withoutComment=Pattern.compile("^(.*) <(.*)>$");
  matcher=withoutComment.matcher(userId);
  if (matcher.matches()) {
    mName.setText(matcher.group(1));
    mEmail.setText(matcher.group(2));
    return;
  }
}
 

Example 54

From project Arecibo, under directory /agent/src/main/java/com/ning/arecibo/agent/config/jmx/.

Source file: JMXDynamicUtils.java

  17 
vote

private static String expandAccessorName(JMXConfig config,String expObjectName){
  try {
    String wildCardedObjectName=config.getObjectName();
    String objectNameRE=wildCardedObjectName.replace(wildCardDelim,"(.+)");
    objectNameRE=objectNameRE.replace("$","\\$");
    Pattern pattern=Pattern.compile(objectNameRE);
    Matcher matcher=pattern.matcher(expObjectName);
    if (!matcher.matches()) {
      log.warn("ObjectName mismatch, for config objectName '%s' and found objectName '%s' for host %s",objectNameRE,expObjectName,config.getHost());
      return "";
    }
    String expEventType=config.getEventType();
    for (int i=1; i <= matcher.groupCount(); i++) {
      expEventType=expEventType.replaceFirst("\\" + wildCardDelim,matcher.group(i));
    }
    if (log.isDebugEnabled() && (!wildCardedObjectName.equals(expObjectName) || !config.getEventType().equals(expEventType)))     log.debug("DynoAcc %s --> %s ; %s --> %s",wildCardedObjectName,expObjectName,config.getEventType(),expEventType);
    return expEventType;
  }
 catch (  Exception ex) {
    return config.getEventType();
  }
}
 

Example 55

From project arquillian-container-glassfish, under directory /glassfish-common/src/main/java/org/jboss/arquillian/container/glassfish/clientutils/.

Source file: GlassFishClientService.java

  17 
vote

/** 
 * Get the port number of a network listener. Firstly, this method parses the provided String as a number. If this fails, the provided String is parsed as a system property stored in the format - <blockquote>${systemProperty}</blockquote>. The value of the referenced system property is then read from the GlassFish configuration.
 * @param attributes The attributes which references the configuration (server or cluster configuration)
 * @param serverName The name of the server instance
 * @param portNum The port number or a system property that stores the port number
 * @return The port number as stored in the network listener configurationor in the system property
 */
private int getPortValue(Map<String,String> attributes,String serverName,String portNum){
  int portValue=-1;
  try {
    portValue=Integer.parseInt(portNum);
  }
 catch (  NumberFormatException formatEx) {
    Pattern propertyRegex=Pattern.compile(SYSTEM_PROPERTY_REGEX);
    Matcher matcher=propertyRegex.matcher(portNum);
    if (matcher.find()) {
      String propertyName=matcher.group(1);
      portValue=getSystemProperty(attributes,propertyName);
      portValue=getServerSystemProperty(serverName,propertyName,portValue);
    }
  }
  return portValue;
}
 

Example 56

From project arquillian-extension-android, under directory /android-impl/src/main/java/org/jboss/arquillian/android/impl/.

Source file: AndroidDeviceSelector.java

  17 
vote

private Set<String> getAvdDeviceNames(ProcessExecutor executor,AndroidSdk sdk) throws AndroidExecutionException {
  final Pattern deviceName=Pattern.compile("[\\s]*Name: ([^\\s]+)[\\s]*");
  Set<String> names=new HashSet<String>();
  List<String> output;
  try {
    output=executor.execute(sdk.getAndroidPath(),"list","avd");
  }
 catch (  InterruptedException e) {
    throw new AndroidExecutionException("Unable to get list of available AVDs",e);
  }
catch (  ExecutionException e) {
    throw new AndroidExecutionException("Unable to get list of available AVDs",e);
  }
  for (  String line : output) {
    Matcher m;
    if (line.trim().startsWith("Name: ") && (m=deviceName.matcher(line)).matches()) {
      String name=m.group(1);
      if (name == null || name.trim().length() == 0) {
        continue;
      }
      names.add(name);
      if (log.isLoggable(Level.FINE)) {
        log.fine("Available Android Device: " + name);
      }
    }
  }
  return names;
}
 

Example 57

From project aws-maven, under directory /src/main/java/org/springframework/build/aws/maven/.

Source file: SimpleStorageServiceWagon.java

  17 
vote

@Override protected List<String> listDirectory(String directory) throws ResourceDoesNotExistException {
  List<String> directoryContents=new ArrayList<String>();
  try {
    String prefix=getKey(directory);
    Pattern pattern=Pattern.compile(String.format(RESOURCE_FORMAT,prefix));
    ListObjectsRequest listObjectsRequest=new ListObjectsRequest().withBucketName(this.bucketName).withPrefix(prefix).withDelimiter("/");
    ObjectListing objectListing;
    objectListing=this.amazonS3.listObjects(listObjectsRequest);
    directoryContents.addAll(getResourceNames(objectListing,pattern));
    while (objectListing.isTruncated()) {
      objectListing=this.amazonS3.listObjects(listObjectsRequest);
      directoryContents.addAll(getResourceNames(objectListing,pattern));
    }
    return directoryContents;
  }
 catch (  AmazonServiceException e) {
    throw new ResourceDoesNotExistException(String.format("'%s' does not exist",directory),e);
  }
}
 

Example 58

From project aws-toolkit-for-eclipse, under directory /com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui/databinding/.

Source file: ConfigurationSettingValidator.java

  17 
vote

public IStatus validate(Object value){
  String s=(String)value;
  if (configOption.getMaxValue() != null) {
    try {
      Integer i=Integer.parseInt(s);
      if (i > configOption.getMaxValue()) {
        return ValidationStatus.error(configOption.getName() + " must be at most " + configOption.getMaxValue());
      }
    }
 catch (    NumberFormatException e) {
      return ValidationStatus.error(s + " isn't an integer");
    }
  }
  if (configOption.getMinValue() != null) {
    try {
      Integer i=Integer.parseInt(s);
      if (i < configOption.getMinValue()) {
        return ValidationStatus.error(configOption.getName() + " must be at least " + configOption.getMinValue());
      }
    }
 catch (    NumberFormatException e) {
      return ValidationStatus.error(s + " isn't an integer");
    }
  }
  if (configOption.getMaxLength() != null) {
    if (s.length() > configOption.getMaxLength()) {
      return ValidationStatus.error(s + " is too long (max length  " + configOption.getMaxLength()+ ")");
    }
  }
  if (configOption.getRegex() != null) {
    Pattern regex=Pattern.compile(configOption.getRegex().getPattern());
    if (!regex.matcher(s).matches()) {
      return ValidationStatus.error(configOption.getName() + " must match the regular expression " + configOption.getRegex().getPattern());
    }
  }
  return ValidationStatus.ok();
}
 

Example 59

From project Baseform-Epanet-Java-Library, under directory /src/org/addition/epanet/network/io/input/.

Source file: ExcelParser.java

  17 
vote

@Override public Network parse(Network net,File f) throws ENException {
  FileInputStream stream=null;
  try {
    stream=new FileInputStream(f);
    XSSFWorkbook workbook=new XSSFWorkbook(stream);
    findTimeStyle(workbook);
    Pattern tagPattern=Pattern.compile("\\[.*\\]");
    int errSum=0;
    List<XSSFSheet> sheetPC=new ArrayList<XSSFSheet>();
    List<XSSFSheet> sheetOthers=new ArrayList<XSSFSheet>();
    List<XSSFSheet> sheetNodes=new ArrayList<XSSFSheet>();
    List<XSSFSheet> sheetTanks=new ArrayList<XSSFSheet>();
    for (int i=0; i < workbook.getNumberOfSheets(); i++) {
      XSSFSheet sh=workbook.getSheetAt(i);
      if (sh.getSheetName().equalsIgnoreCase("Patterns") || sh.getSheetName().equalsIgnoreCase("Curves")) {
        sheetPC.add(sh);
      }
 else       if (sh.getSheetName().equals("Junctions"))       sheetNodes.add(sh);
 else       if (sh.getSheetName().equals("Tanks") || sh.getSheetName().equals("Reservoirs"))       sheetTanks.add(sh);
 else       sheetOthers.add(sh);
    }
    errSum=parseWorksheet(net,sheetPC,tagPattern,errSum);
    errSum=parseWorksheet(net,sheetNodes,tagPattern,errSum);
    errSum=parseWorksheet(net,sheetTanks,tagPattern,errSum);
    errSum=parseWorksheet(net,sheetOthers,tagPattern,errSum);
    if (errSum != 0)     throw new ENException(200);
    stream.close();
  }
 catch (  IOException e) {
    throw new ENException(302);
  }
  adjust(net);
  net.getFieldsMap().prepare(net.getPropertiesMap().getUnitsflag(),net.getPropertiesMap().getFlowflag(),net.getPropertiesMap().getPressflag(),net.getPropertiesMap().getQualflag(),net.getPropertiesMap().getChemUnits(),net.getPropertiesMap().getSpGrav(),net.getPropertiesMap().getHstep());
  convert(net);
  return net;
}
 

Example 60

From project behemoth, under directory /io/src/main/java/com/digitalpebble/behemoth/io/warc/.

Source file: WarcHTMLResponseRecord.java

  17 
vote

private HashSet<String> getMatchesOutputSet(Vector<String> tagSet,String baseURL){
  HashSet<String> retSet=new HashSet<String>();
  Iterator<String> vIter=tagSet.iterator();
  while (vIter.hasNext()) {
    String thisCheckPiece=vIter.next();
    Iterator<Pattern> pIter=patternSet.iterator();
    boolean hasAdded=false;
    while (!hasAdded && pIter.hasNext()) {
      Pattern thisPattern=pIter.next();
      Matcher matcher=thisPattern.matcher(thisCheckPiece);
      if (matcher.find() && (matcher.groupCount() > 0)) {
        String thisMatch=getNormalizedContentURL(baseURL,matcher.group(1));
        if (HTTP_START_PATTERN.matcher(thisMatch).matches()) {
          if (!retSet.contains(thisMatch) && !baseURL.equals(thisMatch)) {
            retSet.add(thisMatch);
            hasAdded=true;
          }
        }
      }
      matcher.reset();
    }
  }
  return retSet;
}
 

Example 61

From project BF3-Battlelog, under directory /src/com/ninetwozero/battlelog/activity/forum/.

Source file: ForumThreadFragment.java

  17 
vote

private void generatePopupWithLinks(String string){
  if (string == null) {
    Toast.makeText(mContext,R.string.info_forum_links_no,Toast.LENGTH_SHORT).show();
  }
  List<String> links=new ArrayList<String>();
  boolean linkFound=false;
  Pattern linkPattern=Pattern.compile("<a href=\"([^\"]+)\" rel=\"nofollow\">");
  Matcher linkMatcher=linkPattern.matcher(string);
  while (linkMatcher.find()) {
    linkFound=true;
    links.add(linkMatcher.group(1));
  }
  if (linkFound) {
    generateDialogLinkList(mContext,links).show();
  }
 else {
    Toast.makeText(mContext,R.string.info_forum_links_no,Toast.LENGTH_SHORT).show();
  }
}
 

Example 62

From project Bio-PEPA, under directory /uk.ac.ed.inf.biopepa.core/src/uk/ac/ed/inf/biopepa/core/sba/export/.

Source file: SBMLExport.java

  17 
vote

private void mapNames(Set<String> names){
  String s;
  Set<String> currentlyUsed=new HashSet<String>();
  currentlyUsed.addAll(sbmlMap.values());
  Pattern p;
  ArrayList<Integer> numbers;
  int[] intArray;
  for (  String next : names) {
    s=flattenName(next);
    numbers=new ArrayList<Integer>();
    p=Pattern.compile(s + "_\\d+");
    for (    String existing : currentlyUsed)     if (p.matcher(existing).matches())     numbers.add(new Integer(existing.substring(s.length() + 1)));
    if (numbers.size() > 0) {
      intArray=new int[numbers.size()];
      for (int i=0; i < intArray.length; i++)       intArray[i]=numbers.get(i);
      Arrays.sort(intArray);
      s=s + "_" + (intArray[intArray.length - 1] + 1);
    }
 else     s=s + "_2";
    currentlyUsed.add(s);
    sbmlMap.put(next,s);
  }
}
 

Example 63

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

Source file: QuickFindDialog.java

  17 
vote

public void showFor(final JTextComponent target){
  oldCaretPosition=target.getCaretPosition();
  Container view=target.getParent();
  Dimension wd=getSize();
  wd.width=target.getVisibleRect().width;
  Point loc=new Point(0,view.getHeight());
  setSize(wd);
  setLocationRelativeTo(view);
  SwingUtilities.convertPointToScreen(loc,view);
  setLocation(loc);
  jTxtFind.setFont(target.getFont());
  jTxtFind.getDocument().addDocumentListener(this);
  WindowAdapter closeListener=new WindowAdapter(){
    @Override public void windowDeactivated(    WindowEvent e){
      target.getDocument().removeDocumentListener(QuickFindDialog.this);
      Markers.removeMarkers(target,marker);
      if (escaped) {
        Rectangle aRect;
        try {
          aRect=target.modelToView(oldCaretPosition);
          target.setCaretPosition(oldCaretPosition);
          target.scrollRectToVisible(aRect);
        }
 catch (        BadLocationException ex) {
        }
      }
      dispose();
    }
  }
;
  addWindowListener(closeListener);
  this.target=new WeakReference<JTextComponent>(target);
  Pattern p=dsd.get().getPattern();
  if (p != null) {
    jTxtFind.setText(p.pattern());
  }
  jChkWrap.setSelected(dsd.get().isWrap());
  setVisible(true);
}
 

Example 64

From project activemq-apollo, under directory /apollo-selector/src/main/java/org/apache/activemq/apollo/filter/.

Source file: ComparisonExpression.java

  15 
vote

/** 
 * @param left
 */
public LikeExpression(Expression right,String like,int escape){
  super(right);
  StringBuffer regexp=new StringBuffer(like.length() * 2);
  regexp.append("\\A");
  for (int i=0; i < like.length(); i++) {
    char c=like.charAt(i);
    if (escape == (0xFFFF & c)) {
      i++;
      if (i >= like.length()) {
        break;
      }
      char t=like.charAt(i);
      regexp.append("\\x");
      regexp.append(Integer.toHexString(0xFFFF & t));
    }
 else     if (c == '%') {
      regexp.append(".*?");
    }
 else     if (c == '_') {
      regexp.append(".");
    }
 else     if (REGEXP_CONTROL_CHARS.contains(new Character(c))) {
      regexp.append("\\x");
      regexp.append(Integer.toHexString(0xFFFF & c));
    }
 else {
      regexp.append(c);
    }
  }
  regexp.append("\\z");
  likePattern=Pattern.compile(regexp.toString(),Pattern.DOTALL);
}
 

Example 65

From project agit, under directory /agit/src/main/java/com/madgag/agit/filepath/.

Source file: FilePathMatcher.java

  15 
vote

private static Pattern patternFor(CharSequence constraint){
  StringBuilder builder=new StringBuilder(".*");
  for (int i=0; i < constraint.length(); ++i) {
    builder.append("(").append(quote("" + constraint.charAt(i))).append(").*?");
  }
  builder.append("$");
  return Pattern.compile(builder.toString(),CASE_INSENSITIVE);
}
 

Example 66

From project AirCastingAndroidClient, under directory /src/main/java/pl/llp/aircasting/helper/.

Source file: CSVHelper.java

  15 
vote

String fileName(String title){
  StringBuilder result=new StringBuilder();
  if (!Strings.isNullOrEmpty(title)) {
    try {
      Matcher matcher=Pattern.compile("([_\\-a-zA-Z0-9])*").matcher(title.toLowerCase());
      while (matcher.find()) {
        result.append(matcher.group());
      }
    }
 catch (    IllegalStateException ignore) {
    }
  }
  return result.length() > 0 ? result.append(".csv").toString() : SESSION_TEMP_FILE;
}
 

Example 67

From project AndroidDevWeekendDub-BookLibrary, under directory /src/org/curiouscreature/android/shelves/provider/.

Source file: BooksProvider.java

  15 
vote

private String keyFor(String name){
  if (name == null)   name="";
  name=name.trim().toLowerCase();
  if (mKeyPrefixes == null) {
    final Resources resources=getContext().getResources();
    final String[] keyPrefixes=resources.getStringArray(R.array.prefixes);
    final int count=keyPrefixes.length;
    mKeyPrefixes=new Pattern[count];
    for (int i=0; i < count; i++) {
      mKeyPrefixes[i]=Pattern.compile("^" + keyPrefixes[i] + "\\s+");
    }
  }
  if (mKeySuffixes == null) {
    final Resources resources=getContext().getResources();
    final String[] keySuffixes=resources.getStringArray(R.array.suffixes);
    final int count=keySuffixes.length;
    mKeySuffixes=new Pattern[count];
    for (int i=0; i < count; i++) {
      mKeySuffixes[i]=Pattern.compile("\\s*" + keySuffixes[i] + "$");
    }
  }
  final Pattern[] prefixes=mKeyPrefixes;
  for (  Pattern prefix : prefixes) {
    final Matcher matcher=prefix.matcher(name);
    if (matcher.find()) {
      name=name.substring(matcher.end());
      break;
    }
  }
  final Pattern[] suffixes=mKeySuffixes;
  for (  Pattern suffix : suffixes) {
    final Matcher matcher=suffix.matcher(name);
    if (matcher.find()) {
      name=name.substring(0,matcher.start());
      break;
    }
  }
  return name;
}
 

Example 68

From project android_external_guava, under directory /src/com/google/common/base/.

Source file: Splitter.java

  15 
vote

/** 
 * Returns a splitter that considers any subsequence matching  {@code pattern} to be a separator. For example, {@code Splitter.on(Pattern.compile("\r?\n")).split(entireFile)} splits a stringinto lines whether it uses DOS-style or UNIX-style line terminators.
 * @param separatorPattern the pattern that determines whether a subsequenceis a separator. This pattern may not match the empty string.
 * @return a splitter, with default settings, that uses this pattern
 * @throws IllegalArgumentException if {@code separatorPattern} matches theempty string
 */
public static Splitter on(final Pattern separatorPattern){
  checkNotNull(separatorPattern);
  checkArgument(!separatorPattern.matcher("").matches(),"The pattern may not match the empty string: %s",separatorPattern);
  return new Splitter(new Strategy(){
    public SplittingIterator iterator(    final Splitter splitter,    CharSequence toSplit){
      final Matcher matcher=separatorPattern.matcher(toSplit);
      return new SplittingIterator(splitter,toSplit){
        @Override public int separatorStart(        int start){
          return matcher.find(start) ? matcher.start() : -1;
        }
        @Override public int separatorEnd(        int separatorPosition){
          return matcher.end();
        }
      }
;
    }
  }
);
}
 

Example 69

From project archive-commons, under directory /archive-commons/src/main/java/org/archive/resource/html/.

Source file: ExtractingParseObserver.java

  15 
vote

private void patternCSSExtract(HTMLMetaData data,Pattern pattern,String content){
  Matcher m=pattern.matcher(content);
  int idx=0;
  int contentLen=content.length();
  while ((idx < contentLen) && m.find(idx)) {
    String url=m.group(1);
    int origUrlLength=url.length();
    int urlStart=m.start(1);
    int urlEnd=m.end(1);
    idx=urlEnd;
    if (url.length() < 2) {
      continue;
    }
    if ((url.charAt(0) == '(') && (url.charAt(origUrlLength - 1) == ')')) {
      url=url.substring(1,origUrlLength - 1);
      urlStart+=1;
      origUrlLength-=2;
    }
    if (url.charAt(0) == '"') {
      url=url.substring(1,origUrlLength - 1);
      urlStart+=1;
    }
 else     if (url.charAt(0) == '\'') {
      url=url.substring(1,origUrlLength - 1);
      urlStart+=1;
    }
 else     if (url.charAt(0) == '\\') {
      if (url.length() == 2)       continue;
      url=url.substring(2,origUrlLength - 2);
      urlStart+=2;
    }
    int urlLength=url.length();
    data.addHref("path","STYLE/#text","href",url);
    idx+=urlLength;
  }
}
 

Example 70

From project arquillian-graphene, under directory /graphene-selenium/graphene-selenium-impl/src/main/java/org/jboss/arquillian/ajocado/utils/.

Source file: ColorUtils.java

  15 
vote

/** 
 * <p> Converts a string representation of color to integer. </p> <p> Works with two formats: </p> <ul> <li><code>#09FE4A</code> - <b>hexadecimal</b></li> <li><code>rgb(132, 5, 18)</code> - <b>decimal</b></li> </ul>
 * @param colorValue string represented in one of two formats
 * @return integer value of color derived from string representation
 */
public static int convertToInteger(String colorValue){
  Validate.notNull(colorValue);
  int result=0;
  if (colorValue.charAt(0) == '#') {
    result=Integer.parseInt(colorValue.substring(1),HEX_RADIX);
  }
 else {
    Matcher matcher=Pattern.compile("(\\d+)").matcher(colorValue);
    int[] array=new int[RGB_PARTS];
    for (int i=0; i < RGB_PARTS; i++) {
      if (!matcher.find()) {
        throw new IllegalArgumentException(colorValue);
      }
      array[i]=Short.parseShort(matcher.group(1));
    }
    result=new Color(array[RED_COMPONENT],array[GREEN_COMPONENT],array[BLUE_COMPONENT]).getRGB();
  }
  return result;
}
 

Example 71

From project arquillian_deprecated, under directory /frameworks/cobertura/src/main/java/org/jboss/arquillian/framework/cobertura/.

Source file: CoberturaWrapperAsset.java

  15 
vote

public InputStream openStream(){
  ProjectData projectData=new ProjectData();
  PROJECT_DATA.add(projectData);
  try {
    InputStream inputStream=asset.openStream();
    ClassReader cr=new ClassReader(inputStream);
    ClassWriter cw=new ClassWriter(ClassWriter.COMPUTE_MAXS);
    cr.accept(new ClassInstrumenter(projectData,cw,new ArrayList<Pattern>(),new ArrayList<Pattern>()),0);
    return new ByteArrayInputStream(cw.toByteArray());
  }
 catch (  Exception e) {
    throw new RuntimeException("Could not instrument Asset " + asset,e);
  }
}
 

Example 72

From project artifactory-plugin, under directory /src/main/java/org/jfrog/hudson/util/.

Source file: IssuesTrackerHelper.java

  15 
vote

private Set<String> manuallyCollectIssues(AbstractBuild build,Pattern issuePattern) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
  Class<?> jiraUpdaterClass=Class.forName("hudson.plugins.jira.Updater");
  Method findIssueIdsRecursive=jiraUpdaterClass.getDeclaredMethod("findIssueIdsRecursive",AbstractBuild.class,Pattern.class,BuildListener.class);
  findIssueIdsRecursive.setAccessible(true);
  return (Set<String>)findIssueIdsRecursive.invoke(null,build,issuePattern,new StreamBuildListener(new NullOutputStream()));
}
 

Example 73

From project asterisk-java, under directory /src/main/java/org/asteriskjava/util/internal/.

Source file: SocketConnectionFacadeImpl.java

  15 
vote

/** 
 * Creates a new instance for use with the Manager API that uses the given line delimiter.
 * @param host        the foreign host to connect to.
 * @param port        the foreign port to connect to.
 * @param ssl         <code>true</code> to use SSL, <code>false</code> otherwise.
 * @param timeout     0 incidcates default
 * @param readTimeout see {@link Socket#setSoTimeout(int)}
 * @param lineDelimiter a {@link Pattern} for matching the line delimiter for the socket
 * @throws IOException if the connection cannot be established.
 */
public SocketConnectionFacadeImpl(String host,int port,boolean ssl,int timeout,int readTimeout,Pattern lineDelimiter) throws IOException {
  Socket socket;
  if (ssl) {
    socket=SSLSocketFactory.getDefault().createSocket();
  }
 else {
    socket=SocketFactory.getDefault().createSocket();
  }
  socket.setSoTimeout(readTimeout);
  socket.connect(new InetSocketAddress(host,port),timeout);
  initialize(socket,lineDelimiter);
  if (System.getProperty(Trace.TRACE_PROPERTY,"false").equalsIgnoreCase("true")) {
    trace=new FileTrace(socket);
  }
}
 

Example 74

From project aviator, under directory /src/main/java/com/googlecode/aviator/runtime/type/.

Source file: AviatorPattern.java

  15 
vote

@Override public int compare(AviatorObject other,Map<String,Object> env){
  if (this == other)   return 0;
switch (other.getAviatorType()) {
case Pattern:
    return this.pattern.pattern().compareTo(((AviatorPattern)other).pattern.pattern());
case JavaType:
  if (other.getValue(env) == null) {
    return 1;
  }
 else {
    throw new ExpressionRuntimeException("Could not compare Pattern with " + other.getAviatorType());
  }
case Nil:
return 1;
default :
throw new ExpressionRuntimeException("Could not compare Pattern with " + other.getAviatorType());
}
}
 

Example 75

From project avro, under directory /lang/java/avro/src/test/java/org/apache/avro/util/.

Source file: CaseFinder.java

  15 
vote

/** 
 * Scan test-case file <code>in</code> looking for test subcases marked with <code>caseLabel</code>.  Any such cases are appended (in order) to the "cases" parameter.  If <code>caseLabel</code> equals the string <code>"INPUT"</code>, then returns the list of &lt;<i>input</i>, <code>null</code>&gt; pairs for <i>input</i> equal to all heredoc's named INPUT's found in the input stream. 
 */
public static List<Object[]> find(BufferedReader in,String label,List<Object[]> cases) throws IOException {
  if (!Pattern.matches(LABEL_REGEX,label))   throw new IllegalArgumentException("Bad case subcase label: " + label);
  final String subcaseMarker="<<" + label;
  for (String line=in.readLine(); ; ) {
    while (line != null && !line.startsWith(NEW_CASE_MARKER))     line=in.readLine();
    if (line == null)     break;
    String input;
    input=processHereDoc(in,line);
    if (label.equals(NEW_CASE_NAME)) {
      cases.add(new Object[]{input,null});
      line=in.readLine();
      continue;
    }
    do {
      line=in.readLine();
    }
 while (line != null && (!line.startsWith(NEW_CASE_MARKER) && !line.startsWith(subcaseMarker)));
    if (line == null || line.startsWith(NEW_CASE_MARKER))     continue;
    String expectedOutput=processHereDoc(in,line);
    cases.add(new Object[]{input,expectedOutput});
  }
  in.close();
  return cases;
}
 

Example 76

From project babel, under directory /src/babel/content/eqclasses/properties/.

Source file: PhrasePropertyCollector.java

  15 
vote

protected static InvertibleHashMap<IdxPair,Integer> getAllDelims(String sent,Pattern delimPattern){
  InvertibleHashMap<IdxPair,Integer> spaces=new InvertibleHashMap<IdxPair,Integer>();
  Matcher m=delimPattern.matcher(sent);
  boolean startsWithDelim=false;
  boolean endsWithDelim=false;
  int idx=1;
  int sentLength=sent.length();
  if (sent.length() > 0) {
    while (m.find()) {
      if (m.start() == 0) {
        startsWithDelim=true;
        idx=0;
      }
      if (m.end() == sentLength) {
        endsWithDelim=true;
      }
      spaces.put(new IdxPair(m.start(),m.end()),idx++);
    }
    if (!startsWithDelim) {
      spaces.put(new IdxPair(0,0),0);
    }
    if (!endsWithDelim) {
      spaces.put(new IdxPair(sent.length(),sent.length()),idx);
    }
  }
  return spaces;
}
 

Example 77

From project bagheera, under directory /src/main/java/com/mozilla/bagheera/validation/.

Source file: Validator.java

  15 
vote

public Validator(final String[] validNamespaces){
  if (validNamespaces == null || validNamespaces.length == 0) {
    throw new IllegalArgumentException("No valid namespace was specified");
  }
  StringBuilder nsPatternBuilder=new StringBuilder("(");
  int i=0, size=validNamespaces.length;
  for (  String name : validNamespaces) {
    nsPatternBuilder.append(name.replaceAll("\\*",".+"));
    if ((i + 1) < size) {
      nsPatternBuilder.append("|");
    }
    i++;
  }
  nsPatternBuilder.append(")");
  LOG.info("Namespace pattern: " + nsPatternBuilder.toString());
  validNamespacePattern=Pattern.compile(nsPatternBuilder.toString());
  jsonFactory=new JsonFactory();
}
 

Example 78

From project BazaarUtils, under directory /src/com/android/vending/licensing/.

Source file: ResponseData.java

  15 
vote

/** 
 * Parses response string into ResponseData.
 * @param responseData response data string
 * @throws IllegalArgumentException upon parsing error
 * @return ResponseData object
 */
public static ResponseData parse(String responseData){
  TextUtils.StringSplitter splitter=new TextUtils.SimpleStringSplitter(':');
  splitter.setString(responseData);
  Iterator<String> it=splitter.iterator();
  if (!it.hasNext()) {
    throw new IllegalArgumentException("Blank response.");
  }
  final String mainData=it.next();
  String extraData="";
  if (it.hasNext()) {
    extraData=it.next();
  }
  String[] fields=TextUtils.split(mainData,Pattern.quote("|"));
  if (fields.length < 6) {
    throw new IllegalArgumentException("Wrong number of fields.");
  }
  ResponseData data=new ResponseData();
  data.extra=extraData;
  data.responseCode=Integer.parseInt(fields[0]);
  data.nonce=Integer.parseInt(fields[1]);
  data.packageName=fields[2];
  data.versionCode=fields[3];
  data.userId=fields[4];
  data.timestamp=Long.parseLong(fields[5]);
  return data;
}
 

Example 79

From project beanmill_1, under directory /src/main/java/com/traxel/lumbermill/filter/.

Source file: Regex.java

  15 
vote

/** 
 * ------------------------------------------ Instance Accessors ------------------------------------------
 * @param regex  DOCUMENT ME!
 * @throws Exception  DOCUMENT ME!
 */
public void setRegex(String regex) throws Exception {
  if ((regex == null) || "".equals(regex)) {
    _pattern=null;
  }
 else {
    regex=".*" + regex + ".*";
    regex=regex.replaceAll("(\\.\\*)+",".*");
    _pattern=Pattern.compile(regex,Pattern.DOTALL);
  }
  FILTER_NOTIFIER.fireFilterChange();
}
 

Example 80

From project BeeQueue, under directory /src/org/beequeue/util/.

Source file: Strings.java

  15 
vote

/** 
 * check input against list of regex'es
 * @param input
 * @param regexs
 * @return <code>null</code> if list of regex'es empty, <code>true</code>if any of regex'es match, or <code>false</code> otherwise
 */
public static Boolean matchesAny(String input,List<Pattern> regexs){
  if (regexs == null || regexs.size() == 0) {
    return null;
  }
  for (  Pattern p : regexs) {
    Matcher m=p.matcher(input);
    if (m.matches()) {
      return true;
    }
  }
  return false;
}
 

Example 81

From project BetterShop_1, under directory /src/me/jascotty2/lib/io/.

Source file: CheckInput.java

  15 
vote

public static long GetLong(String input,long onError){
  if (input == null) {
    return onError;
  }
  try {
    return Pattern.matches(IntPattern,input) ? Long.parseLong(input) : onError;
  }
 catch (  NumberFormatException e) {
    return onError;
  }
}
 

Example 82

From project big-data-plugin, under directory /shims/common/src/org/pentaho/hadoop/shim/common/.

Source file: DistributedCacheUtilImpl.java

  15 
vote

/** 
 * Looks for all files in the path within the given file system that match the pattern provided. Only the direct descendants of  {@code path} will be evaluated; this is not recursive.
 * @param fs File system to search within
 * @param path Path to search in
 * @param fileNamePattern Pattern of file name to match. If {@code null}, all files will be matched.
 * @return All {@link Path}s that match the provided pattern.
 * @throws IOException Error retrieving listing status of a path from the file system
 */
public List<Path> findFiles(FileSystem fs,Path path,Pattern fileNamePattern) throws IOException {
  FileStatus[] files=fs.listStatus(path);
  List<Path> found=new ArrayList<Path>(files.length);
  for (  FileStatus file : files) {
    if (fileNamePattern == null || fileNamePattern.matcher(file.getPath().toString()).matches()) {
      found.add(file.getPath());
    }
  }
  return found;
}
 

Example 83

From project Birthday-widget, under directory /Birthday/src/main/java/cz/krtinec/birthday/data/.

Source file: BirthdayProvider.java

  15 
vote

/** 
 * @param string
 * @return
 * @throws ParseException
 * @throws IllegalArgumentException
 */
public static ParseResult tryParseBDay(String string) throws ParseException {
  if (string == null) {
    throw new ParseException("Cannot parse: <null>",0);
  }
  if (string.matches(TIMESTAMP_PATTERN)) {
    LocalDate date=new DateTime(Long.parseLong(string)).withZone(DateTimeZone.UTC).toLocalDate();
    return new ParseResult(date,DateIntegrity.FULL);
  }
  Matcher m;
  for (  DatePattern pat : PATTERNS) {
    m=Pattern.compile(pat.pattern).matcher(string);
    if (m.find()) {
      string=string.substring(m.start(),m.end());
      LocalDate date=pat.format.withZone(DateTimeZone.UTC).parseDateTime(string).toLocalDate();
      return new ParseResult(date,pat.integrity);
    }
  }
  throw new ParseException("Cannot parse: " + string,0);
}
 

Example 84

From project Bitcoin-Wallet-for-Android, under directory /wallet/src/de/schildbach/wallet/util/.

Source file: ErrorReporter.java

  15 
vote

private static void sendErrorMail(final Context context,final String errorContent){
  final Intent sendIntent=new Intent(Intent.ACTION_SEND);
  final Matcher m=Pattern.compile("Version: (.+?) ").matcher(errorContent);
  final String versionName=m.find() ? m.group(1) : "";
  final String subject=REPORT_SUBJECT + " " + versionName;
  sendIntent.putExtra(Intent.EXTRA_EMAIL,new String[]{REPORT_EMAIL});
  sendIntent.putExtra(Intent.EXTRA_TEXT,errorContent);
  sendIntent.putExtra(Intent.EXTRA_SUBJECT,subject);
  sendIntent.setType("message/rfc822");
  context.startActivity(Intent.createChooser(sendIntent,"Send Crash Report using..."));
}
 

Example 85

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

Source file: BlameSubversionSCM.java

  15 
vote

private Pattern[] getExcludedRegionsPatterns(){
  String[] excluded=getExcludedRegionsNormalized();
  if (excluded != null) {
    Pattern[] patterns=new Pattern[excluded.length];
    int i=0;
    for (    String excludedRegion : excluded) {
      patterns[i++]=Pattern.compile(excludedRegion);
    }
    return patterns;
  }
  return new Pattern[0];
}
 

Example 86

From project Blueprint, under directory /blueprint-core/src/main/java/org/codemined/util/.

Source file: Strings.java

  15 
vote

public static List<String> split(String str,String separator){
  if (str == null) {
    throw new IllegalArgumentException("cannot split null string");
  }
  if (separator == null) {
    throw new IllegalArgumentException("separator cannot be null");
  }
  if (separator.isEmpty()) {
    throw new IllegalArgumentException("separator cannot be an empty string");
  }
  return Arrays.asList(str.split(Pattern.quote(separator)));
}
 

Example 87

From project blueprint-namespaces, under directory /blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/ext/.

Source file: AbstractPropertyPlaceholder.java

  15 
vote

protected Pattern getPattern(){
  if (pattern == null) {
    pattern=Pattern.compile("\\Q" + placeholderPrefix + "\\E(.+?)\\Q"+ placeholderSuffix+ "\\E");
  }
  return pattern;
}