构建正则表达式

从"TimeExp-Rules.txt"文件中抽取时间表达式相关的正则表达式，
将所有正则表达式整合，构成一个完整的正则表达式用于识别文本中的时间表达式

@param none 该方法没有参数
@return String 返回整合后的正则表达式
@throws IOException 文件读取错误时抛出
326531
private static String loadtxt(String path){
		String rules = "";
		try {		
			InputStreamReader  read = new InputStreamReader (new FileInputStream(path),"utf-8");
			BufferedReader bin = new BufferedReader(read);
			String _ruleunit = bin.readLine();
			while (_ruleunit!=null)
			{
				if (!_ruleunit.startsWith("-"))
				{
					if(rules.equals(""))
						rules=rules+"("+_ruleunit+")";
					else
						rules=rules+"|("+_ruleunit+")";
				}	
				_ruleunit=bin.readLine();
			}
		}catch(Exception e){
			System.out.println("正则表达式文件未找到！");
		}
		return rules;
	}
77570
public String getRawTimestamp() throws IOException {

        final NetTimeConfiguration config = this.getNetTimeConfiguration();

        String address = config.getTimeServerAddress();
        int port = config.getTimeServerPort();
        int timeout = config.getConnectionTimeout();

        return getDaytimeReply(address, port, timeout);

    }
