code
stringlengths
73
34.1k
label
stringclasses
1 value
public void setAttributes(Map<String, String> actions) { this.actions = actions; this.actionCounter = actions.keySet().size(); }
java
public void publish() { /* * Some care is required here to correctly swap the DataBuffers, * but not hold the synchronization object while compiling stats * (a potentially long computation). This ensures that continued * data collection (calls to noteValue()) will not be blo...
java
public double[] getPercentiles(double[] percents, double[] percentiles) { for (int i = 0; i < percents.length; i++) { percentiles[i] = computePercentile(percents[i]); } return percentiles; }
java
public static boolean applyFilters(Object event, Set<EventFilter> filters, StatsTimer filterStats, String invokerDesc, Logger logger) { if (filters.isEmpty()) { return true; } Stopwatch filterStart = filterStats.start(); try { ...
java
protected Predicate<Object> getEqualFilter() { String xpath = getXPath(getChild(0)); Tree valueNode = getChild(1); switch(valueNode.getType()){ case NUMBER: Number value = (Number)((ValueTreeNode)valueNode).getValue(); return new PathValueEventFilter(xpath, new NumericVal...
java
public static boolean equalObjects(Object o1, Object o2) { if (o1 == null) { return (o2 == null); } else if (o2 == null) { return false; } else { return o1.equals(o2); } }
java
@SuppressWarnings("deprecation") @Override public <S extends T> S save(final S entity) { if (arangoOperations.getVersion().getVersion().compareTo("3.4.0") < 0) { arangoOperations.upsert(entity, UpsertStrategy.REPLACE); } else { arangoOperations.repsert(entity); } return entity; }
java
@SuppressWarnings("deprecation") @Override public <S extends T> Iterable<S> saveAll(final Iterable<S> entities) { if (arangoOperations.getVersion().getVersion().compareTo("3.4.0") < 0) { arangoOperations.upsert(entities, UpsertStrategy.UPDATE); } else { final S first = StreamSupport.stream(entities.splitera...
java
@Override public Optional<T> findById(final ID id) { return arangoOperations.find(id, domainClass); }
java
@Override public Iterable<T> findAllById(final Iterable<ID> ids) { return arangoOperations.find(ids, domainClass); }
java
@Override public void delete(final T entity) { String id = null; try { id = (String) arangoOperations.getConverter().getMappingContext().getPersistentEntity(domainClass) .getIdProperty().getField().get(entity); } catch (final IllegalAccessException e) { e.printStackTrace(); } arangoOperations.dele...
java
@Override public Iterable<T> findAll(final Sort sort) { return new Iterable<T>() { @Override public Iterator<T> iterator() { return findAllInternal(sort, null, new HashMap<>()); } }; }
java
@Override public Page<T> findAll(final Pageable pageable) { if (pageable == null) { LOGGER.debug("Pageable in findAll(Pageable) is null"); } final ArangoCursor<T> result = findAllInternal(pageable, null, new HashMap<>()); final List<T> content = result.asListRemaining(); return new PageImpl<>(content, pa...
java
@Override public <S extends T> Optional<S> findOne(final Example<S> example) { final ArangoCursor cursor = findAllInternal((Pageable) null, example, new HashMap()); return cursor.hasNext() ? Optional.ofNullable((S) cursor.next()) : Optional.empty(); }
java
@Override public <S extends T> Iterable<S> findAll(final Example<S> example) { final ArangoCursor cursor = findAllInternal((Pageable) null, example, new HashMap<>()); return cursor; }
java
@Override public <S extends T> Iterable<S> findAll(final Example<S> example, final Sort sort) { final ArangoCursor cursor = findAllInternal(sort, example, new HashMap()); return cursor; }
java
@Override public <S extends T> Page<S> findAll(final Example<S> example, final Pageable pageable) { final ArangoCursor cursor = findAllInternal(pageable, example, new HashMap()); final List<T> content = cursor.asListRemaining(); return new PageImpl<>((List<S>) content, pageable, cursor.getStats().getFullCount())...
java
@Override public <S extends T> long count(final Example<S> example) { final Map<String, Object> bindVars = new HashMap<>(); final String predicate = exampleConverter.convertExampleToPredicate(example, bindVars); final String filter = predicate.length() == 0 ? "" : " FILTER " + predicate; final String query = S...
java
private String escapeSpecialCharacters(final String string) { final StringBuilder escaped = new StringBuilder(); for (final char character : string.toCharArray()) { if (character == '%' || character == '_' || character == '\\') { escaped.append('\\'); } escaped.append(character); } return escaped.t...
java
public static String determineDocumentKeyFromId(final String id) { final int lastSlash = id.lastIndexOf(KEY_DELIMITER); return id.substring(lastSlash + 1); }
java
public static String determineCollectionFromId(final String id) { final int delimiter = id.indexOf(KEY_DELIMITER); return delimiter == -1 ? null : id.substring(0, delimiter); }
java
private boolean shouldIgnoreCase(final Part part) { final Class<?> propertyClass = part.getProperty().getLeafProperty().getType(); final boolean isLowerable = String.class.isAssignableFrom(propertyClass); final boolean shouldIgnoreCase = part.shouldIgnoreCase() != Part.IgnoreCaseType.NEVER && isLowerable && !...
java
private void checkUniquePoint(final Point point) { final boolean isStillUnique = (uniquePoint == null || uniquePoint.equals(point)); if (!isStillUnique) { isUnique = false; } if (!geoFields.isEmpty()) { Assert.isTrue(uniquePoint == null || uniquePoint.equals(point), "Different Points are used - Distan...
java
private void checkUniqueLocation(final Part part) { isUnique = isUnique == null ? true : isUnique; isUnique = (uniqueLocation == null || uniqueLocation.equals(ignorePropertyCase(part))) ? isUnique : false; if (!geoFields.isEmpty()) { Assert.isTrue(isUnique, "Different location fields are used - Distance is amb...
java
public Object convertResult(final Class<?> type) { try { if (type.isArray()) { return TYPE_MAP.get("array").invoke(this); } if (!TYPE_MAP.containsKey(type)) { return getNext(result); } return TYPE_MAP.get(type).invoke(this); } catch (final Exception e) { e.printStackTrace(); return null...
java
private Set<?> buildSet(final ArangoCursor<?> cursor) { return StreamSupport.stream(Spliterators.spliteratorUnknownSize(cursor, 0), false).collect(Collectors.toSet()); }
java
private GeoResult<?> buildGeoResult(final ArangoCursor<?> cursor) { GeoResult<?> geoResult = null; while (cursor.hasNext() && geoResult == null) { final Object object = cursor.next(); if (!(object instanceof VPackSlice)) { continue; } final VPackSlice slice = (VPackSlice) object; final VPackSlic...
java
@SuppressWarnings({ "rawtypes", "unchecked" }) private GeoResults<?> buildGeoResults(final ArangoCursor<?> cursor) { final List<GeoResult<?>> list = new LinkedList<>(); cursor.forEachRemaining(o -> { final GeoResult<?> geoResult = buildGeoResult(o); if (geoResult != null) { list.add(geoResult); } })...
java
@Deprecated public static Zone create(String name, String id) { return new Zone(id, name, 86400, "nil@" + name); }
java
public StringRecordBuilder<D> addAll(String... records) { return addAll(Arrays.asList(checkNotNull(records, "records"))); }
java
private Zone zipWithSOA(Zone next) { Record soa = api.recordsByNameAndType(Integer.parseInt(next.id()), next.name(), "SOA").get(0); return Zone.create(next.id(), next.name(), soa.ttl, next.email()); }
java
private Integer getPriority(Map<String, Object> mutableRData) { Integer priority = null; if (mutableRData.containsKey("priority")) { // SRVData priority = Integer.class.cast(mutableRData.remove("priority")); } else if (mutableRData.containsKey("preference")) { // MXData priority = Integer.class...
java
public static Filter<ResourceRecordSet<?>> alwaysVisible() { return new Filter<ResourceRecordSet<?>>() { @Override public boolean apply(ResourceRecordSet<?> in) { return in != null && in.qualifier() == null; } @Override public String toString() { return "alwaysVisible...
java
public static ResourceRecordSet<SOAData> soa(ResourceRecordSet<?> soa, String email, int ttl) { SOAData soaData = (SOAData) soa.records().get(0); soaData = soaData.toBuilder().serial(soaData.serial() + 1).rname(email).build(); return ResourceRecordSet.<SOAData>builder() .name(soa.name()) .ty...
java
public static List<String> split(char delim, String toSplit) { checkNotNull(toSplit, "toSplit"); if (toSplit.indexOf(delim) == -1) { return Arrays.asList(toSplit); // sortable in JRE 7 and 8 } List<String> out = new LinkedList<String>(); StringBuilder currentString = new StringBuilder(); f...
java
@Override public Iterator<Zone> iterator() { final Iterator<String> delegate = api.getZonesOfAccount(account.get()).iterator(); return new Iterator<Zone>() { @Override public boolean hasNext() { return delegate.hasNext(); } @Override public Zone next() { return f...
java
@Override public Object put(String key, Object val) { val = val != null && val instanceof Number ? Number.class.cast(val).intValue() : val; return super.put(key, val); }
java
static Map<String, String> parseJson(String in) { if (in == null) { return Collections.emptyMap(); } String noBraces = in.replace('{', ' ').replace('}', ' ').trim(); Map<String, String> builder = new LinkedHashMap<String, String>(); Matcher matcher = JSON_FIELDS.matcher(noBraces); while (m...
java
public static List<String> list(URI metadataService, String path) { checkArgument(checkNotNull(path, "path").endsWith("/"), "path must end with '/'; %s provided", path); String content = get(metadataService, path); if (content != null) { return split('\n', content); } return ...
java
public static String get(URI metadataService, String path) { checkNotNull(metadataService, "metadataService"); checkArgument(metadataService.getPath().endsWith("/"), "metadataService must end with '/'; %s provided", metadataService); checkNotNull(path, "path"); InputS...
java
@Override public Iterator<ResourceRecordSet<?>> iterateByName(String name) { Filter<ResourceRecordSet<?>> filter = andNotAlias(nameEqualTo(name)); return lazyIterateRRSets(api.listResourceRecordSets(zoneId, name), filter); }
java
@Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_MENU) { startActivity(new Intent(this, PreferencesActivity.class)); return true; } return super.onKeyDown(keyCode, event); }
java
@Subscribe public void onZones(ZoneList.SuccessEvent event) { String durationEvent = getString(R.string.list_duration, event.duration); Toast.makeText(this, durationEvent, LENGTH_SHORT).show(); }
java
@Subscribe public void onFailure(Throwable t) { Toast.makeText(this, t.getMessage(), LENGTH_LONG).show(); }
java
@Override public Iterator<Zone> iterateByName(final String name) { final Iterator<HostedZone> delegate = api.listHostedZonesByName(name).iterator(); return new PeekingIterator<Zone>() { @Override protected Zone computeNext() { if (delegate.hasNext()) { HostedZone next = delegate....
java
private void deleteEverythingExceptNSAndSOA(String id, String name) { List<ActionOnResourceRecordSet> deletes = new ArrayList<ActionOnResourceRecordSet>(); ResourceRecordSetList page = api.listResourceRecordSets(id); while (!page.isEmpty()) { for (ResourceRecordSet<?> rrset : page) { if (rrset...
java
static Object logModule(boolean quiet, boolean verbose) { checkArgument(!(quiet && verbose), "quiet and verbose flags cannot be used at the same time!"); Logger.Level logLevel; if (quiet) { return null; } else if (verbose) { logLevel = Logger.Level.FULL; } else { logLevel = Logger....
java
@Override public boolean hasNext() { if (!peekingIterator.hasNext()) { return false; } DirectionalRecord record = peekingIterator.peek(); if (record.noResponseRecord) { // TODO: log as this is unsupported peekingIterator.next(); } return true; }
java
static String awaitComplete(CloudDNS api, Job job) { RetryableException retryableException = new RetryableException( format("Job %s did not complete. Check your logs.", job.id), null); Retryer retryer = new Retryer.Default(500, 1000, 30); while (true) { job = api.getStatus(job.id); if ...
java
static Map<String, Object> toRDataMap(Record record) { if ("MX".equals(record.type)) { return MXData.create(record.priority, record.data()); } else if ("TXT".equals(record.type)) { return TXTData.create(record.data()); } else if ("SRV".equals(record.type)) { List<String> rdata = split(' ',...
java
public void stop() { MessageBatcher batcher = null; for (String originalAppenderName : originalAsyncAppenderNameMap.keySet()) { String batcherName = AsyncAppender.class.getName() + "." + originalAppenderName; batcher = BatcherFactory.getBatcher(batcherName); if (batch...
java
public synchronized void reconfigure(Properties props) { // First isolate any property that is different from the immutable // set of original initialization properties Properties newOverrideProps = new Properties(); for (Entry<Object, Object> prop : props.entrySet()) { if (i...
java
private void reConfigureAsynchronously() { refreshCount.incrementAndGet(); if (pendingRefreshes.incrementAndGet() == 1) { executorPool.submit(new Runnable() { @Override public void run() { do { try { ...
java
private void reconfigure() throws ConfigurationException, FileNotFoundException { Properties consolidatedProps = getConsolidatedProperties(); logger.info("The root category for log4j.rootCategory now is {}", consolidatedProps.getProperty(LOG4J_ROOT_CATEGORY)); logger.info("The root cate...
java
private void configureLog4j(Properties props) throws ConfigurationException, FileNotFoundException { if (blitz4jConfig.shouldUseLockFree() && (props.getProperty(LOG4J_LOGGER_FACTORY) == null)) { props.setProperty(LOG4J_LOGGER_FACTORY, LOG4J_FACTORY_IMPL); } convertConfiguredAppenders...
java
private void closeNonexistingAsyncAppenders() { org.apache.log4j.Logger rootLogger = LogManager.getRootLogger(); if (NFLockFreeLogger.class.isInstance(rootLogger)) { ((NFLockFreeLogger)rootLogger).reconcileAppenders(); } Enumeration enums = LogManager.getCurrentLoggers(); ...
java
public Logger getOrCreateLogger(String clazz) { Logger logger = appenderLoggerMap.get(clazz); if (logger == null) { // If multiple threads do the puts, that is fine as it is a one time thing logger = Logger.getLogger(clazz); appenderLoggerMap.put(clazz, logger); } r...
java
public void setProcessorMaxThreads(int maxThreads) { if (processor.getCorePoolSize() > maxThreads) { processor.setCorePoolSize(maxThreads); } processor.setMaximumPoolSize(maxThreads); }
java
public boolean process(T message) { // If this batcher has been shutdown, do not accept any more messages if (isShutDown) { return false; } try { queueSizeTracer.record(queue.size()); } catch (Throwable ignored) { } if (!queue.offer(messag...
java
public void processSync(T message) { // If this batcher has been shutdown, do not accept any more messages if (isShutDown) { return; } try { queueSizeTracer.record(queue.size()); } catch (Throwable ignored) { } try { Stopwatch...
java
public void process(List<T> objects) { for (T message : objects) { // If this batcher has been shutdown, do not accept any more // messages if (isShutDown) { return; } process(message); } }
java
@Monitor(name = "batcherQueueSize", type = DataSourceType.GAUGE) public int getSize() { if (queue != null) { return queue.size(); } else { return 0; } }
java
public void reconcileAppenders() { for (Appender appender : appenderList) { if (!configuredAppenderList.contains(appender.getName())) { appender.close(); appenderList.remove(appender); } } }
java
public static MessageBatcher getBatcher(String name) { MessageBatcher batcher = batcherMap.get(name); return batcher; }
java
public static MessageBatcher createBatcher(String name, MessageProcessor processor) { MessageBatcher batcher = batcherMap.get(name); if (batcher == null) { synchronized (BatcherFactory.class) { batcher = batcherMap.get(name); if (batcher == null) { batcher = new MessageBatcher(name, processor); ...
java
public StackTraceElement getStackTraceElement(Class stackClass) { Stopwatch s = stackTraceTimer.start(); Throwable t = new Throwable(); StackTraceElement[] stArray = t.getStackTrace(); int stackSize = stArray.length; StackTraceElement st = null; for (int i = 0; i < stack...
java
public LocationInfo getLocationInfo(Class wrapperClassName) { LocationInfo locationInfo = null; try { if (stackLocal.get() == null) { stackLocal.set(this.getStackTraceElement(wrapperClassName)); } locationInfo = new LocationInfo(stackLocal.get().getF...
java
public LocationInfo generateLocationInfo(LoggingEvent event) { // If the event is not the same, clear the cache if (event != loggingEvent.get()) { loggingEvent.set(event); clearLocationInfo(); } LocationInfo locationInfo = null; try { // We sho...
java
private void initBatcher(String appenderName) { MessageProcessor<LoggingEvent> messageProcessor = new MessageProcessor<LoggingEvent>() { @Override public void process(List<LoggingEvent> objects) { processLoggingEvents(objects); } }; String batc...
java
private void processLoggingEvents(List<LoggingEvent> loggingEvents) { // Lazy initialization of the appender. This is needed because the // original appenders configuration may be available only after the // complete // log4j initialization. while (appenders.getAllAppenders() == ...
java
private Counter initAndRegisterCounter(String name) { BasicCounter counter = new BasicCounter(MonitorConfig.builder(name).build()); DefaultMonitorRegistry.getInstance().register(counter); return counter; }
java
private boolean putInBuffer(final LoggingEvent event) { putInBufferCounter.increment(); Stopwatch t = putBufferTimeTracer.start(); boolean hasPut = false; if (batcher.process(event)) { hasPut = true; } else { hasPut = false; } t.stop(); ...
java
public void add(long n) { int index = Arrays.binarySearch(bucketOffsets, n); if (index < 0) { // inexact match, take the first bucket higher than n index = -index - 1; } // else exact match; we're good buckets.incrementAndGet(index); }
java
public <R> Connection<CL> getConnectionForOperation(BaseOperation<CL, R> baseOperation) { return selectionStrategy.getConnection(baseOperation, cpConfiguration.getMaxTimeoutWhenExhausted(), TimeUnit.MILLISECONDS); }
java
private Connection<CL> getConnectionForTokenOnRackNoFallback(BaseOperation<CL, ?> op, Long token, String rack, int duration, TimeUnit unit, RetryPolicy retry) throws NoAvailableHostsException, PoolExhaustedException, PoolTimeoutException, PoolOfflineException { DynoConnectException lastEx = null; ...
java
public void initWithHosts(Map<Host, HostConnectionPool<CL>> hPools) { // Get the list of tokens for these hosts //tokenSupplier.initWithHosts(hPools.keySet()); List<HostToken> allHostTokens = tokenSupplier.getTokens(hPools.keySet()); Map<HostToken, HostConnectionPool<CL>> tokenPoolMap = new HashMap<HostToken, ...
java
private void checkKey(final byte[] key) { if (theBinaryKey.get() != null) { verifyKey(key); } else { boolean success = theBinaryKey.compareAndSet(null, key); if (!success) { // someone already beat us to it. that's fine, just verify // that the key is the same verifyKey(key); } else { pi...
java
private void checkKey(final String key) { /* * Get hashtag from the first host of the active pool We cannot use the * connection object because as of now we have not selected a connection. A * connection is selected based on the key or hashtag respectively. */ String hashtag = connPool.getConfiguration...
java
private void verifyKey(final String key) { if (!theKey.get().equals(key)) { try { throw new RuntimeException("Must have same key for Redis Pipeline in Dynomite. This key: " + key); } finally { discardPipelineAndReleaseConnection(); } } }
java
public static int hash32(final byte[] data, int length, int seed) { // 'm' and 'r' are mixing constants generated offline. // They're not really 'magic', they just happen to work well. final int m = 0x5bd1e995; final int r = 24; // Initialize the hash to a random value i...
java
public static int hash32(final String text) { final byte[] bytes = text.getBytes(); return hash32(bytes, bytes.length); }
java
public static int hash32(final String text, int from, int length) { return hash32(text.substring( from, from+length)); }
java
public static long hash64(final String text) { final byte[] bytes = text.getBytes(); return hash64(bytes, bytes.length); }
java
public static long hash64(final String text, int from, int length) { return hash64(text.substring( from, from+length)); }
java
public static byte[] compressBytesNonBase64(byte[] value) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(value.length); try (GZIPOutputStream gos = new GZIPOutputStream(baos)) { gos.write(value); } byte[] compressed = baos.toByteArray(); b...
java
public static byte[] decompressBytesNonBase64(byte[] compressed) throws IOException { ByteArrayInputStream is = new ByteArrayInputStream(compressed); try (InputStream gis = new GZIPInputStream(is)) { return IOUtils.toByteArray(gis); } }
java
public static String decompressStringNonBase64(byte[] compressed) throws IOException { ByteArrayInputStream is = new ByteArrayInputStream(compressed); try (InputStream gis = new GZIPInputStream(is)) { return new String(IOUtils.toByteArray(gis), StandardCharsets.UTF_8); } }
java
public static String compressStringToBase64String(String value) throws IOException { return new String(Base64.encode(compressString(value)), StandardCharsets.UTF_8); }
java
public static String decompressString(byte[] compressed) throws IOException { ByteArrayInputStream is = new ByteArrayInputStream(compressed); try (InputStream gis = new GZIPInputStream(is)) { return new String(Base64.decode(IOUtils.toByteArray(gis)), StandardCharsets.UTF_8); } }
java
public static String decompressFromBase64String(String compressed) throws IOException { return decompressString(Base64.decode(compressed.getBytes(StandardCharsets.UTF_8))); }
java
public static boolean isCompressed(byte[] bytes) throws IOException { return bytes != null && bytes.length >= 2 && bytes[0] == (byte) (GZIPInputStream.GZIP_MAGIC) && bytes[1] == (byte) (GZIPInputStream.GZIP_MAGIC >> 8); }
java
public static boolean isCompressed(InputStream inputStream) throws IOException { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); byte[] data = new byte[2]; int nRead = inputStream.read(data, 0, 2); buffer.write(data, 0, nRead); buffer.flush(); return isComp...
java
public boolean inactiveSetChanged(Collection<Host> hostsUp, Collection<Host> hostsDown) { boolean newInactiveHostsFound = false; // Check for condition 1. for (Host hostDown : hostsDown) { if (activeHosts.contains(hostDown)) { newInactiveHostsFound = true; break; } } // Check for condi...
java
public HostStatusTracker computeNewHostStatus(Collection<Host> hostsUp, Collection<Host> hostsDown) { verifyMutuallyExclusive(hostsUp, hostsDown); Set<Host> nextActiveHosts = new HashSet<Host>(hostsUp); // Get the hosts that are currently down Set<Host> nextInactiveHosts = new HashSet<Host>(hostsDown);...
java
public void swapWithList(Collection<T> newList) { InnerList newInnerList = new InnerList(newList); ref.set(newInnerList); }
java
public synchronized void addElement(T element) { List<T> origList = ref.get().list; boolean isPresent = origList.contains(element); if (isPresent) { return; } List<T> newList = new ArrayList<T>(origList); newList.add(element); swapWithList(newList); }
java
public synchronized void removeElement(T element) { List<T> origList = ref.get().list; boolean isPresent = origList.contains(element); if (!isPresent) { return; } List<T> newList = new ArrayList<T>(origList); newList.remove(element); swapWithList(newList); }
java
public List<T> getEntireList() { InnerList iList = ref.get(); return iList != null ? iList.getList() : null; }
java
public int getSize() { InnerList iList = ref.get(); return iList != null ? iList.getList().size() : 0; }
java
public static int hash(byte[] data, int offset, int length, int seed) { return hash(ByteBuffer.wrap(data, offset, length), seed); }
java