code
stringlengths
73
34.1k
label
stringclasses
1 value
protected boolean sendLeaveReqToCoord(final Address coord) { if(coord == null) { log.warn("%s: cannot send LEAVE request to null coord", gms.getLocalAddress()); return false; } Promise<Address> leave_promise=gms.getLeavePromise(); gms.setLeaving(true); log...
java
public static boolean isBinaryCompatible(short ver) { if(version == ver) return true; short tmp_major=(short)((ver & MAJOR_MASK) >> MAJOR_SHIFT); short tmp_minor=(short)((ver & MINOR_MASK) >> MINOR_SHIFT); return major == tmp_major && minor == tmp_minor; }
java
public void connect(String group, Address addr, String logical_name, PhysicalAddress phys_addr) throws Exception { synchronized(this) { _doConnect(); } try { writeRequest(new GossipData(GossipType.REGISTER, group, addr, logical_name, phys_addr)); } catch(E...
java
public int compareTo(Address o) { int h1, h2, rc; // added Nov 7 2005, makes sense with canonical addresses if(this == o) return 0; if(!(o instanceof IpAddress)) throw new ClassCastException("comparison between different classes: the other object is " + (o != nul...
java
public Membership add(Collection<Address> v) { if(v != null) v.forEach(this::add); return this; }
java
public Membership remove(Address old_member) { if(old_member != null) { synchronized(members) { members.remove(old_member); } } return this; }
java
public Membership remove(Collection<Address> v) { if(v != null) { synchronized(members) { members.removeAll(v); } } return this; }
java
public Membership merge(Collection<Address> new_mems, Collection<Address> suspects) { remove(suspects); return add(new_mems); }
java
public boolean contains(Address member) { if(member == null) return false; synchronized(members) { return members.contains(member); } }
java
public Set getChildrenNames(String fqn) { Node n=findNode(fqn); Map m; if(n == null) return null; m=n.getChildren(); if(m != null) return m.keySet(); else return null; }
java
public boolean containsKeys(Collection<K> keys) { for(K key: keys) if(!map.containsKey(key)) return false; return true; }
java
public Set<V> nonRemovedValues() { return map.values().stream().filter(entry -> !entry.removable).map(entry -> entry.val).collect(Collectors.toSet()); }
java
public void removeMarkedElements(boolean force) { long curr_time=System.nanoTime(); for(Iterator<Map.Entry<K,Entry<V>>> it=map.entrySet().iterator(); it.hasNext();) { Map.Entry<K, Entry<V>> entry=it.next(); Entry<V> tmp=entry.getValue(); if(tmp == null) ...
java
public void setResult(T result) { lock.lock(); try { if(Objects.equals(expected_result, result)) super.setResult(result); } finally { lock.unlock(); } }
java
protected static String sanitize(final String name) { String retval=name; retval=retval.replace('/', '-'); retval=retval.replace('\\', '-'); return retval; }
java
public Map<Thread, Runnable> getCurrentRunningTasks() { Map<Thread, Runnable> map = new HashMap<>(); for (Entry<Thread, Holder<Runnable>> entry : _runnables.entrySet()) { map.put(entry.getKey(), entry.getValue().value); } return map; }
java
public boolean add(T obj) { if(obj == null) return false; while(size() >= max_capacity && size() > 0) { poll(); } return super.add(obj); }
java
protected static FORK getFORK(JChannel ch, ProtocolStack.Position position, Class<? extends Protocol> neighbor, boolean create_fork_if_absent) throws Exception { ProtocolStack stack=ch.getProtocolStack(); FORK fork=stack.findProtocol(FORK.class); if(fork == null...
java
protected void copyFields() { for(Field field: copied_fields) { Object value=Util.getField(field,main_channel); Util.setField(field, this, value); } }
java
protected Map<String,Map<String,Object>> dumpAttrsSelectedProtocol(String protocol_name, List<String> attrs) { return ch.dumpStats(protocol_name, attrs); }
java
protected void handleOperation(Map<String, String> map, String operation) throws Exception { int index=operation.indexOf('.'); if(index == -1) throw new IllegalArgumentException("operation " + operation + " is missing the protocol name"); String prot_name=operation.substring(0, index...
java
public void send(Message msg) throws Exception { num_senders.incrementAndGet(); long size=msg.size(); lock.lock(); try { if(count + size >= transport.getMaxBundleSize()) sendBundledMessages(); addMessage(msg, size); // at this point,...
java
public int getNumDeliverable() { NumDeliverable visitor=new NumDeliverable(); lock.lock(); try { forEach(hd+1, hr, visitor); return visitor.getResult(); } finally { lock.unlock(); } }
java
public boolean add(final List<LongTuple<T>> list, boolean remove_added_elements) { return add(list, remove_added_elements, null); }
java
public boolean add(final List<LongTuple<T>> list, boolean remove_added_elements, T const_value) { if(list == null || list.isEmpty()) return false; boolean added=false; // find the highest seqno (unfortunately, the list is not ordered by seqno) long highest_seqno=findHighestSe...
java
public T get(long seqno) { lock.lock(); try { if(seqno - low <= 0 || seqno - hr > 0) return null; int row_index=computeRow(seqno); if(row_index < 0 || row_index >= matrix.length) return null; T[] row=matrix[row_index]; ...
java
public T _get(long seqno) { lock.lock(); try { int row_index=computeRow(seqno); if(row_index < 0 || row_index >= matrix.length) return null; T[] row=matrix[row_index]; if(row == null) return null; int index=compu...
java
public T remove(boolean nullify) { lock.lock(); try { int row_index=computeRow(hd+1); if(row_index < 0 || row_index >= matrix.length) return null; T[] row=matrix[row_index]; if(row == null) return null; int index...
java
public <R> R removeMany(boolean nullify, int max_results, Predicate<T> filter, Supplier<R> result_creator, BiConsumer<R,T> accumulator) { lock.lock(); try { Remover<R> remover=new Remover<>(nullify, max_results, filter, result_creator, accumulator); fo...
java
protected long findHighestSeqno(List<LongTuple<T>> list) { long seqno=-1; for(LongTuple<T> tuple: list) { long val=tuple.getVal1(); if(val - seqno > 0) seqno=val; } return seqno; }
java
public SeqnoList getMissing(int max_msgs) { lock.lock(); try { if(size == 0) return null; long start_seqno=getHighestDeliverable() +1; int capacity=(int)(hr - start_seqno); int max_size=max_msgs > 0? Math.min(max_msgs, capacity) : capacity;...
java
public String dump() { lock.lock(); try { return stream(low, hr).filter(Objects::nonNull).map(Object::toString) .collect(Collectors.joining(", ")); } finally { lock.unlock(); } }
java
@GuardedBy("lock") protected T[] getRow(int index) { T[] row=matrix[index]; if(row == null) { row=(T[])new Object[elements_per_row]; matrix[index]=row; } return row; }
java
protected Tuple<SecretKey,byte[]> getSecretKeyFromAbove() { return (Tuple<SecretKey,byte[]>)up_prot.up(new Event(Event.GET_SECRET_KEY)); }
java
protected void setSecretKeyAbove(Tuple<SecretKey,byte[]> key) { up_prot.up(new Event(Event.SET_SECRET_KEY, key)); }
java
public static ProtocolStackConfigurator getStackConfigurator(File file) throws Exception { checkJAXPAvailability(); InputStream input=getConfigStream(file); return XmlConfigurator.getInstance(input); }
java
public static ProtocolStackConfigurator getStackConfigurator(URL url) throws Exception { checkForNullConfiguration(url); checkJAXPAvailability(); return XmlConfigurator.getInstance(url); }
java
public static ProtocolStackConfigurator getStackConfigurator(Element element) throws Exception { checkForNullConfiguration(element); return XmlConfigurator.getInstance(element); }
java
public static ProtocolStackConfigurator getStackConfigurator(String properties) throws Exception { if(properties == null) properties=Global.DEFAULT_PROTOCOL_STACK; // Attempt to treat the properties string as a pointer to an XML configuration. XmlConfigurator configurator = null; ...
java
public static InputStream getConfigStream(String properties) throws IOException { InputStream configStream = null; // Check to see if the properties string is the name of a file. try { configStream=new FileInputStream(properties); } catch(FileNotFoundException | Acce...
java
static void checkJAXPAvailability() { try { XmlConfigurator.class.getName(); } catch (NoClassDefFoundError error) { Error tmp=new NoClassDefFoundError(JAXP_MISSING_ERROR_MSG); tmp.initCause(error); throw tmp; } }
java
public T getValue(Object key) { Rsp<T> rsp=get(key); return rsp != null? rsp.getValue() : null; }
java
public T getFirst() { Optional<Rsp<T>> retval=values().stream().filter(rsp -> rsp.getValue() != null).findFirst(); return retval.isPresent()? retval.get().getValue() : null; }
java
public List<T> getResults() { return values().stream().filter(rsp -> rsp.wasReceived() && rsp.getValue() != null) .collect(() -> new ArrayList<>(size()), (list,rsp) -> list.add(rsp.getValue()), (l,r) -> {}); }
java
public void renameThread(String base_name, Thread thread, String addr, String cluster_name) { String thread_name=getThreadName(base_name, thread, addr, cluster_name); if(thread_name != null) thread.setName(thread_name); }
java
public RingBuffer<T> put(T element) throws InterruptedException { if(element == null) return this; lock.lock(); try { while(count == buf.length) not_full.await(); buf[wi]=element; if(++wi == buf.length) wi=0; ...
java
public int drainTo(T[] c) { int num=Math.min(count, c.length); // count may increase in the mean time, but that's ok if(num == 0) return num; int read_index=ri; // no lock as we're the only reader for(int i=0; i < num; i++) { int real_index=realIndex(read_index +i...
java
public int waitForMessages(int num_spins, final BiConsumer<Integer,Integer> wait_strategy) throws InterruptedException { // try spinning first (experimental) for(int i=0; i < num_spins && count == 0; i++) { if(wait_strategy != null) wait_strategy.accept(i, num_spins); ...
java
public ByteBuffer readLengthAndData(SocketChannel ch) throws Exception { if(bufs[0].hasRemaining() && ch.read(bufs[0]) < 0) throw new EOFException(); if(bufs[0].hasRemaining()) return null; int len=bufs[0].getInt(0); if(bufs[1] == null || len > bufs[1].capacity(...
java
public Buffers copy() { for(int i=Math.max(position, next_to_copy); i < limit; i++) { this.bufs[i]=copyBuffer(this.bufs[i]); next_to_copy=(short)(i+1); } return this; }
java
public static ByteBuffer copyBuffer(final ByteBuffer buf) { if(buf == null) return null; int offset=buf.hasArray()? buf.arrayOffset() + buf.position() : buf.position(), len=buf.remaining(); byte[] tmp=new byte[len]; if(!buf.isDirect()) System.arraycopy(buf.array()...
java
@GuardedBy("lock") protected void sendBundledMessages() { for(Map.Entry<Address,List<Message>> entry: msgs.entrySet()) { List<Message> list=entry.getValue(); if(list.isEmpty()) continue; output.position(0); if(list.size() == 1) sen...
java
@ManagedOperation public V get(K key) { // 1. Try the L1 cache first if(l1_cache != null) { V val=l1_cache.get(key); if(val != null) { if(log.isTraceEnabled()) log.trace("returned value " + val + " for " + key + " from L1 cache"); ...
java
@ManagedOperation public void remove(K key, boolean synchronous) { try { disp.callRemoteMethods(null, new MethodCall(REMOVE, key), new RequestOptions(synchronous? ResponseMode.GET_ALL : ResponseMode.GET_NONE, call_timeout)); if(l1_cache != null) ...
java
@ManagedOperation public void clear() { Set<K> keys=new HashSet<>(l2_cache.getInternalMap().keySet()); mcastClear(keys, false); }
java
protected boolean installViewIfValidJoinRsp(final Promise<JoinRsp> join_promise, boolean block_for_rsp) { boolean success=false; JoinRsp rsp=null; try { if(join_promise.hasResult()) rsp=join_promise.getResult(1, true); else if(block_for_rsp) ...
java
private static List<Address> getCoords(Iterable<PingData> mbrs) { if(mbrs == null) return null; List<Address> coords=null; for(PingData mbr: mbrs) { if(mbr.isCoord()) { if(coords == null) coords=new ArrayList<>(); if(!c...
java
public static Protocol createProtocol(String prot_spec, ProtocolStack stack) throws Exception { ProtocolConfiguration config; Protocol prot; if(prot_spec == null) throw new Exception("Configurator.createProtocol(): prot_spec is null"); // parse the configuration for this protocol ...
java
public static Protocol connectProtocols(List<Protocol> protocol_list) throws Exception { Protocol current_layer=null, next_layer=null; for(int i=0; i < protocol_list.size(); i++) { current_layer=protocol_list.get(i); if(i + 1 >= protocol_list.size()) break; ...
java
public static List<Protocol> createProtocols(List<ProtocolConfiguration> protocol_configs, final ProtocolStack stack) throws Exception { List<Protocol> retval=new LinkedList<>(); for(int i=0; i < protocol_configs.size(); i++) { ProtocolConfiguration protocol_config=protocol_configs.get(i); ...
java
public static void sanityCheck(List<Protocol> protocols) throws Exception { // check for unique IDs Set<Short> ids=new HashSet<>(); for(Protocol protocol: protocols) { short id=protocol.getId(); if(id > 0 && !ids.add(id)) throw new Exception("Protocol ID ...
java
protected static void removeProvidedUpServices(Protocol protocol, List<Integer> events) { if(protocol == null || events == null) return; for(Protocol prot=protocol.getDownProtocol(); prot != null && !events.isEmpty(); prot=prot.getDownProtocol()) { List<Integer> provided_up_servi...
java
protected static void removeProvidedDownServices(Protocol protocol, List<Integer> events) { if(protocol == null || events == null) return; for(Protocol prot=protocol.getUpProtocol(); prot != null && !events.isEmpty(); prot=prot.getUpProtocol()) { List<Integer> provided_down_servi...
java
public static Collection<InetAddress> getAddresses(Map<String, Map<String, InetAddressInfo>> inetAddressMap) throws Exception { Set<InetAddress> addrs=new HashSet<>(); for(Map.Entry<String, Map<String, InetAddressInfo>> inetAddressMapEntry : inetAddressMap.entrySet()) { Map<String, InetAddr...
java
public static void ensureValidBindAddresses(List<Protocol> protocols) throws Exception { for(Protocol protocol : protocols) { String protocolName=protocol.getName(); //traverse class hierarchy and find all annotated fields and add them to the list if annotated Field[] fields...
java
static void addPropertyToDependencyList(List<AccessibleObject> orderedList, Map<String, AccessibleObject> props, Stack<AccessibleObject> stack, AccessibleObject obj) { if (orderedList.contains(obj)) return ; if (stack.search(obj) > 0) { throw new RuntimeException("Deadlock in @Property ...
java
public int length() { if(keys == null) return 0; int retval=0; for(byte[] key: keys) if(key != null) retval++; return retval; }
java
protected void resize(int new_length) { if(keys == null) { keys=new byte[Math.min(new_length, 0xff)][]; values=new byte[Math.min(new_length, 0xff)][]; return; } if(new_length > 0xff) { if(keys.length < 0xff) new_length=0xff; ...
java
public static Map<String,List<ProtocolConfiguration>> parse(InputStream input) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); // for now DocumentBuilder builder=factory.newDocumentBuilder(); Document document=builde...
java
public static void writeInt(int num, ByteBuffer buf) { if(num == 0) { buf.put((byte)0); return; } final byte bytes_needed=bytesRequiredFor(num); buf.put(bytes_needed); for(int i=0; i < bytes_needed; i++) buf.put(getByteAt(num, i)); }
java
public static void writeInt(int num, DataOutput out) throws IOException { if(num == 0) { out.write(0); return; } final byte bytes_needed=bytesRequiredFor(num); out.write(bytes_needed); for(int i=0; i < bytes_needed; i++) out.write(getByteAt(num...
java
public static int readInt(ByteBuffer buf) { byte len=buf.get(); if(len == 0) return 0; return makeInt(buf, len); }
java
public static int readInt(DataInput in) throws IOException { byte len=in.readByte(); if(len == 0) return 0; return makeInt(in, len); }
java
public static long readLong(ByteBuffer buf) { byte len=buf.get(); if(len == 0) return 0; return makeLong(buf, len); }
java
public static void writeFloat(float num, DataOutput out) throws IOException { writeInt(Float.floatToIntBits(num), out); }
java
public static void writeDouble(double num, DataOutput out) throws IOException { writeLong(Double.doubleToLongBits(num), out); }
java
public static int size(AsciiString str) { return str == null? Global.SHORT_SIZE : Global.SHORT_SIZE + str.length(); }
java
protected void removeAndDispatchNonBundledMessages(MessageBatch oob_batch) { if(oob_batch == null) return; AsciiString tmp=oob_batch.clusterName(); byte[] cname=tmp != null? tmp.chars() : null; for(Iterator<Message> it=oob_batch.iterator(); it.hasNext();) { Messag...
java
public void waitFor(Condition condition) { boolean intr=false; lock.lock(); try { while(!condition.isMet()) { try { cond.await(); } catch(InterruptedException e) { intr=true; } ...
java
public boolean waitFor(Condition condition, long timeout, TimeUnit unit) { boolean intr=false; final long timeout_ns=TimeUnit.NANOSECONDS.convert(timeout, unit); lock.lock(); try { for(long wait_time=timeout_ns, start=System.nanoTime(); wait_time > 0 && !condition.isMet();...
java
void deliverSingleDestinationMessage(Message msg, MessageID messageID) { synchronized (deliverySet) { long sequenceNumber = sequenceNumberManager.get(); MessageInfo messageInfo = new MessageInfo(messageID, msg, sequenceNumber); messageInfo.updateAndMarkReadyToDeliver(sequence...
java
@Override public List<Message> getNextMessagesToDeliver() throws InterruptedException { LinkedList<Message> toDeliver = new LinkedList<>(); synchronized (deliverySet) { while (deliverySet.isEmpty() || !deliverySet.first().isReadyToDeliver()) { deliverySet.wait(); ...
java
public boolean containsMember(Address mbr) { if(mbr == null || members == null) return false; for(Address member: members) if(Objects.equals(member, mbr)) return true; return false; }
java
public boolean containsMembers(Address ... mbrs) { if(mbrs == null || members == null) return false; for(Address mbr: mbrs) { if(!containsMember(mbr)) return false; } return true; }
java
public static List<Address> leftMembers(View one, View two) { if(one == null || two == null) return null; List<Address> retval=new ArrayList<>(one.getMembers()); retval.removeAll(two.getMembers()); return retval; }
java
public static Address[][] diff(final View from, final View to) { if(to == null) throw new IllegalArgumentException("the second view cannot be null"); if(from == to) return new Address[][]{{},{}}; if(from == null) { Address[] joined=new Address[to.size()]; ...
java
public static boolean sameViews(View ... views) { ViewId first_view_id=views[0].getViewId(); return Stream.of(views).allMatch(v -> v.getViewId().equals(first_view_id)); }
java
public byte[] getBuffer() { if(buf == null) return null; if(offset == 0 && length == buf.length) return buf; else { byte[] retval=new byte[length]; System.arraycopy(buf, offset, retval, 0, length); return retval; } }
java
public Message setFlag(Flag ... flags) { if(flags != null) { short tmp=this.flags; for(Flag flag : flags) { if(flag != null) tmp|=flag.value(); } this.flags=tmp; } return this; }
java
public Message clearFlag(Flag ... flags) { if(flags != null) { short tmp=this.flags; for(Flag flag : flags) if(flag != null) tmp&=~flag.value(); this.flags=tmp; } return this; }
java
public Message putHeader(short id, Header hdr) { if(id < 0) throw new IllegalArgumentException("An ID of " + id + " is invalid"); if(hdr != null) hdr.setProtId(id); synchronized(this) { Header[] resized_array=Headers.putHeader(this.headers, id, hdr, true); ...
java
public <T extends Header> T getHeader(short ... ids) { if(ids == null || ids.length == 0) return null; return Headers.getHeader(this.headers, ids); }
java
public Message copy(boolean copy_buffer, short starting_id, short ... copy_only_ids) { Message retval=copy(copy_buffer, false); for(Map.Entry<Short,Header> entry: getHeaders().entrySet()) { short id=entry.getKey(); if(id >= starting_id || Util.containsId(id, copy_only_ids)) ...
java
@Override public void writeTo(DataOutput out) throws IOException { byte leading=0; if(dest != null) leading=Util.setFlag(leading, DEST_SET); if(sender != null) leading=Util.setFlag(leading, SRC_SET); if(buf != null) leading=Util.setFlag(leading, BUF...
java
public void writeToNoAddrs(Address src, DataOutput out, short ... excluded_headers) throws IOException { byte leading=0; boolean write_src_addr=src == null || sender != null && !sender.equals(src); if(write_src_addr) leading=Util.setFlag(leading, SRC_SET); if(buf != null) ...
java
@Override public void readFrom(DataInput in) throws IOException, ClassNotFoundException { // 1. read the leading byte first byte leading=in.readByte(); // 2. the flags flags=in.readShort(); // 3. dest_addr if(Util.isFlagSet(leading, DEST_SET)) dest=Util.read...
java
public void forEach(Consumer<RouterStub> action) { stubs.stream().filter(RouterStub::isConnected).forEach(action::accept); }
java
public void forAny(Consumer<RouterStub> action) { while(!stubs.isEmpty()) { RouterStub stub=Util.pickRandomElement(stubs); if(stub != null && stub.isConnected()) { action.accept(stub); return; } } }
java
public Element<T> get() { // start at a random index, so different threads don't all start at index 0 and compete for the lock int starting_index=((int)(Math.random() * pool.length)) & (pool.length - 1); for(int i=0; i < locks.length; i++) { int index=(starting_index + i) & (pool.len...
java
protected static String toLowerCase(String input) { if(Character.isUpperCase(input.charAt(0))) return input.substring(0, 1).toLowerCase() + input.substring(1); return input; }
java