123760
public synchronized DownloadResponse getJnlpFileEx( JnlpResource jnlpres, DownloadRequest dreq )
            throws IOException
    {
        String path = jnlpres.getPath();
        URL resource = jnlpres.getResource();
        long lastModified = jnlpres.getLastModified();

        _log.addDebug( "lastModified: " + lastModified + " " + new Date( lastModified ) );
        if ( lastModified == 0 )
        {
            _log.addWarning( "servlet.log.warning.nolastmodified", path );
        }

        // fix for 4474854:  use the request URL as key to look up jnlp file
        // in hash map
        String reqUrl = HttpUtils.getRequestURL( dreq.getHttpRequest() ).toString();
        // SQE: To support query string, we changed the hash key from Request URL to (Request URL + query string)
        if ( dreq.getQuery() != null )
        {
            reqUrl += dreq.getQuery();
        }

        // Check if entry already exist in HashMap
        JnlpFileEntry jnlpFile = (JnlpFileEntry) _jnlpFiles.get( reqUrl );

        if ( jnlpFile != null && jnlpFile.getLastModified() == lastModified )
        {
            // Entry found in cache, so return it
            return jnlpFile.getResponse();
        }

        // Read information from WAR file
        long timeStamp = lastModified;
        String mimeType = _servletContext.getMimeType( path );
        if ( mimeType == null )
        {
            mimeType = JNLP_MIME_TYPE;
        }

        StringBuilder jnlpFileTemplate = new StringBuilder();
        URLConnection conn = resource.openConnection();
        BufferedReader br = new BufferedReader( new InputStreamReader( conn.getInputStream(), "UTF-8" ) );
        String line = br.readLine();
        if ( line != null && line.startsWith( "TS:" ) )
        {
            timeStamp = parseTimeStamp( line.substring( 3 ) );
            _log.addDebug( "Timestamp: " + timeStamp + " " + new Date( timeStamp ) );
            if ( timeStamp == 0 )
            {
                _log.addWarning( "servlet.log.warning.notimestamp", path );
                timeStamp = lastModified;
            }
            line = br.readLine();
        }
        while ( line != null )
        {
            jnlpFileTemplate.append( line );
            line = br.readLine();
        }

        String jnlpFileContent = specializeJnlpTemplate( dreq.getHttpRequest(), path, jnlpFileTemplate.toString() );

        /* SQE: We need to add query string back to href in jnlp file. We also need to handle JRE requirement for
       * the test. We reconstruct the xml DOM object, modify the value, then regenerate the jnlpFileContent.
       */
        String query = dreq.getQuery();
        String testJRE = dreq.getTestJRE();
        _log.addDebug( "Double check query string: " + query );
        // For backward compatibility: Always check if the href value exists.
        // Bug 4939273: We will retain the jnlp template structure and will NOT add href value. Above old
        // approach to always check href value caused some test case not run.
        if ( query != null )
        {
            byte[] cb = jnlpFileContent.getBytes( "UTF-8" );
            ByteArrayInputStream bis = new ByteArrayInputStream( cb );
            try
            {
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                DocumentBuilder builder = factory.newDocumentBuilder();
                Document document = builder.parse( bis );
                if ( document != null && document.getNodeType() == Node.DOCUMENT_NODE )
                {
                    boolean modified = false;
                    Element root = document.getDocumentElement();

                    if ( root.hasAttribute( "href" ) )
                    {
                        String href = root.getAttribute( "href" );
                        root.setAttribute( "href", href + "?" + query );
                        modified = true;
                    }
                    // Update version value for j2se tag
                    if ( testJRE != null )
                    {
                        NodeList j2seNL = root.getElementsByTagName( "j2se" );
                        if ( j2seNL != null )
                        {
                            Element j2se = (Element) j2seNL.item( 0 );
                            String ver = j2se.getAttribute( "version" );
                            if ( ver.length() > 0 )
                            {
                                j2se.setAttribute( "version", testJRE );
                                modified = true;
                            }
                        }
                    }
                    _hook.preCommit( dreq, document );
                    TransformerFactory tFactory = TransformerFactory.newInstance();
                    Transformer transformer = tFactory.newTransformer();
                    DOMSource source = new DOMSource( document );
                    StringWriter sw = new StringWriter();
                    StreamResult result = new StreamResult( sw );
                    transformer.transform( source, result );
                    jnlpFileContent = sw.toString();
                    _log.addDebug( "Converted jnlpFileContent: " + jnlpFileContent );
                    // Since we modified the file on the fly, we always update the timestamp value with current time
                    if ( modified )
                    {
                        timeStamp = new java.util.Date().getTime();
                        _log.addDebug( "Last modified on the fly:  " + timeStamp );
                    }
                }
            }
            catch ( Exception e )
            {
                _log.addDebug( e.toString(), e );
            }
        }

        // Convert to bytes as a UTF-8 encoding
        byte[] byteContent = jnlpFileContent.getBytes( "UTF-8" );

        // Create entry
        DownloadResponse resp =
                DownloadResponse.getFileDownloadResponse( byteContent, mimeType, timeStamp, jnlpres.getReturnVersionId() );
        jnlpFile = new JnlpFileEntry( resp, lastModified );
        _jnlpFiles.put( reqUrl, jnlpFile );

        return resp;
    }
1064856
public String waitForStringInLog(String regexp, long timeout,
                                     File outputFile) {
        int waited = 0;
        final int waitIncrement = 500;

        log(MessageFormat.format(messages.getString("info.search.string"), regexp, outputFile.getAbsolutePath(), timeout / 1000));

        try {
            while (waited <= timeout) {
                String string = findStringInFile(regexp, outputFile);
                if (string == null) {
                    try {
                        Thread.sleep(waitIncrement);
                    } catch (InterruptedException e) {
                        // Ignore and carry on
                    }
                    waited += waitIncrement;
                } else {
                    return string;
                }
            }
            log(MessageFormat.format(messages.getString("error.serch.string.timeout"), regexp, outputFile.getAbsolutePath()));
        } catch (Exception e) {
            // I think we can assume if we can't read the file it doesn't
            // contain our string
            throw new BuildException(e);
        }
        return null;

    }
