code
stringlengths
73
34.1k
label
stringclasses
1 value
public void handleDatagram (InetSocketAddress source, DatagramChannel channel, ByteBuffer buf, long when) { // lazily create our various bits and bobs if (_digest == null) { try { _digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmExce...
java
protected void inheritStreams (PresentsConnection other) { _fin = other._fin; _oin = other._oin; _oout = other._oout; if (_loader != null) { _oin.setClassLoader(_loader); } }
java
public void setDefaultAccessController (AccessController controller) { AccessController oldDefault = _defaultController; _defaultController = controller; // switch all objects from the old default (null, usually) to the new default. for (DObject obj : _objects.values()) { ...
java
public void clearProxyObject (int origObjectId, DObject object) { if (_proxies.remove(object.getOid()) == null) { log.warning("Missing proxy mapping for cleared proxy", "ooid", origObjectId); } _objects.remove(object.getOid()); }
java
public Stats getStats (boolean snapshot) { if (snapshot) { _recent = _current; _current = new Stats(); _current.maxQueueSize = _evqueue.size(); } return _recent; }
java
public void run () { log.info("DOMGR running."); // make a note of the thread that's processing events synchronized (this) { _dobjThread = Thread.currentThread(); } while (isRunning()) { // pop the next unit off the queue and process it p...
java
public void dumpUnitProfiles () { for (Map.Entry<String, UnitProfile> entry : _profiles.entrySet()) { log.info("P: " + entry.getKey() + " => " + entry.getValue()); } }
java
protected void processUnit (Object unit) { long start = System.nanoTime(); // keep track of the largest queue size we've seen int queueSize = _evqueue.size(); if (queueSize > _current.maxQueueSize) { _current.maxQueueSize = queueSize; } try { ...
java
protected void processCompoundEvent (CompoundEvent event) { List<DEvent> events = event.getEvents(); int ecount = events.size(); // look up the target object DObject target = _objects.get(event.getTargetOid()); if (target == null) { log.debug("Compound event targ...
java
protected void processEvent (DEvent event) { // look up the target object DObject target = _objects.get(event.getTargetOid()); if (target == null) { log.debug("Event target no longer exists", "event", event); return; } // check the event's permissions...
java
protected void handleFatalError (Object causer, Error error) { if (_fatalThrottle.throttleOp()) { throw error; } log.warning("Fatal error caused by '" + causer + "': " + error, error); }
java
protected void registerEventHelpers () { try { _helpers.put(ObjectDestroyedEvent.class, new EventHelper () { public boolean invoke (DEvent event, DObject target) { return objectDestroyed(event, target); } }); _helpers.pu...
java
public void setHeader (File header) { try { _header = StreamUtil.toString(new FileReader(header)); } catch (IOException ioe) { System.err.println("Unabled to load header '" + header + ": " + ioe.getMessage()); } }
java
protected boolean wouldProduceSameFile (String generated, File existing) throws IOException { Iterator<String> generatedLines = Splitter.on(EOL).split(generated).iterator(); for (String prev : Files.readLines(existing, UTF_8)) { if (!generatedLines.hasNext()) { re...
java
protected String mergeTemplate (String template, Object... data) throws IOException { return mergeTemplate(template, createMap(data)); }
java
protected String mergeTemplate (String template, Map<String, Object> data) throws IOException { Reader reader = new InputStreamReader(getClass().getClassLoader().getResourceAsStream(template), UTF_8); return convertEols(Mustache.compiler().escapeHTML(false).compile(reader).execut...
java
public static String comicChars (int length) { char[] chars = new char[length]; for (int ii=0; ii < length; ii++) { chars[ii] = RandomUtil.pickRandom(COMIC_CHARS); } return new String(chars); }
java
public String filter (String msg, Name otherUser, boolean outgoing) { // first, check against the drop-always list _stopMatcher.reset(msg); if (_stopMatcher.find()) { return null; } // then see what kind of curse filtering the user has configured Mode lev...
java
protected void configureCurseWords (String curseWords) { StringTokenizer st = new StringTokenizer(curseWords); int numWords = st.countTokens(); _matchers = new Matcher[numWords]; _replacements = new String[numWords]; _vernacular = new String[numWords]; _comicLength =...
java
protected void configureStopWords (String stopWords) { List<String> patterns = Lists.newArrayList(); for (StringTokenizer st = new StringTokenizer(stopWords); st.hasMoreTokens(); ) { patterns.add(getStopWordRegexp(st.nextToken())); } String pattern = patterns.isEmpty() ...
java
protected void setStopPattern (String pattern) { _stopMatcher = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE).matcher(""); }
java
public static <T> T queueAndWait ( RunQueue runq, final String name, final Callable<T> action) throws ServiceException { final ServletWaiter<T> waiter = new ServletWaiter<T>(name); runq.postRunnable(new Runnable() { public void run () { try { ...
java
public static <T extends TOP> int count(final Class<T> type, final JCas aJCas) { return JCasUtil.select(aJCas, type).size(); }
java
public static <T extends TOP> boolean hasAny(final Class<T> type, final JCas aJCas) { return count(type, aJCas) != 0; }
java
public static <T extends TOP> boolean hasNo(final Class<T> type, final JCas aJCas) { return !hasAny(type, aJCas); }
java
public static <T extends TOP> List<T> selectAsList(final JCas jCas, final Class<T> type) { return new ArrayList<>(JCasUtil.select(jCas, type)); }
java
public static <T extends Annotation> boolean doOverlap(final T anno1, final T anno2) { return anno1.getEnd() > anno2.getBegin() && anno1.getBegin() < anno2.getEnd(); }
java
public static boolean haveSameSpan(final Annotation anno1, final Annotation anno2) { return anno1.getBegin() == anno2.getBegin() && anno1.getEnd() == anno2.getEnd(); }
java
public static JCas getJCas(final Annotation annotation) { JCas result = null; try { result = annotation.getCAS().getJCas(); } catch (final CASException e) { throw new IllegalArgumentException(e); } return result; }
java
public static boolean isFirstCoveredToken(final Token token, final Annotation annotation) { final JCas jCas = getJCas(annotation); final List<Token> coveredTokens = JCasUtil.selectCovered(jCas, Token.class, annotation); if (coveredTokens.isEmpty()) { return false; } ...
java
public static void updateEnd(final Annotation annotation, final int end) { annotation.removeFromIndexes(); annotation.setEnd(end); annotation.addToIndexes(); }
java
public static void updateBegin(final Annotation annotation, final int begin) { annotation.removeFromIndexes(); annotation.setBegin(begin); annotation.addToIndexes(); }
java
public static Token findTokenByBeginPosition(JCas jCas, int begin) { for (Token token : JCasUtil.select(getInitialView(jCas), Token.class)) { if (token.getBegin() == begin) { return token; } } return null; }
java
public static Token findTokenByEndPosition(JCas jCas, int end) { for (Token token : JCasUtil.select(getInitialView(jCas), Token.class)) { if (token.getEnd() == end) { return token; } } return null; }
java
public static List<Token> getPrecedingTokens(JCas jCas, Token token) { List<Token> result = new ArrayList<Token>(); for (Token t : JCasUtil.select(getInitialView(jCas), Token.class)) { if (t.getBegin() < token.getBegin()) { result.add(t); } } ...
java
public static List<Sentence> getPrecedingSentences(JCas jCas, Sentence annotation) { List<Sentence> result = new ArrayList<Sentence>(); for (Sentence sentence : JCasUtil.select(getInitialView(jCas), Sentence.class)) { if (sentence.getBegin() < annotation.getBegin()) { re...
java
public byte[] getSecret (PrivateKey key) { if (_secret == null) { _secret = SecureUtil.decryptBytes(key, _encodedSecret, _salt); } return _secret; }
java
public void addTranslation (String className, String streamedName) { if (_translations == null) { _translations = Maps.newHashMap(); } _translations.put(className, streamedName); }
java
public void writeIntern (String value) throws IOException { // if the value to be written is null, simply write a zero if (value == null) { writeShort(0); return; } // create our intern map if necessary if (_internmap == null) { _i...
java
protected ClassMapping writeClassMapping (Class<?> sclass) throws IOException { // create our classmap if necessary if (_classmap == null) { _classmap = Maps.newHashMap(); } // look up the class mapping record ClassMapping cmap = _classmap.get(sclass); ...
java
protected void writeClassMapping (int code, Class<?> sclass) throws IOException { writeShort(code); String cname = sclass.getName(); if (_translations != null) { String tname = _translations.get(cname); if (tname != null) { cname = tname; ...
java
public void getTimeOid (String arg1, TimeBaseService.GotTimeBaseListener arg2) { TimeBaseMarshaller.GotTimeBaseMarshaller listener2 = new TimeBaseMarshaller.GotTimeBaseMarshaller(); listener2.listener = arg2; sendRequest(GET_TIME_OID, new Object[] { arg1, listener2 }); ...
java
public synchronized void writeDatagram (Message datagram) throws IOException { // first write the sequence and acknowledge numbers _uout.writeInt(++_lastNumber); _uout.writeInt(_lastReceived); // make sure the mapped sets are clear Set<Class<?>> mappedClasses = _uout...
java
public synchronized Message readDatagram () throws IOException, ClassNotFoundException { // read in the sequence number and determine if it's out-of-order int number = _uin.readInt(); if (number <= _lastReceived) { return null; } _missedCount = number - _l...
java
protected <T extends InvocationMarshaller<?>> T addProvider ( InvocationProvider prov, Class<T> mclass) { return _plmgr.addProvider(prov, mclass); }
java
protected <T extends InvocationMarshaller<?>> T addDispatcher (InvocationDispatcher<T> disp) { return _plmgr.addDispatcher(disp); }
java
public byte[] createSecret (PublicKeyCredentials pkcred, PrivateKey key, int length) { _data = new AuthResponseData(); byte[] clientSecret = pkcred.getSecret(key); if (clientSecret == null) { _data.code = FAILED_TO_SECURE; return null; } byte[] secret ...
java
public byte[] getCodeBytes (PublicKeyCredentials pkcreds) { return pkcreds == null || _data.code == null || _data.code.equals(FAILED_TO_SECURE) ? null : SecureUtil.xorBytes(StringUtil.unhexlate(_data.code), pkcreds.getSecret()); }
java
public void activatePeriodicReport (RootDObjectManager omgr) { // queue up an interval which will generate reports as long as the omgr is alive omgr.newInterval(new Runnable() { public void run () { logReport(LOG_REPORT_HEADER + generateReport(DE...
java
protected String generateReport (String type, long now, boolean reset) { long sinceLast = now - _lastReportStamp; long uptime = now - _serverStartTime; StringBuilder report = new StringBuilder(); // add standard bits to the default report if (DEFAULT_TYPE.equals(type)) { ...
java
public void init (NodeRecord record) { _record = record; _client = new Client(null, _omgr) { @Override protected void convertFromRemote (DObject target, DEvent event) { super.convertFromRemote(target, event); // rewrite the event's target oid using the oid...
java
public void objectAvailable (NodeObject object) { // listen for lock and cache updates nodeobj = object; nodeobj.addListener(_listener = createListener()); _peermgr.connectedToPeer(this); String nodeName = getNodeName(); for (ClientInfo clinfo : nodeobj.clients) { ...
java
public List<NodeRecord> loadNodes (String namespace, boolean includeShutdown) { // we specifically avoid caching this query because we want the servers to always see the // most up to date set of nodes Query<NodeRecord> query = from(NodeRecord.class).noCache(); List<SQLExpression<?>>...
java
public List<NodeRecord> loadNodesFromRegion (String region) { return from(NodeRecord.class) .noCache() .where(NodeRecord.REGION.eq(region), Ops.not(NodeRecord.SHUTDOWN)) .select(); }
java
public void updateNode (NodeRecord record) { record.lastUpdated = new Timestamp(System.currentTimeMillis()); store(record); }
java
public void shutdownNode (String nodeName) { updatePartial(NodeRecord.getKey(nodeName), NodeRecord.SHUTDOWN, true); }
java
public List<byte[]> split(byte sep) { List<byte[]> l = new LinkedList<>(); int start = 0; for (int i = 0; i < bytes.length; i++) { if (sep == bytes[i]) { byte[] b = Arrays.copyOfRange(bytes, start, i); if (b.length > 0) { l.add(b); ...
java
public OccupantInfo getOccupantInfo (int bodyOid) { // make sure we're somewhere return (_place == null) ? null : _place.occupantInfo.get(Integer.valueOf(bodyOid)); }
java
public OccupantInfo getOccupantInfo (Name username) { return (_place == null) ? null : _place.getOccupantInfo(username); }
java
public void entryAdded (EntryAddedEvent<OccupantInfo> event) { // bail if this isn't for the OCCUPANT_INFO field if (!event.getName().equals(PlaceObject.OCCUPANT_INFO)) { return; } // now let the occupant observers know what's up final OccupantInfo info = event.g...
java
public void entryUpdated (EntryUpdatedEvent<OccupantInfo> event) { // bail if this isn't for the OCCUPANT_INFO field if (!event.getName().equals(PlaceObject.OCCUPANT_INFO)) { return; } // now let the occupant observers know what's up final OccupantInfo info = eve...
java
public void entryRemoved (EntryRemovedEvent<OccupantInfo> event) { // bail if this isn't for the OCCUPANT_INFO field if (!event.getName().equals(PlaceObject.OCCUPANT_INFO)) { return; } // let the occupant observers know what's up final OccupantInfo oinfo = event....
java
public void start(Activity activity) { Intent i = new Intent(activity, CalculatorActivity.class); if (!TextUtils.isEmpty(activityTitle)) { i.putExtra(CalculatorActivity.TITLE_ACTIVITY, activityTitle); } if (!TextUtils.isEmpty(value)) { i.putExtra(CalculatorActivi...
java
public void start(Fragment fragment) { Intent i = new Intent(fragment.getContext(), CalculatorActivity.class); if (!TextUtils.isEmpty(activityTitle)) { i.putExtra(CalculatorActivity.TITLE_ACTIVITY, activityTitle); } if (!TextUtils.isEmpty(value)) { i.putExtra(Cal...
java
public int getIndexWithinSections(int listPosition) { boolean isSection = false; int numPrecedingSections = 0; for (Integer sectionPosition : mSections.keySet()) { if (listPosition > sectionPosition) numPrecedingSections++; else if (listPosition == section...
java
@Override public int getPositionForSection(int sectionIndex) { if (mSectionList.size() == 0) { for (Integer key : mSections.keySet()) { mSectionList.add(key); } } return sectionIndex < mSectionList.size() ? mSectionList.get(sectionIndex) : getCount(); ...
java
@Override public int getSectionForPosition(int position) { Object[] objects = getSections(); // the fast scroll section objects int sectionIndex = getIndexWithinSections(position); return sectionIndex < objects.length ? sectionIndex : 0; }
java
public double getNumericValue() { String original = getText().toString().replaceAll(mNumberFilterRegex, ""); if (hasCustomDecimalSeparator) { // swap custom decimal separator with locale one to allow parsing original = StringUtils.replace(original, String.valu...
java
private String format(final String original) { final String[] parts = original.split("\\" + mDecimalSeparator, -1); String number = parts[0] // since we split with limit -1 there will always be at least 1 part .replaceAll(mNumberFilterRegex, "") .replaceFirst(LEADING_ZERO...
java
public static Document createEmptyDocument() { Document output = null; try { final DocumentBuilder db = FACTORY.newDocumentBuilder(); db.setErrorHandler(new ParserErrorHandler()); output = db.newDocument(); } catch (final Exception ex) { LOG...
java
public static boolean validate(final Source input, final Source[] schemas) { boolean isValid = true; try { final SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); factory.setResourceResolver(new SchemaLSResourceResolver()); fi...
java
public static void transform(final Source input, final Source sheet, final Result output) { try { final DOMResult intermediate = new DOMResult(createEmptyDocument()); // Transform. createTransformer(sheet).transform(input, intermediate); // Format. ...
java
static Document loadDefinition(final File def) { // Parse the jDPL definition into a DOM tree. final Document document = XmlUtils.parseFile(def); if (document == null) { return null; } // Log the jPDL version from the process definition (if applicable and avai...
java
private static void transform(final String xmlFileName, final String xsltFileName, final String outputFileName) { Source xsltSource = null; if (StringUtils.isNotBlank(xsltFileName)) { // Use the given stylesheet. xsltSource = new StreamSource(new File(xsltFileName)); } el...
java
private static Version parseVersion(String version) { String[] parts = version.split("\\."); int nbParts = parts.length; int majorIndex = nbParts > 1 ? 1 : 0; int major = Integer.parseInt(parts[majorIndex]); return new Version(major); }
java
@Override public void initialize(URL location, ResourceBundle resources) { // Add an event handler to automatically close the stage in the event of // any exception encountered. addEventHandler(WindowEvent.ANY, new EventHandler<WindowEvent>() { @Override public void ...
java
private void setHeadlessPadding() { if (dialogType == DialogType.INPUT_TEXT) { bodyContainer.setStyle( PreDefinedStyle.INPUT_DIALOG_HEADLESS_PADDING.getStyle()); } else if (dialogType == DialogType.EXCEPTION) { bodyContainer.setStyle( PreD...
java
public final void setHeaderColorStyle(HeaderColorStyle headerColorStyle) { this.headerColorStyle = headerColorStyle; if (!headerColorStyle.getColorStyle().isEmpty()) { this.getHeaderLabel().setStyle(headerColorStyle.getColorStyle()); // It's either DEFAULT or CUSTOM value (all ...
java
public void setFont(String header_font_family, int header_font_size, String details_font_family, int details_font_size) { this.headerLabel .setStyle("-fx-font-family: \"" + header_font_family + "\";" + "-fx-font-size:" + Integer.toString(header_font_size) + "p...
java
public void setHeaderFont(String font_family, int font_size) { this.headerLabel .setStyle("-fx-font-family: \"" + font_family + "\";" + "-fx-font-size:" + Integer.toString(font_size) + "px;"); }
java
public void setDetailsFont(String font_family, int font_size) { this.detailsLabel .setStyle("-fx-font-family: \"" + font_family + "\";" + "-fx-font-size:" + Integer.toString(font_size) + "px;"); }
java
@FXML private void send_btn_on_click(ActionEvent event) { // Future proof for other uses of send event handler if (this.dialogType == DialogType.INPUT_TEXT) { this.textEntry = this.inputTextField.getText(); } setResponse(DialogResponse.SEND); close(); }
java
public static String fingerprint(String str) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); return byteArrayToHexString(md.digest(str.getBytes())); } catch (NoSuchAlgorithmException nsae) { LOGGER.warning("Unable to calculate the fingerprint for string [" + str + "]."); return null; ...
java
public static String fingerprint(Class cl, Method m) { return fingerprint(cl, m.getName()); }
java
public static String fingerprint(Class cl, String methodName) { return fingerprint(cl.getCanonicalName() + "." + methodName); }
java
public static Set<String> getContributors(Set<String> baseContributors, ProbeTest methodAnnotation, ProbeTestClass classAnnotation) { Set<String> contributors; if (baseContributors == null) { contributors = new HashSet<>(); } else { contributors = populateContributors(baseContributors, new HashSet<String>...
java
private static Set<String> populateContributors(Set<String> source, Set<String> destination) { for (String contributor : source) { if (!emailPattern.matcher(contributor).matches()) { LOGGER.warning("The contributor '" + contributor + "' does not respect the email pattern " + emailPattern.pattern() + " and is i...
java
protected int binarySearchHashCode(int elemHash) { int left = 0; int right = size()-1; while(left <= right) { int mid = (left + right)>>1; int midHash = get(mid).hashCode(); if(elemHash==midHash) return mid; if(elemHash<midHash) right = mid-1; else left = mid+1; } return -(left+1); }
java
public int indexOf(int hashCode) { int pos=binarySearchHashCode(hashCode); if(pos<0) return -1; // Try backwards until different hashCode while(pos>0 && get(pos-1).hashCode()==hashCode) pos--; return pos; }
java
@Override public boolean add(E o) { // Shortcut for empty int size=size(); if(size==0) { super.add(o); } else { int Ohash=o.hashCode(); // Shortcut for adding to end (makes imports of already-sorted data operate at constant-time instead of logarithmic complexity) if(Ohash>=get(size-1).hashCode()) ...
java
public static HttpParameters wrap(HttpParameters wrapped) { // null remains null if(wrapped == null) return null; // Empty are unmodifiable if(wrapped == EmptyParameters.getInstance()) return wrapped; // ServletRequest parameters are unmodifiable already if(wrapped instanceof ServletRequestParameters) retur...
java
public static boolean isRssEnabled(ServletContext servletContext) { // Note: no locking performed since it's ok for two threads to do the work concurrently at first Boolean isRssEnabled = (Boolean)servletContext.getAttribute(ISS_RSS_ENABLED_CACHE_KEY); if(isRssEnabled == null) { try { Class.forName(RSS_SER...
java
public static boolean isProtectedExtension(String path) { for(String extension : PROTECTED_EXTENSIONS) { if(path.endsWith(extension)) return true; } return false; }
java
public static String getRssServletPath(PageRef pageRef) { String servletPath = pageRef.getBookRef().getPrefix() + pageRef.getPath(); for(String extension : RESOURCE_EXTENSIONS) { if(servletPath.endsWith(extension)) { servletPath = servletPath.substring(0, servletPath.length() - extension.length()); break...
java
public int compareTo(BookRef o) { int diff = domain.compareTo(o.domain); if(diff != 0) return diff; return path.compareTo(o.path); }
java
@Override public List<String> sources() { List<String> sources = new ArrayList<>(); for (int i = 0; i < this._sections.size(); i++) { for (int j = 0; j < this._sections.get(i).consumer.sources().size(); j++) { sources.add(this._sections.get(i).consumer.sources().get(j)); ...
java
public static long syncFile(InputStream in, RandomAccessFile out) throws IOException { byte[] inBuff = new byte[BLOCK_SIZE]; byte[] outBuff = new byte[BLOCK_SIZE]; long pos = 0; long bytesWritten = 0; int numBytes; while((numBytes=in.read(inBuff, 0, BLOCK_SIZE))!=-1) { if(DEBUG) System.err.println(pos+":...
java
protected void evaluateAttributes(E element, ELContext elContext) throws JspTagException, IOException { String idStr = nullIfEmpty(resolveValue(id, String.class, elContext)); if(idStr != null) element.setId(idStr); }
java
protected void doBody(E element, CaptureLevel captureLevel) throws JspException, IOException { JspFragment body = getJspBody(); if(body != null) { if(captureLevel == CaptureLevel.BODY) { final PageContext pageContext = (PageContext)getJspContext(); // Invoke tag body, capturing output BufferWriter ca...
java
public static Properties loadFromResource(ServletContext servletContext, String resource) throws IOException { Properties props = new Properties(); InputStream in = servletContext.getResourceAsStream(resource); if(in==null) throw new LocalizedIOException(accessor, "PropertiesUtils.readProperties.resourceNotFound"...
java