code
stringlengths
73
34.1k
label
stringclasses
1 value
@Override public int read() throws IOException { // Read from the queue synchronized(file) { while(true) { long len=file.getLength(); if(len>=1) { long pos=file.getFirstIndex(); file.file.seek(pos+16); int b=file.file.read(); if(b==-1) throw new EOFException("Unexpected EOF"); a...
java
@Override public int read(byte[] b, int off, int len) throws IOException { // Read from the queue synchronized(file) { while(true) { long fileLen=file.getLength(); if(fileLen>=1) { long pos=file.getFirstIndex(); file.file.seek(pos+16); int readSize=fileLen>len?len:(int)fileLen; // Wh...
java
@Override public long skip(long n) throws IOException { // Skip in the queue synchronized(file) { while(true) { long fileLen=file.getLength(); if(fileLen>=1) { long pos=file.getFirstIndex(); long skipSize=fileLen>n?n:fileLen; // When at the end of the file, skip the remaining bytes i...
java
@Override public int available() throws IOException { synchronized(file) { long len=file.getLength(); return len>Integer.MAX_VALUE?Integer.MAX_VALUE:(int)len; } }
java
protected void init(final String name, final Properties props) { init = new InitUtil("", props, false); this.name = name; }
java
public List<GeneratedPosition> allGeneratedPositionsFor(int line, Integer column, String source) { // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping // returns the index of the closest mapping less than the needle. By // setting needle.originalColumn to 0, we thus fi...
java
<T> int _findMapping(T aNeedle, List<T> aMappings, Object aLineName, Object aColumnName, BinarySearch.Comparator<T> aComparator, BinarySearch.Bias aBias) { // To return the position we are searching for, we must first find the // mapping for the given position and then return the opposite po...
java
public static InputStream getHTMLInputStream(Class<?> clazz) throws IOException { return HTMLInputStreamPage.class.getResourceAsStream('/'+clazz.getName().replace('.', '/')+".html"); }
java
public void save(ProbeTestRun probeTestRun) throws IOException { OutputStreamWriter osw = new OutputStreamWriter( new FileOutputStream(new File(getTmpDir(probeTestRun), UUID.randomUUID().toString())), Charset.forName(Constants.ENCODING).newEncoder() ); serializer.serializePayload(osw, probeTestRun, true)...
java
void onClose(AbstractSocket socket) { synchronized(sockets) { if(sockets.remove(socket.getId()) == null) throw new AssertionError("Socket not part of this context. onClose called twice?"); } }
java
protected void addSocket(final S newSocket) { if(isClosed()) throw new IllegalStateException("SocketContext is closed"); Future<?> future; synchronized(sockets) { Identifier id = newSocket.getId(); if(sockets.containsKey(id)) throw new IllegalStateException("Socket with the same ID has already been added");...
java
public void writeCompressedUTF(String str, int slot) throws IOException { if(slot<0 || slot>0x3f) throw new IOException("Slot out of range (0-63): "+slot); if(lastStrings==null) lastStrings=new String[64]; String last=lastStrings[slot]; if(last==null) last=""; int strLen=str.length(); int lastLen=last.lengt...
java
public void writeLongUTF(String str) throws IOException { int length = str.length(); writeCompressedInt(length); for(int position = 0; position<length; position+=20480) { int blockLength = length - position; if(blockLength>20480) blockLength = 20480; String block = str.substring(position, position+blockL...
java
public static void printPageList(ChainWriter out, WebSiteRequest req, HttpServletResponse resp, WebPage[] pages, WebPageLayout layout) throws IOException, SQLException { int len = pages.length; for (int c = 0; c < len; c++) { WebPage page = pages[c]; out.print(" <tr>\n" + " <td style='white-space:now...
java
public static void printPageList(ChainWriter out, WebSiteRequest req, HttpServletResponse resp, WebPage parent, WebPageLayout layout) throws IOException, SQLException { printPageList(out, req, resp, parent.getCachedPages(req), layout); }
java
private boolean generatedPositionAfter(Mapping mappingA, Mapping mappingB) { // Optimized for most common case int lineA = mappingA.generated.line; int lineB = mappingB.generated.line; int columnA = mappingA.generated.column; int columnB = mappingB.generated.column; retur...
java
void add(Mapping aMapping) { if (generatedPositionAfter(this._last, aMapping)) { this._last = aMapping; this._array.add(aMapping); } else { this._sorted = false; this._array.add(aMapping); } }
java
List<Mapping> toArray() { if (!this._sorted) { Collections.sort(this._array, Util::compareByGeneratedPositionsInflated); this._sorted = true; } return this._array; }
java
private static void loadDriver(String classname) throws ClassNotFoundException, InstantiationException, IllegalAccessException { if(!driversLoaded.containsKey(classname)) { Object O = Class.forName(classname).newInstance(); driversLoaded.putIfAbsent(classname, O); } }
java
@Override // @NotThreadSafe protected void ensureCapacity(long capacity) throws IOException { long curCapacity = pbuffer.capacity(); if(curCapacity<capacity) expandCapacity(curCapacity, capacity); }
java
private static String getRelativePath(File file, FilesystemIterator iterator) throws IOException { String path = file.getPath(); String prefix = iterator.getStartPath(); if(!path.startsWith(prefix)) throw new IOException("path doesn't start with prefix: path=\""+path+"\", prefix=\""+prefix+"\""); return path.su...
java
private String toLabel(final TimeUnit unit) { switch(unit) { case DAYS: return "day"; case HOURS: return "hour"; case MINUTES: return "minute"; case SECONDS: return "second"; case MILLISECONDS: return "ms"; case MICROSECONDS: return "us"; case NANOSEC...
java
public void connect( final String endpoint, final Callback<? super HttpSocket> onConnect, final Callback<? super Exception> onError ) { executors.getUnbounded().submit( new Runnable() { @Override public void run() { try { // Build request bytes AoByteArrayOutputStream bout = new AoB...
java
static final String encode(int aValue) { String encoded = ""; int digit; int vlq = toVLQSigned(aValue); do { digit = vlq & VLQ_BASE_MASK; vlq >>>= VLQ_BASE_SHIFT; if (vlq > 0) { // There are still more digits in this value, so we must...
java
static Base64VLQResult decode(String aStr, int aIndex) { int strLen = aStr.length(); int result = 0; int shift = 0; boolean continuation; int digit; do { if (aIndex >= strLen) { throw new Error("Expected more digits in base 64 VLQ value."); ...
java
public static StringBuilder generateIdPrefix(String template, String prefix) { NullArgumentException.checkNotNull(template, "template"); NullArgumentException.checkNotNull(prefix, "prefix"); assert isValidId(prefix); final int len = template.length(); // First character must be [A-Za-z] int pos = 0; while...
java
void setPage(Page page) { synchronized(lock) { checkNotFrozen(); if(this.page != null) throw new IllegalStateException("element already has a page: " + this); this.page = page; } assert checkPageAndParentElement(); }
java
public String getId() { if(id == null) { synchronized(lock) { if(id == null) { if(page != null) { Map<String,Element> elementsById = page.getElementsById(); // Generate the ID now String template = getElementIdTemplate(); if(template == null) { throw new IllegalStateExceptio...
java
public ElementRef getElementRef() throws IllegalStateException { Page p = page; if(p == null) throw new IllegalStateException("page not set"); PageRef pageRef = p.getPageRef(); String i = getId(); if(i == null) throw new IllegalStateException("page not set so no id generated"); ElementRef er = elementRef; ...
java
private void setParentElement(Element parentElement) { synchronized(lock) { checkNotFrozen(); if(this.parentElement != null) throw new IllegalStateException("parentElement already set"); this.parentElement = parentElement; } assert checkPageAndParentElement(); }
java
@Override public Long addChildElement(Element childElement, ElementWriter elementWriter) { Long elementKey = super.addChildElement(childElement, elementWriter); childElement.setParentElement(this); return elementKey; }
java
private static void log(File logFile, long connectionId, char separator, String line) { synchronized(logFile) { try { try (Writer out = new FileWriter(logFile, true)) { out.write(Long.toString(connectionId)); out.write(separator); out.write(' '); out.write(line); out.write('\n'); }...
java
public static Optional<Object> tryValue(ReadableRepresentation representation, String name) { try { return Optional.fromNullable(representation.getValue(name)); } catch (RepresentationException e) { return Optional.absent(); } }
java
private static final int intcmp(Integer i1, Integer i2) { if (i1 == null && i2 == null) { return 0; } if (i1 == null) { return -i2; } if (i2 == null) { return i1; } return i1 - i2; }
java
@Override public int compareTo(News o) { int diff = o.getPubDate().compareTo(getPubDate()); if(diff != 0) return diff; return getPage().compareTo(o.getPage()); }
java
public static JmxExporterConfig defaultJmxExporterConfig(final InetAddress hostname, final Integer rmiRegistryPort, final Integer rmiServerPort, final boolean useRandomIds) throws IOException { return new JmxExporterConfig( (hostname != null) ? hostname : InetAddress.getByName(null), ...
java
public static Writer getInstance(Writer out) { // Already in Unix format, no conversion necessary if(UNIX_EOL.equals(EOL)) return out; // Use FindReplaceWriter return new FindReplaceWriter(out, EOL, UNIX_EOL); }
java
public static int[] getRGB(BufferedImage image) { int[] pixels = getRGBArray(image); getRGB(image, pixels); return pixels; }
java
public static Image getImageFromResources(Class<?> clazz, String name) throws IOException { return getImageFromResources(clazz, name, Toolkit.getDefaultToolkit()); }
java
public static Image getImageFromResources(Class<?> clazz, String name, Toolkit toolkit) throws IOException { byte[] imageData; InputStream in = clazz.getResourceAsStream(name); if(in==null) throw new IOException("Unable to find resource: "+name); try { imageData = IoUtils.readFully(in); } finally { in.c...
java
public void printLoginForm(WebPage page, LoginException loginException, WebSiteRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException { getParent().printLoginForm(page, loginException, req, resp); }
java
public void printUnauthorizedPage(WebPage page, WebSiteRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException { getParent().printUnauthorizedPage(page, req, resp); }
java
protected final long getClassLastModified() throws IOException, SQLException { String dir=getServletContext().getRealPath("/WEB-INF/classes"); if(dir!=null && dir.length()>0) { // Try to get from the class file long lastMod=new File(dir, getClass().getName().replace('.', File.separatorChar) + ".class").lastMo...
java
public long getWebPageAndChildrenLastModified(WebSiteRequest req) throws IOException, SQLException { WebPage[] myPages = getCachedPages(req); int len = myPages.length; long mostRecent = getClassLastModified(); if(mostRecent==-1) return -1; for (int c = 0; c < len; c++) { long time = myPages[c].getLastModif...
java
final public long getLastModifiedRecursive(WebSiteRequest req) throws IOException, SQLException { long time=getLastModified(req); WebPage[] myPages=getCachedPages(req); int len=myPages.length; for(int c=0; c<len; c++) { long time2=myPages[c].getLastModifiedRecursive(req); if(time2>time) time=time2; } ...
java
public static long getLastModifiedRecursive(File file) { long time=file.lastModified(); if(file.isDirectory()) { String[] list=file.list(); if(list!=null) { int len=list.length; for(int c=0; c<len; c++) { long time2=getLastModifiedRecursive(new File(file, list[c])); if (time2 > time) time=ti...
java
public void doGet( ChainWriter out, WebSiteRequest req, HttpServletResponse resp ) throws ServletException, IOException, SQLException { }
java
public final WebPage getRootPage() throws IOException, SQLException { WebPage page = this; WebPage parent; while ((parent = page.getParent()) != null) page = parent; return page; }
java
public String getNavImageURL(WebSiteRequest req, HttpServletResponse resp, Object params) throws IOException, SQLException { return resp.encodeURL(req.getContextPath()+req.getURL(this, params)); }
java
final public int getPageIndexInParent(WebSiteRequest req) throws IOException, SQLException { WebPage[] myPages=getParent().getCachedPages(req); int len=myPages.length; for(int c=0;c<len;c++) if(myPages[c].equals(this)) return c; throw new RuntimeException("Unable to find page index in parent."); }
java
public static Class<? extends WebPage> loadClass(String className) throws ClassNotFoundException { return Class.forName(className).asSubclass(WebPage.class); }
java
public String getCopyright(WebSiteRequest req, HttpServletResponse resp, WebPage requestPage) throws IOException, SQLException { return getParent().getCopyright(req, resp, requestPage); }
java
public static String join(Iterable<?> objects, String delimiter) throws ConcurrentModificationException { int delimiterLength = delimiter.length(); // Find total length int totalLength = 0; boolean didOne = false; for(Object obj : objects) { if(didOne) totalLength += delimiterLength; else didOne = true;...
java
public static <A extends Appendable> A join(Iterable<?> objects, String delimiter, A out) throws IOException { boolean didOne = false; for(Object obj : objects) { if(didOne) out.append(delimiter); else didOne = true; out.append(String.valueOf(obj)); } return out; }
java
public static int compareToDDMMYYYY(String date1, String date2) { if(date1.length()!=8 || date2.length()!=8) return 0; return compareToDDMMYYYY0(date1)-compareToDDMMYYYY0(date2); }
java
public static int indexOf(String S, char[] chars, int start) { int Slen=S.length(); int clen=chars.length; for(int c=start;c<Slen;c++) { char ch=S.charAt(c); for(int d=0;d<clen;d++) if(ch==chars[d]) return c; } return -1; }
java
public static String replace(final String string, final String find, final String replacement) { int pos = string.indexOf(find); //System.out.println(string+": "+find+" at "+pos); if (pos == -1) return string; StringBuilder SB = new StringBuilder(); int lastpos = 0; final int findLen = find.length(); do {...
java
public static void replace(final StringBuffer sb, final String find, final String replacement) { int pos = 0; while(pos<sb.length()) { pos = sb.indexOf(find, pos); if(pos==-1) break; sb.replace(pos, pos+find.length(), replacement); pos += replacement.length(); } }
java
public static List<String> splitLines(String S) { List<String> V=new ArrayList<>(); int start=0; int pos; while((pos=S.indexOf('\n', start))!=-1) { String line; if(pos>start && S.charAt(pos-1)=='\r') line = S.substring(start, pos-1); else line = S.substring(start, pos); V.add(line); start=pos+1; ...
java
public static List<String> splitStringCommaSpace(String line) { List<String> words=new ArrayList<>(); int len=line.length(); int pos=0; while(pos<len) { // Skip past blank space char ch; while(pos<len && ((ch=line.charAt(pos))<=' ' || ch==',')) pos++; int start=pos; // Skip to the next blank spac...
java
public static void convertToHex(int value, Appendable out) throws IOException { out.append(getHexChar(value >>> 28)); out.append(getHexChar(value >>> 24)); out.append(getHexChar(value >>> 20)); out.append(getHexChar(value >>> 16)); out.append(getHexChar(value >>> 12)); out.append(getHexChar(value >>> 8)); ...
java
public static int compareToIgnoreCaseCarefulEquals(String S1, String S2) { int diff=S1.compareToIgnoreCase(S2); if(diff==0) diff=S1.compareTo(S2); return diff; }
java
public static int indexOf(String source, String target, int fromIndex, int toIndex) { if(fromIndex>toIndex) throw new IllegalArgumentException("fromIndex>toIndex: fromIndex="+fromIndex+", toIndex="+toIndex); int sourceCount = source.length(); // This line makes it different than regular String indexOf method. ...
java
public static String nullIfEmpty(String value) { return value==null || value.isEmpty() ? null : value; }
java
@Override public boolean isEmpty() { for(List<? extends Method<? extends E>> methods : methodsByClass.values()) { for(Method<? extends E> method : methods) { E singleton = method.getSingleton(target); if(singleton!=null) return false; Set<? extends E> set = method.getSet(target); if(set!=null && !...
java
@Override @SuppressWarnings("unchecked") public boolean addAll(Collection<? extends E> c) { if(c.isEmpty()) return false; if(c instanceof Set) return addAll((Set<? extends E>)c); else throw new UnsupportedOperationException("May only add sets"); }
java
public TempFile createTempFile() throws IOException { TempFile tempFile = new TempFile(prefix, suffix, directory); synchronized(tempFiles) { tempFiles.add(new WeakReference<>(tempFile)); } return tempFile; }
java
public void delete() throws IOException { synchronized(tempFiles) { for(WeakReference<TempFile> tempFileRef : tempFiles) { TempFile tempFile = tempFileRef.get(); if(tempFile!=null) tempFile.delete(); } tempFiles.clear(); } }
java
private static File getFileUploadDirectory(ServletContext servletContext) throws FileNotFoundException { File uploadDir = new File( (File)servletContext.getAttribute(ServletContext.TEMPDIR), "uploads" ); if( !uploadDir.exists() && !uploadDir.mkdirs() // Check exists again, another thread may have c...
java
protected static boolean appendParams(StringBuilder SB, Object optParam, List<String> finishedParams, boolean alreadyAppended) { if (optParam != null) { if (optParam instanceof String) { List<String> nameValuePairs=StringUtility.splitString((String)optParam, '&'); int len=nameValuePairs.size(); for(int...
java
public String getURL(String classAndParams) throws IOException, SQLException { String className, params; int pos=classAndParams.indexOf('?'); if(pos==-1) { className=classAndParams; params=null; } else { className=classAndParams.substring(0, pos); params=classAndParams.substring(pos+1); } return...
java
public String getURL(String classname, String params) throws IOException, SQLException { try { Class<? extends WebPage> clazz=Class.forName(classname).asSubclass(WebPage.class); return getURL(clazz, params); } catch(ClassNotFoundException err) { throw new IOException("Unable to load class: "+classname, err...
java
public String getURL(String url, Object optParam, boolean keepSettings) throws IOException { StringBuilder SB=new StringBuilder(); SB.append(url); List<String> finishedParams=new SortedArrayList<>(); boolean alreadyAppended=appendParams(SB, optParam, finishedParams, false); if(keepSettings) appendSettings(fin...
java
public String getURL(WebPage page) throws IOException, SQLException { return getURL(page, (Object)null); }
java
public String getURL(String url, Object optParam) throws IOException { return getURL(url, optParam, true); }
java
public boolean isLynx() { if(!isLynxDone) { String agent = req.getHeader("user-agent"); isLynx=agent != null && agent.toLowerCase(Locale.ROOT).contains("lynx"); isLynxDone=true; } return isLynx; }
java
public boolean isBlackBerry() { if(!isBlackBerryDone) { String agent = req.getHeader("user-agent"); isBlackBerry=agent != null && agent.startsWith("BlackBerry"); isBlackBerryDone=true; } return isBlackBerry; }
java
public boolean isLinux() { if(!isLinuxDone) { String agent = req.getHeader("user-agent"); isLinux=agent == null || agent.toLowerCase(Locale.ROOT).contains("linux"); isLinuxDone=true; } return isLinux; }
java
public static String addParams(String href, HttpParameters params, String encoding) throws UnsupportedEncodingException { if(params!=null) { StringBuilder sb = new StringBuilder(href); // First find any anchor and if has parameters int anchorStart = href.lastIndexOf('#'); String anchor; boolean hasQues...
java
public static String toJSONString(Object o) { try { return objectMapper.writer().without(SerializationFeature.INDENT_OUTPUT).writeValueAsString(o); } catch (JsonProcessingException e) { throw new RuntimeException(e); } }
java
final public void beginLightArea(WebSiteRequest req, HttpServletResponse resp, ChainWriter out) throws IOException { beginLightArea(req, resp, out, null, false); }
java
private void makeNewFile() throws IOException { String filename=prefix+(files.size()+1)+suffix; File file=new File(parent, filename); out=new FileOutputStream(file); bytesOut=0; files.add(file); }
java
public static FileMessage decode(String encodedMessage, File file) throws IOException { return decode( encodedMessage.isEmpty() ? ByteArray.EMPTY_BYTE_ARRAY : new ByteArray( Base64Coder.decode( encodedMessage ) ), file ); }
java
@Deprecated public static FileMessage decode(String encodedMessage) throws IOException { return decode( encodedMessage.isEmpty() ? ByteArray.EMPTY_BYTE_ARRAY : new ByteArray( Base64Coder.decode( encodedMessage ) ) ); }
java
public static FileMessage decode(ByteArray encodedMessage, File file) throws IOException { try (OutputStream out = new FileOutputStream(file)) { out.write(encodedMessage.array, 0, encodedMessage.size); } return new FileMessage(true, file); }
java
@Deprecated public static FileMessage decode(ByteArray encodedMessage) throws IOException { File file = File.createTempFile("FileMessage.", null); file.deleteOnExit(); return decode(encodedMessage, file); }
java
public static Registry createRegistry(int port, RMIClientSocketFactory csf, RMIServerSocketFactory ssf) throws RemoteException { synchronized(registryCache) { Integer portObj = port; Registry registry = registryCache.get(portObj); if(registry==null) { registry = LocateRegistry.createRegistry(port, csf, s...
java
final public void close() { List<C> connsToClose; synchronized(poolLock) { // Prevent any new connections isClosed = true; // Find any connections that are available and open connsToClose = new ArrayList<>(availableConnections.size()); for(PooledConnection<C> availableConnection : availableConnection...
java
final public int getConnectionCount() { int total = 0; synchronized(poolLock) { for(PooledConnection<C> pooledConnection : allConnections) { if(pooledConnection.connection!=null) total++; } } return total; }
java
private void release(PooledConnection<C> pooledConnection) { long currentTime = System.currentTimeMillis(); long useTime; synchronized(pooledConnection) { pooledConnection.releaseTime = currentTime; useTime = currentTime - pooledConnection.startTime; if(useTime>0) pooledConnection.totalTime.addAndGet(use...
java
final public long getConnects() { long total = 0; synchronized(poolLock) { for(PooledConnection<C> conn : allConnections) { total += conn.connectCount.get(); } } return total; }
java
@Override final public void run() { while(true) { try { try { sleep(delayTime); } catch(InterruptedException err) { logger.log(Level.WARNING, null, err); } long time = System.currentTimeMillis(); List<C> connsToClose; synchronized(poolLock) { if(isClosed) return; // Fin...
java
public static byte[] md5(File file) throws IOException { try (InputStream in = new FileInputStream(file)) { return md5(in); } }
java
public static byte[] md5(InputStream in) throws IOException { MD5InputStream md5in=new MD5InputStream(in); byte[] trashBuffer = BufferManager.getBytes(); try { while(md5in.read(trashBuffer, 0, BufferManager.BUFFER_SIZE) != -1) { // Intentional empty block } } finally { BufferManager.release(trashBu...
java
public void delete() throws IOException { File f = tempFile; if(f!=null) { FileUtils.delete(f); tempFile = null; } }
java
public File getFile() throws IllegalStateException { File f = tempFile; if(f==null) throw new IllegalStateException(); return f; }
java
private void buildData(String path, WebPage page, List<TreePageData> data, WebSiteRequest req) throws IOException, SQLException { if(isVisible(page)) { if(path.length()>0) path=path+'/'+page.getShortTitle(); else path=page.getShortTitle(); WebPage[] pages=page.getCachedPages(req); int len=pages.length; ...
java
@Override public void doGet( ChainWriter out, WebSiteRequest req, HttpServletResponse resp ) throws IOException, SQLException { if(req!=null) super.doGet(out, req, resp); }
java
private void saveProperties() { assert Thread.holdsLock(properties); try { // Create a properties instance that sorts the output by keys (case-insensitive) Properties writer = new Properties() { private static final long serialVersionUID = 6953022173340009928L; @Override public Enumeration<Object>...
java
@Override public void checkGraph() throws AsymmetricException, CycleException, EX { Set<V> vertices = graph.getVertices(); Map<V,Color> colors = new HashMap<>(vertices.size()*4/3+1); Map<V,V> predecessors = new HashMap<>(); // Could this be a simple sequence like TopologicalSorter? Any benefit? for(V v : vert...
java