109800
private File extractToTemp(InputStream _fileToExtract, String _tmpName, String _fileSuffix) throws IOException {
        if (_fileToExtract == null) {
            throw new IOException("Null stream");
        }
        File tempFile = File.createTempFile(_tmpName, _fileSuffix);
        tempFile.deleteOnExit();

        if (!tempFile.exists()) {
            throw new FileNotFoundException("File " + tempFile.getAbsolutePath() + " could not be created");
        }

        byte[] buffer = new byte[1024];
        int readBytes;

        OutputStream os = new FileOutputStream(tempFile);
        try {
            while ((readBytes = _fileToExtract.read(buffer)) != -1) {
                os.write(buffer, 0, readBytes);
            }
        } finally {
            os.close();
            _fileToExtract.close();
        }
        return tempFile;
    }
1171058
static String parseAttachmentFilename(Header header) throws UnsupportedEncodingException {
    if (header == null) {
      return null;
    }
    String value = header.getValue();
    String filenameWild = "filename*";
    int filenameWildIndex = value.indexOf(filenameWild);
    if (filenameWildIndex != -1) {
      int lastIndex = value.indexOf(';', filenameWildIndex);
      String substring;
      if (lastIndex == -1) {
        substring = value.substring(filenameWildIndex + filenameWild.length() + 1);
      } else {
        substring = value.substring(filenameWildIndex + filenameWild.length() + 1, lastIndex);
      }
      String[] ary = substring.split("''");
      return URLDecoder.decode(ary[1], ary[0]);
    }
    String filename = "filename";
    int filenameIndex = value.indexOf(filename);
    if (filenameIndex != -1) {
      int lastIndex = value.indexOf(';', filenameIndex);
      String substring;
      // 处理filename=文件名，不包含双引号的情况
      int offset = 2;
      if (value.substring(filenameIndex + filename.length() + 1).charAt(0) != '\"') {
        offset = 1;
      }
      if (lastIndex == -1) {
        substring = value.substring(filenameIndex + filename.length() + offset);
      } else {
        substring = value
            .substring(filenameIndex + filename.length() + offset, offset == 2 ? lastIndex - 1 : lastIndex);
      }
      return URLDecoder.decode(substring, "UTF-8");
    }
    throw new IllegalStateException("不合法的附件头信息" + header.getName() + ": " + header.getValue());
  }
975861
def readline(self, timeout=None):  # timeout is not in use
        
        fil = self.port.makefile()
        line = fil.readline()
        return strip_escape(line.strip())
1012063
protected static final Object parseNext(Source src) throws IOException {
		skipWhitespaces(src);
		switch (src.ch) {

		case '"':
			return parseString(src);

		case 't':
			src.idx += 4;
			return Boolean.TRUE;

		case 'f':
			src.idx += 5;
			return Boolean.FALSE;

		case 'n':
			src.idx += 4;
			return null;

		case '[':
			return parseList(src);

		case '{':
			return parseMap(src);

		case '0':
		case '1':
		case '2':
		case '3':
		case '4':
		case '5':
		case '6':
		case '7':
		case '8':
		case '9':
		case '-':
			return parseNumber(src);

		default:
			throw new IOException(
					"Unable to determine the next character, it is not a string, number, array, or object!");
		}
	}
1252402
public int read() throws IOException {
        synchronized (lock) {
            ensureOpen();
            for (;;) {
                if (nextChar >= nChars) {
                    fill();
                    if (nextChar >= nChars)
                        return -1;
                }
                if (skipLF) {
                    skipLF = false;
                    if (cb[nextChar] == '\n') {
                        nextChar++;
                        continue;
                    }
                }
                return cb[nextChar++];
            }
        }
    }
411240
public static File writeStringToTempFileNoExceptions(String contents, String path, String encoding) {
		OutputStream writer = null;
		File tmp = null;
		try{
			tmp = File.createTempFile(path,".tmp");
			if (path.endsWith(".gz")) {
				writer = new GZIPOutputStream(new FileOutputStream(tmp));
			} else {
				writer = new BufferedOutputStream(new FileOutputStream(tmp));
			}
			writer.write(contents.getBytes(encoding));
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(writer != null){ closeIgnoringExceptions(writer); }
		}
		return tmp;
	}
