code
stringlengths
73
34.1k
label
stringclasses
1 value
protected void parseComment() { int commentEndPos = sql.indexOf("*/", position); int commentEndPos2 = sql.indexOf("*#", position); if (0 < commentEndPos2 && commentEndPos2 < commentEndPos) { commentEndPos = commentEndPos2; } if (commentEndPos < 0) { ...
java
@SuppressWarnings("unchecked") public BeanDesc getBeanDesc(Object obj){ if(obj instanceof Map){ return new MapBeanDescImpl((Map<String, Object>) obj); } else { return getBeanDesc(obj.getClass()); } }
java
public BeanDesc getBeanDesc(Class<?> clazz){ if(clazz == Map.class || clazz == HashMap.class || clazz == LinkedHashMap.class){ return new MapBeanDescImpl(); } if(cacheEnabled && cacheMap.containsKey(clazz)){ return cacheMap.get(clazz); } BeanDes...
java
protected void parseSql() { String sql = tokenizer.getToken(); if (isElseMode()) { sql = StringUtil.replace(sql, "--", ""); } Node node = peek(); if ((node instanceof IfNode || node instanceof ElseNode) && node.getChildSize() == 0) { ...
java
protected void parseComment() { String comment = tokenizer.getToken(); if (isTargetComment(comment)) { if (isIfComment(comment)) { parseIf(); } else if (isBeginComment(comment)) { parseBegin(); } else if (isEndComment(comment)) {...
java
protected void parseIf() { String condition = tokenizer.getToken().substring(2).trim(); if (StringUtil.isEmpty(condition)) { throw new TwoWaySQLException("If condition not found."); } IfNode ifNode = new IfNode(condition); peek().addChild(ifNode); push(...
java
protected void parseBegin() { BeginNode beginNode = new BeginNode(); peek().addChild(beginNode); push(beginNode); parseEnd(); }
java
protected void parseEnd() { while (TokenType.EOF != tokenizer.next()) { if (tokenizer.getTokenType() == TokenType.COMMENT && isEndComment(tokenizer.getToken())) { pop(); return; } parseToken(); } t...
java
protected void parseElse() { Node parent = peek(); if (!(parent instanceof IfNode)) { return; } IfNode ifNode = (IfNode) pop(); ElseNode elseNode = new ElseNode(); ifNode.setElseNode(elseNode); push(elseNode); tokenizer.skipWhitespace(...
java
protected void parseBindVariable() { String expr = tokenizer.getToken(); peek().addChild(new BindVariableNode(expr, beanDescFactory)); }
java
protected synchronized WriterPoolMember makeNewWriterIfAppropriate() { long now = System.currentTimeMillis(); lastWriterNeededTime = now; if(currentActive < maxActive) { currentActive++; lastWriterRolloverTime = now; return makeWriter(); } return ...
java
public synchronized void invalidateFile(WriterPoolMember f) throws IOException { try { destroyWriter(f); } catch (Exception e) { // Convert exception. throw new IOException(e.getMessage()); } // It'll have been closed. Rename with an '.invalid' su...
java
public void skipHttpHeader() throws IOException { if (this.contentHeaderStream == null) { return; } // Empty the contentHeaderStream for (int available = this.contentHeaderStream.available(); this.contentHeaderStream != null && (available = this.co...
java
private InputStream readContentHeaders() throws IOException { // If judged a record that doesn't have an http header, return // immediately. if (!hasContentHeaders()) { return null; } byte [] statusBytes = LaxHttpParser.readRawLine(getIn()); int eolCharCount =...
java
public static ProcessUtils.ProcessResult exec(String [] args) throws IOException { Process p = Runtime.getRuntime().exec(args); ProcessUtils pu = new ProcessUtils(); // Gobble up any output. StreamGobbler err = pu.new StreamGobbler(p.getErrorStream(), "stderr"); err.setDaemon...
java
public void open(OutputStream wrappedStream) throws IOException { if(isOpen()) { // error; should not be opening/wrapping in an unclosed // stream remains open throw new IOException("ROS already open for " +Thread.currentThread().getName()); } ...
java
protected void checkLimits() throws RecorderIOException { // too much material before finding end of headers? if (messageBodyBeginMark<0) { // no mark yet if(position>MAX_HEADER_MATERIAL) { throw new RecorderTooMuchHeaderException(); } } ...
java
private void record(int b) throws IOException { if (this.shouldDigest) { this.digest.update((byte)b); } if (this.position >= this.buffer.length) { this.ensureDiskStream().write(b); } else { this.buffer[(int) this.position] = (byte) b; } ...
java
private void record(byte[] b, int off, int len) throws IOException { if(this.shouldDigest) { assert this.digest != null: "Digest is null."; this.digest.update(b, off, len); } tailRecord(b, off, len); }
java
private void tailRecord(byte[] b, int off, int len) throws IOException { if(this.position >= this.buffer.length){ this.ensureDiskStream().write(b, off, len); this.position += len; } else { assert this.buffer != null: "Buffer is null"; int toCopy = (int)Mat...
java
public void setLimits(long length, long milliseconds, long rateKBps) { maxLength = (length>0) ? length : Long.MAX_VALUE; timeoutMs = (milliseconds>0) ? milliseconds : Long.MAX_VALUE; maxRateBytesPerMs = (rateKBps>0) ? rateKBps*1024/1000 : Long.MAX_VALUE; }
java
public void resetLimits() { maxLength = Long.MAX_VALUE; timeoutMs = Long.MAX_VALUE; maxRateBytesPerMs = Long.MAX_VALUE; }
java
protected static InputStream countingStream(InputStream in, int lookback) throws IOException { CountingInputStream cin = new CountingInputStream(in); cin.mark(lookback); return cin; }
java
public char charAt(int index) { if (index < 0 || index >= this.length()) { throw new IndexOutOfBoundsException("index=" + index + " - should be between 0 and length()=" + this.length()); } // is it in the buffer if (index < prefixBuffer.limit()) { ...
java
public static final byte[] decodeUrlLoose(byte[] bytes) { if (bytes == null) { return null; } ByteArrayOutputStream buffer = new ByteArrayOutputStream(); for (int i = 0; i < bytes.length; i++) { int b = bytes[i]; if (b == '+') { b...
java
public String encode(BitSet safe, String pString, String cs) throws UnsupportedEncodingException { if (pString == null) { return null; } return new String(encodeUrl(safe,pString.getBytes(cs)), Charsets.US_ASCII); }
java
public void importFrom(Reader r) { BufferedReader reader = new BufferedReader(r); String s; Iterator<String> iter = new RegexLineIterator( new LineReadingIterator(reader), RegexLineIterator.COMMENT_LINE, RegexLineI...
java
public void importFromMixed(Reader r, boolean deduceFromSeeds) { BufferedReader reader = new BufferedReader(r); String s; Iterator<String> iter = new RegexLineIterator( new LineReadingIterator(reader), RegexLineIterator.COMMENT_LINE, ...
java
public static String fromURI(String s, boolean preserveCase) { Matcher m = TextUtils.getMatcher(URI_SPLITTER,s); if(!m.matches()) { // not an authority-based URI scheme; return unchanged TextUtils.recycleMatcher(m); return s; } // preallocate enough sp...
java
public static void main(String[] args) throws IOException { if (args.length != 1) { System.out.println("Usage: java java " + "-Djava.protocol.handler.pkgs=org.archive.net " + "org.archive.net.rsync.Handler RSYNC_URL"); System.exit(1); } ...
java
public void position(long p) throws IOException { if ((p < 0) || (p > array.length)) { throw new IOException("Invalid position: " + p); } offset = (int)p; }
java
public int getFieldIndex(String name) { Integer val = this.nameToIndex.get(name); if (val == null) { return -1; } return val; }
java
public static ByteBufferInputStream map( final FileChannel fileChannel, final MapMode mapMode ) throws IOException { final long size = fileChannel.size(); final int chunks = (int)( ( size + ( CHUNK_SIZE - 1 ) ) / CHUNK_SIZE ); final ByteBuffer[] byteBuffer = new ByteBuffer[ chunks ]; for( int i = 0; i < chunks;...
java
public static String formatMillisecondsToConventional(long duration, int unitCount) { if(unitCount <=0) { unitCount = 5; } if(duration==0) { return "0ms"; } StringBuffer sb = new StringBuffer(); if(duration<0) { sb.append("-");...
java
public synchronized static String getUnique14DigitDate(){ long effectiveNow = System.currentTimeMillis(); effectiveNow = Math.max(effectiveNow, LAST_UNIQUE_NOW14+1); String candidate = get14DigitDate(effectiveNow); while(candidate.equals(LAST_TIMESTAMP14)) { effectiveNo...
java
protected boolean lookahead() { try { next = this.reader.readLine(); if(next == null) { // TODO: make this close-on-exhaust optional? reader.close(); } return (next!=null); } catch (IOException e) { logger.warnin...
java
public static File decodeGZToTemp(String uriGZ) throws IOException { final int BUFFER_SIZE = 8192; Stream stream = null; try { stream = GeneralURIStreamFactory.createStream(uriGZ); InputStream input = new StreamWrappedInputStream(stream); input = new OpenJDK7GZIPInputStream(input); File uncompresse...
java
public String getField(String name, String defaultVal) { int index = getFieldIndex(name); return (isInRange(index) ? this.fields.get(index) : defaultVal); }
java
public static boolean copyFile(final File src, final File dest) throws FileNotFoundException, IOException { return copyFile(src, dest, -1, true); }
java
public static boolean copyFile(final File src, final File dest, long extent, final boolean overwrite) throws FileNotFoundException, IOException { boolean result = false; if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("Copying file " + src + " to " + dest + " extent " + ...
java
public static File [] getFilesWithPrefix(File dir, final String prefix) { FileFilter prefixFilter = new FileFilter() { public boolean accept(File pathname) { return pathname.getName().toLowerCase(). startsWith(prefix.toLowerCase()); ...
java
public static File assertReadable(final File f) throws FileNotFoundException { if (!f.exists()) { throw new FileNotFoundException(f.getAbsolutePath() + " does not exist."); } if (!f.canRead()) { throw new FileNotFoundException(f.getAbsolutePath() + ...
java
public static Properties loadProperties(File file) throws IOException { FileInputStream finp = new FileInputStream(file); try { Properties p = new Properties(); p.load(finp); return p; } finally { ArchiveUtils.closeQuietly(finp); } }
java
public static void storeProperties(Properties p, File file) throws IOException { FileOutputStream fos = new FileOutputStream(file); try { p.store(fos,""); } finally { ArchiveUtils.closeQuietly(fos); } }
java
public static List<File> ensureWriteableDirectory(List<File> dirs) throws IOException { for (Iterator<File> i = dirs.iterator(); i.hasNext();) { FileUtils.ensureWriteableDirectory(i.next()); } return dirs; }
java
public static File ensureWriteableDirectory(File dir) throws IOException { if (!dir.exists()) { boolean success = dir.mkdirs(); if (!success) { throw new IOException("Failed to create directory: " + dir); } } else { if (!dir.canWrite())...
java
public InputStream inputWrap(InputStream is) throws IOException { logger.fine(Thread.currentThread().getName() + " wrapping input"); // discard any state from previously-recorded input this.characterEncoding = null; this.inputIsChunked = false; this.contentEncoding ...
java
public void close() { logger.fine(Thread.currentThread().getName() + " closing"); try { this.ris.close(); } catch (IOException e) { // TODO: Can we not let the exception out of here and report it // higher up in the caller? DevUtils.logger.log(Leve...
java
public void closeRecorders() { try { this.ris.closeRecorder(); this.ros.closeRecorder(); } catch (IOException e) { DevUtils.warnHandle(e, "Convert to runtime exception?"); } }
java
private void delete(String name) { File f = new File(name); if (f.exists()) { f.delete(); } }
java
public String getContentReplayPrefixString(int size, Charset cs) { try { InputStreamReader isr = new InputStreamReader(getContentReplayInputStream(), cs); char[] chars = new char[size]; int count = isr.read(chars); isr.close(); if (count > 0) { ...
java
public static Recorder wrapInputStreamWithHttpRecord(File dir, String basename, InputStream in, String encoding) throws IOException { Recorder rec = new Recorder(dir, basename); if (encoding != null && encoding.length() > 0) { rec.setCharset(Charset.forName(encoding)); } ...
java
protected String createRecordHeader(WARCRecordInfo metaRecord) throws IllegalArgumentException { final StringBuilder sb = new StringBuilder(2048/*A SWAG: TODO: Do analysis.*/); sb.append(WARC_ID).append(CRLF); sb.append(HEADER_KEY_TYPE).append(COLON_SPACE).append(metaRecord.getType()). ...
java
public static Matcher getMatcher(String pattern, CharSequence input) { if (pattern == null) { throw new IllegalArgumentException("String 'pattern' must not be null"); } input = new InterruptibleCharSequence(input); final Map<String,Matcher> matchers = TL_MATCHER_MAP.get(); ...
java
public static String replaceAll( String pattern, CharSequence input, String replacement) { input = new InterruptibleCharSequence(input); Matcher m = getMatcher(pattern, input); String res = m.replaceAll(replacement); recycleMatcher(m); return res; }
java
public static boolean matches(String pattern, CharSequence input) { input = new InterruptibleCharSequence(input); Matcher m = getMatcher(pattern, input); boolean res = m.matches(); recycleMatcher(m); return res; }
java
public static String[] split(String pattern, CharSequence input) { input = new InterruptibleCharSequence(input); Matcher m = getMatcher(pattern,input); String[] retVal = m.pattern().split(input); recycleMatcher(m); return retVal; }
java
public static CharSequence unescapeHtml(final CharSequence cs) { if (cs == null) { return cs; } return StringEscapeUtils.unescapeHtml(cs.toString()); }
java
@SuppressWarnings("deprecation") public static String urlEscape(String s) { try { return URLEncoder.encode(s,"UTF8"); } catch (UnsupportedEncodingException e) { // should be impossible; all JVMs must support UTF8 // but have a fallback just in case ret...
java
@SuppressWarnings("deprecation") public static String urlUnescape(String s) { try { return URLDecoder.decode(s, "UTF8"); } catch (UnsupportedEncodingException e) { // should be impossible; all JVMs must support UTF8 // but have a fallback just in case ...
java
public boolean containsPrefixOf(String s) { SortedSet<String> sub = headSet(s); // because redundant prefixes have been eliminated, // only a test against last item in headSet is necessary if (!sub.isEmpty() && s.startsWith((String)sub.last())) { return true; // prefix s...
java
public static void warnHandle(Throwable ex, String note) { logger.warning(TextUtils.exceptionToString(note, ex)); }
java
public static String truncate(String contentType) { if (contentType == null) { contentType = NO_TYPE_MIMETYPE; } else { Matcher matcher = TRUNCATION_REGEX.matcher(contentType); if (matcher.matches()) { contentType = matcher.group(1); } else { ...
java
public static char littleChar(InputStream input) throws IOException { int lo = input.read(); if (lo < 0) { throw new EOFException(); } int hi = input.read(); if (hi < 0) { throw new EOFException(); } return (char)((hi << 8) | lo); }
java
public static int littleInt(InputStream input) throws IOException { char lo = littleChar(input); char hi = littleChar(input); return (hi << 16) | lo; }
java
public static char bigChar(InputStream input) throws IOException { int hi = input.read(); if (hi < 0) { throw new EOFException(); } int lo = input.read(); if (lo < 0) { throw new EOFException(); } return (char)((hi << 8) | lo); }
java
public static int bigInt(InputStream input) throws IOException { char hi = bigChar(input); char lo = bigChar(input); return (hi << 16) | lo; }
java
public void restoreFile(File destination) throws IOException { String nameAsStored = readUTF(); long lengthAtStoreTime = readLong(); File storedFile = new File(getAuxiliaryDirectory(),nameAsStored); FileUtils.copyFile(storedFile, destination, lengthAtStoreTime); }
java
private int getTokenizedHeaderLine(final InputStream stream, List<String> list) throws IOException { // Preallocate usual line size. StringBuilder buffer = new StringBuilder(2048 + 20); int read = 0; int previous = -1; for (int c = -1; true;) { previou...
java
public void skipHttpHeader() throws IOException { if (this.httpHeaderStream != null) { // Empty the httpHeaderStream for (int available = this.httpHeaderStream.available(); this.httpHeaderStream != null && (available = this.httpHead...
java
protected UsableURI validityCheck(UsableURI uuri) throws URIException { if (uuri.getRawURI().length > UsableURI.MAX_URL_LENGTH) { throw new URIException("Created (escaped) uuri > " + UsableURI.MAX_URL_LENGTH +": "+uuri.toString()); } return uuri; }
java
private String fixupAuthority(String uriAuthority, String charset) throws URIException { // Lowercase the host part of the uriAuthority; don't destroy any // userinfo capitalizations. Make sure no illegal characters in // domainlabel substring of the uri authority. if (uriAuthority != n...
java
private String fixupDomainlabel(String label) throws URIException { // apply IDN-punycoding, as necessary try { // TODO: optimize: only apply when necessary, or // keep cache of recent encodings label = IDNA.toASCII(label); } catch (IDNAException ...
java
protected ARCRecord createArchiveRecord(InputStream is, long offset) throws IOException { try { String version = super.getVersion(); ARCRecord record = new ARCRecord(is, getReaderIdentifier(), offset, isDigest(), isStrict(), isParseHttpHeaders(), ...
java
public static void dump(Node alt, int lv, PrintWriter out) { for (int i = 0; i < lv; i++) out.print(" "); out.println(alt.cs != null ? ('"'+alt.cs.toString()+'"') : "(null)"); if (alt.branches != null) { for (Node br : alt.branches) { dump(br, lv + 1, out...
java
public static String reduceSurtToAssignmentLevel(String surt) { Matcher matcher = TextUtils.getMatcher( getTopmostAssignedSurtPrefixRegex(), surt); if (matcher.find()) { surt = matcher.group(); } TextUtils.recycleMatcher(matcher); return surt; }
java
private void buffer() throws IOException { int remaining = buffer.length; while (remaining > 0) { int r = input.read(buffer, buffer.length - remaining, remaining); if (r <= 0) { // Not enough information to fill the buffer offset = 0; ...
java
public void position(long p) throws IOException { long blockStart = (input.position() - maxOffset) / buffer.length * buffer.length; long blockEnd = blockStart + maxOffset; if ((p >= blockStart) && (p < blockEnd)) { // Desired position is somewhere inside current buffer ...
java
private void positionDirect(long p) throws IOException { long newBlockStart = p / buffer.length * buffer.length; input.position(newBlockStart); buffer(); offset = (int)(p % buffer.length); }
java
protected InputStream getInputStream(final File f, final long offset) throws IOException { FileInputStream fin = new FileInputStream(f); return new BufferedInputStream(fin); }
java
protected void cleanupCurrentRecord() throws IOException { if (this.currentRecord != null) { this.currentRecord.close(); gotoEOR(this.currentRecord); this.currentRecord = null; } }
java
public List<ArchiveRecordHeader> validate(int numRecords) throws IOException { List<ArchiveRecordHeader> hdrList = new ArrayList<ArchiveRecordHeader>(); int recordCount = 0; setStrict(true); for (Iterator<ArchiveRecord> i = iterator(); i.hasNext();) { recordCount++; ...
java
public boolean isValid() { boolean valid = false; try { validate(); valid = true; } catch(Exception e) { // File is not valid if exception thrown parsing. valid = false; } return valid; }
java
public void logStdErr(Level level, String message) { System.err.println(level.toString() + " " + message); }
java
public long alignOnMagic3(InputStream is) throws IOException { long bytesSkipped = 0; byte lookahead[] = new byte[3]; int keep = 0; while(true) { if(keep == 2) { lookahead[0] = lookahead[1]; lookahead[1] = lookahead[2]; } else if(keep == 1) { lookahead[0] = lookahead[2]; } int amt...
java
protected static void output(WARCReader reader, String format) throws IOException, java.text.ParseException { if (!reader.output(format)) { throw new IOException("Unsupported format: " + format); } }
java
protected String transform(String line) { ignoreLine.reset(line); if(ignoreLine.matches()) { return null; } extractLine.reset(line); if(extractLine.matches()) { StringBuffer output = new StringBuffer(); // TODO: consider if a loop that find()s...
java
protected static String decode(String component, String charset) throws URIException { if (component == null) { throw new IllegalArgumentException( "Component array of chars may not be null"); } byte[] rawdata = null; // try { rawda...
java
protected void parseAuthority(String original, boolean escaped) throws URIException { super.parseAuthority(original, escaped); if (_host != null && _authority != null && _host.length == _authority.length) { _host = _authority; } }
java
protected void setURI() { if (_scheme != null) { if (_scheme.length == 4 && Arrays.equals(_scheme, HTTP_SCHEME)) { _scheme = HTTP_SCHEME; } else if (_scheme.length == 5 && Arrays.equals(_scheme, HTTPS_SCHEME)) { _scheme = HTTPS_SCHEME; ...
java
protected void generateNewBasename() { Properties localProps = new Properties(); localProps.setProperty("prefix", settings.getPrefix()); synchronized(this.getClass()) { // ensure that serialNo and timestamp are minted together (never inverted sort order) String paddedSer...
java
protected String getBaseFilename() { String name = this.f.getName(); if (settings.getCompress() && name.endsWith(DOT_COMPRESSED_FILE_EXTENSION)) { return name.substring(0,name.length() - 3); } else if(settings.getCompress() && name.endsWith(DOT_COMPRESSED_FILE_EXTENSI...
java
protected void preWriteRecordTasks() throws IOException { if (this.out == null) { createFile(); } if (settings.getCompress()) { // Wrap stream in GZIP Writer. // The below construction immediately writes the GZIP 'default' // header out on the ...
java
protected void postWriteRecordTasks() throws IOException { if (settings.getCompress()) { CompressedStream o = (CompressedStream)this.out; o.finish(); o.flush(); o.end(); this.out = o.getWrappedStream(); } }
java
public long computeTotalLines() { long numLines = 0; try { numLines = this.getNumLines(summary.getRange("", "")); } catch (IOException e) { LOGGER.warning(e.toString()); return 0; } long adjustment = getTotalAdjustment(); numLines -= (getNumBlocks() - 1); numLines *= this.getCdxLinesPerB...
java
protected String getCharsetFromMeta(byte buffer[],int len) throws IOException { String charsetName = null; // convert to UTF-8 String -- which hopefully will not mess up the // characters we're interested in... String sample = new String(buffer,0,len,DEFAULT_CHARSET); String metaContentType = findMetaContent...
java
protected String getCharsetFromBytes(byte buffer[], int len) throws IOException { String charsetName = null; UniversalDetector detector = new UniversalDetector(null); detector.handleData(buffer, 0, len); detector.dataEnd(); charsetName = detector.getDetectedCharset(); detector.reset(); if(is...
java
public void readContentTo(OutputStream os, long maxSize) throws IOException { setToResponseBodyStart(); byte[] buf = new byte[4096]; int c = read(buf); long tot = 0; while (c != -1 && tot < maxSize) { os.write(buf,0,c); c = read(buf); tot += c;...
java
public void position(long p) throws IOException { if (p < 0) { throw new IOException("Negative seek offset."); } if (p > size) { throw new IOException("Desired position exceeds size."); } if (p < buffer.length) { // Only seek file if necessary ...
java
public void close() throws IOException { if (this.in != null) { skip(); this.in = null; if (this.digest != null) { this.digestStr = Base32.encode(this.digest.digest()); } } }
java