1088676
def CopyToDateTimeString(self):
    
    if (self._timestamp is None or self._timestamp < 0 or
        self._timestamp > self._UINT64_MAX):
      return None

    timestamp, remainder = divmod(self._timestamp, self._100NS_PER_SECOND)
    number_of_days, hours, minutes, seconds = self._GetTimeValues(timestamp)

    year, month, day_of_month = self._GetDateValuesWithEpoch(
        number_of_days, self._EPOCH)

    return '{0:04d}-{1:02d}-{2:02d} {3:02d}:{4:02d}:{5:02d}.{6:07d}'.format(
        year, month, day_of_month, hours, minutes, seconds, remainder)
1029569
public static Timestamp getTimeStamp(String time) {
	if (time.equalsIgnoreCase("now")) {
	    return Timestamp.now();
	} else {
	    int quantity = 0;
	    String unit = "";
	    Pattern lastNUnitsPattern = Pattern
		    .compile(
			    "last\\s*(\\d*)\\s*(min|mins|hour|hours|day|days|week|weeks).*",
			    Pattern.CASE_INSENSITIVE);
	    Matcher lastNUnitsMatcher = lastNUnitsPattern.matcher(time);
	    while (lastNUnitsMatcher.find()) {
		quantity = "".equals(lastNUnitsMatcher.group(1)) ? 1 : Integer
			.valueOf(lastNUnitsMatcher.group(1));
		unit = lastNUnitsMatcher.group(2).toLowerCase();
		switch (unit) {
		case "min":
		case "mins":
		    return Timestamp.now().minus(
			    TimeDuration.ofMinutes(quantity));
		case "hour":
		case "hours":
		    return Timestamp.now()
			    .minus(TimeDuration.ofHours(quantity));
		case "day":
		case "days":
		    return Timestamp.now().minus(
			    TimeDuration.ofHours(quantity * 24));
		case "week":
		case "weeks":
		    return Timestamp.now().minus(
			    TimeDuration.ofHours(quantity * 24 * 7));
		default:
		    break;
		}
	    }

	    Pattern nUnitsAgoPattern = Pattern
		    .compile(
			    "(\\d*)\\s*(min|mins|hour|hours|day|days|week|weeks)\\s*ago",
			    Pattern.CASE_INSENSITIVE);
	    Matcher nUnitsAgoMatcher = nUnitsAgoPattern.matcher(time);
	    while (nUnitsAgoMatcher.find()) {
		quantity = "".equals(nUnitsAgoMatcher.group(1)) ? 1 : Integer
			.valueOf(nUnitsAgoMatcher.group(1));
		unit = nUnitsAgoMatcher.group(2).toLowerCase();
		switch (unit) {
		case "min":
		case "mins":
		    return Timestamp.now().minus(
			    TimeDuration.ofMinutes(quantity));

		case "hour":
		case "hours":
		    return Timestamp.now()
			    .minus(TimeDuration.ofHours(quantity));
		case "day":
		case "days":
		    return Timestamp.now().minus(
			    TimeDuration.ofHours(quantity * 24));
		case "week":
		case "weeks":
		    return Timestamp.now().minus(
			    TimeDuration.ofHours(quantity * 24 * 7));
		default:
		    break;
		}
	    }
	    TimestampFormat format = new TimestampFormat(
		    "yyyy-MM-dd'T'HH:mm:ss");
	    try {
		return format.parse(time);
	    } catch (ParseException e) {
		return null;
	    }
	}
    }
97248
def CopyToDateTimeString(self):
    
    if (self._timestamp is None or self._timestamp < self._INT64_MIN or
        self._timestamp > self._INT64_MAX):
      return None

    return super(JavaTime, self).CopyToDateTimeString()
970887
public String format(String clientID, String name, long time, Level level, Object message,
	        Throwable t){

		if (!patternParsed && pattern != null) {
			parsePattern(pattern);
		}

		StringBuffer formattedStringBuffer = new StringBuffer(64);
		if (commandArray != null) {
			int length = commandArray.length;

			for (int index = 0; index < length; index++) {
				FormatCommandInterface currentConverter = commandArray[index];
				if (currentConverter != null) {
					formattedStringBuffer.append(currentConverter.execute(clientID, name, time,
					        level, message, t));
				}
			}
		}

		return formattedStringBuffer.toString();
	}
653261
public String getresp(int timeout)
    throws SoccomException
    {
    int size, n;
    String sizestr;
    try {
        byte[] _header = new byte[SoccomMessage.HEADER_SIZE];
        _socket.setSoTimeout(timeout*1000);
        n = _in.read(_header, 0, SoccomMessage.HEADER_SIZE);
        if (n!=SoccomMessage.HEADER_SIZE)
        throw new SoccomException(SoccomException.RECV_HEADER);
        logline("RECV HDR: " + new String(_header));
        check_msgid(_msgid, _header);
        sizestr = new String(_header, SoccomMessage.MSGSIZE_OFFSET, 8);
        if (sizestr.startsWith("ENDM")) size = -1;
        else size = Integer.parseInt(sizestr);
    } catch (InterruptedIOException e) {
        throw new SoccomException(SoccomException.POLL_TIMEOUT);
    } catch (IOException e) {
        throw new SoccomException(SoccomException.RECV_HEADER);
    }
    try {
        String msg;
        if (size == -1) {
        String endm = sizestr.substring(4,8);
        String line;
        StringBuffer sb = new StringBuffer();
        byte[] buffer = new byte[1024];
        int k;
        boolean done = false;
        while (!done) {
            k = readLine(_in, buffer, 0, 1024);
            line = new String(buffer,0,k);
            if (k==5 && line.startsWith(endm)) done = true;
            else sb.append(line);
        }
        msg = sb.toString();
        } else {
        byte[] buffer = new byte[size+SoccomMessage.HEADER_SIZE];
        int got = 0;
        while (got<size) {
            n = _in.read(buffer, got, size-got);
            if (n>0) got += n;
            else if (n==-1)
            throw new SoccomException(SoccomException.SOCKET_CLOSED);
            else throw new SoccomException(SoccomException.RECV_ERROR);
        }
        msg = new String(buffer, 0, size);
        }
        logline("RECV MSG: " + msg);
        return msg;
    } catch (InterruptedIOException e) {
        throw new SoccomException(SoccomException.RECV_ERROR);
    } catch (IOException e) {
        throw new SoccomException(SoccomException.RECV_ERROR);
    }
    }
997742
function getTimeIncreaseFromName(methodName) {
  const matchNumbers = String(methodName).match(/_increaseTimeBy(\d+)/);

  if (matchNumbers !== null
    && typeof matchNumbers[1] === 'string') {
    return parseInt(matchNumbers[1], 10);
  }

  return 0;
}
86229
def find(path,
         level=None,
         message=None,
         time_lower=None, time_upper=None,
         case_sensitive=False):  # pragma: no cover
    
    if level:
        level = level.upper()  # level name has to be capitalized.

    if not case_sensitive:
        message = message.lower()

    with open(path, "r") as f:
        result = Result(path=path,
                        level=level, message=message,
                        time_lower=time_lower, time_upper=time_upper,
                        case_sensitive=case_sensitive,
                        )

        for line in f:
            try:
                _time, _level, _message = [i.strip() for i in line.split(";")]

                if level:
                    if _level != level:
                        continue

                if time_lower:
                    if _time < time_lower:
                        continue

                if time_upper:
                    if _time > time_upper:
                        continue

                if message:
                    if not case_sensitive:
                        _message = _message.lower()

                    if message not in _message:
                        continue

                result.lines.append(line)
            except Exception as e:
                print(e)

    return result