proj_name
stringclasses
131 values
relative_path
stringlengths
30
228
class_name
stringlengths
1
68
func_name
stringlengths
1
48
masked_class
stringlengths
78
9.82k
func_body
stringlengths
46
9.61k
len_input
int64
29
2.01k
len_output
int64
14
1.94k
total
int64
55
2.05k
relevant_context
stringlengths
0
38.4k
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/socket/Stream.java
Outpipe
xhasIn
class Outpipe { private final Pipe pipe; private boolean active; public Outpipe(Pipe pipe, boolean active) { this.pipe = pipe; this.active = active; } } // Outbound pipes indexed by the peer IDs. private final Map<Blob, Outpipe> outpipes = new HashMap<>(); // The pipe we are currently writing to. private Pipe currentOut; // If true, more outgoing message parts are expected. private boolean moreOut; // Routing IDs are generated. It's a simple increment and wrap-over // algorithm. This value is the next ID to use (if not used already). private int nextRid; public Stream(Ctx parent, int tid, int sid) { super(parent, tid, sid); prefetched = false; identitySent = false; currentOut = null; moreOut = false; nextRid = Utils.randomInt(); options.type = ZMQ.ZMQ_STREAM; options.rawSocket = true; fq = new FQ(); prefetchedId = new Msg(); prefetchedMsg = new Msg(); } @Override protected void xattachPipe(Pipe pipe, boolean icanhasall, boolean isLocallyInitiated) { assert (pipe != null); identifyPeer(pipe, isLocallyInitiated); fq.attach(pipe); } @Override protected void xpipeTerminated(Pipe pipe) { Outpipe outpipe = outpipes.remove(pipe.getIdentity()); assert (outpipe != null); fq.terminated(pipe); if (pipe == currentOut) { currentOut = null; } } @Override protected void xreadActivated(Pipe pipe) { fq.activated(pipe); } @Override protected void xwriteActivated(Pipe pipe) { Outpipe out = null; for (Outpipe outpipe : outpipes.values()) { if (outpipe.pipe == pipe) { out = outpipe; break; } } assert (out != null); assert (!out.active); out.active = true; } @Override protected boolean xsend(Msg msg) { // If this is the first part of the message it's the ID of the // peer to send the message to. if (!moreOut) { assert (currentOut == null); // If we have malformed message (prefix with no subsequent message) // then just silently ignore it. // TODO: The connections should be killed instead. if (msg.hasMore()) { moreOut = true; // Find the pipe associated with the identity stored in the prefix. // If there's no such pipe return an error Blob identity = Blob.createBlob(msg); Outpipe op = outpipes.get(identity); if (op != null) { currentOut = op.pipe; if (!currentOut.checkWrite()) { op.active = false; currentOut = null; errno.set(ZError.EAGAIN); return false; } } else { errno.set(ZError.EHOSTUNREACH); return false; } } // Expect one more message frame. moreOut = true; return true; } // Ignore the MORE flag msg.resetFlags(Msg.MORE); // This is the last part of the message. moreOut = false; // Push the message into the pipe. If there's no out pipe, just drop it. if (currentOut != null) { // Close the remote connection if user has asked to do so // by sending zero length message. // Pending messages in the pipe will be dropped (on receiving term- ack) if (msg.size() == 0) { currentOut.terminate(false); currentOut = null; return true; } boolean ok = currentOut.write(msg); if (ok) { currentOut.flush(); } currentOut = null; } return true; } @Override protected boolean xsetsockopt(int option, Object optval) { switch (option) { case ZMQ.ZMQ_CONNECT_RID: connectRid = (String) optval; return true; default: errno.set(ZError.EINVAL); return false; } } @Override public Msg xrecv() { Msg msg; if (prefetched) { if (!identitySent) { msg = prefetchedId; prefetchedId = null; identitySent = true; } else { msg = prefetchedMsg; prefetchedMsg = null; prefetched = false; } return msg; } ValueReference<Pipe> pipe = new ValueReference<>(); prefetchedMsg = fq.recvPipe(errno, pipe); // TODO DIFF V4 we sometimes need to process the commands to receive data, let's just return and give it another chance if (prefetchedMsg == null) { errno.set(ZError.EAGAIN); return null; } assert (pipe.get() != null); assert (!prefetchedMsg.hasMore()); // We have received a frame with TCP data. // Rather than sending this frame, we keep it in prefetched // buffer and send a frame with peer's ID. Blob identity = pipe.get().getIdentity(); msg = new Msg(identity.data()); // forward metadata (if any) Metadata metadata = prefetchedMsg.getMetadata(); if (metadata != null) { msg.setMetadata(metadata); } msg.setFlags(Msg.MORE); prefetched = true; identitySent = true; return msg; } @Override protected boolean xhasIn() {<FILL_FUNCTION_BODY>
// We may already have a message pre-fetched. if (prefetched) { return true; } // Try to read the next message. // The message, if read, is kept in the pre-fetch buffer. ValueReference<Pipe> pipe = new ValueReference<>(); prefetchedMsg = fq.recvPipe(errno, pipe); if (prefetchedMsg == null) { return false; } assert (pipe.get() != null); assert (!prefetchedMsg.hasMore()); Blob identity = pipe.get().getIdentity(); prefetchedId = new Msg(identity.data()); // forward metadata (if any) Metadata metadata = prefetchedMsg.getMetadata(); if (metadata != null) { prefetchedId.setMetadata(metadata); } prefetchedId.setFlags(Msg.MORE); prefetched = true; identitySent = false; return true;
1,652
264
1,916
<methods>public final boolean bind(java.lang.String) ,public final void cancel(java.util.concurrent.atomic.AtomicBoolean) ,public final void close() ,public final boolean connect(java.lang.String) ,public final int connectPeer(java.lang.String) ,public boolean disconnectPeer(int) ,public final int errno() ,public final void eventAcceptFailed(java.lang.String, int) ,public final void eventAccepted(java.lang.String, java.nio.channels.SelectableChannel) ,public final void eventBindFailed(java.lang.String, int) ,public final void eventCloseFailed(java.lang.String, int) ,public final void eventClosed(java.lang.String, java.nio.channels.SelectableChannel) ,public final void eventConnectDelayed(java.lang.String, int) ,public final void eventConnectRetried(java.lang.String, int) ,public final void eventConnected(java.lang.String, java.nio.channels.SelectableChannel) ,public final void eventDisconnected(java.lang.String, java.nio.channels.SelectableChannel) ,public final void eventHandshakeFailedAuth(java.lang.String, int) ,public final void eventHandshakeFailedNoDetail(java.lang.String, int) ,public final void eventHandshakeFailedProtocol(java.lang.String, int) ,public final void eventHandshakeSucceeded(java.lang.String, int) ,public final void eventHandshaken(java.lang.String, int) ,public final void eventListening(java.lang.String, java.nio.channels.SelectableChannel) ,public final java.nio.channels.SelectableChannel getFD() ,public final int getSocketOpt(int) ,public final java.lang.Object getSocketOptx(int) ,public final void hiccuped(zmq.pipe.Pipe) ,public final void inEvent() ,public final boolean join(java.lang.String) ,public final boolean leave(java.lang.String) ,public final boolean monitor(java.lang.String, int) ,public final void pipeTerminated(zmq.pipe.Pipe) ,public final int poll(int, int, java.util.concurrent.atomic.AtomicBoolean) ,public final void readActivated(zmq.pipe.Pipe) ,public final zmq.Msg recv(int) ,public final zmq.Msg recv(int, java.util.concurrent.atomic.AtomicBoolean) ,public final boolean send(zmq.Msg, int) ,public final boolean send(zmq.Msg, int, java.util.concurrent.atomic.AtomicBoolean) ,public final boolean setEventHook(zmq.ZMQ.EventConsummer, int) ,public final boolean setSocketOpt(int, java.lang.Object) ,public final boolean termEndpoint(java.lang.String) ,public java.lang.String toString() ,public java.lang.String typeString() ,public final void writeActivated(zmq.pipe.Pipe) <variables>private boolean active,protected java.lang.String connectRid,private final non-sealed java.util.concurrent.atomic.AtomicBoolean ctxTerminated,private final non-sealed java.util.concurrent.atomic.AtomicBoolean destroyed,private final non-sealed MultiMap<java.lang.String,zmq.SocketBase.EndpointPipe> endpoints,private java.nio.channels.SocketChannel fileDesc,private zmq.poll.Poller.Handle handle,private final non-sealed MultiMap<java.lang.String,zmq.pipe.Pipe> inprocs,private final non-sealed ThreadLocal<java.lang.Boolean> isInEventThreadLocal,private long lastTsc,private final non-sealed zmq.IMailbox mailbox,private final non-sealed AtomicReference<zmq.ZMQ.EventConsummer> monitor,private int monitorEvents,private final non-sealed Set<zmq.pipe.Pipe> pipes,private zmq.poll.Poller poller,private boolean rcvmore,private final non-sealed boolean threadSafe,private final non-sealed java.util.concurrent.locks.ReentrantLock threadSafeSync,private int ticks
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/socket/clientserver/Client.java
Client
xsend
class Client extends SocketBase { // Messages are fair-queued from inbound pipes. And load-balanced to // the outbound pipes. private final FQ fq; private final LB lb; // Holds the prefetched message. public Client(Ctx parent, int tid, int sid) { super(parent, tid, sid, true); options.type = ZMQ.ZMQ_CLIENT; options.canSendHelloMsg = true; options.canReceiveHiccupMsg = true; fq = new FQ(); lb = new LB(); } @Override protected void xattachPipe(Pipe pipe, boolean subscribe2all, boolean isLocallyInitiated) { assert (pipe != null); fq.attach(pipe); lb.attach(pipe); } @Override protected boolean xsend(Msg msg) {<FILL_FUNCTION_BODY>} @Override protected Msg xrecv() { Msg msg = fq.recvPipe(errno, null); // Drop any messages with more flag while (msg != null && msg.hasMore()) { // drop all frames of the current multi-frame message msg = fq.recvPipe(errno, null); while (msg != null && msg.hasMore()) { fq.recvPipe(errno, null); } // get the new message if (msg != null) { fq.recvPipe(errno, null); } } return msg; } @Override protected boolean xhasIn() { return fq.hasIn(); } @Override protected boolean xhasOut() { return lb.hasOut(); } @Override protected Blob getCredential() { return fq.getCredential(); } @Override protected void xreadActivated(Pipe pipe) { fq.activated(pipe); } @Override protected void xwriteActivated(Pipe pipe) { lb.activated(pipe); } @Override protected void xpipeTerminated(Pipe pipe) { fq.terminated(pipe); lb.terminated(pipe); } }
// CLIENT sockets do not allow multipart data (ZMQ_SNDMORE) if (msg.hasMore()) { errno.set(ZError.EINVAL); return false; } return lb.sendpipe(msg, errno, null);
640
75
715
<methods>public final boolean bind(java.lang.String) ,public final void cancel(java.util.concurrent.atomic.AtomicBoolean) ,public final void close() ,public final boolean connect(java.lang.String) ,public final int connectPeer(java.lang.String) ,public boolean disconnectPeer(int) ,public final int errno() ,public final void eventAcceptFailed(java.lang.String, int) ,public final void eventAccepted(java.lang.String, java.nio.channels.SelectableChannel) ,public final void eventBindFailed(java.lang.String, int) ,public final void eventCloseFailed(java.lang.String, int) ,public final void eventClosed(java.lang.String, java.nio.channels.SelectableChannel) ,public final void eventConnectDelayed(java.lang.String, int) ,public final void eventConnectRetried(java.lang.String, int) ,public final void eventConnected(java.lang.String, java.nio.channels.SelectableChannel) ,public final void eventDisconnected(java.lang.String, java.nio.channels.SelectableChannel) ,public final void eventHandshakeFailedAuth(java.lang.String, int) ,public final void eventHandshakeFailedNoDetail(java.lang.String, int) ,public final void eventHandshakeFailedProtocol(java.lang.String, int) ,public final void eventHandshakeSucceeded(java.lang.String, int) ,public final void eventHandshaken(java.lang.String, int) ,public final void eventListening(java.lang.String, java.nio.channels.SelectableChannel) ,public final java.nio.channels.SelectableChannel getFD() ,public final int getSocketOpt(int) ,public final java.lang.Object getSocketOptx(int) ,public final void hiccuped(zmq.pipe.Pipe) ,public final void inEvent() ,public final boolean join(java.lang.String) ,public final boolean leave(java.lang.String) ,public final boolean monitor(java.lang.String, int) ,public final void pipeTerminated(zmq.pipe.Pipe) ,public final int poll(int, int, java.util.concurrent.atomic.AtomicBoolean) ,public final void readActivated(zmq.pipe.Pipe) ,public final zmq.Msg recv(int) ,public final zmq.Msg recv(int, java.util.concurrent.atomic.AtomicBoolean) ,public final boolean send(zmq.Msg, int) ,public final boolean send(zmq.Msg, int, java.util.concurrent.atomic.AtomicBoolean) ,public final boolean setEventHook(zmq.ZMQ.EventConsummer, int) ,public final boolean setSocketOpt(int, java.lang.Object) ,public final boolean termEndpoint(java.lang.String) ,public java.lang.String toString() ,public java.lang.String typeString() ,public final void writeActivated(zmq.pipe.Pipe) <variables>private boolean active,protected java.lang.String connectRid,private final non-sealed java.util.concurrent.atomic.AtomicBoolean ctxTerminated,private final non-sealed java.util.concurrent.atomic.AtomicBoolean destroyed,private final non-sealed MultiMap<java.lang.String,zmq.SocketBase.EndpointPipe> endpoints,private java.nio.channels.SocketChannel fileDesc,private zmq.poll.Poller.Handle handle,private final non-sealed MultiMap<java.lang.String,zmq.pipe.Pipe> inprocs,private final non-sealed ThreadLocal<java.lang.Boolean> isInEventThreadLocal,private long lastTsc,private final non-sealed zmq.IMailbox mailbox,private final non-sealed AtomicReference<zmq.ZMQ.EventConsummer> monitor,private int monitorEvents,private final non-sealed Set<zmq.pipe.Pipe> pipes,private zmq.poll.Poller poller,private boolean rcvmore,private final non-sealed boolean threadSafe,private final non-sealed java.util.concurrent.locks.ReentrantLock threadSafeSync,private int ticks
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/socket/clientserver/Server.java
Outpipe
xsend
class Outpipe { private final Pipe pipe; private boolean active; public Outpipe(Pipe pipe, boolean active) { this.pipe = pipe; this.active = active; } } // Outbound pipes indexed by the peer IDs. private final Map<Integer, Outpipe> outpipes; // Routing IDs are generated. It's a simple increment and wrap-over // algorithm. This value is the next ID to use (if not used already). private int nextRid; public Server(Ctx parent, int tid, int sid) { super(parent, tid, sid, true); nextRid = Utils.randomInt(); options.type = ZMQ.ZMQ_SERVER; options.canSendHelloMsg = true; options.canReceiveDisconnectMsg = true; fq = new FQ(); outpipes = new HashMap<>(); } @Override protected void destroy() { assert (outpipes.isEmpty()); super.destroy(); } @Override public void xattachPipe(Pipe pipe, boolean subscribe2all, boolean isLocallyInitiated) { assert (pipe != null); int routingId = nextRid++; if (routingId == 0) { routingId = nextRid++; // Never use Routing ID zero } pipe.setRoutingId(routingId); // Add the record into output pipes lookup table Outpipe outpipe = new Outpipe(pipe, true); Outpipe prev = outpipes.put(routingId, outpipe); assert (prev == null); fq.attach(pipe); } @Override public void xpipeTerminated(Pipe pipe) { Outpipe old = outpipes.remove(pipe.getRoutingId()); assert (old != null); fq.terminated(pipe); } @Override public void xreadActivated(Pipe pipe) { fq.activated(pipe); } @Override public void xwriteActivated(Pipe pipe) { Outpipe out = outpipes.get(pipe.getRoutingId()); assert (out != null); assert (!out.active); out.active = true; } @Override protected boolean xsend(Msg msg) {<FILL_FUNCTION_BODY>
// SERVER sockets do not allow multipart data (ZMQ_SNDMORE) if (msg.hasMore()) { errno.set(ZError.EINVAL); return false; } // Find the pipe associated with the routing stored in the message. int routingId = msg.getRoutingId(); Outpipe out = outpipes.get(routingId); if (out != null) { if (!out.pipe.checkWrite()) { out.active = false; errno.set(ZError.EAGAIN); return false; } } else { errno.set(ZError.EHOSTUNREACH); return false; } // Message might be delivered over inproc, so we reset routing id msg.resetRoutingId(); boolean ok = out.pipe.write(msg); if (ok) { out.pipe.flush(); } return true;
650
255
905
<methods>public final boolean bind(java.lang.String) ,public final void cancel(java.util.concurrent.atomic.AtomicBoolean) ,public final void close() ,public final boolean connect(java.lang.String) ,public final int connectPeer(java.lang.String) ,public boolean disconnectPeer(int) ,public final int errno() ,public final void eventAcceptFailed(java.lang.String, int) ,public final void eventAccepted(java.lang.String, java.nio.channels.SelectableChannel) ,public final void eventBindFailed(java.lang.String, int) ,public final void eventCloseFailed(java.lang.String, int) ,public final void eventClosed(java.lang.String, java.nio.channels.SelectableChannel) ,public final void eventConnectDelayed(java.lang.String, int) ,public final void eventConnectRetried(java.lang.String, int) ,public final void eventConnected(java.lang.String, java.nio.channels.SelectableChannel) ,public final void eventDisconnected(java.lang.String, java.nio.channels.SelectableChannel) ,public final void eventHandshakeFailedAuth(java.lang.String, int) ,public final void eventHandshakeFailedNoDetail(java.lang.String, int) ,public final void eventHandshakeFailedProtocol(java.lang.String, int) ,public final void eventHandshakeSucceeded(java.lang.String, int) ,public final void eventHandshaken(java.lang.String, int) ,public final void eventListening(java.lang.String, java.nio.channels.SelectableChannel) ,public final java.nio.channels.SelectableChannel getFD() ,public final int getSocketOpt(int) ,public final java.lang.Object getSocketOptx(int) ,public final void hiccuped(zmq.pipe.Pipe) ,public final void inEvent() ,public final boolean join(java.lang.String) ,public final boolean leave(java.lang.String) ,public final boolean monitor(java.lang.String, int) ,public final void pipeTerminated(zmq.pipe.Pipe) ,public final int poll(int, int, java.util.concurrent.atomic.AtomicBoolean) ,public final void readActivated(zmq.pipe.Pipe) ,public final zmq.Msg recv(int) ,public final zmq.Msg recv(int, java.util.concurrent.atomic.AtomicBoolean) ,public final boolean send(zmq.Msg, int) ,public final boolean send(zmq.Msg, int, java.util.concurrent.atomic.AtomicBoolean) ,public final boolean setEventHook(zmq.ZMQ.EventConsummer, int) ,public final boolean setSocketOpt(int, java.lang.Object) ,public final boolean termEndpoint(java.lang.String) ,public java.lang.String toString() ,public java.lang.String typeString() ,public final void writeActivated(zmq.pipe.Pipe) <variables>private boolean active,protected java.lang.String connectRid,private final non-sealed java.util.concurrent.atomic.AtomicBoolean ctxTerminated,private final non-sealed java.util.concurrent.atomic.AtomicBoolean destroyed,private final non-sealed MultiMap<java.lang.String,zmq.SocketBase.EndpointPipe> endpoints,private java.nio.channels.SocketChannel fileDesc,private zmq.poll.Poller.Handle handle,private final non-sealed MultiMap<java.lang.String,zmq.pipe.Pipe> inprocs,private final non-sealed ThreadLocal<java.lang.Boolean> isInEventThreadLocal,private long lastTsc,private final non-sealed zmq.IMailbox mailbox,private final non-sealed AtomicReference<zmq.ZMQ.EventConsummer> monitor,private int monitorEvents,private final non-sealed Set<zmq.pipe.Pipe> pipes,private zmq.poll.Poller poller,private boolean rcvmore,private final non-sealed boolean threadSafe,private final non-sealed java.util.concurrent.locks.ReentrantLock threadSafeSync,private int ticks
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/socket/pipeline/Push.java
Push
xattachPipe
class Push extends SocketBase { // Load balancer managing the outbound pipes. private final LB lb; public Push(Ctx parent, int tid, int sid) { super(parent, tid, sid); options.type = ZMQ.ZMQ_PUSH; lb = new LB(); } @Override protected void xattachPipe(Pipe pipe, boolean subscribe2all, boolean isLocallyInitiated) {<FILL_FUNCTION_BODY>} @Override protected void xwriteActivated(Pipe pipe) { lb.activated(pipe); } @Override protected void xpipeTerminated(Pipe pipe) { lb.terminated(pipe); } @Override public boolean xsend(Msg msg) { return lb.sendpipe(msg, errno, null); } @Override protected boolean xhasOut() { return lb.hasOut(); } }
assert (pipe != null); // Don't delay pipe termination as there is no one // to receive the delimiter. pipe.setNoDelay(); lb.attach(pipe);
278
58
336
<methods>public final boolean bind(java.lang.String) ,public final void cancel(java.util.concurrent.atomic.AtomicBoolean) ,public final void close() ,public final boolean connect(java.lang.String) ,public final int connectPeer(java.lang.String) ,public boolean disconnectPeer(int) ,public final int errno() ,public final void eventAcceptFailed(java.lang.String, int) ,public final void eventAccepted(java.lang.String, java.nio.channels.SelectableChannel) ,public final void eventBindFailed(java.lang.String, int) ,public final void eventCloseFailed(java.lang.String, int) ,public final void eventClosed(java.lang.String, java.nio.channels.SelectableChannel) ,public final void eventConnectDelayed(java.lang.String, int) ,public final void eventConnectRetried(java.lang.String, int) ,public final void eventConnected(java.lang.String, java.nio.channels.SelectableChannel) ,public final void eventDisconnected(java.lang.String, java.nio.channels.SelectableChannel) ,public final void eventHandshakeFailedAuth(java.lang.String, int) ,public final void eventHandshakeFailedNoDetail(java.lang.String, int) ,public final void eventHandshakeFailedProtocol(java.lang.String, int) ,public final void eventHandshakeSucceeded(java.lang.String, int) ,public final void eventHandshaken(java.lang.String, int) ,public final void eventListening(java.lang.String, java.nio.channels.SelectableChannel) ,public final java.nio.channels.SelectableChannel getFD() ,public final int getSocketOpt(int) ,public final java.lang.Object getSocketOptx(int) ,public final void hiccuped(zmq.pipe.Pipe) ,public final void inEvent() ,public final boolean join(java.lang.String) ,public final boolean leave(java.lang.String) ,public final boolean monitor(java.lang.String, int) ,public final void pipeTerminated(zmq.pipe.Pipe) ,public final int poll(int, int, java.util.concurrent.atomic.AtomicBoolean) ,public final void readActivated(zmq.pipe.Pipe) ,public final zmq.Msg recv(int) ,public final zmq.Msg recv(int, java.util.concurrent.atomic.AtomicBoolean) ,public final boolean send(zmq.Msg, int) ,public final boolean send(zmq.Msg, int, java.util.concurrent.atomic.AtomicBoolean) ,public final boolean setEventHook(zmq.ZMQ.EventConsummer, int) ,public final boolean setSocketOpt(int, java.lang.Object) ,public final boolean termEndpoint(java.lang.String) ,public java.lang.String toString() ,public java.lang.String typeString() ,public final void writeActivated(zmq.pipe.Pipe) <variables>private boolean active,protected java.lang.String connectRid,private final non-sealed java.util.concurrent.atomic.AtomicBoolean ctxTerminated,private final non-sealed java.util.concurrent.atomic.AtomicBoolean destroyed,private final non-sealed MultiMap<java.lang.String,zmq.SocketBase.EndpointPipe> endpoints,private java.nio.channels.SocketChannel fileDesc,private zmq.poll.Poller.Handle handle,private final non-sealed MultiMap<java.lang.String,zmq.pipe.Pipe> inprocs,private final non-sealed ThreadLocal<java.lang.Boolean> isInEventThreadLocal,private long lastTsc,private final non-sealed zmq.IMailbox mailbox,private final non-sealed AtomicReference<zmq.ZMQ.EventConsummer> monitor,private int monitorEvents,private final non-sealed Set<zmq.pipe.Pipe> pipes,private zmq.poll.Poller poller,private boolean rcvmore,private final non-sealed boolean threadSafe,private final non-sealed java.util.concurrent.locks.ReentrantLock threadSafeSync,private int ticks
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/socket/pubsub/Dist.java
Dist
match
class Dist { // List of outbound pipes. private final List<Pipe> pipes; // Number of all the pipes to send the next message to. private int matching; // Number of active pipes. All the active pipes are located at the // beginning of the pipes array. These are the pipes the messages // can be sent to at the moment. private int active; // Number of pipes eligible for sending messages to. This includes all // the active pipes plus all the pipes that we can in theory send // messages to (the HWM is not yet reached), but sending a message // to them would result in partial message being delivered, ie. message // with initial parts missing. private int eligible; // True if last we are in the middle of a multipart message. private boolean more; public Dist() { matching = 0; active = 0; eligible = 0; more = false; pipes = new ArrayList<>(); } // Adds the pipe to the distributor object. public void attach(Pipe pipe) { // If we are in the middle of sending a message, we'll add new pipe // into the list of eligible pipes. Otherwise we add it to the list // of active pipes. if (more) { pipes.add(pipe); Collections.swap(pipes, eligible, pipes.size() - 1); } else { pipes.add(pipe); Collections.swap(pipes, active, pipes.size() - 1); active++; } eligible++; } // Mark the pipe as matching. Subsequent call to sendToMatching // will send message also to this pipe. public void match(Pipe pipe) {<FILL_FUNCTION_BODY>} // Mark all pipes as non-matching. public void unmatch() { matching = 0; } // Removes the pipe from the distributor object. public void terminated(Pipe pipe) { // Remove the pipe from the list; adjust number of matching, active and/or // eligible pipes accordingly. if (pipes.indexOf(pipe) < matching) { Collections.swap(pipes, pipes.indexOf(pipe), matching - 1); matching--; } if (pipes.indexOf(pipe) < active) { Collections.swap(pipes, pipes.indexOf(pipe), active - 1); active--; } if (pipes.indexOf(pipe) < eligible) { Collections.swap(pipes, pipes.indexOf(pipe), eligible - 1); eligible--; } pipes.remove(pipe); } // Activates pipe that have previously reached high watermark. public void activated(Pipe pipe) { // Move the pipe from passive to eligible state. if (eligible < pipes.size()) { Collections.swap(pipes, pipes.indexOf(pipe), eligible); eligible++; } // If there's no message being sent at the moment, move it to // the active state. if (!more && active < pipes.size()) { Collections.swap(pipes, eligible - 1, active); active++; } } // Send the message to all the outbound pipes. public boolean sendToAll(Msg msg) { matching = active; return sendToMatching(msg); } // Send the message to the matching outbound pipes. public boolean sendToMatching(Msg msg) { // Is this end of a multipart message? boolean msgMore = msg.hasMore(); // Push the message to matching pipes. distribute(msg); // If multipart message is fully sent, activate all the eligible pipes. if (!msgMore) { active = eligible; } more = msgMore; return true; } // Put the message to all active pipes. private void distribute(Msg msg) { // If there are no matching pipes available, simply drop the message. if (matching == 0) { return; } // TODO isVsm // Push copy of the message to each matching pipe. for (int idx = 0; idx < matching; ++idx) { if (!write(pipes.get(idx), msg)) { --idx; // Retry last write because index will have been swapped } } } public boolean hasOut() { return true; } // Write the message to the pipe. Make the pipe inactive if writing // fails. In such a case false is returned. private boolean write(Pipe pipe, Msg msg) { if (!pipe.write(msg)) { Collections.swap(pipes, pipes.indexOf(pipe), matching - 1); matching--; Collections.swap(pipes, pipes.indexOf(pipe), active - 1); active--; Collections.swap(pipes, active, eligible - 1); eligible--; return false; } if (!msg.hasMore()) { pipe.flush(); } return true; } public boolean checkHwm() { for (int idx = 0; idx < matching; ++idx) { if (!pipes.get(idx).checkHwm()) { return false; } } return true; } int active() { return active; } int eligible() { return eligible; } int matching() { return matching; } }
int idx = pipes.indexOf(pipe); // If pipe is already matching do nothing. if (idx < matching) { return; } // If the pipe isn't eligible, ignore it. if (idx >= eligible) { return; } // Mark the pipe as matching. Collections.swap(pipes, idx, matching); matching++;
1,481
104
1,585
<no_super_class>
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/socket/pubsub/Pub.java
Pub
xattachPipe
class Pub extends XPub { public Pub(Ctx parent, int tid, int sid) { super(parent, tid, sid); options.type = ZMQ.ZMQ_PUB; } @Override protected void xattachPipe(Pipe pipe, boolean subscribeToAll, boolean isLocallyInitiated) {<FILL_FUNCTION_BODY>} @Override protected Msg xrecv() { errno.set(ZError.ENOTSUP); // Messages cannot be received from PUB socket. throw new UnsupportedOperationException(); } @Override protected boolean xhasIn() { return false; } }
assert (pipe != null); // Don't delay pipe termination as there is no one // to receive the delimiter. pipe.setNoDelay(); super.xattachPipe(pipe, subscribeToAll, isLocallyInitiated);
189
70
259
<methods>public void <init>(zmq.Ctx, int, int) ,public boolean xsetsockopt(int, java.lang.Object) <variables>private final non-sealed zmq.socket.pubsub.Dist dist,private zmq.pipe.Pipe lastPipe,private boolean lossy,private boolean manual,private final non-sealed zmq.socket.pubsub.Mtrie manualSubscriptions,private static final zmq.socket.pubsub.Mtrie.IMtrieHandler markAsMatching,private boolean more,private final non-sealed Deque<zmq.util.Blob> pendingData,private final non-sealed Deque<java.lang.Integer> pendingFlags,private final non-sealed Deque<zmq.pipe.Pipe> pendingPipes,private static final zmq.socket.pubsub.Mtrie.IMtrieHandler sendUnsubscription,private final non-sealed zmq.socket.pubsub.Mtrie subscriptions,private boolean verboseSubs,private boolean verboseUnsubs
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/socket/pubsub/Sub.java
Sub
xsetsockopt
class Sub extends XSub { public Sub(Ctx parent, int tid, int sid) { super(parent, tid, sid); options.type = ZMQ.ZMQ_SUB; // Switch filtering messages on (as opposed to XSUB which where the // filtering is off). options.filter = true; } @Override public boolean xsetsockopt(int option, Object optval) {<FILL_FUNCTION_BODY>} @Override protected boolean xsend(Msg msg) { errno.set(ZError.ENOTSUP); // Overload the XSUB's send. throw new UnsupportedOperationException(); } @Override protected boolean xhasOut() { // Overload the XSUB's send. return false; } }
if (option != ZMQ.ZMQ_SUBSCRIBE && option != ZMQ.ZMQ_UNSUBSCRIBE) { errno.set(ZError.EINVAL); return false; } if (optval == null) { errno.set(ZError.EINVAL); return false; } byte[] val = Options.parseBytes(option, optval); // Create the subscription message. Msg msg = new Msg(val.length + 1); if (option == ZMQ.ZMQ_SUBSCRIBE) { msg.put((byte) 1); } else { // option = ZMQ.ZMQ_UNSUBSCRIBE msg.put((byte) 0); } msg.put(val); // Pass it further on in the stack. boolean rc = super.xsend(msg); if (!rc) { errno.set(ZError.EINVAL); throw new IllegalStateException("Failed to send subscribe/unsubscribe message"); } return true;
227
289
516
<methods>public void <init>(zmq.Ctx, int, int) <variables>private final non-sealed zmq.socket.pubsub.Dist dist,private final non-sealed zmq.socket.FQ fq,private boolean hasMessage,private zmq.Msg message,private boolean more,private final zmq.socket.pubsub.Trie.ITrieHandler sendSubscription,private final non-sealed zmq.socket.pubsub.Trie subscriptions
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/socket/pubsub/XPub.java
MarkAsMatching
xreadActivated
class MarkAsMatching implements IMtrieHandler { @Override public void invoke(Pipe pipe, byte[] data, int size, XPub self) { self.markAsMatching(pipe); } } // List of all subscriptions mapped to corresponding pipes. private final Mtrie subscriptions; // List of manual subscriptions mapped to corresponding pipes. private final Mtrie manualSubscriptions; // Distributor of messages holding the list of outbound pipes. private final Dist dist; // If true, send all subscription messages upstream, not just // unique ones private boolean verboseSubs; // If true, send all unsubscription messages upstream, not just // unique ones private boolean verboseUnsubs; // True if we are in the middle of sending a multi-part message. private boolean more; // Drop messages if HWM reached, otherwise return with false private boolean lossy; // Subscriptions will not bed added automatically, only after calling set option with ZMQ_SUBSCRIBE or ZMQ_UNSUBSCRIBE private boolean manual; // Last pipe that sent subscription message, only used if xpub is on manual private Pipe lastPipe; // Pipes that sent subscriptions messages that have not yet been processed, only used if xpub is on manual private final Deque<Pipe> pendingPipes; // List of pending (un)subscriptions, ie. those that were already // applied to the trie, but not yet received by the user. private final Deque<Blob> pendingData; private final Deque<Integer> pendingFlags; private static final IMtrieHandler markAsMatching = new MarkAsMatching(); private static final IMtrieHandler sendUnsubscription = new SendUnsubscription(); public XPub(Ctx parent, int tid, int sid) { super(parent, tid, sid); options.type = ZMQ.ZMQ_XPUB; verboseSubs = false; verboseUnsubs = false; more = false; lossy = true; manual = false; subscriptions = new Mtrie(); manualSubscriptions = new Mtrie(); dist = new Dist(); lastPipe = null; pendingPipes = new ArrayDeque<>(); pendingData = new ArrayDeque<>(); pendingFlags = new ArrayDeque<>(); } @Override protected void xattachPipe(Pipe pipe, boolean subscribeToAll, boolean isLocallyInitiated) { assert (pipe != null); dist.attach(pipe); // If subscribe_to_all_ is specified, the caller would like to subscribe // to all data on this pipe, implicitly. if (subscribeToAll) { subscriptions.addOnTop(pipe); } // The pipe is active when attached. Let's read the subscriptions from // it, if any. xreadActivated(pipe); } @Override protected void xreadActivated(Pipe pipe) {<FILL_FUNCTION_BODY>
// There are some subscriptions waiting. Let's process them. Msg sub; while ((sub = pipe.read()) != null) { // Apply the subscription to the trie boolean subscribe; int size = sub.size(); if (size > 0 && (sub.get(0) == 0 || sub.get(0) == 1)) { subscribe = sub.get(0) == 1; } else { // Process user message coming upstream from xsub socket pendingData.add(Blob.createBlob(sub)); pendingFlags.add(sub.flags()); continue; } if (manual) { // Store manual subscription to use on termination if (!subscribe) { manualSubscriptions.rm(sub, pipe); } else { manualSubscriptions.add(sub, pipe); } pendingPipes.add(pipe); // ZMTP 3.1 hack: we need to support sub/cancel commands, but // we can't give them back to userspace as it would be an API // breakage since the payload of the message is completely // different. Manually craft an old-style message instead. pendingData.add(Blob.createBlob(sub)); pendingFlags.add(0); } else { boolean notify; if (!subscribe) { notify = subscriptions.rm(sub, pipe) || verboseUnsubs; } else { notify = subscriptions.add(sub, pipe) || verboseSubs; } // If the request was a new subscription, or the subscription // was removed, or verbose mode is enabled, store it so that // it can be passed to the user on next recv call. if (options.type == ZMQ.ZMQ_XPUB && notify) { pendingData.add(Blob.createBlob(sub)); pendingFlags.add(0); } } }
821
508
1,329
<methods>public final boolean bind(java.lang.String) ,public final void cancel(java.util.concurrent.atomic.AtomicBoolean) ,public final void close() ,public final boolean connect(java.lang.String) ,public final int connectPeer(java.lang.String) ,public boolean disconnectPeer(int) ,public final int errno() ,public final void eventAcceptFailed(java.lang.String, int) ,public final void eventAccepted(java.lang.String, java.nio.channels.SelectableChannel) ,public final void eventBindFailed(java.lang.String, int) ,public final void eventCloseFailed(java.lang.String, int) ,public final void eventClosed(java.lang.String, java.nio.channels.SelectableChannel) ,public final void eventConnectDelayed(java.lang.String, int) ,public final void eventConnectRetried(java.lang.String, int) ,public final void eventConnected(java.lang.String, java.nio.channels.SelectableChannel) ,public final void eventDisconnected(java.lang.String, java.nio.channels.SelectableChannel) ,public final void eventHandshakeFailedAuth(java.lang.String, int) ,public final void eventHandshakeFailedNoDetail(java.lang.String, int) ,public final void eventHandshakeFailedProtocol(java.lang.String, int) ,public final void eventHandshakeSucceeded(java.lang.String, int) ,public final void eventHandshaken(java.lang.String, int) ,public final void eventListening(java.lang.String, java.nio.channels.SelectableChannel) ,public final java.nio.channels.SelectableChannel getFD() ,public final int getSocketOpt(int) ,public final java.lang.Object getSocketOptx(int) ,public final void hiccuped(zmq.pipe.Pipe) ,public final void inEvent() ,public final boolean join(java.lang.String) ,public final boolean leave(java.lang.String) ,public final boolean monitor(java.lang.String, int) ,public final void pipeTerminated(zmq.pipe.Pipe) ,public final int poll(int, int, java.util.concurrent.atomic.AtomicBoolean) ,public final void readActivated(zmq.pipe.Pipe) ,public final zmq.Msg recv(int) ,public final zmq.Msg recv(int, java.util.concurrent.atomic.AtomicBoolean) ,public final boolean send(zmq.Msg, int) ,public final boolean send(zmq.Msg, int, java.util.concurrent.atomic.AtomicBoolean) ,public final boolean setEventHook(zmq.ZMQ.EventConsummer, int) ,public final boolean setSocketOpt(int, java.lang.Object) ,public final boolean termEndpoint(java.lang.String) ,public java.lang.String toString() ,public java.lang.String typeString() ,public final void writeActivated(zmq.pipe.Pipe) <variables>private boolean active,protected java.lang.String connectRid,private final non-sealed java.util.concurrent.atomic.AtomicBoolean ctxTerminated,private final non-sealed java.util.concurrent.atomic.AtomicBoolean destroyed,private final non-sealed MultiMap<java.lang.String,zmq.SocketBase.EndpointPipe> endpoints,private java.nio.channels.SocketChannel fileDesc,private zmq.poll.Poller.Handle handle,private final non-sealed MultiMap<java.lang.String,zmq.pipe.Pipe> inprocs,private final non-sealed ThreadLocal<java.lang.Boolean> isInEventThreadLocal,private long lastTsc,private final non-sealed zmq.IMailbox mailbox,private final non-sealed AtomicReference<zmq.ZMQ.EventConsummer> monitor,private int monitorEvents,private final non-sealed Set<zmq.pipe.Pipe> pipes,private zmq.poll.Poller poller,private boolean rcvmore,private final non-sealed boolean threadSafe,private final non-sealed java.util.concurrent.locks.ReentrantLock threadSafeSync,private int ticks
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/socket/pubsub/XSub.java
SendSubscription
xhasIn
class SendSubscription implements ITrieHandler { @Override public void added(byte[] data, int size, Pipe pipe) { sendSubscription(data, size, pipe); } } // Fair queuing object for inbound pipes. private final FQ fq; // Object for distributing the subscriptions upstream. private final Dist dist; // The repository of subscriptions. private final Trie subscriptions; // If true, 'message' contains a matching message to return on the // next recv call. private boolean hasMessage; private Msg message; // If true, part of a multipart message was already received, but // there are following parts still waiting. private boolean more; private final ITrieHandler sendSubscription = new SendSubscription(); public XSub(Ctx parent, int tid, int sid) { super(parent, tid, sid); options.type = ZMQ.ZMQ_XSUB; hasMessage = false; more = false; // When socket is being closed down we don't want to wait till pending // subscription commands are sent to the wire. options.linger = 0; fq = new FQ(); dist = new Dist(); subscriptions = new Trie(); message = new Msg(); } @Override protected void xattachPipe(Pipe pipe, boolean subscribe2all, boolean isLocallyInitiated) { assert (pipe != null); fq.attach(pipe); dist.attach(pipe); // Send all the cached subscriptions to the new upstream peer. subscriptions.apply(sendSubscription, pipe); pipe.flush(); } @Override protected void xreadActivated(Pipe pipe) { fq.activated(pipe); } @Override protected void xwriteActivated(Pipe pipe) { dist.activated(pipe); } @Override protected void xpipeTerminated(Pipe pipe) { fq.terminated(pipe); dist.terminated(pipe); } @Override protected void xhiccuped(Pipe pipe) { // Send all the cached subscriptions to the hiccuped pipe. subscriptions.apply(sendSubscription, pipe); pipe.flush(); } @Override protected boolean xsend(Msg msg) { final int size = msg.size(); if (size > 0 && msg.get(0) == 1) { // Process subscribe message // This used to filter out duplicate subscriptions, // however this is already done on the XPUB side and // doing it here as well breaks ZMQ_XPUB_VERBOSE // when there are forwarding devices involved. subscriptions.add(msg, 1, size - 1); return dist.sendToAll(msg); } else if (size > 0 && msg.get(0) == 0) { // Process unsubscribe message if (subscriptions.rm(msg, 1, size - 1)) { return dist.sendToAll(msg); } } else { // User message sent upstream to XPUB socket return dist.sendToAll(msg); } return true; } @Override protected boolean xhasOut() { // Subscription can be added/removed anytime. return true; } @Override protected Msg xrecv() { Msg msg; // If there's already a message prepared by a previous call to zmq_poll, // return it straight ahead. if (hasMessage) { msg = message; hasMessage = false; more = msg.hasMore(); return msg; } // TODO: This can result in infinite loop in the case of continuous // stream of non-matching messages which breaks the non-blocking recv // semantics. while (true) { // Get a message using fair queuing algorithm. msg = fq.recv(errno); // If there's no message available, return immediately. // The same when error occurs. if (msg == null) { return null; } // Check whether the message matches at least one subscription. // Non-initial parts of the message are passed if (more || !options.filter || match(msg)) { more = msg.hasMore(); return msg; } // Message doesn't match. Pop any remaining parts of the message // from the pipe. while (msg.hasMore()) { msg = fq.recv(errno); assert (msg != null); } } } @Override protected boolean xhasIn() {<FILL_FUNCTION_BODY>
// There are subsequent parts of the partly-read message available. if (more) { return true; } // If there's already a message prepared by a previous call to zmq_poll, // return straight ahead. if (hasMessage) { return true; } // TODO: This can result in infinite loop in the case of continuous // stream of non-matching messages. while (true) { // Get a message using fair queuing algorithm. message = fq.recv(errno); // If there's no message available, return immediately. // The same when error occurs. if (message == null) { assert (errno.is(ZError.EAGAIN)); return false; } // Check whether the message matches at least one subscription. if (!options.filter || match(message)) { hasMessage = true; return true; } // Message doesn't match. Pop any remaining parts of the message // from the pipe. while (message.hasMore()) { message = fq.recv(errno); assert (message != null); } }
1,293
312
1,605
<methods>public final boolean bind(java.lang.String) ,public final void cancel(java.util.concurrent.atomic.AtomicBoolean) ,public final void close() ,public final boolean connect(java.lang.String) ,public final int connectPeer(java.lang.String) ,public boolean disconnectPeer(int) ,public final int errno() ,public final void eventAcceptFailed(java.lang.String, int) ,public final void eventAccepted(java.lang.String, java.nio.channels.SelectableChannel) ,public final void eventBindFailed(java.lang.String, int) ,public final void eventCloseFailed(java.lang.String, int) ,public final void eventClosed(java.lang.String, java.nio.channels.SelectableChannel) ,public final void eventConnectDelayed(java.lang.String, int) ,public final void eventConnectRetried(java.lang.String, int) ,public final void eventConnected(java.lang.String, java.nio.channels.SelectableChannel) ,public final void eventDisconnected(java.lang.String, java.nio.channels.SelectableChannel) ,public final void eventHandshakeFailedAuth(java.lang.String, int) ,public final void eventHandshakeFailedNoDetail(java.lang.String, int) ,public final void eventHandshakeFailedProtocol(java.lang.String, int) ,public final void eventHandshakeSucceeded(java.lang.String, int) ,public final void eventHandshaken(java.lang.String, int) ,public final void eventListening(java.lang.String, java.nio.channels.SelectableChannel) ,public final java.nio.channels.SelectableChannel getFD() ,public final int getSocketOpt(int) ,public final java.lang.Object getSocketOptx(int) ,public final void hiccuped(zmq.pipe.Pipe) ,public final void inEvent() ,public final boolean join(java.lang.String) ,public final boolean leave(java.lang.String) ,public final boolean monitor(java.lang.String, int) ,public final void pipeTerminated(zmq.pipe.Pipe) ,public final int poll(int, int, java.util.concurrent.atomic.AtomicBoolean) ,public final void readActivated(zmq.pipe.Pipe) ,public final zmq.Msg recv(int) ,public final zmq.Msg recv(int, java.util.concurrent.atomic.AtomicBoolean) ,public final boolean send(zmq.Msg, int) ,public final boolean send(zmq.Msg, int, java.util.concurrent.atomic.AtomicBoolean) ,public final boolean setEventHook(zmq.ZMQ.EventConsummer, int) ,public final boolean setSocketOpt(int, java.lang.Object) ,public final boolean termEndpoint(java.lang.String) ,public java.lang.String toString() ,public java.lang.String typeString() ,public final void writeActivated(zmq.pipe.Pipe) <variables>private boolean active,protected java.lang.String connectRid,private final non-sealed java.util.concurrent.atomic.AtomicBoolean ctxTerminated,private final non-sealed java.util.concurrent.atomic.AtomicBoolean destroyed,private final non-sealed MultiMap<java.lang.String,zmq.SocketBase.EndpointPipe> endpoints,private java.nio.channels.SocketChannel fileDesc,private zmq.poll.Poller.Handle handle,private final non-sealed MultiMap<java.lang.String,zmq.pipe.Pipe> inprocs,private final non-sealed ThreadLocal<java.lang.Boolean> isInEventThreadLocal,private long lastTsc,private final non-sealed zmq.IMailbox mailbox,private final non-sealed AtomicReference<zmq.ZMQ.EventConsummer> monitor,private int monitorEvents,private final non-sealed Set<zmq.pipe.Pipe> pipes,private zmq.poll.Poller poller,private boolean rcvmore,private final non-sealed boolean threadSafe,private final non-sealed java.util.concurrent.locks.ReentrantLock threadSafeSync,private int ticks
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/socket/radiodish/Dish.java
Dish
xxrecv
class Dish extends SocketBase { // Fair queueing object for inbound pipes. private final FQ fq; // Object for distributing the subscriptions upstream. private final Dist dist; // The repository of subscriptions. private final Set<String> subscriptions; // If true, 'message' contains a matching message to return on the // next recv call. private Msg pendingMsg; // Holds the prefetched message. public Dish(Ctx parent, int tid, int sid) { super(parent, tid, sid, true); options.type = ZMQ.ZMQ_DISH; // When socket is being closed down we don't want to wait till pending // subscription commands are sent to the wire. options.linger = 0; fq = new FQ(); dist = new Dist(); subscriptions = new HashSet<>(); } @Override protected void xattachPipe(Pipe pipe, boolean subscribe2all, boolean isLocallyInitiated) { assert (pipe != null); fq.attach(pipe); dist.attach(pipe); // Send all the cached subscriptions to the new upstream peer. sendSubscriptions(pipe); } @Override protected void xreadActivated(Pipe pipe) { fq.activated(pipe); } @Override protected void xwriteActivated(Pipe pipe) { dist.activated(pipe); } @Override protected void xpipeTerminated(Pipe pipe) { fq.terminated(pipe); dist.terminated(pipe); } @Override protected void xhiccuped(Pipe pipe) { // Send all the cached subscriptions to the hiccuped pipe. sendSubscriptions(pipe); } @Override protected boolean xjoin(String group) { if (group.length() > Msg.MAX_GROUP_LENGTH) { errno.set(ZError.EINVAL); return false; } // User cannot join same group twice if (!subscriptions.add(group)) { errno.set(ZError.EINVAL); return false; } Msg msg = new Msg(); msg.initJoin(); msg.setGroup(group); dist.sendToAll(msg); return true; } @Override protected boolean xleave(String group) { if (group.length() > Msg.MAX_GROUP_LENGTH) { errno.set(ZError.EINVAL); return false; } if (!subscriptions.remove(group)) { errno.set(ZError.EINVAL); return false; } Msg msg = new Msg(); msg.initLeave(); msg.setGroup(group); dist.sendToAll(msg); return true; } @Override protected boolean xsend(Msg msg) { errno.set(ZError.ENOTSUP); throw new UnsupportedOperationException(); } @Override protected Msg xrecv() { // If there's already a message prepared by a previous call to poll, // return it straight ahead. if (pendingMsg != null) { Msg msg = pendingMsg; pendingMsg = null; return msg; } return xxrecv(); } private Msg xxrecv() {<FILL_FUNCTION_BODY>} @Override protected boolean xhasIn() { // If there's already a message prepared by a previous call to zmq_poll, // return straight ahead. if (pendingMsg != null) { return true; } Msg msg = xxrecv(); if (msg == null) { return false; } // Matching message found pendingMsg = msg; return true; } @Override protected boolean xhasOut() { // Subscription can be added/removed anytime. return true; } private void sendSubscriptions(Pipe pipe) { for (String s : subscriptions) { Msg msg = new Msg(); msg.initJoin(); msg.setGroup(s); pipe.write(msg); } pipe.flush(); } public static class DishSession extends SessionBase { static final byte[] JOIN_BYTES = "\4JOIN".getBytes(StandardCharsets.US_ASCII); static final byte[] LEAVE_BYTES = "\5LEAVE".getBytes(StandardCharsets.US_ASCII); enum State { GROUP, BODY } private State state; private String group; public DishSession(IOThread ioThread, boolean connect, SocketBase socket, final Options options, final Address addr) { super(ioThread, connect, socket, options, addr); state = State.GROUP; group = ""; } @Override public boolean pushMsg(Msg msg) { switch (state) { case GROUP: if (!msg.hasMore()) { errno.set(ZError.EFAULT); return false; } if (msg.size() > Msg.MAX_GROUP_LENGTH) { errno.set(ZError.EFAULT); return false; } group = new String(msg.data(), StandardCharsets.US_ASCII); state = State.BODY; return true; case BODY: // Set the message group msg.setGroup(group); // Thread safe socket doesn't support multipart messages if (msg.hasMore()) { errno.set(ZError.EFAULT); return false; } // Push message to dish socket boolean rc = super.pushMsg(msg); if (rc) { state = State.GROUP; } return rc; default: throw new IllegalStateException(); } } @Override protected Msg pullMsg() { Msg msg = super.pullMsg(); if (msg == null) { return null; } if (!msg.isJoin() && !msg.isLeave()) { return msg; } Msg command; byte[] groupBytes = msg.getGroup().getBytes(StandardCharsets.US_ASCII); if (msg.isJoin()) { command = new Msg(groupBytes.length + 5); command.put(JOIN_BYTES); } else { command = new Msg(groupBytes.length + 6); command.put(LEAVE_BYTES); } command.setFlags(Msg.COMMAND); // Copy the group command.put(groupBytes); return command; } @Override protected void reset() { super.reset(); state = State.GROUP; } } }
// Get a message using fair queueing algorithm. Msg msg = fq.recv(errno); // If there's no message available, return immediately. // The same when error occurs. if (msg == null) { return null; } // Skip non matching messages while (!subscriptions.contains(msg.getGroup())) { msg = fq.recv(errno); if (msg == null) { return null; } } // Found a matching message return msg;
1,884
142
2,026
<methods>public final boolean bind(java.lang.String) ,public final void cancel(java.util.concurrent.atomic.AtomicBoolean) ,public final void close() ,public final boolean connect(java.lang.String) ,public final int connectPeer(java.lang.String) ,public boolean disconnectPeer(int) ,public final int errno() ,public final void eventAcceptFailed(java.lang.String, int) ,public final void eventAccepted(java.lang.String, java.nio.channels.SelectableChannel) ,public final void eventBindFailed(java.lang.String, int) ,public final void eventCloseFailed(java.lang.String, int) ,public final void eventClosed(java.lang.String, java.nio.channels.SelectableChannel) ,public final void eventConnectDelayed(java.lang.String, int) ,public final void eventConnectRetried(java.lang.String, int) ,public final void eventConnected(java.lang.String, java.nio.channels.SelectableChannel) ,public final void eventDisconnected(java.lang.String, java.nio.channels.SelectableChannel) ,public final void eventHandshakeFailedAuth(java.lang.String, int) ,public final void eventHandshakeFailedNoDetail(java.lang.String, int) ,public final void eventHandshakeFailedProtocol(java.lang.String, int) ,public final void eventHandshakeSucceeded(java.lang.String, int) ,public final void eventHandshaken(java.lang.String, int) ,public final void eventListening(java.lang.String, java.nio.channels.SelectableChannel) ,public final java.nio.channels.SelectableChannel getFD() ,public final int getSocketOpt(int) ,public final java.lang.Object getSocketOptx(int) ,public final void hiccuped(zmq.pipe.Pipe) ,public final void inEvent() ,public final boolean join(java.lang.String) ,public final boolean leave(java.lang.String) ,public final boolean monitor(java.lang.String, int) ,public final void pipeTerminated(zmq.pipe.Pipe) ,public final int poll(int, int, java.util.concurrent.atomic.AtomicBoolean) ,public final void readActivated(zmq.pipe.Pipe) ,public final zmq.Msg recv(int) ,public final zmq.Msg recv(int, java.util.concurrent.atomic.AtomicBoolean) ,public final boolean send(zmq.Msg, int) ,public final boolean send(zmq.Msg, int, java.util.concurrent.atomic.AtomicBoolean) ,public final boolean setEventHook(zmq.ZMQ.EventConsummer, int) ,public final boolean setSocketOpt(int, java.lang.Object) ,public final boolean termEndpoint(java.lang.String) ,public java.lang.String toString() ,public java.lang.String typeString() ,public final void writeActivated(zmq.pipe.Pipe) <variables>private boolean active,protected java.lang.String connectRid,private final non-sealed java.util.concurrent.atomic.AtomicBoolean ctxTerminated,private final non-sealed java.util.concurrent.atomic.AtomicBoolean destroyed,private final non-sealed MultiMap<java.lang.String,zmq.SocketBase.EndpointPipe> endpoints,private java.nio.channels.SocketChannel fileDesc,private zmq.poll.Poller.Handle handle,private final non-sealed MultiMap<java.lang.String,zmq.pipe.Pipe> inprocs,private final non-sealed ThreadLocal<java.lang.Boolean> isInEventThreadLocal,private long lastTsc,private final non-sealed zmq.IMailbox mailbox,private final non-sealed AtomicReference<zmq.ZMQ.EventConsummer> monitor,private int monitorEvents,private final non-sealed Set<zmq.pipe.Pipe> pipes,private zmq.poll.Poller poller,private boolean rcvmore,private final non-sealed boolean threadSafe,private final non-sealed java.util.concurrent.locks.ReentrantLock threadSafeSync,private int ticks
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/socket/radiodish/Radio.java
RadioSession
pullMsg
class RadioSession extends SessionBase { enum State { GROUP, BODY } private State state; private Msg pending; public RadioSession(IOThread ioThread, boolean connect, SocketBase socket, final Options options, final Address addr) { super(ioThread, connect, socket, options, addr); state = State.GROUP; } @Override public boolean pushMsg(Msg msg) { if (msg.isCommand()) { byte commandNameSize = msg.get(0); if (msg.size() < commandNameSize + 1) { return super.pushMsg(msg); } byte[] data = msg.data(); String commandName = new String(data, 1, commandNameSize, StandardCharsets.US_ASCII); int groupLength; String group; Msg joinLeaveMsg = new Msg(); // Set the msg type to either JOIN or LEAVE if (commandName.equals("JOIN")) { groupLength = msg.size() - 5; group = new String(data, 5, groupLength, StandardCharsets.US_ASCII); joinLeaveMsg.initJoin(); } else if (commandName.equals("LEAVE")) { groupLength = msg.size() - 6; group = new String(data, 6, groupLength, StandardCharsets.US_ASCII); joinLeaveMsg.initLeave(); } // If it is not a JOIN or LEAVE just push the message else { return super.pushMsg(msg); } // Set the group joinLeaveMsg.setGroup(group); // Push the join or leave command msg = joinLeaveMsg; return super.pushMsg(msg); } return super.pushMsg(msg); } @Override protected Msg pullMsg() {<FILL_FUNCTION_BODY>} @Override protected void reset() { super.reset(); state = State.GROUP; } }
Msg msg; switch (state) { case GROUP: pending = super.pullMsg(); if (pending == null) { return null; } // First frame is the group msg = new Msg(pending.getGroup().getBytes(StandardCharsets.US_ASCII)); msg.setFlags(Msg.MORE); // Next status is the body state = State.BODY; break; case BODY: msg = pending; state = State.GROUP; break; default: throw new IllegalStateException(); } return msg;
546
166
712
<methods>public final boolean bind(java.lang.String) ,public final void cancel(java.util.concurrent.atomic.AtomicBoolean) ,public final void close() ,public final boolean connect(java.lang.String) ,public final int connectPeer(java.lang.String) ,public boolean disconnectPeer(int) ,public final int errno() ,public final void eventAcceptFailed(java.lang.String, int) ,public final void eventAccepted(java.lang.String, java.nio.channels.SelectableChannel) ,public final void eventBindFailed(java.lang.String, int) ,public final void eventCloseFailed(java.lang.String, int) ,public final void eventClosed(java.lang.String, java.nio.channels.SelectableChannel) ,public final void eventConnectDelayed(java.lang.String, int) ,public final void eventConnectRetried(java.lang.String, int) ,public final void eventConnected(java.lang.String, java.nio.channels.SelectableChannel) ,public final void eventDisconnected(java.lang.String, java.nio.channels.SelectableChannel) ,public final void eventHandshakeFailedAuth(java.lang.String, int) ,public final void eventHandshakeFailedNoDetail(java.lang.String, int) ,public final void eventHandshakeFailedProtocol(java.lang.String, int) ,public final void eventHandshakeSucceeded(java.lang.String, int) ,public final void eventHandshaken(java.lang.String, int) ,public final void eventListening(java.lang.String, java.nio.channels.SelectableChannel) ,public final java.nio.channels.SelectableChannel getFD() ,public final int getSocketOpt(int) ,public final java.lang.Object getSocketOptx(int) ,public final void hiccuped(zmq.pipe.Pipe) ,public final void inEvent() ,public final boolean join(java.lang.String) ,public final boolean leave(java.lang.String) ,public final boolean monitor(java.lang.String, int) ,public final void pipeTerminated(zmq.pipe.Pipe) ,public final int poll(int, int, java.util.concurrent.atomic.AtomicBoolean) ,public final void readActivated(zmq.pipe.Pipe) ,public final zmq.Msg recv(int) ,public final zmq.Msg recv(int, java.util.concurrent.atomic.AtomicBoolean) ,public final boolean send(zmq.Msg, int) ,public final boolean send(zmq.Msg, int, java.util.concurrent.atomic.AtomicBoolean) ,public final boolean setEventHook(zmq.ZMQ.EventConsummer, int) ,public final boolean setSocketOpt(int, java.lang.Object) ,public final boolean termEndpoint(java.lang.String) ,public java.lang.String toString() ,public java.lang.String typeString() ,public final void writeActivated(zmq.pipe.Pipe) <variables>private boolean active,protected java.lang.String connectRid,private final non-sealed java.util.concurrent.atomic.AtomicBoolean ctxTerminated,private final non-sealed java.util.concurrent.atomic.AtomicBoolean destroyed,private final non-sealed MultiMap<java.lang.String,zmq.SocketBase.EndpointPipe> endpoints,private java.nio.channels.SocketChannel fileDesc,private zmq.poll.Poller.Handle handle,private final non-sealed MultiMap<java.lang.String,zmq.pipe.Pipe> inprocs,private final non-sealed ThreadLocal<java.lang.Boolean> isInEventThreadLocal,private long lastTsc,private final non-sealed zmq.IMailbox mailbox,private final non-sealed AtomicReference<zmq.ZMQ.EventConsummer> monitor,private int monitorEvents,private final non-sealed Set<zmq.pipe.Pipe> pipes,private zmq.poll.Poller poller,private boolean rcvmore,private final non-sealed boolean threadSafe,private final non-sealed java.util.concurrent.locks.ReentrantLock threadSafeSync,private int ticks
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/socket/reqrep/Dealer.java
Dealer
xattachPipe
class Dealer extends SocketBase { // Messages are fair-queued from inbound pipes. And load-balanced to // the outbound pipes. private final FQ fq; private final LB lb; // if true, send an empty message to every connected router peer private boolean probeRouter; // Holds the prefetched message. public Dealer(Ctx parent, int tid, int sid) { super(parent, tid, sid); options.type = ZMQ.ZMQ_DEALER; options.canSendHelloMsg = true; options.canReceiveHiccupMsg = true; fq = new FQ(); lb = new LB(); } @Override protected void xattachPipe(Pipe pipe, boolean subscribe2all, boolean isLocallyInitiated) {<FILL_FUNCTION_BODY>} @Override protected boolean xsetsockopt(int option, Object optval) { if (option == ZMQ.ZMQ_PROBE_ROUTER) { probeRouter = Options.parseBoolean(option, optval); return true; } errno.set(ZError.EINVAL); return false; } @Override protected boolean xsend(Msg msg) { return sendpipe(msg, null); } @Override protected Msg xrecv() { return recvpipe(null); } @Override protected boolean xhasIn() { return fq.hasIn(); } @Override protected boolean xhasOut() { return lb.hasOut(); } @Override protected Blob getCredential() { return fq.getCredential(); } @Override protected void xreadActivated(Pipe pipe) { fq.activated(pipe); } @Override protected void xwriteActivated(Pipe pipe) { lb.activated(pipe); } @Override protected void xpipeTerminated(Pipe pipe) { fq.terminated(pipe); lb.terminated(pipe); } protected final boolean sendpipe(Msg msg, ValueReference<Pipe> pipe) { return lb.sendpipe(msg, errno, pipe); } protected final Msg recvpipe(ValueReference<Pipe> pipe) { return fq.recvPipe(errno, pipe); } }
assert (pipe != null); if (probeRouter) { Msg probe = new Msg(); pipe.write(probe); // assert (rc == 0) is not applicable here, since it is not a bug. pipe.flush(); } fq.attach(pipe); lb.attach(pipe);
676
90
766
<methods>public final boolean bind(java.lang.String) ,public final void cancel(java.util.concurrent.atomic.AtomicBoolean) ,public final void close() ,public final boolean connect(java.lang.String) ,public final int connectPeer(java.lang.String) ,public boolean disconnectPeer(int) ,public final int errno() ,public final void eventAcceptFailed(java.lang.String, int) ,public final void eventAccepted(java.lang.String, java.nio.channels.SelectableChannel) ,public final void eventBindFailed(java.lang.String, int) ,public final void eventCloseFailed(java.lang.String, int) ,public final void eventClosed(java.lang.String, java.nio.channels.SelectableChannel) ,public final void eventConnectDelayed(java.lang.String, int) ,public final void eventConnectRetried(java.lang.String, int) ,public final void eventConnected(java.lang.String, java.nio.channels.SelectableChannel) ,public final void eventDisconnected(java.lang.String, java.nio.channels.SelectableChannel) ,public final void eventHandshakeFailedAuth(java.lang.String, int) ,public final void eventHandshakeFailedNoDetail(java.lang.String, int) ,public final void eventHandshakeFailedProtocol(java.lang.String, int) ,public final void eventHandshakeSucceeded(java.lang.String, int) ,public final void eventHandshaken(java.lang.String, int) ,public final void eventListening(java.lang.String, java.nio.channels.SelectableChannel) ,public final java.nio.channels.SelectableChannel getFD() ,public final int getSocketOpt(int) ,public final java.lang.Object getSocketOptx(int) ,public final void hiccuped(zmq.pipe.Pipe) ,public final void inEvent() ,public final boolean join(java.lang.String) ,public final boolean leave(java.lang.String) ,public final boolean monitor(java.lang.String, int) ,public final void pipeTerminated(zmq.pipe.Pipe) ,public final int poll(int, int, java.util.concurrent.atomic.AtomicBoolean) ,public final void readActivated(zmq.pipe.Pipe) ,public final zmq.Msg recv(int) ,public final zmq.Msg recv(int, java.util.concurrent.atomic.AtomicBoolean) ,public final boolean send(zmq.Msg, int) ,public final boolean send(zmq.Msg, int, java.util.concurrent.atomic.AtomicBoolean) ,public final boolean setEventHook(zmq.ZMQ.EventConsummer, int) ,public final boolean setSocketOpt(int, java.lang.Object) ,public final boolean termEndpoint(java.lang.String) ,public java.lang.String toString() ,public java.lang.String typeString() ,public final void writeActivated(zmq.pipe.Pipe) <variables>private boolean active,protected java.lang.String connectRid,private final non-sealed java.util.concurrent.atomic.AtomicBoolean ctxTerminated,private final non-sealed java.util.concurrent.atomic.AtomicBoolean destroyed,private final non-sealed MultiMap<java.lang.String,zmq.SocketBase.EndpointPipe> endpoints,private java.nio.channels.SocketChannel fileDesc,private zmq.poll.Poller.Handle handle,private final non-sealed MultiMap<java.lang.String,zmq.pipe.Pipe> inprocs,private final non-sealed ThreadLocal<java.lang.Boolean> isInEventThreadLocal,private long lastTsc,private final non-sealed zmq.IMailbox mailbox,private final non-sealed AtomicReference<zmq.ZMQ.EventConsummer> monitor,private int monitorEvents,private final non-sealed Set<zmq.pipe.Pipe> pipes,private zmq.poll.Poller poller,private boolean rcvmore,private final non-sealed boolean threadSafe,private final non-sealed java.util.concurrent.locks.ReentrantLock threadSafeSync,private int ticks
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/socket/reqrep/Rep.java
Rep
xrecv
class Rep extends Router { // If true, we are in process of sending the reply. If false we are // in process of receiving a request. private boolean sendingReply; // If true, we are starting to receive a request. The beginning // of the request is the backtrace stack. private boolean requestBegins; public Rep(Ctx parent, int tid, int sid) { super(parent, tid, sid); sendingReply = false; requestBegins = true; options.type = ZMQ.ZMQ_REP; options.canSendHelloMsg = false; } @Override protected boolean xsend(Msg msg) { // If we are in the middle of receiving a request, we cannot send reply. if (!sendingReply) { errno.set(ZError.EFSM); return false; } boolean more = msg.hasMore(); // Push message to the reply pipe. boolean rc = super.xsend(msg); if (!rc) { return false; } // If the reply is complete flip the FSM back to request receiving state. if (!more) { sendingReply = false; } return true; } @Override protected Msg xrecv() {<FILL_FUNCTION_BODY>} @Override protected boolean xhasIn() { return !sendingReply && super.xhasIn(); } @Override protected boolean xhasOut() { return sendingReply && super.xhasOut(); } }
// If we are in middle of sending a reply, we cannot receive next request. if (sendingReply) { errno.set(ZError.EFSM); } Msg msg; // First thing to do when receiving a request is to copy all the labels // to the reply pipe. if (requestBegins) { while (true) { msg = super.xrecv(); if (msg == null) { return null; } if (msg.hasMore()) { // Empty message part delimits the traceback stack. boolean bottom = (msg.size() == 0); // Push it to the reply pipe. boolean rc = super.xsend(msg); assert (rc); if (bottom) { break; } } else { // If the traceback stack is malformed, discard anything // already sent to pipe (we're at end of invalid message). super.rollback(); } } requestBegins = false; } // Get next message part to return to the user. msg = super.xrecv(); if (msg == null) { return null; } // If whole request is read, flip the FSM to reply-sending state. if (!msg.hasMore()) { sendingReply = true; requestBegins = true; } return msg;
433
376
809
<methods>public void <init>(zmq.Ctx, int, int) ,public void xattachPipe(zmq.pipe.Pipe, boolean, boolean) ,public void xpipeTerminated(zmq.pipe.Pipe) ,public void xreadActivated(zmq.pipe.Pipe) ,public boolean xsetsockopt(int, java.lang.Object) ,public void xwriteActivated(zmq.pipe.Pipe) <variables>private final non-sealed Set<zmq.pipe.Pipe> anonymousPipes,private zmq.pipe.Pipe currentOut,private final non-sealed zmq.socket.FQ fq,private boolean handover,private boolean identitySent,private boolean mandatory,private boolean moreIn,private boolean moreOut,private int nextRid,private final non-sealed Map<zmq.util.Blob,zmq.socket.reqrep.Router.Outpipe> outpipes,private boolean prefetched,private zmq.Msg prefetchedId,private zmq.Msg prefetchedMsg,private boolean probeRouter,private boolean rawSocket
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/socket/reqrep/Req.java
ReqSession
pushMsg
class ReqSession extends SessionBase { enum State { BOTTOM, REQUEST_ID, BODY } private State state; public ReqSession(IOThread ioThread, boolean connect, SocketBase socket, final Options options, final Address addr) { super(ioThread, connect, socket, options, addr); state = State.BOTTOM; } @Override public boolean pushMsg(Msg msg) {<FILL_FUNCTION_BODY>} @Override public void reset() { super.reset(); state = State.BOTTOM; } }
// Ignore commands, they are processed by the engine and should not // affect the state machine. if (msg.isCommand()) { return true; } switch (state) { case BOTTOM: if (msg.hasMore()) { // In case option ZMQ_CORRELATE is on, allow request_id to be // transfered as first frame (would be too cumbersome to check // whether the option is actually on or not). if (msg.size() == 4) { state = State.REQUEST_ID; return super.pushMsg(msg); } else if (msg.size() == 0) { state = State.BODY; return super.pushMsg(msg); } } break; case REQUEST_ID: if (msg.hasMore() && msg.size() == 0) { state = State.BODY; return super.pushMsg(msg); } break; case BODY: if (msg.hasMore()) { return super.pushMsg(msg); } if (msg.flags() == 0) { state = State.BOTTOM; return super.pushMsg(msg); } break; default: break; } errno.set(ZError.EFAULT); return false;
175
357
532
<methods>public void <init>(zmq.Ctx, int, int) <variables>private final non-sealed zmq.socket.FQ fq,private final non-sealed zmq.socket.LB lb,private boolean probeRouter
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/socket/reqrep/Router.java
Outpipe
xsend
class Outpipe { private final Pipe pipe; private boolean active; public Outpipe(Pipe pipe, boolean active) { this.pipe = pipe; this.active = active; } } // We keep a set of pipes that have not been identified yet. private final Set<Pipe> anonymousPipes; // Outbound pipes indexed by the peer IDs. private final Map<Blob, Outpipe> outpipes; // The pipe we are currently writing to. private Pipe currentOut; // If true, more outgoing message parts are expected. private boolean moreOut; // Routing IDs are generated. It's a simple increment and wrap-over // algorithm. This value is the next ID to use (if not used already). private int nextRid; // If true, report EAGAIN to the caller instead of silently dropping // the message targeting an unknown peer. private boolean mandatory; private boolean rawSocket; // if true, send an empty message to every connected router peer private boolean probeRouter; // If true, the router will reassign an identity upon encountering a // name collision. The new pipe will take the identity, the old pipe // will be terminated. private boolean handover; public Router(Ctx parent, int tid, int sid) { super(parent, tid, sid); prefetched = false; identitySent = false; moreIn = false; currentOut = null; moreOut = false; nextRid = Utils.randomInt(); mandatory = false; // raw_sock functionality in ROUTER is deprecated rawSocket = false; handover = false; options.type = ZMQ.ZMQ_ROUTER; options.recvIdentity = true; options.rawSocket = false; options.canSendHelloMsg = true; options.canReceiveDisconnectMsg = true; fq = new FQ(); prefetchedId = new Msg(); prefetchedMsg = new Msg(); anonymousPipes = new HashSet<>(); outpipes = new HashMap<>(); } @Override protected void destroy() { assert (anonymousPipes.isEmpty()); assert (outpipes.isEmpty()); super.destroy(); } @Override public void xattachPipe(Pipe pipe, boolean subscribe2all, boolean isLocallyInitiated) { assert (pipe != null); if (probeRouter) { Msg probe = new Msg(); pipe.write(probe); // assert (rc) is not applicable here, since it is not a bug. pipe.flush(); } boolean identityOk = identifyPeer(pipe, isLocallyInitiated); if (identityOk) { fq.attach(pipe); } else { anonymousPipes.add(pipe); } } @Override public boolean xsetsockopt(int option, Object optval) { if (option == ZMQ.ZMQ_CONNECT_RID) { connectRid = Options.parseString(option, optval); return true; } if (option == ZMQ.ZMQ_ROUTER_RAW) { rawSocket = Options.parseBoolean(option, optval); if (rawSocket) { options.recvIdentity = false; options.rawSocket = true; } return true; } if (option == ZMQ.ZMQ_ROUTER_MANDATORY) { mandatory = Options.parseBoolean(option, optval); return true; } if (option == ZMQ.ZMQ_PROBE_ROUTER) { probeRouter = Options.parseBoolean(option, optval); return true; } if (option == ZMQ.ZMQ_ROUTER_HANDOVER) { handover = Options.parseBoolean(option, optval); return true; } errno.set(ZError.EINVAL); return false; } @Override public void xpipeTerminated(Pipe pipe) { if (!anonymousPipes.remove(pipe)) { Outpipe old = outpipes.remove(pipe.getIdentity()); assert (old != null); fq.terminated(pipe); if (pipe == currentOut) { currentOut = null; } } } @Override public void xreadActivated(Pipe pipe) { if (!anonymousPipes.contains(pipe)) { fq.activated(pipe); } else { boolean identityOk = identifyPeer(pipe, false); if (identityOk) { anonymousPipes.remove(pipe); fq.attach(pipe); } } } @Override public void xwriteActivated(Pipe pipe) { for (Outpipe out : outpipes.values()) { if (out.pipe == pipe) { assert (!out.active); out.active = true; break; } } } @Override protected boolean xsend(Msg msg) {<FILL_FUNCTION_BODY>
// If this is the first part of the message it's the ID of the // peer to send the message to. if (!moreOut) { assert (currentOut == null); // If we have malformed message (prefix with no subsequent message) // then just silently ignore it. // TODO: The connections should be killed instead. if (msg.hasMore()) { moreOut = true; // Find the pipe associated with the identity stored in the prefix. // If there's no such pipe just silently ignore the message, unless // mandatory is set. Blob identity = Blob.createBlob(msg); Outpipe op = outpipes.get(identity); if (op != null) { currentOut = op.pipe; if (!currentOut.checkWrite()) { op.active = false; currentOut = null; if (mandatory) { moreOut = false; errno.set(ZError.EAGAIN); return false; } } } else if (mandatory) { moreOut = false; errno.set(ZError.EHOSTUNREACH); return false; } } return true; } // Ignore the MORE flag for raw-sock or assert? if (options.rawSocket) { msg.resetFlags(Msg.MORE); } // Check whether this is the last part of the message. moreOut = msg.hasMore(); // Push the message into the pipe. If there's no out pipe, just drop it. if (currentOut != null) { // Close the remote connection if user has asked to do so // by sending zero length message. // Pending messages in the pipe will be dropped (on receiving term- ack) if (rawSocket && msg.size() == 0) { currentOut.terminate(false); currentOut = null; return true; } boolean ok = currentOut.write(msg); if (!ok) { // Message failed to send - we must close it ourselves. currentOut = null; } else if (!moreOut) { currentOut.flush(); currentOut = null; } } return true;
1,390
593
1,983
<methods>public final boolean bind(java.lang.String) ,public final void cancel(java.util.concurrent.atomic.AtomicBoolean) ,public final void close() ,public final boolean connect(java.lang.String) ,public final int connectPeer(java.lang.String) ,public boolean disconnectPeer(int) ,public final int errno() ,public final void eventAcceptFailed(java.lang.String, int) ,public final void eventAccepted(java.lang.String, java.nio.channels.SelectableChannel) ,public final void eventBindFailed(java.lang.String, int) ,public final void eventCloseFailed(java.lang.String, int) ,public final void eventClosed(java.lang.String, java.nio.channels.SelectableChannel) ,public final void eventConnectDelayed(java.lang.String, int) ,public final void eventConnectRetried(java.lang.String, int) ,public final void eventConnected(java.lang.String, java.nio.channels.SelectableChannel) ,public final void eventDisconnected(java.lang.String, java.nio.channels.SelectableChannel) ,public final void eventHandshakeFailedAuth(java.lang.String, int) ,public final void eventHandshakeFailedNoDetail(java.lang.String, int) ,public final void eventHandshakeFailedProtocol(java.lang.String, int) ,public final void eventHandshakeSucceeded(java.lang.String, int) ,public final void eventHandshaken(java.lang.String, int) ,public final void eventListening(java.lang.String, java.nio.channels.SelectableChannel) ,public final java.nio.channels.SelectableChannel getFD() ,public final int getSocketOpt(int) ,public final java.lang.Object getSocketOptx(int) ,public final void hiccuped(zmq.pipe.Pipe) ,public final void inEvent() ,public final boolean join(java.lang.String) ,public final boolean leave(java.lang.String) ,public final boolean monitor(java.lang.String, int) ,public final void pipeTerminated(zmq.pipe.Pipe) ,public final int poll(int, int, java.util.concurrent.atomic.AtomicBoolean) ,public final void readActivated(zmq.pipe.Pipe) ,public final zmq.Msg recv(int) ,public final zmq.Msg recv(int, java.util.concurrent.atomic.AtomicBoolean) ,public final boolean send(zmq.Msg, int) ,public final boolean send(zmq.Msg, int, java.util.concurrent.atomic.AtomicBoolean) ,public final boolean setEventHook(zmq.ZMQ.EventConsummer, int) ,public final boolean setSocketOpt(int, java.lang.Object) ,public final boolean termEndpoint(java.lang.String) ,public java.lang.String toString() ,public java.lang.String typeString() ,public final void writeActivated(zmq.pipe.Pipe) <variables>private boolean active,protected java.lang.String connectRid,private final non-sealed java.util.concurrent.atomic.AtomicBoolean ctxTerminated,private final non-sealed java.util.concurrent.atomic.AtomicBoolean destroyed,private final non-sealed MultiMap<java.lang.String,zmq.SocketBase.EndpointPipe> endpoints,private java.nio.channels.SocketChannel fileDesc,private zmq.poll.Poller.Handle handle,private final non-sealed MultiMap<java.lang.String,zmq.pipe.Pipe> inprocs,private final non-sealed ThreadLocal<java.lang.Boolean> isInEventThreadLocal,private long lastTsc,private final non-sealed zmq.IMailbox mailbox,private final non-sealed AtomicReference<zmq.ZMQ.EventConsummer> monitor,private int monitorEvents,private final non-sealed Set<zmq.pipe.Pipe> pipes,private zmq.poll.Poller poller,private boolean rcvmore,private final non-sealed boolean threadSafe,private final non-sealed java.util.concurrent.locks.ReentrantLock threadSafeSync,private int ticks
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/socket/scattergather/Gather.java
Gather
xrecv
class Gather extends SocketBase { // Fair queueing object for inbound pipes. private final FQ fq; // Holds the prefetched message. public Gather(Ctx parent, int tid, int sid) { super(parent, tid, sid, true); options.type = ZMQ.ZMQ_GATHER; fq = new FQ(); } @Override protected void xattachPipe(Pipe pipe, boolean subscribe2all, boolean isLocallyInitiated) { assert (pipe != null); fq.attach(pipe); } @Override protected Msg xrecv() {<FILL_FUNCTION_BODY>} @Override protected boolean xhasIn() { return fq.hasIn(); } @Override protected Blob getCredential() { return fq.getCredential(); } @Override protected void xreadActivated(Pipe pipe) { fq.activated(pipe); } @Override protected void xpipeTerminated(Pipe pipe) { fq.terminated(pipe); } }
Msg msg = fq.recvPipe(errno, null); // Drop any messages with more flag while (msg != null && msg.hasMore()) { // drop all frames of the current multi-frame message msg = fq.recvPipe(errno, null); while (msg != null && msg.hasMore()) { fq.recvPipe(errno, null); } // get the new message if (msg != null) { fq.recvPipe(errno, null); } } return msg;
326
156
482
<methods>public final boolean bind(java.lang.String) ,public final void cancel(java.util.concurrent.atomic.AtomicBoolean) ,public final void close() ,public final boolean connect(java.lang.String) ,public final int connectPeer(java.lang.String) ,public boolean disconnectPeer(int) ,public final int errno() ,public final void eventAcceptFailed(java.lang.String, int) ,public final void eventAccepted(java.lang.String, java.nio.channels.SelectableChannel) ,public final void eventBindFailed(java.lang.String, int) ,public final void eventCloseFailed(java.lang.String, int) ,public final void eventClosed(java.lang.String, java.nio.channels.SelectableChannel) ,public final void eventConnectDelayed(java.lang.String, int) ,public final void eventConnectRetried(java.lang.String, int) ,public final void eventConnected(java.lang.String, java.nio.channels.SelectableChannel) ,public final void eventDisconnected(java.lang.String, java.nio.channels.SelectableChannel) ,public final void eventHandshakeFailedAuth(java.lang.String, int) ,public final void eventHandshakeFailedNoDetail(java.lang.String, int) ,public final void eventHandshakeFailedProtocol(java.lang.String, int) ,public final void eventHandshakeSucceeded(java.lang.String, int) ,public final void eventHandshaken(java.lang.String, int) ,public final void eventListening(java.lang.String, java.nio.channels.SelectableChannel) ,public final java.nio.channels.SelectableChannel getFD() ,public final int getSocketOpt(int) ,public final java.lang.Object getSocketOptx(int) ,public final void hiccuped(zmq.pipe.Pipe) ,public final void inEvent() ,public final boolean join(java.lang.String) ,public final boolean leave(java.lang.String) ,public final boolean monitor(java.lang.String, int) ,public final void pipeTerminated(zmq.pipe.Pipe) ,public final int poll(int, int, java.util.concurrent.atomic.AtomicBoolean) ,public final void readActivated(zmq.pipe.Pipe) ,public final zmq.Msg recv(int) ,public final zmq.Msg recv(int, java.util.concurrent.atomic.AtomicBoolean) ,public final boolean send(zmq.Msg, int) ,public final boolean send(zmq.Msg, int, java.util.concurrent.atomic.AtomicBoolean) ,public final boolean setEventHook(zmq.ZMQ.EventConsummer, int) ,public final boolean setSocketOpt(int, java.lang.Object) ,public final boolean termEndpoint(java.lang.String) ,public java.lang.String toString() ,public java.lang.String typeString() ,public final void writeActivated(zmq.pipe.Pipe) <variables>private boolean active,protected java.lang.String connectRid,private final non-sealed java.util.concurrent.atomic.AtomicBoolean ctxTerminated,private final non-sealed java.util.concurrent.atomic.AtomicBoolean destroyed,private final non-sealed MultiMap<java.lang.String,zmq.SocketBase.EndpointPipe> endpoints,private java.nio.channels.SocketChannel fileDesc,private zmq.poll.Poller.Handle handle,private final non-sealed MultiMap<java.lang.String,zmq.pipe.Pipe> inprocs,private final non-sealed ThreadLocal<java.lang.Boolean> isInEventThreadLocal,private long lastTsc,private final non-sealed zmq.IMailbox mailbox,private final non-sealed AtomicReference<zmq.ZMQ.EventConsummer> monitor,private int monitorEvents,private final non-sealed Set<zmq.pipe.Pipe> pipes,private zmq.poll.Poller poller,private boolean rcvmore,private final non-sealed boolean threadSafe,private final non-sealed java.util.concurrent.locks.ReentrantLock threadSafeSync,private int ticks
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/socket/scattergather/Scatter.java
Scatter
xattachPipe
class Scatter extends SocketBase { // Load balancer managing the outbound pipes. private final LB lb; // Holds the prefetched message. public Scatter(Ctx parent, int tid, int sid) { super(parent, tid, sid, true); options.type = ZMQ.ZMQ_SCATTER; lb = new LB(); } @Override protected void xattachPipe(Pipe pipe, boolean subscribe2all, boolean isLocallyInitiated) {<FILL_FUNCTION_BODY>} @Override protected boolean xsend(Msg msg) { // SCATTER sockets do not allow multipart data (ZMQ_SNDMORE) if (msg.hasMore()) { errno.set(ZError.EINVAL); return false; } return lb.sendpipe(msg, errno, null); } @Override protected boolean xhasOut() { return lb.hasOut(); } @Override protected void xwriteActivated(Pipe pipe) { lb.activated(pipe); } @Override protected void xpipeTerminated(Pipe pipe) { lb.terminated(pipe); } }
assert (pipe != null); // Don't delay pipe termination as there is no one // to receive the delimiter. pipe.setNoDelay(); lb.attach(pipe);
350
58
408
<methods>public final boolean bind(java.lang.String) ,public final void cancel(java.util.concurrent.atomic.AtomicBoolean) ,public final void close() ,public final boolean connect(java.lang.String) ,public final int connectPeer(java.lang.String) ,public boolean disconnectPeer(int) ,public final int errno() ,public final void eventAcceptFailed(java.lang.String, int) ,public final void eventAccepted(java.lang.String, java.nio.channels.SelectableChannel) ,public final void eventBindFailed(java.lang.String, int) ,public final void eventCloseFailed(java.lang.String, int) ,public final void eventClosed(java.lang.String, java.nio.channels.SelectableChannel) ,public final void eventConnectDelayed(java.lang.String, int) ,public final void eventConnectRetried(java.lang.String, int) ,public final void eventConnected(java.lang.String, java.nio.channels.SelectableChannel) ,public final void eventDisconnected(java.lang.String, java.nio.channels.SelectableChannel) ,public final void eventHandshakeFailedAuth(java.lang.String, int) ,public final void eventHandshakeFailedNoDetail(java.lang.String, int) ,public final void eventHandshakeFailedProtocol(java.lang.String, int) ,public final void eventHandshakeSucceeded(java.lang.String, int) ,public final void eventHandshaken(java.lang.String, int) ,public final void eventListening(java.lang.String, java.nio.channels.SelectableChannel) ,public final java.nio.channels.SelectableChannel getFD() ,public final int getSocketOpt(int) ,public final java.lang.Object getSocketOptx(int) ,public final void hiccuped(zmq.pipe.Pipe) ,public final void inEvent() ,public final boolean join(java.lang.String) ,public final boolean leave(java.lang.String) ,public final boolean monitor(java.lang.String, int) ,public final void pipeTerminated(zmq.pipe.Pipe) ,public final int poll(int, int, java.util.concurrent.atomic.AtomicBoolean) ,public final void readActivated(zmq.pipe.Pipe) ,public final zmq.Msg recv(int) ,public final zmq.Msg recv(int, java.util.concurrent.atomic.AtomicBoolean) ,public final boolean send(zmq.Msg, int) ,public final boolean send(zmq.Msg, int, java.util.concurrent.atomic.AtomicBoolean) ,public final boolean setEventHook(zmq.ZMQ.EventConsummer, int) ,public final boolean setSocketOpt(int, java.lang.Object) ,public final boolean termEndpoint(java.lang.String) ,public java.lang.String toString() ,public java.lang.String typeString() ,public final void writeActivated(zmq.pipe.Pipe) <variables>private boolean active,protected java.lang.String connectRid,private final non-sealed java.util.concurrent.atomic.AtomicBoolean ctxTerminated,private final non-sealed java.util.concurrent.atomic.AtomicBoolean destroyed,private final non-sealed MultiMap<java.lang.String,zmq.SocketBase.EndpointPipe> endpoints,private java.nio.channels.SocketChannel fileDesc,private zmq.poll.Poller.Handle handle,private final non-sealed MultiMap<java.lang.String,zmq.pipe.Pipe> inprocs,private final non-sealed ThreadLocal<java.lang.Boolean> isInEventThreadLocal,private long lastTsc,private final non-sealed zmq.IMailbox mailbox,private final non-sealed AtomicReference<zmq.ZMQ.EventConsummer> monitor,private int monitorEvents,private final non-sealed Set<zmq.pipe.Pipe> pipes,private zmq.poll.Poller poller,private boolean rcvmore,private final non-sealed boolean threadSafe,private final non-sealed java.util.concurrent.locks.ReentrantLock threadSafeSync,private int ticks
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/util/Blob.java
Blob
createBlob
class Blob { private final byte[] buf; private Blob(byte[] data) { buf = data; } private static Blob createBlob(byte[] data, boolean copy) {<FILL_FUNCTION_BODY>} public static Blob createBlob(Msg msg) { return createBlob(msg.data(), true); } public static Blob createBlob(byte[] data) { return createBlob(data, false); } public int size() { return buf.length; } public byte[] data() { return buf; } @Override public boolean equals(Object t) { if (t instanceof Blob) { return Arrays.equals(buf, ((Blob) t).buf); } return false; } @Override public int hashCode() { return Arrays.hashCode(buf); } }
if (copy) { byte[] b = new byte[data.length]; System.arraycopy(data, 0, b, 0, data.length); return new Blob(b); } else { return new Blob(data); }
261
72
333
<no_super_class>
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/util/MultiMap.java
EntryComparator
remove
class EntryComparator implements Comparator<Entry<V, K>> { @Override public int compare(Entry<V, K> first, Entry<V, K> second) { return first.getValue().compareTo(second.getValue()); } } private final Comparator<? super Entry<V, K>> comparator = new EntryComparator(); // where all the data will be put private final Map<K, List<V>> data; // inverse mapping to speed-up the process private final Map<V, K> inverse; public MultiMap() { data = new HashMap<>(); inverse = new HashMap<>(); } public void clear() { data.clear(); inverse.clear(); } public Collection<Entry<V, K>> entries() { List<Entry<V, K>> list = new ArrayList<>(inverse.entrySet()); list.sort(comparator); return list; } @Deprecated public Collection<V> values() { return inverse.keySet(); } public boolean contains(V value) { return inverse.containsKey(value); } public K key(V value) { return inverse.get(value); } public V find(V copy) { K key = inverse.get(copy); if (key != null) { List<V> list = data.get(key); return list.get(list.indexOf(copy)); } return null; } public boolean hasValues(K key) { List<V> list = data.get(key); if (list == null) { return false; } return !list.isEmpty(); } public boolean isEmpty() { return inverse.isEmpty(); } private List<V> getValues(K key) { return data.computeIfAbsent(key, k -> new ArrayList<>()); } public boolean insert(K key, V value) { K old = inverse.get(value); if (old != null) { boolean rc = removeData(old, value); assert rc; } boolean inserted = getValues(key).add(value); if (inserted) { inverse.put(value, key); } else { inverse.remove(value); } return inserted; } public Collection<V> remove(K key) {<FILL_FUNCTION_BODY>
List<V> removed = data.remove(key); if (removed != null) { for (V val : removed) { inverse.remove(val); } } return removed;
668
57
725
<no_super_class>
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/util/Timers.java
Timer
execute
class Timer { private final Timers parent; private long interval; private boolean alive = true; private final Handler handler; private final Object[] args; private Timer(Timers parent, long interval, Handler handler, Object... args) { assert (args != null); this.parent = parent; this.interval = interval; this.handler = handler; this.args = args; } /** * Changes the interval of the timer. * This method is slow, canceling existing and adding a new timer yield better performance. * @param interval the new interval of the timer. * @return true if set, otherwise false. */ public boolean setInterval(long interval) { if (alive) { this.interval = interval; return parent.insert(this); } return false; } /** * Reset the timer. * This method is slow, canceling existing and adding a new timer yield better performance. * @return true if reset, otherwise false. */ public boolean reset() { if (alive) { return parent.insert(this); } return false; } /** * Cancels a timer. * @return true if cancelled, otherwise false. */ public boolean cancel() { if (alive) { alive = false; return true; } return false; } } public interface Handler { void time(Object... args); } private final MultiMap<Long, Timer> timers = new MultiMap<>(); private final Supplier<Long> clock; public Timers() { this(() -> TimeUnit.NANOSECONDS.toMillis(Clock.nowNS())); } /** * Builds a new timer. * <p> * <strong>This constructor is for testing and is not intended to be used in production code.</strong> * @param clock the supplier of the current time in milliseconds. */ public Timers(Supplier<Long> clock) { this.clock = clock; } private long now() { return clock.get(); } private boolean insert(Timer timer) { return timers.insert(now() + timer.interval, timer); } /** * Add timer to the set, timer repeats forever, or until cancel is called. * @param interval the interval of repetition in milliseconds. * @param handler the callback called at the expiration of the timer. * @param args the optional arguments for the handler. * @return an opaque handle for further cancel. */ public Timer add(long interval, Handler handler, Object... args) { if (handler == null) { return null; } Utils.checkArgument(interval > 0, "Delay of a timer has to be strictly greater than 0"); final Timer timer = new Timer(this, interval, handler, args); final boolean rc = insert(timer); assert (rc); return timer; } /** * Changes the interval of the timer. * This method is slow, canceling existing and adding a new timer yield better performance. * @param timer the timer to change the interval to. * @return true if set, otherwise false. * @deprecated use {@link Timer#setInterval(long)} instead */ @Deprecated public boolean setInterval(Timer timer, long interval) { assert (timer.parent == this); return timer.setInterval(interval); } /** * Reset the timer. * This method is slow, canceling existing and adding a new timer yield better performance. * @param timer the timer to reset. * @return true if reset, otherwise false. * @deprecated use {@link Timer#reset()} instead */ @Deprecated public boolean reset(Timer timer) { assert (timer.parent == this); return timer.reset(); } /** * Cancel a timer. * @param timer the timer to cancel. * @return true if cancelled, otherwise false. * @deprecated use {@link Timer#cancel()} instead */ @Deprecated public boolean cancel(Timer timer) { assert (timer.parent == this); return timer.cancel(); } /** * Returns the time in millisecond until the next timer. * @return the time in millisecond until the next timer. */ public long timeout() { final long now = now(); for (Entry<Timer, Long> entry : entries()) { final Timer timer = entry.getKey(); final Long expiration = entry.getValue(); if (timer.alive) { // Live timer, lets return the timeout if (expiration - now > 0) { return expiration - now; } else { return 0; } } // Remove it from the list of active timers. timers.remove(expiration, timer); } // Wait forever as no timers are alive return -1; } /** * Execute the timers. * @return the number of timers triggered. */ public int execute() {<FILL_FUNCTION_BODY>
int executed = 0; final long now = now(); for (Entry<Timer, Long> entry : entries()) { final Timer timer = entry.getKey(); final Long expiration = entry.getValue(); // Dead timer, lets remove it and continue if (!timer.alive) { // Remove it from the list of active timers. timers.remove(expiration, timer); continue; } // Map is ordered, if we have to wait for current timer we can stop. if (expiration - now > 0) { break; } insert(timer); timer.handler.time(timer.args); ++executed; } return executed;
1,396
185
1,581
<no_super_class>
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/util/Utils.java
Utils
getPeerIpAddress
class Utils { private static final ThreadLocal<SecureRandom> random = ThreadLocal.withInitial(SecureRandom::new); private Utils() { } public static int randomInt() { return random.get().nextInt(); } public static int randomInt(int bound) { return random.get().nextInt(bound); } public static byte[] randomBytes(int length) { byte[] bytes = new byte[length]; random.get().nextBytes(bytes); return bytes; } /** * Finds a string whose hashcode is the number in input. * * @param port the port to find String hashcode-equivalent of. Has to be positive or 0. * @return a String whose hashcode is the number in input. */ public static String unhash(int port) { return unhash(new StringBuilder(), port, 'z').toString(); } private static StringBuilder unhash(StringBuilder builder, int port, char boundary) { int div = port / 31; int remainder = port % 31; if (div <= boundary) { if (div != 0) { builder.append((char) div); } } else { unhash(builder, div, boundary); } builder.append((char) remainder); return builder; } public static int findOpenPort() throws IOException { try (ServerSocket tmpSocket = new ServerSocket(0, 0)) { return tmpSocket.getLocalPort(); } } public static void unblockSocket(SelectableChannel... channels) throws IOException { TcpUtils.unblockSocket(channels); } @SuppressWarnings("unchecked") public static <T> T[] realloc(Class<T> klass, T[] src, int size, boolean ended) { T[] dest; if (size > src.length) { dest = (T[]) Array.newInstance(klass, size); if (ended) { System.arraycopy(src, 0, dest, 0, src.length); } else { System.arraycopy(src, 0, dest, size - src.length, src.length); } } else if (size < src.length) { dest = (T[]) Array.newInstance(klass, size); if (ended) { System.arraycopy(src, src.length - size, dest, 0, size); } else { System.arraycopy(src, 0, dest, 0, size); } } else { dest = src; } return dest; } public static byte[] bytes(ByteBuffer buf) { byte[] d = new byte[buf.limit()]; buf.get(d); return d; } public static byte[] realloc(byte[] src, int size) { byte[] dest = new byte[size]; if (src != null) { System.arraycopy(src, 0, dest, 0, src.length); } return dest; } public static boolean delete(File path) { if (!path.exists()) { return false; } boolean ret = true; if (path.isDirectory()) { File[] files = path.listFiles(); if (files != null) { for (File f : files) { ret = ret && delete(f); } } } return ret && path.delete(); } /** * Resolve the remote address of the channel. * @param fd the channel, should be a TCP socket channel * @return a new {@link Address} * @throws ZError.IOException if the channel is closed or an I/O errors occurred * @throws IllegalArgumentException if the SocketChannel is not a TCP channel */ public static Address getPeerIpAddress(SocketChannel fd) {<FILL_FUNCTION_BODY>} /** * Resolve the local address of the channel. * @param fd the channel, should be a TCP socket channel * @return a new {@link Address} * @throws ZError.IOException if the channel is closed or an I/O errors occurred * @throws IllegalArgumentException if the SocketChannel is not a TCP channel */ public static Address getLocalIpAddress(SocketChannel fd) { try { SocketAddress address = fd.getLocalAddress(); return new Address(address); } catch (IOException e) { throw new ZError.IOException(e); } } public static String dump(ByteBuffer buffer, int pos, int limit) { int oldpos = buffer.position(); int oldlimit = buffer.limit(); buffer.limit(limit).position(pos); StringBuilder builder = new StringBuilder("["); for (int idx = buffer.position(); idx < buffer.limit(); ++idx) { builder.append(buffer.get(idx)); builder.append(','); } builder.append(']'); buffer.limit(oldlimit).position(oldpos); return builder.toString(); } public static void checkArgument(boolean expression, String errorMessage) { checkArgument(expression, () -> errorMessage); } public static void checkArgument(boolean expression, Supplier<String> errorMessage) { if (!expression) { throw new IllegalArgumentException(errorMessage.get()); } } }
try { SocketAddress address = fd.getRemoteAddress(); return new Address(address); } catch (IOException e) { throw new ZError.IOException(e); }
1,442
54
1,496
<no_super_class>
zeromq_jeromq
jeromq/jeromq-core/src/main/java/zmq/util/Z85.java
Z85
decode
class Z85 { private Z85() { } // Maps base 256 to base 85 private static final String encoder = "0123456789" + "abcdefghij" + "klmnopqrst" + "uvwxyzABCD" + "EFGHIJKLMN" + "OPQRSTUVWX" + "YZ.-:+=^!/" + "*?&<>()[]{" + "}@%$#"; // Maps base 85 to base 256 // We chop off lower 32 and higher 128 ranges private static final byte[] decoder = { 0x00, 0x44, 0x00, 0x54, 0x53, 0x52, 0x48, 0x00, 0x4B, 0x4C, 0x46, 0x41, 0x00, 0x3F, 0x3E, 0x45, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x40, 0x00, 0x49, 0x42, 0x4A, 0x47, 0x51, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x4D, 0x00, 0x4E, 0x43, 0x00, 0x00, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x4F, 0x00, 0x50, 0x00, 0x00 }; // -------------------------------------------------------------------------- // Encode a binary frame as a string; destination string MUST be at least // size * 5 / 4 bytes long plus 1 byte for the null terminator. Returns // dest. Size must be a multiple of 4. // Returns NULL and sets errno = EINVAL for invalid input. public static String encode(byte[] data, int size) { if (size % 4 != 0) { return null; } StringBuilder builder = new StringBuilder(); int byteNbr = 0; long value = 0; while (byteNbr < size) { // Accumulate value in base 256 (binary) int d = data[byteNbr++] & 0xff; value = value * 256 + d; if (byteNbr % 4 == 0) { // Output value in base 85 int divisor = 85 * 85 * 85 * 85; while (divisor != 0) { int index = (int) (value / divisor % 85); builder.append(encoder.charAt(index)); divisor /= 85; } value = 0; } } assert (builder.length() == size * 5 / 4); return builder.toString(); } // -------------------------------------------------------------------------- // Decode an encoded string into a binary frame; dest must be at least // strlen (string) * 4 / 5 bytes long. Returns dest. strlen (string) // must be a multiple of 5. // Returns NULL and sets errno = EINVAL for invalid input. public static byte[] decode(String string) {<FILL_FUNCTION_BODY>} }
if (string.length() % 5 != 0) { return null; } ByteBuffer buf = ByteBuffer.allocate(string.length() * 4 / 5); int byteNbr = 0; int charNbr = 0; int stringLen = string.length(); long value = 0; while (charNbr < stringLen) { // Accumulate value in base 85 value = value * 85 + (decoder[string.charAt(charNbr++) - 32] & 0xff); if (charNbr % 5 == 0) { // Output value in base 256 int divisor = 256 * 256 * 256; while (divisor != 0) { buf.put(byteNbr++, (byte) ((value / divisor) % 256)); divisor /= 256; } value = 0; } } assert (byteNbr == string.length() * 4 / 5); return buf.array();
1,219
280
1,499
<no_super_class>
alibaba_jetcache
jetcache/jetcache-anno/src/main/java/com/alicp/jetcache/anno/aop/CachePointcut.java
CachePointcut
matchesImpl
class CachePointcut extends StaticMethodMatcherPointcut implements ClassFilter { private static final Logger logger = LoggerFactory.getLogger(CachePointcut.class); private ConfigMap cacheConfigMap; private String[] basePackages; public CachePointcut(String[] basePackages) { setClassFilter(this); this.basePackages = basePackages; } @Override public boolean matches(Class clazz) { boolean b = matchesImpl(clazz); logger.trace("check class match {}: {}", b, clazz); return b; } private boolean matchesImpl(Class clazz) { if (matchesThis(clazz)) { return true; } Class[] cs = clazz.getInterfaces(); if (cs != null) { for (Class c : cs) { if (matchesImpl(c)) { return true; } } } if (!clazz.isInterface()) { Class sp = clazz.getSuperclass(); if (sp != null && matchesImpl(sp)) { return true; } } return false; } public boolean matchesThis(Class clazz) { String name = clazz.getName(); if (exclude(name)) { return false; } return include(name); } private boolean include(String name) { if (basePackages != null) { for (String p : basePackages) { if (name.startsWith(p)) { return true; } } } return false; } private boolean exclude(String name) { if (name.startsWith("java")) { return true; } if (name.startsWith("org.springframework")) { return true; } if (name.indexOf("$$EnhancerBySpringCGLIB$$") >= 0) { return true; } if (name.indexOf("$$FastClassBySpringCGLIB$$") >= 0) { return true; } return false; } @Override public boolean matches(Method method, Class targetClass) { boolean b = matchesImpl(method, targetClass); if (b) { if (logger.isDebugEnabled()) { logger.debug("check method match true: method={}, declaringClass={}, targetClass={}", method.getName(), ClassUtil.getShortClassName(method.getDeclaringClass().getName()), targetClass == null ? null : ClassUtil.getShortClassName(targetClass.getName())); } } else { if (logger.isTraceEnabled()) { logger.trace("check method match false: method={}, declaringClass={}, targetClass={}", method.getName(), ClassUtil.getShortClassName(method.getDeclaringClass().getName()), targetClass == null ? null : ClassUtil.getShortClassName(targetClass.getName())); } } return b; } private boolean matchesImpl(Method method, Class targetClass) {<FILL_FUNCTION_BODY>} public static String getKey(Method method, Class targetClass) { StringBuilder sb = new StringBuilder(); sb.append(method.getDeclaringClass().getName()); sb.append('.'); sb.append(method.getName()); sb.append(Type.getMethodDescriptor(method)); if (targetClass != null) { sb.append('_'); sb.append(targetClass.getName()); } return sb.toString(); } private void parseByTargetClass(CacheInvokeConfig cac, Class<?> clazz, String name, Class<?>[] paramTypes) { if (!clazz.isInterface() && clazz.getSuperclass() != null) { parseByTargetClass(cac, clazz.getSuperclass(), name, paramTypes); } Class<?>[] intfs = clazz.getInterfaces(); for (Class<?> it : intfs) { parseByTargetClass(cac, it, name, paramTypes); } boolean matchThis = matchesThis(clazz); if (matchThis) { Method[] methods = clazz.getDeclaredMethods(); for (Method method : methods) { if (methodMatch(name, method, paramTypes)) { CacheConfigUtil.parse(cac, method); break; } } } } private boolean methodMatch(String name, Method method, Class<?>[] paramTypes) { if (!Modifier.isPublic(method.getModifiers())) { return false; } if (!name.equals(method.getName())) { return false; } Class<?>[] ps = method.getParameterTypes(); if (ps.length != paramTypes.length) { return false; } for (int i = 0; i < ps.length; i++) { if (!ps[i].equals(paramTypes[i])) { return false; } } return true; } public void setCacheConfigMap(ConfigMap cacheConfigMap) { this.cacheConfigMap = cacheConfigMap; } }
if (!matchesThis(method.getDeclaringClass())) { return false; } if (exclude(targetClass.getName())) { return false; } String key = getKey(method, targetClass); CacheInvokeConfig cac = cacheConfigMap.getByMethodInfo(key); if (cac == CacheInvokeConfig.getNoCacheInvokeConfigInstance()) { return false; } else if (cac != null) { return true; } else { cac = new CacheInvokeConfig(); CacheConfigUtil.parse(cac, method); String name = method.getName(); Class<?>[] paramTypes = method.getParameterTypes(); parseByTargetClass(cac, targetClass, name, paramTypes); if (!cac.isEnableCacheContext() && cac.getCachedAnnoConfig() == null && cac.getInvalidateAnnoConfigs() == null && cac.getUpdateAnnoConfig() == null) { cacheConfigMap.putByMethodInfo(key, CacheInvokeConfig.getNoCacheInvokeConfigInstance()); return false; } else { cacheConfigMap.putByMethodInfo(key, cac); return true; } }
1,340
317
1,657
<no_super_class>
alibaba_jetcache
jetcache/jetcache-anno/src/main/java/com/alicp/jetcache/anno/aop/JetCacheInterceptor.java
JetCacheInterceptor
invoke
class JetCacheInterceptor implements MethodInterceptor, ApplicationContextAware { private static final Logger logger = LoggerFactory.getLogger(JetCacheInterceptor.class); @Autowired private ConfigMap cacheConfigMap; private ApplicationContext applicationContext; private GlobalCacheConfig globalCacheConfig; ConfigProvider configProvider; CacheManager cacheManager; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } @Override public Object invoke(final MethodInvocation invocation) throws Throwable {<FILL_FUNCTION_BODY>} public void setCacheConfigMap(ConfigMap cacheConfigMap) { this.cacheConfigMap = cacheConfigMap; } }
if (configProvider == null) { configProvider = applicationContext.getBean(ConfigProvider.class); } if (configProvider != null && globalCacheConfig == null) { globalCacheConfig = configProvider.getGlobalCacheConfig(); } if (globalCacheConfig == null || !globalCacheConfig.isEnableMethodCache()) { return invocation.proceed(); } if (cacheManager == null) { cacheManager = applicationContext.getBean(CacheManager.class); if (cacheManager == null) { logger.error("There is no cache manager instance in spring context"); return invocation.proceed(); } } Method method = invocation.getMethod(); Object obj = invocation.getThis(); CacheInvokeConfig cac = null; if (obj != null) { String key = CachePointcut.getKey(method, obj.getClass()); cac = cacheConfigMap.getByMethodInfo(key); } /* if(logger.isTraceEnabled()){ logger.trace("JetCacheInterceptor invoke. foundJetCacheConfig={}, method={}.{}(), targetClass={}", cac != null, method.getDeclaringClass().getName(), method.getName(), invocation.getThis() == null ? null : invocation.getThis().getClass().getName()); } */ if (cac == null || cac == CacheInvokeConfig.getNoCacheInvokeConfigInstance()) { return invocation.proceed(); } CacheInvokeContext context = configProvider.newContext(cacheManager).createCacheInvokeContext(cacheConfigMap); context.setTargetObject(invocation.getThis()); context.setInvoker(invocation::proceed); context.setMethod(method); context.setArgs(invocation.getArguments()); context.setCacheInvokeConfig(cac); context.setHiddenPackages(globalCacheConfig.getHiddenPackages()); return CacheHandler.invoke(context);
199
512
711
<no_super_class>
alibaba_jetcache
jetcache/jetcache-anno/src/main/java/com/alicp/jetcache/anno/config/CacheAnnotationParser.java
CacheAnnotationParser
doParse
class CacheAnnotationParser implements BeanDefinitionParser { private final ReentrantLock reentrantLock = new ReentrantLock(); @Override public BeanDefinition parse(Element element, ParserContext parserContext) { reentrantLock.lock(); try { doParse(element, parserContext); }finally { reentrantLock.unlock(); } return null; } private void doParse(Element element, ParserContext parserContext) {<FILL_FUNCTION_BODY>} }
String[] basePackages = StringUtils.tokenizeToStringArray(element.getAttribute("base-package"), ",; \t\n"); AopNamespaceUtils.registerAutoProxyCreatorIfNecessary(parserContext, element); if (!parserContext.getRegistry().containsBeanDefinition(CacheAdvisor.CACHE_ADVISOR_BEAN_NAME)) { Object eleSource = parserContext.extractSource(element); RootBeanDefinition configMapDef = new RootBeanDefinition(ConfigMap.class); configMapDef.setSource(eleSource); configMapDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); String configMapName = parserContext.getReaderContext().registerWithGeneratedName(configMapDef); RootBeanDefinition interceptorDef = new RootBeanDefinition(JetCacheInterceptor.class); interceptorDef.setSource(eleSource); interceptorDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); interceptorDef.getPropertyValues().addPropertyValue(new PropertyValue("cacheConfigMap", new RuntimeBeanReference(configMapName))); String interceptorName = parserContext.getReaderContext().registerWithGeneratedName(interceptorDef); RootBeanDefinition advisorDef = new RootBeanDefinition(CacheAdvisor.class); advisorDef.setSource(eleSource); advisorDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); advisorDef.getPropertyValues().addPropertyValue(new PropertyValue("adviceBeanName", interceptorName)); advisorDef.getPropertyValues().addPropertyValue(new PropertyValue("cacheConfigMap", new RuntimeBeanReference(configMapName))); advisorDef.getPropertyValues().addPropertyValue(new PropertyValue("basePackages", basePackages)); parserContext.getRegistry().registerBeanDefinition(CacheAdvisor.CACHE_ADVISOR_BEAN_NAME, advisorDef); CompositeComponentDefinition compositeDef = new CompositeComponentDefinition(element.getTagName(), eleSource); compositeDef.addNestedComponent(new BeanComponentDefinition(configMapDef, configMapName)); compositeDef.addNestedComponent(new BeanComponentDefinition(interceptorDef, interceptorName)); compositeDef.addNestedComponent(new BeanComponentDefinition(advisorDef, CacheAdvisor.CACHE_ADVISOR_BEAN_NAME)); parserContext.registerComponent(compositeDef); }
135
612
747
<no_super_class>
alibaba_jetcache
jetcache/jetcache-anno/src/main/java/com/alicp/jetcache/anno/config/ConfigSelector.java
ConfigSelector
getProxyImports
class ConfigSelector extends AdviceModeImportSelector<EnableMethodCache> { @Override public String[] selectImports(AdviceMode adviceMode) { switch (adviceMode) { case PROXY: return getProxyImports(); case ASPECTJ: // return getAspectJImports(); default: return null; } } /** * Return the imports to use if the {@link AdviceMode} is set to {@link AdviceMode#PROXY}. * <p>Take care of adding the necessary JSR-107 import if it is available. */ private String[] getProxyImports() {<FILL_FUNCTION_BODY>} /** * Return the imports to use if the {@link AdviceMode} is set to {@link AdviceMode#ASPECTJ}. * <p>Take care of adding the necessary JSR-107 import if it is available. */ // private String[] getAspectJImports() { // List<String> result = new ArrayList<String>(); // result.add(CACHE_ASPECT_CONFIGURATION_CLASS_NAME); // return result.toArray(new String[result.size()]); // } }
List<String> result = new ArrayList<String>(); result.add(AutoProxyRegistrar.class.getName()); result.add(JetCacheProxyConfiguration.class.getName()); return result.toArray(new String[result.size()]);
311
65
376
<no_super_class>
alibaba_jetcache
jetcache/jetcache-anno/src/main/java/com/alicp/jetcache/anno/config/JetCacheProxyConfiguration.java
JetCacheProxyConfiguration
jetcacheAdvisor
class JetCacheProxyConfiguration implements ImportAware, ApplicationContextAware { protected AnnotationAttributes enableMethodCache; private ApplicationContext applicationContext; @Override public void setImportMetadata(AnnotationMetadata importMetadata) { this.enableMethodCache = AnnotationAttributes.fromMap( importMetadata.getAnnotationAttributes(EnableMethodCache.class.getName(), false)); if (this.enableMethodCache == null) { throw new IllegalArgumentException( "@EnableMethodCache is not present on importing class " + importMetadata.getClassName()); } } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } @Bean(name = CacheAdvisor.CACHE_ADVISOR_BEAN_NAME) @Role(BeanDefinition.ROLE_INFRASTRUCTURE) public CacheAdvisor jetcacheAdvisor(JetCacheInterceptor jetCacheInterceptor) {<FILL_FUNCTION_BODY>} @Bean @Role(BeanDefinition.ROLE_INFRASTRUCTURE) public JetCacheInterceptor jetCacheInterceptor() { return new JetCacheInterceptor(); } }
CacheAdvisor advisor = new CacheAdvisor(); advisor.setAdvice(jetCacheInterceptor); advisor.setBasePackages(this.enableMethodCache.getStringArray("basePackages")); advisor.setOrder(this.enableMethodCache.<Integer>getNumber("order")); return advisor;
316
84
400
<no_super_class>
alibaba_jetcache
jetcache/jetcache-anno/src/main/java/com/alicp/jetcache/anno/field/CreateCacheAnnotationBeanPostProcessor.java
CreateCacheAnnotationBeanPostProcessor
findAutowiringMetadata
class CreateCacheAnnotationBeanPostProcessor extends AutowiredAnnotationBeanPostProcessor { private static Logger logger = LoggerFactory.getLogger(CreateCacheAnnotationBeanPostProcessor.class); private ConfigurableListableBeanFactory beanFactory; private final Map<String, InjectionMetadata> injectionMetadataCache = new ConcurrentHashMap<String, InjectionMetadata>(); private final ReentrantLock reentrantLock = new ReentrantLock(); @Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { super.setBeanFactory(beanFactory); if (!(beanFactory instanceof ConfigurableListableBeanFactory)) { throw new IllegalArgumentException( "AutowiredAnnotationBeanPostProcessor requires a ConfigurableListableBeanFactory"); } this.beanFactory = (ConfigurableListableBeanFactory) beanFactory; } // removed in spring 6 //@Override public PropertyValues postProcessPropertyValues( PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeanCreationException { return postProcessProperties(pvs, bean, beanName); } //@Override //since 5.1 @SuppressWarnings("AliMissingOverrideAnnotation") public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) { InjectionMetadata metadata = findAutowiringMetadata(beanName, bean.getClass(), pvs); try { metadata.inject(bean, beanName, pvs); } catch (BeanCreationException ex) { throw ex; } catch (Throwable ex) { throw new BeanCreationException(beanName, "Injection of autowired dependencies failed", ex); } return pvs; } private InjectionMetadata findAutowiringMetadata(String beanName, Class<?> clazz, PropertyValues pvs) {<FILL_FUNCTION_BODY>} private volatile boolean clearInited = false; private Method cleanMethod; /** * clear method not found in Spring 4.0. * @param obj * @param param */ private void clear(InjectionMetadata obj, PropertyValues param) { if(!clearInited){ try { cleanMethod = InjectionMetadata.class.getMethod("clear", PropertyValues.class); } catch (NoSuchMethodException e) { } clearInited = true; } if (cleanMethod != null) { try { cleanMethod.invoke(obj, param); } catch (IllegalAccessException | InvocationTargetException e) { throw new IllegalStateException(e); } } } private InjectionMetadata buildAutowiringMetadata(final Class<?> clazz) { LinkedList<InjectionMetadata.InjectedElement> elements = new LinkedList<InjectionMetadata.InjectedElement>(); Class<?> targetClass = clazz; do { final LinkedList<InjectionMetadata.InjectedElement> currElements = new LinkedList<InjectionMetadata.InjectedElement>(); doWithLocalFields(targetClass, new ReflectionUtils.FieldCallback() { @Override public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { CreateCache ann = field.getAnnotation(CreateCache.class); if (ann != null) { if (Modifier.isStatic(field.getModifiers())) { if (logger.isWarnEnabled()) { logger.warn("Autowired annotation is not supported on static fields: " + field); } return; } currElements.add(new AutowiredFieldElement(field, ann)); } } }); elements.addAll(0, currElements); targetClass = targetClass.getSuperclass(); } while (targetClass != null && targetClass != Object.class); return new InjectionMetadata(clazz, elements); } private void doWithLocalFields(Class clazz, ReflectionUtils.FieldCallback fieldCallback) { Field fs[] = clazz.getDeclaredFields(); for (Field field : fs) { try { fieldCallback.doWith(field); } catch (IllegalAccessException ex) { throw new IllegalStateException("Not allowed to access field '" + field.getName() + "': " + ex); } } } private class AutowiredFieldElement extends InjectionMetadata.InjectedElement { private Field field; private CreateCache ann; public AutowiredFieldElement(Field field, CreateCache ann) { super(field, null); this.field = field; this.ann = ann; } @Override protected void inject(Object bean, String beanName, PropertyValues pvs) throws Throwable { beanFactory.registerDependentBean(beanName, "globalCacheConfig"); CreateCacheWrapper wrapper = new CreateCacheWrapper(beanFactory, ann, field); field.setAccessible(true); field.set(bean, wrapper.getCache()); } } }
// Fall back to class name as cache key, for backwards compatibility with custom callers. String cacheKey = (StringUtils.hasLength(beanName) ? beanName : clazz.getName()); // Quick check on the concurrent map first, with minimal locking. InjectionMetadata metadata = this.injectionMetadataCache.get(cacheKey); if (InjectionMetadata.needsRefresh(metadata, clazz)) { reentrantLock.lock(); try{ metadata = this.injectionMetadataCache.get(cacheKey); if (InjectionMetadata.needsRefresh(metadata, clazz)) { if (metadata != null) { clear(metadata, pvs); } try { metadata = buildAutowiringMetadata(clazz); this.injectionMetadataCache.put(cacheKey, metadata); } catch (NoClassDefFoundError err) { throw new IllegalStateException("Failed to introspect bean class [" + clazz.getName() + "] for autowiring metadata: could not find class that it depends on", err); } } }finally { reentrantLock.unlock(); } } return metadata;
1,266
295
1,561
<no_super_class>
alibaba_jetcache
jetcache/jetcache-anno/src/main/java/com/alicp/jetcache/anno/field/CreateCacheWrapper.java
CreateCacheWrapper
init
class CreateCacheWrapper { private static final Logger logger = LoggerFactory.getLogger(CreateCacheWrapper.class); private Cache cache; private ConfigurableListableBeanFactory beanFactory; private CreateCache ann; private Field field; private RefreshPolicy refreshPolicy; private PenetrationProtectConfig protectConfig; public CreateCacheWrapper(ConfigurableListableBeanFactory beanFactory, CreateCache ann, Field field) { this.beanFactory = beanFactory; this.ann = ann; this.field = field; CacheRefresh cr = field.getAnnotation(CacheRefresh.class); if (cr != null) { refreshPolicy = CacheConfigUtil.parseRefreshPolicy(cr); } CachePenetrationProtect penetrateProtect = field.getAnnotation(CachePenetrationProtect.class); if (penetrateProtect != null) { protectConfig = CacheConfigUtil.parsePenetrationProtectConfig(penetrateProtect); } init(); } private void init() {<FILL_FUNCTION_BODY>} public Cache getCache() { return cache; } }
GlobalCacheConfig globalCacheConfig = beanFactory.getBean(GlobalCacheConfig.class); ConfigProvider configProvider = beanFactory.getBean(ConfigProvider.class); CacheManager cacheManager = beanFactory.getBean(CacheManager.class); if (cacheManager == null) { logger.error("There is no cache manager instance in spring context"); } CachedAnnoConfig cac = new CachedAnnoConfig(); cac.setArea(ann.area()); cac.setName(ann.name()); cac.setTimeUnit(ann.timeUnit()); cac.setExpire(ann.expire()); cac.setLocalExpire(ann.localExpire()); cac.setCacheType(ann.cacheType()); cac.setSyncLocal(ann.syncLocal()); cac.setLocalLimit(ann.localLimit()); cac.setSerialPolicy(ann.serialPolicy()); cac.setKeyConvertor(ann.keyConvertor()); cac.setRefreshPolicy(refreshPolicy); cac.setPenetrationProtectConfig(protectConfig); String cacheName = cac.getName(); if (CacheConsts.isUndefined(cacheName)) { String[] hiddenPackages = globalCacheConfig.getHiddenPackages(); CacheNameGenerator g = configProvider.createCacheNameGenerator(hiddenPackages); cacheName = g.generateCacheName(field); } cache = configProvider.newContext(cacheManager).__createOrGetCache(cac, ann.area(), cacheName);
297
390
687
<no_super_class>
alibaba_jetcache
jetcache/jetcache-anno/src/main/java/com/alicp/jetcache/anno/method/CacheConfigUtil.java
CacheConfigUtil
parse
class CacheConfigUtil { private static CachedAnnoConfig parseCached(Method m) { Cached anno = m.getAnnotation(Cached.class); if (anno == null) { return null; } CachedAnnoConfig cc = new CachedAnnoConfig(); cc.setArea(anno.area()); cc.setName(anno.name()); cc.setCacheType(anno.cacheType()); cc.setSyncLocal(anno.syncLocal()); cc.setEnabled(anno.enabled()); cc.setTimeUnit(anno.timeUnit()); cc.setExpire(anno.expire()); cc.setLocalExpire(anno.localExpire()); cc.setLocalLimit(anno.localLimit()); cc.setCacheNullValue(anno.cacheNullValue()); cc.setCondition(anno.condition()); cc.setPostCondition(anno.postCondition()); cc.setSerialPolicy(anno.serialPolicy()); cc.setKeyConvertor(anno.keyConvertor()); cc.setKey(anno.key()); cc.setDefineMethod(m); CacheRefresh cacheRefresh = m.getAnnotation(CacheRefresh.class); if (cacheRefresh != null) { RefreshPolicy policy = parseRefreshPolicy(cacheRefresh); cc.setRefreshPolicy(policy); } CachePenetrationProtect protectAnno = m.getAnnotation(CachePenetrationProtect.class); if (protectAnno != null) { PenetrationProtectConfig protectConfig = parsePenetrationProtectConfig(protectAnno); cc.setPenetrationProtectConfig(protectConfig); } return cc; } public static PenetrationProtectConfig parsePenetrationProtectConfig(CachePenetrationProtect protectAnno) { PenetrationProtectConfig protectConfig = new PenetrationProtectConfig(); protectConfig.setPenetrationProtect(protectAnno.value()); if (!CacheConsts.isUndefined(protectAnno.timeout())) { long timeout = protectAnno.timeUnit().toMillis(protectAnno.timeout()); protectConfig.setPenetrationProtectTimeout(Duration.ofMillis(timeout)); } return protectConfig; } public static RefreshPolicy parseRefreshPolicy(CacheRefresh cacheRefresh) { RefreshPolicy policy = new RefreshPolicy(); TimeUnit t = cacheRefresh.timeUnit(); policy.setRefreshMillis(t.toMillis(cacheRefresh.refresh())); if (!CacheConsts.isUndefined(cacheRefresh.stopRefreshAfterLastAccess())) { policy.setStopRefreshAfterLastAccessMillis(t.toMillis(cacheRefresh.stopRefreshAfterLastAccess())); } if (!CacheConsts.isUndefined(cacheRefresh.refreshLockTimeout())) { policy.setRefreshLockTimeoutMillis(t.toMillis(cacheRefresh.refreshLockTimeout())); } return policy; } public static List<CacheInvalidateAnnoConfig> parseCacheInvalidates(Method m) { List<CacheInvalidateAnnoConfig> annoList = null; CacheInvalidate ci = m.getAnnotation(CacheInvalidate.class); if (ci != null) { annoList = new ArrayList<>(1); annoList.add(createCacheInvalidateAnnoConfig(ci, m)); } else { CacheInvalidateContainer cic = m.getAnnotation(CacheInvalidateContainer.class); if (cic != null) { CacheInvalidate[] cacheInvalidates = cic.value(); annoList = new ArrayList<>(cacheInvalidates.length); for (CacheInvalidate cacheInvalidate : cacheInvalidates) { annoList.add(createCacheInvalidateAnnoConfig(cacheInvalidate, m)); } } } return annoList; } private static CacheInvalidateAnnoConfig createCacheInvalidateAnnoConfig(CacheInvalidate anno, Method m) { CacheInvalidateAnnoConfig cc = new CacheInvalidateAnnoConfig(); cc.setArea(anno.area()); cc.setName(anno.name()); if (cc.getName() == null || cc.getName().trim().equals("")) { throw new CacheConfigException("name is required for @CacheInvalidate: " + m.getClass().getName() + "." + m.getName()); } cc.setKey(anno.key()); cc.setCondition(anno.condition()); cc.setMulti(anno.multi()); cc.setDefineMethod(m); return cc; } private static CacheUpdateAnnoConfig parseCacheUpdate(Method m) { CacheUpdate anno = m.getAnnotation(CacheUpdate.class); if (anno == null) { return null; } CacheUpdateAnnoConfig cc = new CacheUpdateAnnoConfig(); cc.setArea(anno.area()); cc.setName(anno.name()); if (cc.getName() == null || cc.getName().trim().equals("")) { throw new CacheConfigException("name is required for @CacheUpdate: " + m.getClass().getName() + "." + m.getName()); } cc.setKey(anno.key()); cc.setValue(anno.value()); if (cc.getValue() == null || cc.getValue().trim().equals("")) { throw new CacheConfigException("value is required for @CacheUpdate: " + m.getClass().getName() + "." + m.getName()); } cc.setCondition(anno.condition()); cc.setMulti(anno.multi()); cc.setDefineMethod(m); return cc; } private static boolean parseEnableCache(Method m) { EnableCache anno = m.getAnnotation(EnableCache.class); return anno != null; } public static boolean parse(CacheInvokeConfig cac, Method method) {<FILL_FUNCTION_BODY>} }
boolean hasAnnotation = false; CachedAnnoConfig cachedConfig = parseCached(method); if (cachedConfig != null) { cac.setCachedAnnoConfig(cachedConfig); hasAnnotation = true; } boolean enable = parseEnableCache(method); if (enable) { cac.setEnableCacheContext(true); hasAnnotation = true; } List<CacheInvalidateAnnoConfig> invalidateAnnoConfigs = parseCacheInvalidates(method); if (invalidateAnnoConfigs != null) { cac.setInvalidateAnnoConfigs(invalidateAnnoConfigs); hasAnnotation = true; } CacheUpdateAnnoConfig updateAnnoConfig = parseCacheUpdate(method); if (updateAnnoConfig != null) { cac.setUpdateAnnoConfig(updateAnnoConfig); hasAnnotation = true; } if (cachedConfig != null && (invalidateAnnoConfigs != null || updateAnnoConfig != null)) { throw new CacheConfigException("@Cached can't coexists with @CacheInvalidate or @CacheUpdate: " + method); } return hasAnnotation;
1,540
304
1,844
<no_super_class>
alibaba_jetcache
jetcache/jetcache-anno/src/main/java/com/alicp/jetcache/anno/method/ClassUtil.java
ClassUtil
getAllInterfaces
class ClassUtil { private static ConcurrentHashMap<Method, String> methodSigMap = new ConcurrentHashMap(); public static String getShortClassName(String className) { if (className == null) { return null; } String[] ss = className.split("\\."); StringBuilder sb = new StringBuilder(className.length()); for (int i = 0; i < ss.length; i++) { String s = ss[i]; if (i != ss.length - 1) { sb.append(s.charAt(0)).append('.'); } else { sb.append(s); } } return sb.toString(); } public static Class<?>[] getAllInterfaces(Object obj) {<FILL_FUNCTION_BODY>} private static void getMethodSig(StringBuilder sb, Method m) { sb.append(m.getName()); sb.append(Type.getType(m).getDescriptor()); } public static String getMethodSig(Method m) { String sig = methodSigMap.get(m); if (sig != null) { return sig; } else { StringBuilder sb = new StringBuilder(); getMethodSig(sb, m); sig = sb.toString(); methodSigMap.put(m, sig); return sig; } } }
Class<?> c = obj.getClass(); HashSet<Class<?>> s = new HashSet<>(); do { Class<?>[] its = c.getInterfaces(); Collections.addAll(s, its); c = c.getSuperclass(); } while (c != null); return s.toArray(new Class<?>[s.size()]);
360
102
462
<no_super_class>
alibaba_jetcache
jetcache/jetcache-anno/src/main/java/com/alicp/jetcache/anno/method/ExpressionEvaluator.java
SpelEvaluator
apply
class SpelEvaluator implements Function<Object, Object> { private static ExpressionParser parser; private static ParameterNameDiscoverer parameterNameDiscoverer; static { parser = new SpelExpressionParser(); parameterNameDiscoverer = new DefaultParameterNameDiscoverer(); } private final Expression expression; private String[] parameterNames; public SpelEvaluator(String script, Method defineMethod) { expression = parser.parseExpression(script); if (defineMethod.getParameterCount() > 0) { parameterNames = parameterNameDiscoverer.getParameterNames(defineMethod); } } @Override public Object apply(Object rootObject) {<FILL_FUNCTION_BODY>} }
EvaluationContext context = new StandardEvaluationContext(rootObject); CacheInvokeContext cic = (CacheInvokeContext) rootObject; if (parameterNames != null) { for (int i = 0; i < parameterNames.length; i++) { context.setVariable(parameterNames[i], cic.getArgs()[i]); } } context.setVariable("result", cic.getResult()); return expression.getValue(context);
190
116
306
<no_super_class>
alibaba_jetcache
jetcache/jetcache-anno/src/main/java/com/alicp/jetcache/anno/method/ExpressionUtil.java
ExpressionUtil
evalKey
class ExpressionUtil { private static final Logger logger = LoggerFactory.getLogger(ExpressionUtil.class); static Object EVAL_FAILED = new Object(); public static boolean evalCondition(CacheInvokeContext context, CacheAnnoConfig cac) { String condition = cac.getCondition(); try { if (cac.getConditionEvaluator() == null) { if (CacheConsts.isUndefined(condition)) { cac.setConditionEvaluator(o -> true); } else { ExpressionEvaluator e = new ExpressionEvaluator(condition, cac.getDefineMethod()); cac.setConditionEvaluator((o) -> (Boolean) e.apply(o)); } } return cac.getConditionEvaluator().apply(context); } catch (Exception e) { logger.error("error occurs when eval condition \"" + condition + "\" in " + context.getMethod() + ":" + e.getMessage(), e); return false; } } public static boolean evalPostCondition(CacheInvokeContext context, CachedAnnoConfig cac) { String postCondition = cac.getPostCondition(); try { if (cac.getPostConditionEvaluator() == null) { if (CacheConsts.isUndefined(postCondition)) { cac.setPostConditionEvaluator(o -> true); } else { ExpressionEvaluator e = new ExpressionEvaluator(postCondition, cac.getDefineMethod()); cac.setPostConditionEvaluator((o) -> (Boolean) e.apply(o)); } } return cac.getPostConditionEvaluator().apply(context); } catch (Exception e) { logger.error("error occurs when eval postCondition \"" + postCondition + "\" in " + context.getMethod() + ":" + e.getMessage(), e); return false; } } public static Object evalKey(CacheInvokeContext context, CacheAnnoConfig cac) {<FILL_FUNCTION_BODY>} public static Object evalValue(CacheInvokeContext context, CacheUpdateAnnoConfig cac) { String valueScript = cac.getValue(); try { if (cac.getValueEvaluator() == null) { ExpressionEvaluator e = new ExpressionEvaluator(valueScript, cac.getDefineMethod()); cac.setValueEvaluator((o) -> e.apply(o)); } return cac.getValueEvaluator().apply(context); } catch (Exception e) { logger.error("error occurs when eval value \"" + valueScript + "\" in " + context.getMethod() + ":" + e.getMessage(), e); return EVAL_FAILED; } } }
String keyScript = cac.getKey(); try { if (cac.getKeyEvaluator() == null) { if (CacheConsts.isUndefined(keyScript)) { cac.setKeyEvaluator(o -> { CacheInvokeContext c = (CacheInvokeContext) o; return c.getArgs() == null || c.getArgs().length == 0 ? "_$JETCACHE_NULL_KEY$_" : c.getArgs(); }); } else { ExpressionEvaluator e = new ExpressionEvaluator(keyScript, cac.getDefineMethod()); cac.setKeyEvaluator((o) -> e.apply(o)); } } return cac.getKeyEvaluator().apply(context); } catch (Exception e) { logger.error("error occurs when eval key \"" + keyScript + "\" in " + context.getMethod() + ":" + e.getMessage(), e); return null; }
722
256
978
<no_super_class>
alibaba_jetcache
jetcache/jetcache-anno/src/main/java/com/alicp/jetcache/anno/method/ProxyUtil.java
ProxyUtil
processMethod
class ProxyUtil { public static <T> T getProxyByAnnotation(T target, ConfigProvider configProvider, CacheManager cacheManager) { final ConfigMap configMap = new ConfigMap(); processType(configMap, target.getClass()); Class<?>[] its = ClassUtil.getAllInterfaces(target); CacheHandler h = new CacheHandler(target, configMap, () -> configProvider.newContext(cacheManager).createCacheInvokeContext(configMap), configProvider.getGlobalCacheConfig().getHiddenPackages()); Object o = Proxy.newProxyInstance(target.getClass().getClassLoader(), its, h); return (T) o; } private static void processType(ConfigMap configMap, Class<?> clazz) { if (clazz.isAnnotation() || clazz.isArray() || clazz.isEnum() || clazz.isPrimitive()) { throw new IllegalArgumentException(clazz.getName()); } if (clazz.getName().startsWith("java")) { return; } Method[] methods = clazz.getDeclaredMethods(); for (Method m : methods) { if (Modifier.isPublic(m.getModifiers())) { processMethod(configMap, m); } } Class<?>[] interfaces = clazz.getInterfaces(); for (Class<?> it : interfaces) { processType(configMap, it); } if (!clazz.isInterface()) { if (clazz.getSuperclass() != null) { processType(configMap, clazz.getSuperclass()); } } } private static void processMethod(ConfigMap configMap, Method m) {<FILL_FUNCTION_BODY>} }
String sig = ClassUtil.getMethodSig(m); CacheInvokeConfig cac = configMap.getByMethodInfo(sig); if (cac == null) { cac = new CacheInvokeConfig(); if (CacheConfigUtil.parse(cac, m)) { configMap.putByMethodInfo(sig, cac); } } else { CacheConfigUtil.parse(cac, m); }
445
113
558
<no_super_class>
alibaba_jetcache
jetcache/jetcache-anno/src/main/java/com/alicp/jetcache/anno/support/CacheContext.java
CacheContext
__createOrGetCache
class CacheContext { private static Logger logger = LoggerFactory.getLogger(CacheContext.class); private static ThreadLocal<CacheThreadLocal> cacheThreadLocal = new ThreadLocal<CacheThreadLocal>() { @Override protected CacheThreadLocal initialValue() { return new CacheThreadLocal(); } }; private ConfigProvider configProvider; private GlobalCacheConfig globalCacheConfig; private CacheManager cacheManager; public CacheContext(CacheManager cacheManager, ConfigProvider configProvider, GlobalCacheConfig globalCacheConfig) { this.cacheManager = cacheManager; this.globalCacheConfig = globalCacheConfig; this.configProvider = configProvider; } public CacheInvokeContext createCacheInvokeContext(ConfigMap configMap) { CacheInvokeContext c = newCacheInvokeContext(); c.setCacheFunction((cic, cac) -> createOrGetCache(cic, cac, configMap)); return c; } private Cache createOrGetCache(CacheInvokeContext invokeContext, CacheAnnoConfig cacheAnnoConfig, ConfigMap configMap) { Cache cache = cacheAnnoConfig.getCache(); if (cache != null) { return cache; } if (cacheAnnoConfig instanceof CachedAnnoConfig) { cache = createCacheByCachedConfig((CachedAnnoConfig) cacheAnnoConfig, invokeContext); } else if ((cacheAnnoConfig instanceof CacheInvalidateAnnoConfig) || (cacheAnnoConfig instanceof CacheUpdateAnnoConfig)) { cache = cacheManager.getCache(cacheAnnoConfig.getArea(), cacheAnnoConfig.getName()); if (cache == null) { CachedAnnoConfig cac = configMap.getByCacheName(cacheAnnoConfig.getArea(), cacheAnnoConfig.getName()); if (cac == null) { String message = "can't find cache definition with area=" + cacheAnnoConfig.getArea() + " name=" + cacheAnnoConfig.getName() + ", specified in " + cacheAnnoConfig.getDefineMethod(); CacheConfigException e = new CacheConfigException(message); logger.error("Cache operation aborted because can't find cached definition", e); return null; } cache = createCacheByCachedConfig(cac, invokeContext); } } cacheAnnoConfig.setCache(cache); return cache; } private Cache createCacheByCachedConfig(CachedAnnoConfig ac, CacheInvokeContext invokeContext) { String area = ac.getArea(); String cacheName = ac.getName(); if (CacheConsts.isUndefined(cacheName)) { cacheName = configProvider.createCacheNameGenerator(invokeContext.getHiddenPackages()) .generateCacheName(invokeContext.getMethod(), invokeContext.getTargetObject()); } Cache cache = __createOrGetCache(ac, area, cacheName); return cache; } public Cache __createOrGetCache(CachedAnnoConfig cac, String area, String cacheName) {<FILL_FUNCTION_BODY>} protected CacheInvokeContext newCacheInvokeContext() { return new CacheInvokeContext(); } /** * Enable cache in current thread, for @Cached(enabled=false). * * @param callback * @see EnableCache */ public static <T> T enableCache(Supplier<T> callback) { CacheThreadLocal var = cacheThreadLocal.get(); try { var.setEnabledCount(var.getEnabledCount() + 1); return callback.get(); } finally { var.setEnabledCount(var.getEnabledCount() - 1); } } protected static void enable() { CacheThreadLocal var = cacheThreadLocal.get(); var.setEnabledCount(var.getEnabledCount() + 1); } protected static void disable() { CacheThreadLocal var = cacheThreadLocal.get(); var.setEnabledCount(var.getEnabledCount() - 1); } protected static boolean isEnabled() { return cacheThreadLocal.get().getEnabledCount() > 0; } }
QuickConfig.Builder b = QuickConfig.newBuilder(area, cacheName); TimeUnit timeUnit = cac.getTimeUnit(); if (cac.getExpire() > 0) { b.expire(Duration.ofMillis(timeUnit.toMillis(cac.getExpire()))); } if (cac.getLocalExpire() > 0) { b.localExpire(Duration.ofMillis(timeUnit.toMillis(cac.getLocalExpire()))); } if (cac.getLocalLimit() > 0) { b.localLimit(cac.getLocalLimit()); } b.cacheType(cac.getCacheType()); b.syncLocal(cac.isSyncLocal()); if (!CacheConsts.isUndefined(cac.getKeyConvertor())) { b.keyConvertor(configProvider.parseKeyConvertor(cac.getKeyConvertor())); } if (!CacheConsts.isUndefined(cac.getSerialPolicy())) { b.valueEncoder(configProvider.parseValueEncoder(cac.getSerialPolicy())); b.valueDecoder(configProvider.parseValueDecoder(cac.getSerialPolicy())); } b.cacheNullValue(cac.isCacheNullValue()); b.useAreaInPrefix(globalCacheConfig.isAreaInCacheName()); PenetrationProtectConfig ppc = cac.getPenetrationProtectConfig(); if (ppc != null) { b.penetrationProtect(ppc.isPenetrationProtect()); b.penetrationProtectTimeout(ppc.getPenetrationProtectTimeout()); } b.refreshPolicy(cac.getRefreshPolicy()); return cacheManager.getOrCreateCache(b.build());
1,044
457
1,501
<no_super_class>
alibaba_jetcache
jetcache/jetcache-anno/src/main/java/com/alicp/jetcache/anno/support/ConfigMap.java
ConfigMap
putByMethodInfo
class ConfigMap { private ConcurrentHashMap<String, CacheInvokeConfig> methodInfoMap = new ConcurrentHashMap<>(); private ConcurrentHashMap<String, CachedAnnoConfig> cacheNameMap = new ConcurrentHashMap<>(); public void putByMethodInfo(String key, CacheInvokeConfig config) {<FILL_FUNCTION_BODY>} public CacheInvokeConfig getByMethodInfo(String key) { return methodInfoMap.get(key); } public CachedAnnoConfig getByCacheName(String area, String cacheName) { return cacheNameMap.get(area + "_" + cacheName); } }
methodInfoMap.put(key, config); CachedAnnoConfig cac = config.getCachedAnnoConfig(); if (cac != null && !CacheConsts.isUndefined(cac.getName())) { cacheNameMap.put(cac.getArea() + "_" + cac.getName(), cac); }
165
89
254
<no_super_class>
alibaba_jetcache
jetcache/jetcache-anno/src/main/java/com/alicp/jetcache/anno/support/ConfigProvider.java
ConfigProvider
doInit
class ConfigProvider extends AbstractLifecycle { private static final Logger logger = LoggerFactory.getLogger(ConfigProvider.class); protected GlobalCacheConfig globalCacheConfig; protected EncoderParser encoderParser; protected KeyConvertorParser keyConvertorParser; private Consumer<StatInfo> metricsCallback; private CacheBuilderTemplate cacheBuilderTemplate; public ConfigProvider() { encoderParser = new DefaultEncoderParser(); keyConvertorParser = new DefaultKeyConvertorParser(); metricsCallback = new StatInfoLogger(false); } @Override protected void doInit() {<FILL_FUNCTION_BODY>} protected void initCacheMonitorInstallers() { cacheBuilderTemplate.getCacheMonitorInstallers().add(metricsMonitorInstaller()); cacheBuilderTemplate.getCacheMonitorInstallers().add(notifyMonitorInstaller()); for (CacheMonitorInstaller i : cacheBuilderTemplate.getCacheMonitorInstallers()) { if (i instanceof AbstractLifecycle) { ((AbstractLifecycle) i).init(); } } } protected CacheMonitorInstaller metricsMonitorInstaller() { Duration interval = null; if (globalCacheConfig.getStatIntervalMinutes() > 0) { interval = Duration.ofMinutes(globalCacheConfig.getStatIntervalMinutes()); } MetricsMonitorInstaller i = new MetricsMonitorInstaller(metricsCallback, interval); i.init(); return i; } protected CacheMonitorInstaller notifyMonitorInstaller() { return new NotifyMonitorInstaller(area -> globalCacheConfig.getRemoteCacheBuilders().get(area)); } public CacheBuilderTemplate getCacheBuilderTemplate() { return cacheBuilderTemplate; } @Override public void doShutdown() { try { for (CacheMonitorInstaller i : cacheBuilderTemplate.getCacheMonitorInstallers()) { if (i instanceof AbstractLifecycle) { ((AbstractLifecycle) i).shutdown(); } } } catch (Exception e) { logger.error("close fail", e); } } /** * Keep this method for backward compatibility. * NOTICE: there is no getter for encoderParser. */ public Function<Object, byte[]> parseValueEncoder(String valueEncoder) { return encoderParser.parseEncoder(valueEncoder); } /** * Keep this method for backward compatibility. * NOTICE: there is no getter for encoderParser. */ public Function<byte[], Object> parseValueDecoder(String valueDecoder) { return encoderParser.parseDecoder(valueDecoder); } /** * Keep this method for backward compatibility. * NOTICE: there is no getter for keyConvertorParser. */ public Function<Object, Object> parseKeyConvertor(String convertor) { return keyConvertorParser.parseKeyConvertor(convertor); } public CacheNameGenerator createCacheNameGenerator(String[] hiddenPackages) { return new DefaultCacheNameGenerator(hiddenPackages); } public CacheContext newContext(CacheManager cacheManager) { return new CacheContext(cacheManager, this, globalCacheConfig); } public void setEncoderParser(EncoderParser encoderParser) { this.encoderParser = encoderParser; } public void setKeyConvertorParser(KeyConvertorParser keyConvertorParser) { this.keyConvertorParser = keyConvertorParser; } public GlobalCacheConfig getGlobalCacheConfig() { return globalCacheConfig; } public void setGlobalCacheConfig(GlobalCacheConfig globalCacheConfig) { this.globalCacheConfig = globalCacheConfig; } public void setMetricsCallback(Consumer<StatInfo> metricsCallback) { this.metricsCallback = metricsCallback; } }
cacheBuilderTemplate = new CacheBuilderTemplate(globalCacheConfig.isPenetrationProtect(), globalCacheConfig.getLocalCacheBuilders(), globalCacheConfig.getRemoteCacheBuilders()); for (CacheBuilder builder : globalCacheConfig.getLocalCacheBuilders().values()) { EmbeddedCacheBuilder eb = (EmbeddedCacheBuilder) builder; if (eb.getConfig().getKeyConvertor() instanceof ParserFunction) { ParserFunction f = (ParserFunction) eb.getConfig().getKeyConvertor(); eb.setKeyConvertor(parseKeyConvertor(f.getValue())); } } for (CacheBuilder builder : globalCacheConfig.getRemoteCacheBuilders().values()) { ExternalCacheBuilder eb = (ExternalCacheBuilder) builder; if (eb.getConfig().getKeyConvertor() instanceof ParserFunction) { ParserFunction f = (ParserFunction) eb.getConfig().getKeyConvertor(); eb.setKeyConvertor(parseKeyConvertor(f.getValue())); } if (eb.getConfig().getValueEncoder() instanceof ParserFunction) { ParserFunction f = (ParserFunction) eb.getConfig().getValueEncoder(); eb.setValueEncoder(parseValueEncoder(f.getValue())); } if (eb.getConfig().getValueDecoder() instanceof ParserFunction) { ParserFunction f = (ParserFunction) eb.getConfig().getValueDecoder(); eb.setValueDecoder(parseValueDecoder(f.getValue())); } } initCacheMonitorInstallers();
976
392
1,368
<methods>public non-sealed void <init>() ,public final void init() ,public final void shutdown() <variables>private boolean init,final java.util.concurrent.locks.ReentrantLock reentrantLock,private boolean shutdown
alibaba_jetcache
jetcache/jetcache-anno/src/main/java/com/alicp/jetcache/anno/support/DefaultCacheNameGenerator.java
DefaultCacheNameGenerator
getDescriptor
class DefaultCacheNameGenerator implements CacheNameGenerator { protected final String[] hiddenPackages; protected final ConcurrentHashMap<Method, String> cacheNameMap = new ConcurrentHashMap(); public DefaultCacheNameGenerator(String[] hiddenPackages) { this.hiddenPackages = hiddenPackages; } @Override public String generateCacheName(Method method, Object targetObject) { String cacheName = cacheNameMap.get(method); if (cacheName == null) { final StringBuilder sb = new StringBuilder(); String className = method.getDeclaringClass().getName(); sb.append(ClassUtil.getShortClassName(removeHiddenPackage(hiddenPackages, className))); sb.append('.'); sb.append(method.getName()); sb.append('('); for(Class<?> c : method.getParameterTypes()){ getDescriptor(sb, c , hiddenPackages); } sb.append(')'); String str = sb.toString(); cacheNameMap.put(method, str); return str; } return cacheName; } @Override public String generateCacheName(Field field) { StringBuilder sb = new StringBuilder(); String className = field.getDeclaringClass().getName(); className = removeHiddenPackage(hiddenPackages, className); className = ClassUtil.getShortClassName(className); sb.append(className); sb.append(".").append(field.getName()); return sb.toString(); } @SuppressWarnings("PMD.AvoidPatternCompileInMethodRule") protected String removeHiddenPackage(String[] hiddenPackages, String packageOrFullClassName) { if (hiddenPackages != null && packageOrFullClassName != null) { for (String p : hiddenPackages) { if (p != null && packageOrFullClassName.startsWith(p)) { packageOrFullClassName = Pattern.compile(p, Pattern.LITERAL).matcher( packageOrFullClassName).replaceFirst(""); if (packageOrFullClassName.length() > 0 && packageOrFullClassName.charAt(0) == '.') { packageOrFullClassName = packageOrFullClassName.substring(1); } return packageOrFullClassName; } } } return packageOrFullClassName; } protected void getDescriptor(final StringBuilder sb, final Class<?> c, String[] hiddenPackages) {<FILL_FUNCTION_BODY>} }
Class<?> d = c; while (true) { if (d.isPrimitive()) { char car; if (d == Integer.TYPE) { car = 'I'; } else if (d == Void.TYPE) { car = 'V'; } else if (d == Boolean.TYPE) { car = 'Z'; } else if (d == Byte.TYPE) { car = 'B'; } else if (d == Character.TYPE) { car = 'C'; } else if (d == Short.TYPE) { car = 'S'; } else if (d == Double.TYPE) { car = 'D'; } else if (d == Float.TYPE) { car = 'F'; } else /* if (d == Long.TYPE) */{ car = 'J'; } sb.append(car); return; } else if (d.isArray()) { sb.append('['); d = d.getComponentType(); } else { sb.append('L'); String name = d.getName(); name = removeHiddenPackage(hiddenPackages, name); name = ClassUtil.getShortClassName(name); sb.append(name); sb.append(';'); return; } }
644
340
984
<no_super_class>
alibaba_jetcache
jetcache/jetcache-anno/src/main/java/com/alicp/jetcache/anno/support/DefaultEncoderParser.java
DefaultEncoderParser
parseQueryParameters
class DefaultEncoderParser implements EncoderParser { protected static Map<String, String> parseQueryParameters(String query) {<FILL_FUNCTION_BODY>} JavaValueDecoder javaValueDecoder(boolean useIdentityNumber) { return new JavaValueDecoder(useIdentityNumber); } @Override public Function<Object, byte[]> parseEncoder(String valueEncoder) { if (valueEncoder == null) { throw new CacheConfigException("no serialPolicy"); } valueEncoder = valueEncoder.trim(); URI uri = URI.create(valueEncoder); valueEncoder = uri.getPath(); boolean useIdentityNumber = isUseIdentityNumber(uri); if (SerialPolicy.KRYO.equalsIgnoreCase(valueEncoder)) { return new KryoValueEncoder(useIdentityNumber); } else if (SerialPolicy.JAVA.equalsIgnoreCase(valueEncoder)) { return new JavaValueEncoder(useIdentityNumber); } else if (SerialPolicy.KRYO5.equalsIgnoreCase(valueEncoder)) { return new Kryo5ValueEncoder(useIdentityNumber); }/* else if (SerialPolicy.FASTJSON2.equalsIgnoreCase(valueEncoder)) { return new Fastjson2ValueEncoder(useIdentityNumber); }*/ else { throw new CacheConfigException("not supported:" + valueEncoder); } } private boolean isUseIdentityNumber(URI uri) { Map<String, String> params = parseQueryParameters(uri.getQuery()); boolean useIdentityNumber = true; if ("false".equalsIgnoreCase(params.get("useIdentityNumber"))) { useIdentityNumber = false; } return useIdentityNumber; } @Override public Function<byte[], Object> parseDecoder(String valueDecoder) { if (valueDecoder == null) { throw new CacheConfigException("no serialPolicy"); } valueDecoder = valueDecoder.trim(); URI uri = URI.create(valueDecoder); valueDecoder = uri.getPath(); boolean useIdentityNumber = isUseIdentityNumber(uri); if (SerialPolicy.KRYO.equalsIgnoreCase(valueDecoder)) { return new KryoValueDecoder(useIdentityNumber); } else if (SerialPolicy.JAVA.equalsIgnoreCase(valueDecoder)) { return javaValueDecoder(useIdentityNumber); } else if (SerialPolicy.KRYO5.equalsIgnoreCase(valueDecoder)) { return new Kryo5ValueDecoder(useIdentityNumber); }/* else if (SerialPolicy.FASTJSON2.equalsIgnoreCase(valueDecoder)) { return new Kryo5ValueDecoder(useIdentityNumber); }*/ else { throw new CacheConfigException("not supported:" + valueDecoder); } } }
Map<String, String> m = new HashMap<>(); if (query != null) { String[] pairs = query.split("&"); for (String pair : pairs) { int idx = pair.indexOf("="); String key = idx > 0 ? pair.substring(0, idx) : pair; String value = idx > 0 && pair.length() > idx + 1 ? pair.substring(idx + 1) : null; if (key != null && value != null) { m.put(key, value); } } } return m;
718
151
869
<no_super_class>
alibaba_jetcache
jetcache/jetcache-anno/src/main/java/com/alicp/jetcache/anno/support/DefaultKeyConvertorParser.java
DefaultKeyConvertorParser
parseKeyConvertor
class DefaultKeyConvertorParser implements KeyConvertorParser { @Override public Function<Object, Object> parseKeyConvertor(String convertor) {<FILL_FUNCTION_BODY>} }
if (convertor == null) { return null; } if (KeyConvertor.FASTJSON.equalsIgnoreCase(convertor)) { return FastjsonKeyConvertor.INSTANCE; } else if (KeyConvertor.FASTJSON2.equalsIgnoreCase(convertor)) { return Fastjson2KeyConvertor.INSTANCE; } else if (KeyConvertor.JACKSON.equalsIgnoreCase(convertor)) { return JacksonKeyConvertor.INSTANCE; } else if (KeyConvertor.NONE.equalsIgnoreCase(convertor)) { return KeyConvertor.NONE_INSTANCE; } throw new CacheConfigException("not supported:" + convertor);
50
174
224
<no_super_class>
alibaba_jetcache
jetcache/jetcache-anno/src/main/java/com/alicp/jetcache/anno/support/DefaultSpringEncoderParser.java
DefaultSpringEncoderParser
parseDecoder
class DefaultSpringEncoderParser extends DefaultEncoderParser implements ApplicationContextAware { private ApplicationContext applicationContext; static String parseBeanName(String str) { final String beanPrefix = "bean:"; int len = beanPrefix.length(); if (str != null && str.startsWith(beanPrefix) && str.length() > len) { return str.substring(len); } else { return null; } } @Override public Function<Object, byte[]> parseEncoder(String valueEncoder) { String beanName = parseBeanName(valueEncoder); if (beanName == null) { return super.parseEncoder(valueEncoder); } else { Object bean = applicationContext.getBean(beanName); if (bean instanceof Function) { return (Function<Object, byte[]>) bean; } else { return ((SerialPolicy) bean).encoder(); } } } @Override public Function<byte[], Object> parseDecoder(String valueDecoder) {<FILL_FUNCTION_BODY>} @Override JavaValueDecoder javaValueDecoder(boolean useIdentityNumber) { return new SpringJavaValueDecoder(useIdentityNumber); } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } }
String beanName = parseBeanName(valueDecoder); if (beanName == null) { return super.parseDecoder(valueDecoder); } else { Object bean = applicationContext.getBean(beanName); if (bean instanceof Function) { return (Function<byte[], Object>) bean; } else { return ((SerialPolicy)bean).decoder(); } }
358
105
463
<methods>public non-sealed void <init>() ,public Function<byte[],java.lang.Object> parseDecoder(java.lang.String) ,public Function<java.lang.Object,byte[]> parseEncoder(java.lang.String) <variables>
alibaba_jetcache
jetcache/jetcache-anno/src/main/java/com/alicp/jetcache/anno/support/DefaultSpringKeyConvertorParser.java
DefaultSpringKeyConvertorParser
parseKeyConvertor
class DefaultSpringKeyConvertorParser extends DefaultKeyConvertorParser implements ApplicationContextAware { private ApplicationContext applicationContext; @Override public Function<Object, Object> parseKeyConvertor(String convertor) {<FILL_FUNCTION_BODY>} @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } }
String beanName = DefaultSpringEncoderParser.parseBeanName(convertor); if (beanName == null) { return super.parseKeyConvertor(convertor); } else { return (Function<Object, Object>) applicationContext.getBean(beanName); }
104
74
178
<methods>public non-sealed void <init>() ,public Function<java.lang.Object,java.lang.Object> parseKeyConvertor(java.lang.String) <variables>
alibaba_jetcache
jetcache/jetcache-anno/src/main/java/com/alicp/jetcache/anno/support/JetCacheBaseBeans.java
JetCacheBaseBeans
springConfigProvider
class JetCacheBaseBeans { protected SpringConfigProvider createConfigProvider() { return new SpringConfigProvider(); } @Bean(destroyMethod = "shutdown") public SpringConfigProvider springConfigProvider( @Autowired ApplicationContext applicationContext, @Autowired GlobalCacheConfig globalCacheConfig, @Autowired(required = false) EncoderParser encoderParser, @Autowired(required = false) KeyConvertorParser keyConvertorParser, @Autowired(required = false) Consumer<StatInfo> metricsCallback) {<FILL_FUNCTION_BODY>} @Bean(name = "jcCacheManager",destroyMethod = "close") public SimpleCacheManager cacheManager(@Autowired ConfigProvider configProvider) { SimpleCacheManager cacheManager = new SimpleCacheManager(); cacheManager.setCacheBuilderTemplate(configProvider.getCacheBuilderTemplate()); return cacheManager; } }
SpringConfigProvider cp = createConfigProvider(); cp.setApplicationContext(applicationContext); cp.setGlobalCacheConfig(globalCacheConfig); if (encoderParser != null) { cp.setEncoderParser(encoderParser); } if (keyConvertorParser != null) { cp.setKeyConvertorParser(keyConvertorParser); } if (metricsCallback != null) { cp.setMetricsCallback(metricsCallback); } cp.init(); return cp;
229
138
367
<no_super_class>
alibaba_jetcache
jetcache/jetcache-anno/src/main/java/com/alicp/jetcache/anno/support/SpringConfigProvider.java
SpringConfigProvider
doInit
class SpringConfigProvider extends ConfigProvider implements ApplicationContextAware { private ApplicationContext applicationContext; public SpringConfigProvider() { super(); encoderParser = new DefaultSpringEncoderParser(); keyConvertorParser = new DefaultSpringKeyConvertorParser(); } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } @Override protected void doInit() {<FILL_FUNCTION_BODY>} @Override public CacheContext newContext(CacheManager cacheManager) { return new SpringCacheContext(cacheManager, this, globalCacheConfig, applicationContext); } @Autowired(required = false) @Override public void setEncoderParser(EncoderParser encoderParser) { super.setEncoderParser(encoderParser); } @Autowired(required = false) @Override public void setKeyConvertorParser(KeyConvertorParser keyConvertorParser) { super.setKeyConvertorParser(keyConvertorParser); } @Autowired(required = false) @Override public void setMetricsCallback(Consumer<StatInfo> metricsCallback) { super.setMetricsCallback(metricsCallback); } }
if (encoderParser instanceof ApplicationContextAware) { ((ApplicationContextAware) encoderParser).setApplicationContext(applicationContext); } if (keyConvertorParser instanceof ApplicationContextAware) { ((ApplicationContextAware) keyConvertorParser).setApplicationContext(applicationContext); } super.doInit();
323
83
406
<methods>public void <init>() ,public com.alicp.jetcache.anno.support.CacheNameGenerator createCacheNameGenerator(java.lang.String[]) ,public void doShutdown() ,public com.alicp.jetcache.template.CacheBuilderTemplate getCacheBuilderTemplate() ,public com.alicp.jetcache.anno.support.GlobalCacheConfig getGlobalCacheConfig() ,public com.alicp.jetcache.anno.support.CacheContext newContext(com.alicp.jetcache.CacheManager) ,public Function<java.lang.Object,java.lang.Object> parseKeyConvertor(java.lang.String) ,public Function<byte[],java.lang.Object> parseValueDecoder(java.lang.String) ,public Function<java.lang.Object,byte[]> parseValueEncoder(java.lang.String) ,public void setEncoderParser(com.alicp.jetcache.anno.support.EncoderParser) ,public void setGlobalCacheConfig(com.alicp.jetcache.anno.support.GlobalCacheConfig) ,public void setKeyConvertorParser(com.alicp.jetcache.anno.support.KeyConvertorParser) ,public void setMetricsCallback(Consumer<com.alicp.jetcache.support.StatInfo>) <variables>private com.alicp.jetcache.template.CacheBuilderTemplate cacheBuilderTemplate,protected com.alicp.jetcache.anno.support.EncoderParser encoderParser,protected com.alicp.jetcache.anno.support.GlobalCacheConfig globalCacheConfig,protected com.alicp.jetcache.anno.support.KeyConvertorParser keyConvertorParser,private static final Logger logger,private Consumer<com.alicp.jetcache.support.StatInfo> metricsCallback
alibaba_jetcache
jetcache/jetcache-core/src/main/java/com/alicp/jetcache/AbstractCacheBuilder.java
AbstractCacheBuilder
buildCache
class AbstractCacheBuilder<T extends AbstractCacheBuilder<T>> implements CacheBuilder, Cloneable { protected CacheConfig config; private Function<CacheConfig, Cache> buildFunc; public abstract CacheConfig getConfig(); protected T self() { return (T) this; } public T buildFunc(Function<CacheConfig, Cache> buildFunc) { this.buildFunc = buildFunc; return self(); } protected void beforeBuild() { } @Deprecated public final <K, V> Cache<K, V> build() { return buildCache(); } @Override public final <K, V> Cache<K, V> buildCache() {<FILL_FUNCTION_BODY>} @Override public Object clone() { AbstractCacheBuilder copy = null; try { copy = (AbstractCacheBuilder) super.clone(); copy.config = getConfig().clone(); return copy; } catch (CloneNotSupportedException e) { throw new CacheException(e); } } public T keyConvertor(Function<Object, Object> keyConvertor) { getConfig().setKeyConvertor(keyConvertor); return self(); } public void setKeyConvertor(Function<Object, Object> keyConvertor) { getConfig().setKeyConvertor(keyConvertor); } public T expireAfterAccess(long defaultExpire, TimeUnit timeUnit) { getConfig().setExpireAfterAccessInMillis(timeUnit.toMillis(defaultExpire)); return self(); } public void setExpireAfterAccessInMillis(long expireAfterAccessInMillis) { getConfig().setExpireAfterAccessInMillis(expireAfterAccessInMillis); } public T expireAfterWrite(long defaultExpire, TimeUnit timeUnit) { getConfig().setExpireAfterWriteInMillis(timeUnit.toMillis(defaultExpire)); return self(); } public void setExpireAfterWriteInMillis(long expireAfterWriteInMillis) { getConfig().setExpireAfterWriteInMillis(expireAfterWriteInMillis); } public T addMonitor(CacheMonitor monitor) { getConfig().getMonitors().add(monitor); return self(); } public void setMonitors(List<CacheMonitor> monitors) { getConfig().setMonitors(monitors); } public T cacheNullValue(boolean cacheNullValue) { getConfig().setCacheNullValue(cacheNullValue); return self(); } public void setCacheNullValue(boolean cacheNullValue) { getConfig().setCacheNullValue(cacheNullValue); } public <K, V> T loader(CacheLoader<K, V> loader) { getConfig().setLoader(loader); return self(); } public <K, V> void setLoader(CacheLoader<K, V> loader) { getConfig().setLoader(loader); } public T refreshPolicy(RefreshPolicy refreshPolicy) { getConfig().setRefreshPolicy(refreshPolicy); return self(); } public void setRefreshPolicy(RefreshPolicy refreshPolicy) { getConfig().setRefreshPolicy(refreshPolicy); } public T cachePenetrateProtect(boolean cachePenetrateProtect) { getConfig().setCachePenetrationProtect(cachePenetrateProtect); return self(); } public void setCachePenetrateProtect(boolean cachePenetrateProtect) { getConfig().setCachePenetrationProtect(cachePenetrateProtect); } }
if (buildFunc == null) { throw new CacheConfigException("no buildFunc"); } beforeBuild(); CacheConfig c = getConfig().clone(); Cache<K, V> cache = buildFunc.apply(c); if (c.getLoader() != null) { if (c.getRefreshPolicy() == null) { cache = new LoadingCache<>(cache); } else { cache = new RefreshCache<>(cache); } } return cache;
946
130
1,076
<no_super_class>
alibaba_jetcache
jetcache/jetcache-core/src/main/java/com/alicp/jetcache/CacheConfig.java
CacheConfig
clone
class CacheConfig<K, V> implements Cloneable { private long expireAfterWriteInMillis = CacheConsts.DEFAULT_EXPIRE * 1000L; private long expireAfterAccessInMillis = 0; private Function<K, Object> keyConvertor; private CacheLoader<K, V> loader; private List<CacheMonitor> monitors = new ArrayList<>(); private boolean cacheNullValue = false; private RefreshPolicy refreshPolicy; private int tryLockUnlockCount = 2; private int tryLockInquiryCount = 1; private int tryLockLockCount = 2; private boolean cachePenetrationProtect = false; private Duration penetrationProtectTimeout = null; @Override public CacheConfig clone() {<FILL_FUNCTION_BODY>} public Function<K, Object> getKeyConvertor() { return keyConvertor; } public void setKeyConvertor(Function<K, Object> keyConvertor) { this.keyConvertor = keyConvertor; } public boolean isExpireAfterAccess() { return expireAfterAccessInMillis > 0; } public boolean isExpireAfterWrite() { return expireAfterWriteInMillis > 0; } @Deprecated public long getDefaultExpireInMillis() { return expireAfterWriteInMillis; } @Deprecated public void setDefaultExpireInMillis(long defaultExpireInMillis) { this.expireAfterWriteInMillis = defaultExpireInMillis; } public long getExpireAfterWriteInMillis() { return expireAfterWriteInMillis; } public void setExpireAfterWriteInMillis(long expireAfterWriteInMillis) { this.expireAfterWriteInMillis = expireAfterWriteInMillis; } public long getExpireAfterAccessInMillis() { return expireAfterAccessInMillis; } public void setExpireAfterAccessInMillis(long expireAfterAccessInMillis) { this.expireAfterAccessInMillis = expireAfterAccessInMillis; } public CacheLoader<K, V> getLoader() { return loader; } public void setLoader(CacheLoader<K, V> loader) { this.loader = loader; } public boolean isCacheNullValue() { return cacheNullValue; } public void setCacheNullValue(boolean cacheNullValue) { this.cacheNullValue = cacheNullValue; } public List<CacheMonitor> getMonitors() { return monitors; } public void setMonitors(List<CacheMonitor> monitors) { this.monitors = monitors; } public RefreshPolicy getRefreshPolicy() { return refreshPolicy; } public void setRefreshPolicy(RefreshPolicy refreshPolicy) { this.refreshPolicy = refreshPolicy; } public int getTryLockUnlockCount() { return tryLockUnlockCount; } public void setTryLockUnlockCount(int tryLockUnlockCount) { this.tryLockUnlockCount = tryLockUnlockCount; } public int getTryLockInquiryCount() { return tryLockInquiryCount; } public void setTryLockInquiryCount(int tryLockInquiryCount) { this.tryLockInquiryCount = tryLockInquiryCount; } public int getTryLockLockCount() { return tryLockLockCount; } public void setTryLockLockCount(int tryLockLockCount) { this.tryLockLockCount = tryLockLockCount; } public boolean isCachePenetrationProtect() { return cachePenetrationProtect; } public void setCachePenetrationProtect(boolean cachePenetrationProtect) { this.cachePenetrationProtect = cachePenetrationProtect; } public Duration getPenetrationProtectTimeout() { return penetrationProtectTimeout; } public void setPenetrationProtectTimeout(Duration penetrationProtectTimeout) { this.penetrationProtectTimeout = penetrationProtectTimeout; } }
try { CacheConfig copy = (CacheConfig) super.clone(); if (monitors != null) { copy.monitors = new ArrayList(this.monitors); } if (refreshPolicy != null) { copy.refreshPolicy = this.refreshPolicy.clone(); } return copy; } catch (CloneNotSupportedException e) { throw new CacheException(e); }
1,111
112
1,223
<no_super_class>
alibaba_jetcache
jetcache/jetcache-core/src/main/java/com/alicp/jetcache/CacheGetResult.java
CacheGetResult
unwrapValue
class CacheGetResult<V> extends CacheResult { private volatile V value; private volatile CacheValueHolder<V> holder; public static final CacheGetResult NOT_EXISTS_WITHOUT_MSG = new CacheGetResult(CacheResultCode.NOT_EXISTS, null, null); public static final CacheGetResult EXPIRED_WITHOUT_MSG = new CacheGetResult(CacheResultCode.EXPIRED, null ,null); public CacheGetResult(CacheResultCode resultCode, String message, CacheValueHolder<V> holder) { super(CompletableFuture.completedFuture(new ResultData(resultCode, message, holder))); } public CacheGetResult(CompletionStage<ResultData> future) { super(future); } public CacheGetResult(Throwable ex) { super(ex); } public V getValue() { waitForResult(); return value; } @Override protected void fetchResultSuccess(ResultData resultData) { holder = (CacheValueHolder<V>) resultData.getOriginData(); value = (V) unwrapValue(holder); super.fetchResultSuccess(resultData); } static Object unwrapValue(Object holder) {<FILL_FUNCTION_BODY>} @Override protected void fetchResultFail(Throwable e) { value = null; super.fetchResultFail(e); } protected CacheValueHolder<V> getHolder() { waitForResult(); return holder; } }
// if @Cached or @CacheCache change type from REMOTE to BOTH (or from BOTH to REMOTE), // during the dev/publish process, the value type which different application server put into cache server will be different // (CacheValueHolder<V> and CacheValueHolder<CacheValueHolder<V>>, respectively). // So we need correct the problem at here and in MultiLevelCache.unwrapHolder Object v = holder; while (v != null && v instanceof CacheValueHolder) { v = ((CacheValueHolder) v).getValue(); } return v;
387
150
537
<methods>public void <init>(CompletionStage<com.alicp.jetcache.ResultData>) ,public void <init>(com.alicp.jetcache.CacheResultCode, java.lang.String) ,public void <init>(java.lang.Throwable) ,public CompletionStage<com.alicp.jetcache.ResultData> future() ,public java.lang.String getMessage() ,public com.alicp.jetcache.CacheResultCode getResultCode() ,public boolean isSuccess() ,public static void setDefaultTimeout(java.time.Duration) ,public void setTimeout(java.time.Duration) ,public void waitForResult(java.time.Duration) <variables>private static java.time.Duration DEFAULT_TIMEOUT,public static final com.alicp.jetcache.CacheResult EXISTS_WITHOUT_MSG,public static final com.alicp.jetcache.CacheResult FAIL_ILLEGAL_ARGUMENT,public static final com.alicp.jetcache.CacheResult FAIL_WITHOUT_MSG,public static final java.lang.String MSG_ILLEGAL_ARGUMENT,public static final com.alicp.jetcache.CacheResult PART_SUCCESS_WITHOUT_MSG,public static final com.alicp.jetcache.CacheResult SUCCESS_WITHOUT_MSG,private final non-sealed CompletionStage<com.alicp.jetcache.ResultData> future,private volatile java.lang.String message,private volatile com.alicp.jetcache.CacheResultCode resultCode,private volatile java.time.Duration timeout
alibaba_jetcache
jetcache/jetcache-core/src/main/java/com/alicp/jetcache/CacheResult.java
CacheResult
waitForResult
class CacheResult { public static final String MSG_ILLEGAL_ARGUMENT = "illegal argument"; private static Duration DEFAULT_TIMEOUT = CacheConsts.ASYNC_RESULT_TIMEOUT; public static final CacheResult SUCCESS_WITHOUT_MSG = new CacheResult(CacheResultCode.SUCCESS, null); public static final CacheResult PART_SUCCESS_WITHOUT_MSG = new CacheResult(CacheResultCode.PART_SUCCESS, null); public static final CacheResult FAIL_WITHOUT_MSG = new CacheResult(CacheResultCode.FAIL, null); public static final CacheResult FAIL_ILLEGAL_ARGUMENT = new CacheResult(CacheResultCode.FAIL, MSG_ILLEGAL_ARGUMENT); public static final CacheResult EXISTS_WITHOUT_MSG = new CacheResult(CacheResultCode.EXISTS, null); private volatile CacheResultCode resultCode; private volatile String message; private final CompletionStage<ResultData> future; private volatile Duration timeout = DEFAULT_TIMEOUT; public CacheResult(CompletionStage<ResultData> future) { this.future = future; } public CacheResult(CacheResultCode resultCode, String message) { this(CompletableFuture.completedFuture(new ResultData(resultCode, message, null))); } public CacheResult(Throwable ex) { future = CompletableFuture.completedFuture(new ResultData(ex)); } public boolean isSuccess() { return getResultCode() == CacheResultCode.SUCCESS; } protected void waitForResult() { waitForResult(timeout); } public void waitForResult(Duration timeout) {<FILL_FUNCTION_BODY>} protected void fetchResultSuccess(ResultData resultData) { message = resultData.getMessage(); resultCode = resultData.getResultCode(); } protected void fetchResultFail(Throwable e) { message = e.getClass() + ":" + e.getMessage(); resultCode = CacheResultCode.FAIL; } public CacheResultCode getResultCode() { waitForResult(); return resultCode; } public String getMessage() { waitForResult(); return message; } public CompletionStage<ResultData> future() { return future; } public static void setDefaultTimeout(Duration defaultTimeout) { DEFAULT_TIMEOUT = defaultTimeout; } public void setTimeout(Duration timeout) { this.timeout = timeout; } }
if (resultCode != null) { return; } try { ResultData resultData = future.toCompletableFuture().get( timeout.toMillis(), TimeUnit.MILLISECONDS); fetchResultSuccess(resultData); } catch (TimeoutException | InterruptedException | ExecutionException e) { fetchResultFail(e); }
657
96
753
<no_super_class>
alibaba_jetcache
jetcache/jetcache-core/src/main/java/com/alicp/jetcache/CacheUtil.java
CacheUtil
load
class CacheUtil { private interface ProxyLoader<K, V> extends CacheLoader<K, V> { } public static <K, V> ProxyLoader<K, V> createProxyLoader(Cache<K, V> cache, CacheLoader<K, V> loader, Consumer<CacheEvent> eventConsumer) { if (loader instanceof ProxyLoader) { return (ProxyLoader<K, V>) loader; } return new ProxyLoader<K, V>() { @Override public V load(K key) throws Throwable {<FILL_FUNCTION_BODY>} @Override public Map<K, V> loadAll(Set<K> keys) throws Throwable { long t = System.currentTimeMillis(); boolean success = false; Map<K, V> kvMap = null; try { kvMap = loader.loadAll(keys); success = true; } finally { t = System.currentTimeMillis() - t; CacheLoadAllEvent event = new CacheLoadAllEvent(cache, t, keys, kvMap, success); eventConsumer.accept(event); } return kvMap; } @Override public boolean vetoCacheUpdate() { return loader.vetoCacheUpdate(); } }; } public static <K, V> ProxyLoader<K, V> createProxyLoader(Cache<K, V> cache, Function<K, V> loader, Consumer<CacheEvent> eventConsumer) { if (loader instanceof ProxyLoader) { return (ProxyLoader<K, V>) loader; } if (loader instanceof CacheLoader) { return createProxyLoader(cache, (CacheLoader) loader, eventConsumer); } return k -> { long t = System.currentTimeMillis(); V v = null; boolean success = false; try { v = loader.apply(k); success = true; } finally { t = System.currentTimeMillis() - t; CacheLoadEvent event = new CacheLoadEvent(cache, t, k, v, success); eventConsumer.accept(event); } return v; }; } public static <K, V> AbstractCache<K, V> getAbstractCache(Cache<K, V> c) { while (c instanceof ProxyCache) { c = ((ProxyCache) c).getTargetCache(); } return (AbstractCache) c; } }
long t = System.currentTimeMillis(); V v = null; boolean success = false; try { v = loader.load(key); success = true; } finally { t = System.currentTimeMillis() - t; CacheLoadEvent event = new CacheLoadEvent(cache, t, key, v, success); eventConsumer.accept(event); } return v;
646
107
753
<no_super_class>
alibaba_jetcache
jetcache/jetcache-core/src/main/java/com/alicp/jetcache/LoadingCache.java
LoadingCache
getAll
class LoadingCache<K, V> extends SimpleProxyCache<K, V> { protected Consumer<CacheEvent> eventConsumer; protected CacheConfig<K, V> config; public LoadingCache(Cache<K, V> cache) { super(cache); this.config = config(); eventConsumer = CacheUtil.getAbstractCache(cache)::notify; } @Override public V get(K key) throws CacheInvokeException { CacheLoader<K, V> loader = config.getLoader(); if (loader != null) { return AbstractCache.computeIfAbsentImpl(key, loader, config.isCacheNullValue() ,0, null, this); } else { return cache.get(key); } } protected boolean needUpdate(V loadedValue, CacheLoader<K, V> loader) { if (loadedValue == null && !config.isCacheNullValue()) { return false; } if (loader.vetoCacheUpdate()) { return false; } return true; } @Override public Map<K, V> getAll(Set<? extends K> keys) throws CacheInvokeException {<FILL_FUNCTION_BODY>} }
CacheLoader<K, V> loader = config.getLoader(); if (loader != null) { MultiGetResult<K, V> r = GET_ALL(keys); Map<K, V> kvMap; if (r.isSuccess() || r.getResultCode() == CacheResultCode.PART_SUCCESS) { kvMap = r.unwrapValues(); } else { kvMap = new HashMap<>(); } Set<K> keysNeedLoad = new LinkedHashSet<>(); keys.forEach((k) -> { if (!kvMap.containsKey(k)) { keysNeedLoad.add(k); } }); if (!config.isCachePenetrationProtect()) { if (eventConsumer != null) { loader = CacheUtil.createProxyLoader(cache, loader, eventConsumer); } Map<K, V> loadResult; try { loadResult = loader.loadAll(keysNeedLoad); CacheLoader<K, V> theLoader = loader; Map<K, V> updateValues = new HashMap<>(); loadResult.forEach((k,v)->{ if (needUpdate(v, theLoader)){ updateValues.put(k, v); } }); // batch put if (!updateValues.isEmpty()) { PUT_ALL(updateValues); } } catch (Throwable e) { throw new CacheInvokeException(e); } kvMap.putAll(loadResult); } else { AbstractCache<K, V> abstractCache = CacheUtil.getAbstractCache(cache); loader = CacheUtil.createProxyLoader(cache, loader, eventConsumer); for(K key : keysNeedLoad) { Consumer<V> cacheUpdater = (v) -> { if(needUpdate(v, config.getLoader())) { PUT(key, v); } }; V v = AbstractCache.synchronizedLoad(config, abstractCache, key, loader, cacheUpdater); kvMap.put(key, v); } } return kvMap; } else { return cache.getAll(keys); }
316
564
880
<methods>public void <init>(Cache<K,V>) ,public CacheGetResult<V> GET(K) ,public MultiGetResult<K,V> GET_ALL(Set<? extends K>) ,public com.alicp.jetcache.CacheResult PUT(K, V) ,public com.alicp.jetcache.CacheResult PUT(K, V, long, java.util.concurrent.TimeUnit) ,public com.alicp.jetcache.CacheResult PUT_ALL(Map<? extends K,? extends V>) ,public com.alicp.jetcache.CacheResult PUT_ALL(Map<? extends K,? extends V>, long, java.util.concurrent.TimeUnit) ,public com.alicp.jetcache.CacheResult PUT_IF_ABSENT(K, V, long, java.util.concurrent.TimeUnit) ,public com.alicp.jetcache.CacheResult REMOVE(K) ,public com.alicp.jetcache.CacheResult REMOVE_ALL(Set<? extends K>) ,public void close() ,public V computeIfAbsent(K, Function<K,V>) ,public V computeIfAbsent(K, Function<K,V>, boolean) ,public V computeIfAbsent(K, Function<K,V>, boolean, long, java.util.concurrent.TimeUnit) ,public CacheConfig<K,V> config() ,public V get(K) ,public Map<K,V> getAll(Set<? extends K>) ,public Cache<K,V> getTargetCache() ,public void put(K, V) ,public void put(K, V, long, java.util.concurrent.TimeUnit) ,public void putAll(Map<? extends K,? extends V>) ,public void putAll(Map<? extends K,? extends V>, long, java.util.concurrent.TimeUnit) ,public boolean putIfAbsent(K, V) ,public boolean remove(K) ,public void removeAll(Set<? extends K>) ,public com.alicp.jetcache.AutoReleaseLock tryLock(K, long, java.util.concurrent.TimeUnit) ,public boolean tryLockAndRun(K, long, java.util.concurrent.TimeUnit, java.lang.Runnable) ,public T unwrap(Class<T>) <variables>protected Cache<K,V> cache
alibaba_jetcache
jetcache/jetcache-core/src/main/java/com/alicp/jetcache/MultiGetResult.java
MultiGetResult
unwrapValues
class MultiGetResult<K, V> extends CacheResult { private volatile Map<K, CacheGetResult<V>> values; public MultiGetResult(CompletionStage<ResultData> future) { super(future); } public MultiGetResult(CacheResultCode resultCode, String message, Map<K, CacheGetResult<V>> values) { super(CompletableFuture.completedFuture(new ResultData(resultCode, message, values))); } public MultiGetResult(Throwable e) { super(e); } public Map<K, CacheGetResult<V>> getValues() { waitForResult(); return values; } @Override protected void fetchResultSuccess(ResultData resultData) { values = (Map<K, CacheGetResult<V>>) resultData.getOriginData(); super.fetchResultSuccess(resultData); } @Override protected void fetchResultFail(Throwable e) { values = null; super.fetchResultFail(e); } public Map<K, V> unwrapValues() {<FILL_FUNCTION_BODY>} }
waitForResult(); if (values == null) { return null; } Map<K, V> m = new HashMap<>(); values.entrySet().stream().forEach((en) -> { if (en.getValue().isSuccess()) { m.put(en.getKey(), en.getValue().getValue()); } }); return m;
290
97
387
<methods>public void <init>(CompletionStage<com.alicp.jetcache.ResultData>) ,public void <init>(com.alicp.jetcache.CacheResultCode, java.lang.String) ,public void <init>(java.lang.Throwable) ,public CompletionStage<com.alicp.jetcache.ResultData> future() ,public java.lang.String getMessage() ,public com.alicp.jetcache.CacheResultCode getResultCode() ,public boolean isSuccess() ,public static void setDefaultTimeout(java.time.Duration) ,public void setTimeout(java.time.Duration) ,public void waitForResult(java.time.Duration) <variables>private static java.time.Duration DEFAULT_TIMEOUT,public static final com.alicp.jetcache.CacheResult EXISTS_WITHOUT_MSG,public static final com.alicp.jetcache.CacheResult FAIL_ILLEGAL_ARGUMENT,public static final com.alicp.jetcache.CacheResult FAIL_WITHOUT_MSG,public static final java.lang.String MSG_ILLEGAL_ARGUMENT,public static final com.alicp.jetcache.CacheResult PART_SUCCESS_WITHOUT_MSG,public static final com.alicp.jetcache.CacheResult SUCCESS_WITHOUT_MSG,private final non-sealed CompletionStage<com.alicp.jetcache.ResultData> future,private volatile java.lang.String message,private volatile com.alicp.jetcache.CacheResultCode resultCode,private volatile java.time.Duration timeout
alibaba_jetcache
jetcache/jetcache-core/src/main/java/com/alicp/jetcache/MultiLevelCacheBuilder.java
MultiLevelCacheBuilderImpl
keyConvertor
class MultiLevelCacheBuilderImpl extends MultiLevelCacheBuilder<MultiLevelCacheBuilderImpl> { } public static MultiLevelCacheBuilderImpl createMultiLevelCacheBuilder() { return new MultiLevelCacheBuilderImpl(); } protected MultiLevelCacheBuilder() { buildFunc(config -> new MultiLevelCache((MultiLevelCacheConfig) config)); } @Override public MultiLevelCacheConfig getConfig() { if (config == null) { config = new MultiLevelCacheConfig(); } return (MultiLevelCacheConfig) config; } public T addCache(Cache... caches) { for (Cache c : caches) { getConfig().getCaches().add(c); } return self(); } public void setCaches(List<Cache> caches) { getConfig().setCaches(caches); } public T useExpireOfSubCache(boolean useExpireOfSubCache) { getConfig().setUseExpireOfSubCache(useExpireOfSubCache); return self(); } public void setUseExpireOfSubCache(boolean useExpireOfSubCache) { getConfig().setUseExpireOfSubCache(useExpireOfSubCache); } @Override public T keyConvertor(Function<Object, Object> keyConvertor) {<FILL_FUNCTION_BODY>
throw new UnsupportedOperationException("MultiLevelCache do not need a key convertor");
348
23
371
<methods>public non-sealed void <init>() ,public T addMonitor(com.alicp.jetcache.CacheMonitor) ,public final Cache<K,V> build() ,public final Cache<K,V> buildCache() ,public T buildFunc(Function<CacheConfig#RAW,Cache#RAW>) ,public T cacheNullValue(boolean) ,public T cachePenetrateProtect(boolean) ,public java.lang.Object clone() ,public T expireAfterAccess(long, java.util.concurrent.TimeUnit) ,public T expireAfterWrite(long, java.util.concurrent.TimeUnit) ,public abstract CacheConfig#RAW getConfig() ,public T keyConvertor(Function<java.lang.Object,java.lang.Object>) ,public T loader(CacheLoader<K,V>) ,public T refreshPolicy(com.alicp.jetcache.RefreshPolicy) ,public void setCacheNullValue(boolean) ,public void setCachePenetrateProtect(boolean) ,public void setExpireAfterAccessInMillis(long) ,public void setExpireAfterWriteInMillis(long) ,public void setKeyConvertor(Function<java.lang.Object,java.lang.Object>) ,public void setLoader(CacheLoader<K,V>) ,public void setMonitors(List<com.alicp.jetcache.CacheMonitor>) ,public void setRefreshPolicy(com.alicp.jetcache.RefreshPolicy) <variables>private Function<CacheConfig#RAW,Cache#RAW> buildFunc,protected CacheConfig#RAW config
alibaba_jetcache
jetcache/jetcache-core/src/main/java/com/alicp/jetcache/MultiLevelCacheConfig.java
MultiLevelCacheConfig
clone
class MultiLevelCacheConfig<K, V> extends CacheConfig<K, V> { private List<Cache<K, V>> caches = new ArrayList<>(); private boolean useExpireOfSubCache; @Override public MultiLevelCacheConfig clone() {<FILL_FUNCTION_BODY>} public List<Cache<K, V>> getCaches() { return caches; } public void setCaches(List<Cache<K, V>> caches) { this.caches = caches; } public boolean isUseExpireOfSubCache() { return useExpireOfSubCache; } public void setUseExpireOfSubCache(boolean useExpireOfSubCache) { this.useExpireOfSubCache = useExpireOfSubCache; } }
MultiLevelCacheConfig copy = (MultiLevelCacheConfig) super.clone(); if (caches != null) { copy.caches = new ArrayList(this.caches); } return copy;
208
55
263
<methods>public non-sealed void <init>() ,public CacheConfig#RAW clone() ,public long getDefaultExpireInMillis() ,public long getExpireAfterAccessInMillis() ,public long getExpireAfterWriteInMillis() ,public Function<K,java.lang.Object> getKeyConvertor() ,public CacheLoader<K,V> getLoader() ,public List<com.alicp.jetcache.CacheMonitor> getMonitors() ,public java.time.Duration getPenetrationProtectTimeout() ,public com.alicp.jetcache.RefreshPolicy getRefreshPolicy() ,public int getTryLockInquiryCount() ,public int getTryLockLockCount() ,public int getTryLockUnlockCount() ,public boolean isCacheNullValue() ,public boolean isCachePenetrationProtect() ,public boolean isExpireAfterAccess() ,public boolean isExpireAfterWrite() ,public void setCacheNullValue(boolean) ,public void setCachePenetrationProtect(boolean) ,public void setDefaultExpireInMillis(long) ,public void setExpireAfterAccessInMillis(long) ,public void setExpireAfterWriteInMillis(long) ,public void setKeyConvertor(Function<K,java.lang.Object>) ,public void setLoader(CacheLoader<K,V>) ,public void setMonitors(List<com.alicp.jetcache.CacheMonitor>) ,public void setPenetrationProtectTimeout(java.time.Duration) ,public void setRefreshPolicy(com.alicp.jetcache.RefreshPolicy) ,public void setTryLockInquiryCount(int) ,public void setTryLockLockCount(int) ,public void setTryLockUnlockCount(int) <variables>private boolean cacheNullValue,private boolean cachePenetrationProtect,private long expireAfterAccessInMillis,private long expireAfterWriteInMillis,private Function<K,java.lang.Object> keyConvertor,private CacheLoader<K,V> loader,private List<com.alicp.jetcache.CacheMonitor> monitors,private java.time.Duration penetrationProtectTimeout,private com.alicp.jetcache.RefreshPolicy refreshPolicy,private int tryLockInquiryCount,private int tryLockLockCount,private int tryLockUnlockCount
alibaba_jetcache
jetcache/jetcache-core/src/main/java/com/alicp/jetcache/RefreshCache.java
RefreshTask
externalLoad
class RefreshTask implements Runnable { private Object taskId; private K key; private CacheLoader<K, V> loader; private long lastAccessTime; private ScheduledFuture future; RefreshTask(Object taskId, K key, CacheLoader<K, V> loader) { this.taskId = taskId; this.key = key; this.loader = loader; } private void cancel() { logger.debug("cancel refresh: {}", key); future.cancel(false); taskMap.remove(taskId); } private void load() throws Throwable { CacheLoader<K,V> l = loader == null? config.getLoader(): loader; if (l != null) { l = CacheUtil.createProxyLoader(cache, l, eventConsumer); V v = l.load(key); if (needUpdate(v, l)) { cache.PUT(key, v); } } } private void externalLoad(final Cache concreteCache, final long currentTime) throws Throwable {<FILL_FUNCTION_BODY>} private void refreshUpperCaches(K key) { MultiLevelCache<K, V> targetCache = (MultiLevelCache<K, V>) getTargetCache(); Cache[] caches = targetCache.caches(); int len = caches.length; CacheGetResult cacheGetResult = caches[len - 1].GET(key); if (!cacheGetResult.isSuccess()) { return; } for (int i = 0; i < len - 1; i++) { caches[i].PUT(key, cacheGetResult.getValue()); } } @Override public void run() { try { if (config.getRefreshPolicy() == null || (loader == null && !hasLoader())) { cancel(); return; } long now = System.currentTimeMillis(); long stopRefreshAfterLastAccessMillis = config.getRefreshPolicy().getStopRefreshAfterLastAccessMillis(); if (stopRefreshAfterLastAccessMillis > 0) { if (lastAccessTime + stopRefreshAfterLastAccessMillis < now) { logger.debug("cancel refresh: {}", key); cancel(); return; } } logger.debug("refresh key: {}", key); Cache concreteCache = concreteCache(); if (concreteCache instanceof AbstractExternalCache) { externalLoad(concreteCache, now); } else { load(); } } catch (Throwable e) { logger.error("refresh error: key=" + key, e); } } }
byte[] newKey = ((AbstractExternalCache) concreteCache).buildKey(key); byte[] lockKey = combine(newKey, LOCK_KEY_SUFFIX); long loadTimeOut = RefreshCache.this.config.getRefreshPolicy().getRefreshLockTimeoutMillis(); long refreshMillis = config.getRefreshPolicy().getRefreshMillis(); byte[] timestampKey = combine(newKey, TIMESTAMP_KEY_SUFFIX); // AbstractExternalCache buildKey method will not convert byte[] CacheGetResult refreshTimeResult = concreteCache.GET(timestampKey); boolean shouldLoad = false; if (refreshTimeResult.isSuccess()) { shouldLoad = currentTime >= Long.parseLong(refreshTimeResult.getValue().toString()) + refreshMillis; } else if (refreshTimeResult.getResultCode() == CacheResultCode.NOT_EXISTS) { shouldLoad = true; } if (!shouldLoad) { if (multiLevelCache) { refreshUpperCaches(key); } return; } Runnable r = () -> { try { load(); // AbstractExternalCache buildKey method will not convert byte[] concreteCache.put(timestampKey, String.valueOf(System.currentTimeMillis())); } catch (Throwable e) { throw new CacheException("refresh error", e); } }; // AbstractExternalCache buildKey method will not convert byte[] boolean lockSuccess = concreteCache.tryLockAndRun(lockKey, loadTimeOut, TimeUnit.MILLISECONDS, r); if(!lockSuccess && multiLevelCache) { JetCacheExecutor.heavyIOExecutor().schedule( () -> refreshUpperCaches(key), (long)(0.2 * refreshMillis), TimeUnit.MILLISECONDS); }
689
464
1,153
<methods>public void <init>(Cache<K,V>) ,public V get(K) throws com.alicp.jetcache.CacheInvokeException,public Map<K,V> getAll(Set<? extends K>) throws com.alicp.jetcache.CacheInvokeException<variables>protected CacheConfig<K,V> config,protected Consumer<com.alicp.jetcache.event.CacheEvent> eventConsumer
alibaba_jetcache
jetcache/jetcache-core/src/main/java/com/alicp/jetcache/RefreshPolicy.java
RefreshPolicy
clone
class RefreshPolicy implements Cloneable { private long refreshMillis; private long stopRefreshAfterLastAccessMillis; private long refreshLockTimeoutMillis = 60 * 1000; public RefreshPolicy() { } public static RefreshPolicy newPolicy(long time, TimeUnit timeUnit) { RefreshPolicy p = new RefreshPolicy(); p.refreshMillis = timeUnit.toMillis(time); return p; } public RefreshPolicy stopRefreshAfterLastAccess(long time, TimeUnit timeUnit) { this.stopRefreshAfterLastAccessMillis = timeUnit.toMillis(time); return this; } public RefreshPolicy refreshLockTimeout(long time, TimeUnit timeUnit) { this.refreshLockTimeoutMillis = timeUnit.toMillis(time); return this; } @Override public RefreshPolicy clone() {<FILL_FUNCTION_BODY>} public long getRefreshMillis() { return refreshMillis; } public void setRefreshMillis(long refreshMillis) { this.refreshMillis = refreshMillis; } public long getStopRefreshAfterLastAccessMillis() { return stopRefreshAfterLastAccessMillis; } public void setStopRefreshAfterLastAccessMillis(long stopRefreshAfterLastAccessMillis) { this.stopRefreshAfterLastAccessMillis = stopRefreshAfterLastAccessMillis; } public long getRefreshLockTimeoutMillis() { return refreshLockTimeoutMillis; } public void setRefreshLockTimeoutMillis(long refreshLockTimeoutMillis) { this.refreshLockTimeoutMillis = refreshLockTimeoutMillis; } }
try { return (RefreshPolicy) super.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeException(e); }
454
45
499
<no_super_class>
alibaba_jetcache
jetcache/jetcache-core/src/main/java/com/alicp/jetcache/embedded/AbstractEmbeddedCache.java
AbstractEmbeddedCache
parseHolderResult
class AbstractEmbeddedCache<K, V> extends AbstractCache<K, V> { protected EmbeddedCacheConfig<K, V> config; protected InnerMap innerMap; protected abstract InnerMap createAreaCache(); private final ReentrantLock lock = new ReentrantLock(); public AbstractEmbeddedCache(EmbeddedCacheConfig<K, V> config) { this.config = config; innerMap = createAreaCache(); } @Override public CacheConfig<K, V> config() { return config; } public Object buildKey(K key) { Object newKey = key; Function<K, Object> keyConvertor = config.getKeyConvertor(); if (keyConvertor != null) { newKey = keyConvertor.apply(key); } return newKey; } @Override protected CacheGetResult<V> do_GET(K key) { Object newKey = buildKey(key); CacheValueHolder<V> holder = (CacheValueHolder<V>) innerMap.getValue(newKey); return parseHolderResult(holder); } protected CacheGetResult<V> parseHolderResult(CacheValueHolder<V> holder) {<FILL_FUNCTION_BODY>} @Override protected MultiGetResult<K, V> do_GET_ALL(Set<? extends K> keys) { ArrayList<K> keyList = new ArrayList<K>(keys.size()); ArrayList<Object> newKeyList = new ArrayList<Object>(keys.size()); keys.stream().forEach((k) -> { Object newKey = buildKey(k); keyList.add(k); newKeyList.add(newKey); }); Map<Object, CacheValueHolder<V>> innerResultMap = innerMap.getAllValues(newKeyList); Map<K, CacheGetResult<V>> resultMap = new HashMap<>(); for (int i = 0; i < keyList.size(); i++) { K key = keyList.get(i); Object newKey = newKeyList.get(i); CacheValueHolder<V> holder = innerResultMap.get(newKey); resultMap.put(key, parseHolderResult(holder)); } MultiGetResult<K, V> result = new MultiGetResult<>(CacheResultCode.SUCCESS, null, resultMap); return result; } @Override protected CacheResult do_PUT(K key, V value, long expireAfterWrite, TimeUnit timeUnit) { CacheValueHolder<V> cacheObject = new CacheValueHolder(value ,timeUnit.toMillis(expireAfterWrite)); innerMap.putValue(buildKey(key), cacheObject); return CacheResult.SUCCESS_WITHOUT_MSG; } @Override protected CacheResult do_PUT_ALL(Map<? extends K, ? extends V> map, long expireAfterWrite, TimeUnit timeUnit) { HashMap newKeyMap = new HashMap(); for (Map.Entry<? extends K, ? extends V> en : map.entrySet()) { CacheValueHolder<V> cacheObject = new CacheValueHolder(en.getValue(), timeUnit.toMillis(expireAfterWrite)); newKeyMap.put(buildKey(en.getKey()), cacheObject); } innerMap.putAllValues(newKeyMap); final HashMap resultMap = new HashMap(); map.keySet().forEach((k) -> resultMap.put(k, CacheResultCode.SUCCESS)); return CacheResult.SUCCESS_WITHOUT_MSG; } @Override protected CacheResult do_REMOVE(K key) { innerMap.removeValue(buildKey(key)); return CacheResult.SUCCESS_WITHOUT_MSG; } @Override protected CacheResult do_REMOVE_ALL(Set<? extends K> keys) { Set newKeys = keys.stream().map((key) -> buildKey(key)).collect(Collectors.toSet()); innerMap.removeAllValues(newKeys); return CacheResult.SUCCESS_WITHOUT_MSG; } // internal method public void __removeAll(Set<? extends K> keys) { innerMap.removeAllValues(keys); } @Override protected CacheResult do_PUT_IF_ABSENT(K key, V value, long expireAfterWrite, TimeUnit timeUnit) { CacheValueHolder<V> cacheObject = new CacheValueHolder(value, timeUnit.toMillis(expireAfterWrite)); if (innerMap.putIfAbsentValue(buildKey(key), cacheObject)) { return CacheResult.SUCCESS_WITHOUT_MSG; } else { return CacheResult.EXISTS_WITHOUT_MSG; } } }
long now = System.currentTimeMillis(); if (holder == null) { return CacheGetResult.NOT_EXISTS_WITHOUT_MSG; } else if (now >= holder.getExpireTime()) { return CacheGetResult.EXPIRED_WITHOUT_MSG; } else { lock.lock(); try{ long accessTime = holder.getAccessTime(); if (config.isExpireAfterAccess()) { long expireAfterAccess = config.getExpireAfterAccessInMillis(); if (now >= accessTime + expireAfterAccess) { return CacheGetResult.EXPIRED_WITHOUT_MSG; } } holder.setAccessTime(now); }finally { lock.unlock(); } return new CacheGetResult(CacheResultCode.SUCCESS, null, holder); }
1,225
221
1,446
<methods>public non-sealed void <init>() ,public final CacheGetResult<V> GET(K) ,public final MultiGetResult<K,V> GET_ALL(Set<? extends K>) ,public final com.alicp.jetcache.CacheResult PUT(K, V, long, java.util.concurrent.TimeUnit) ,public final com.alicp.jetcache.CacheResult PUT_ALL(Map<? extends K,? extends V>, long, java.util.concurrent.TimeUnit) ,public final com.alicp.jetcache.CacheResult PUT_IF_ABSENT(K, V, long, java.util.concurrent.TimeUnit) ,public final com.alicp.jetcache.CacheResult REMOVE(K) ,public final com.alicp.jetcache.CacheResult REMOVE_ALL(Set<? extends K>) ,public void close() ,public final V computeIfAbsent(K, Function<K,V>, boolean) ,public final V computeIfAbsent(K, Function<K,V>, boolean, long, java.util.concurrent.TimeUnit) ,public boolean isClosed() ,public void notify(com.alicp.jetcache.event.CacheEvent) <variables>protected volatile boolean closed,private volatile ConcurrentHashMap<java.lang.Object,com.alicp.jetcache.AbstractCache.LoaderLock> loaderMap,private static Logger logger,private static final java.util.concurrent.locks.ReentrantLock reentrantLock
alibaba_jetcache
jetcache/jetcache-core/src/main/java/com/alicp/jetcache/embedded/CaffeineCache.java
CaffeineCache
createAreaCache
class CaffeineCache<K, V> extends AbstractEmbeddedCache<K, V> { private com.github.benmanes.caffeine.cache.Cache cache; public CaffeineCache(EmbeddedCacheConfig<K, V> config) { super(config); } @Override public <T> T unwrap(Class<T> clazz) { if (clazz.equals(com.github.benmanes.caffeine.cache.Cache.class)) { return (T) cache; } throw new IllegalArgumentException(clazz.getName()); } @Override @SuppressWarnings("unchecked") protected InnerMap createAreaCache() {<FILL_FUNCTION_BODY>} }
Caffeine<Object, Object> builder = Caffeine.newBuilder(); builder.maximumSize(config.getLimit()); final boolean isExpireAfterAccess = config.isExpireAfterAccess(); final long expireAfterAccess = config.getExpireAfterAccessInMillis(); builder.expireAfter(new Expiry<Object, CacheValueHolder>() { private long getRestTimeInNanos(CacheValueHolder value) { long now = System.currentTimeMillis(); long ttl = value.getExpireTime() - now; if(isExpireAfterAccess){ ttl = Math.min(ttl, expireAfterAccess); } return TimeUnit.MILLISECONDS.toNanos(ttl); } @Override public long expireAfterCreate(Object key, CacheValueHolder value, long currentTime) { return getRestTimeInNanos(value); } @Override public long expireAfterUpdate(Object key, CacheValueHolder value, long currentTime, long currentDuration) { return currentDuration; } @Override public long expireAfterRead(Object key, CacheValueHolder value, long currentTime, long currentDuration) { return getRestTimeInNanos(value); } }); cache = builder.build(); return new InnerMap() { @Override public Object getValue(Object key) { return cache.getIfPresent(key); } @Override public Map getAllValues(Collection keys) { return cache.getAllPresent(keys); } @Override public void putValue(Object key, Object value) { cache.put(key, value); } @Override public void putAllValues(Map map) { cache.putAll(map); } @Override public boolean removeValue(Object key) { return cache.asMap().remove(key) != null; } @Override public void removeAllValues(Collection keys) { cache.invalidateAll(keys); } @Override public boolean putIfAbsentValue(Object key, Object value) { return cache.asMap().putIfAbsent(key, value) == null; } };
196
581
777
<methods>public void <init>(EmbeddedCacheConfig<K,V>) ,public void __removeAll(Set<? extends K>) ,public java.lang.Object buildKey(K) ,public CacheConfig<K,V> config() <variables>protected EmbeddedCacheConfig<K,V> config,protected com.alicp.jetcache.embedded.InnerMap innerMap,private final java.util.concurrent.locks.ReentrantLock lock
alibaba_jetcache
jetcache/jetcache-core/src/main/java/com/alicp/jetcache/embedded/Cleaner.java
Cleaner
run
class Cleaner { static LinkedList<WeakReference<LinkedHashMapCache>> linkedHashMapCaches = new LinkedList<>(); private static final ReentrantLock reentrantLock = new ReentrantLock(); static { ScheduledExecutorService executorService = JetCacheExecutor.defaultExecutor(); executorService.scheduleWithFixedDelay(() -> run(), 60, 60, TimeUnit.SECONDS); } static void add(LinkedHashMapCache cache) { reentrantLock.lock(); try{ linkedHashMapCaches.add(new WeakReference<>(cache)); }finally { reentrantLock.unlock(); } } static void run() {<FILL_FUNCTION_BODY>} }
reentrantLock.lock(); try{ Iterator<WeakReference<LinkedHashMapCache>> it = linkedHashMapCaches.iterator(); while (it.hasNext()) { WeakReference<LinkedHashMapCache> ref = it.next(); LinkedHashMapCache c = ref.get(); if (c == null) { it.remove(); } else { c.cleanExpiredEntry(); } } }finally { reentrantLock.unlock(); }
202
134
336
<no_super_class>
alibaba_jetcache
jetcache/jetcache-core/src/main/java/com/alicp/jetcache/embedded/EmbeddedCacheBuilder.java
EmbeddedCacheBuilderImpl
getConfig
class EmbeddedCacheBuilderImpl extends EmbeddedCacheBuilder<EmbeddedCacheBuilderImpl> { } public static EmbeddedCacheBuilderImpl createEmbeddedCacheBuilder(){ return new EmbeddedCacheBuilderImpl(); } @Override public EmbeddedCacheConfig getConfig() {<FILL_FUNCTION_BODY>
if (config == null) { config = new EmbeddedCacheConfig(); } return (EmbeddedCacheConfig) config;
88
39
127
<methods>public non-sealed void <init>() ,public T addMonitor(com.alicp.jetcache.CacheMonitor) ,public final Cache<K,V> build() ,public final Cache<K,V> buildCache() ,public T buildFunc(Function<CacheConfig#RAW,Cache#RAW>) ,public T cacheNullValue(boolean) ,public T cachePenetrateProtect(boolean) ,public java.lang.Object clone() ,public T expireAfterAccess(long, java.util.concurrent.TimeUnit) ,public T expireAfterWrite(long, java.util.concurrent.TimeUnit) ,public abstract CacheConfig#RAW getConfig() ,public T keyConvertor(Function<java.lang.Object,java.lang.Object>) ,public T loader(CacheLoader<K,V>) ,public T refreshPolicy(com.alicp.jetcache.RefreshPolicy) ,public void setCacheNullValue(boolean) ,public void setCachePenetrateProtect(boolean) ,public void setExpireAfterAccessInMillis(long) ,public void setExpireAfterWriteInMillis(long) ,public void setKeyConvertor(Function<java.lang.Object,java.lang.Object>) ,public void setLoader(CacheLoader<K,V>) ,public void setMonitors(List<com.alicp.jetcache.CacheMonitor>) ,public void setRefreshPolicy(com.alicp.jetcache.RefreshPolicy) <variables>private Function<CacheConfig#RAW,Cache#RAW> buildFunc,protected CacheConfig#RAW config
alibaba_jetcache
jetcache/jetcache-core/src/main/java/com/alicp/jetcache/embedded/LinkedHashMapCache.java
LRUMap
getAllValues
class LRUMap extends LinkedHashMap implements InnerMap { private final int max; // private final Object lockObj; private final ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock(); public LRUMap(int max) { super((int) (max * 1.4f), 0.75f, true); this.max = max; // this.lockObj = lockObj; } @Override protected boolean removeEldestEntry(Map.Entry eldest) { return size() > max; } void cleanExpiredEntry() { Lock lock = readWriteLock.writeLock(); lock.lock(); try{ for (Iterator it = entrySet().iterator(); it.hasNext();) { Map.Entry en = (Map.Entry) it.next(); Object value = en.getValue(); if (value != null && value instanceof CacheValueHolder) { CacheValueHolder h = (CacheValueHolder) value; if (System.currentTimeMillis() >= h.getExpireTime()) { it.remove(); } } else { // assert false if (value == null) { logger.error("key " + en.getKey() + " is null"); } else { logger.error("value of key " + en.getKey() + " is not a CacheValueHolder. type=" + value.getClass()); } } } }finally { lock.unlock(); } } @Override public Object getValue(Object key) { Lock lock = readWriteLock.readLock(); lock.lock(); try{ return get(key); }finally { lock.unlock(); } } @Override public Map getAllValues(Collection keys) {<FILL_FUNCTION_BODY>} @Override public void putValue(Object key, Object value) { Lock lock = readWriteLock.writeLock(); lock.lock(); try{ put(key, value); }finally { lock.unlock(); } } @Override public void putAllValues(Map map) { Lock lock = readWriteLock.writeLock(); lock.lock(); try{ Set<Map.Entry> set = map.entrySet(); for (Map.Entry en : set) { put(en.getKey(), en.getValue()); } }finally { lock.unlock(); } } @Override public boolean removeValue(Object key) { Lock lock = readWriteLock.writeLock(); lock.lock(); try{ return remove(key) != null; }finally { lock.unlock(); } } @Override public void removeAllValues(Collection keys) { Lock lock = readWriteLock.writeLock(); lock.lock(); try{ for (Object k : keys) { remove(k); } }finally { lock.unlock(); } } @Override @SuppressWarnings("unchecked") public boolean putIfAbsentValue(Object key, Object value) { Lock lock = readWriteLock.writeLock(); lock.lock(); try{ CacheValueHolder h = (CacheValueHolder) get(key); if (h == null || parseHolderResult(h).getResultCode() == CacheResultCode.EXPIRED) { put(key, value); return true; } else { return false; } }finally { lock.unlock(); } } }
Lock lock = readWriteLock.readLock(); lock.lock(); Map values = new HashMap(); try{ for (Object key : keys) { Object v = get(key); if (v != null) { values.put(key, v); } } }finally { lock.unlock(); } return values;
934
99
1,033
<methods>public void <init>(EmbeddedCacheConfig<K,V>) ,public void __removeAll(Set<? extends K>) ,public java.lang.Object buildKey(K) ,public CacheConfig<K,V> config() <variables>protected EmbeddedCacheConfig<K,V> config,protected com.alicp.jetcache.embedded.InnerMap innerMap,private final java.util.concurrent.locks.ReentrantLock lock
alibaba_jetcache
jetcache/jetcache-core/src/main/java/com/alicp/jetcache/external/AbstractExternalCache.java
AbstractExternalCache
endWith
class AbstractExternalCache<K, V> extends AbstractCache<K, V> { private ExternalCacheConfig<K, V> config; public AbstractExternalCache(ExternalCacheConfig<K, V> config) { this.config = config; checkConfig(); } protected void checkConfig() { if (config.getValueEncoder() == null) { throw new CacheConfigException("no value encoder"); } if (config.getValueDecoder() == null) { throw new CacheConfigException("no value decoder"); } if (config.getKeyPrefix() == null) { throw new CacheConfigException("keyPrefix is required"); } } public byte[] buildKey(K key) { try { Object newKey = key; if (config.getKeyConvertor() != null) { if (config.getKeyConvertor() instanceof KeyConvertor) { if (!isPreservedKey(key)) { // since 2.7.3 KeyConvertor extends Function<Object, Object> newKey = config.getKeyConvertor().apply(key); } } else { // before 2.7.3, KeyConvertor is interface only place some constants. // "key convertor" is Function<Object, Object> and can't process byte[] and String if (key instanceof byte[]) { newKey = key; } else if (key instanceof String) { newKey = key; } else { newKey = config.getKeyConvertor().apply(key); } } } return ExternalKeyUtil.buildKeyAfterConvert(newKey, config.getKeyPrefix()); } catch (IOException e) { throw new CacheException(e); } } private boolean isPreservedKey(Object key) { if (key instanceof byte[]) { byte[] keyBytes = (byte[]) key; return endWith(keyBytes, RefreshCache.LOCK_KEY_SUFFIX) || endWith(keyBytes, RefreshCache.TIMESTAMP_KEY_SUFFIX); } return false; } private boolean endWith(byte[] key, byte[] suffix) {<FILL_FUNCTION_BODY>} }
int len = suffix.length; if (key.length < len) { return false; } int startPos = key.length - len; for (int i = 0; i < len; i++) { if (key[startPos + i] != suffix[i]) { return false; } } return true;
564
94
658
<methods>public non-sealed void <init>() ,public final CacheGetResult<V> GET(K) ,public final MultiGetResult<K,V> GET_ALL(Set<? extends K>) ,public final com.alicp.jetcache.CacheResult PUT(K, V, long, java.util.concurrent.TimeUnit) ,public final com.alicp.jetcache.CacheResult PUT_ALL(Map<? extends K,? extends V>, long, java.util.concurrent.TimeUnit) ,public final com.alicp.jetcache.CacheResult PUT_IF_ABSENT(K, V, long, java.util.concurrent.TimeUnit) ,public final com.alicp.jetcache.CacheResult REMOVE(K) ,public final com.alicp.jetcache.CacheResult REMOVE_ALL(Set<? extends K>) ,public void close() ,public final V computeIfAbsent(K, Function<K,V>, boolean) ,public final V computeIfAbsent(K, Function<K,V>, boolean, long, java.util.concurrent.TimeUnit) ,public boolean isClosed() ,public void notify(com.alicp.jetcache.event.CacheEvent) <variables>protected volatile boolean closed,private volatile ConcurrentHashMap<java.lang.Object,com.alicp.jetcache.AbstractCache.LoaderLock> loaderMap,private static Logger logger,private static final java.util.concurrent.locks.ReentrantLock reentrantLock
alibaba_jetcache
jetcache/jetcache-core/src/main/java/com/alicp/jetcache/external/ExternalCacheBuilder.java
ExternalCacheBuilder
getConfig
class ExternalCacheBuilder<T extends ExternalCacheBuilder<T>> extends AbstractCacheBuilder<T> { @Override public ExternalCacheConfig getConfig() {<FILL_FUNCTION_BODY>} public boolean supportBroadcast() { return false; } public BroadcastManager createBroadcastManager(CacheManager cacheManager) { return null; } public T broadcastChannel(String broadcastChannel) { getConfig().setBroadcastChannel(broadcastChannel); return self(); } public void setBroadcastChannel(String broadcastChannel) { getConfig().setBroadcastChannel(broadcastChannel); } public T keyPrefix(String keyPrefix) { getConfig().setKeyPrefixSupplier(() -> keyPrefix); return self(); } public T keyPrefixSupplier(Supplier<String> keyPrefixSupplier) { getConfig().setKeyPrefixSupplier(keyPrefixSupplier); return self(); } public T valueEncoder(Function<Object, byte[]> valueEncoder){ getConfig().setValueEncoder(valueEncoder); return self(); } public T valueDecoder(Function<byte[], Object> valueDecoder){ getConfig().setValueDecoder(valueDecoder); return self(); } public void setKeyPrefix(String keyPrefix){ if (keyPrefix != null) { getConfig().setKeyPrefixSupplier(() -> keyPrefix); } else { getConfig().setKeyPrefixSupplier(null); } } public void setKeyPrefixSupplier(Supplier<String> keyPrefixSupplier){ getConfig().setKeyPrefixSupplier(keyPrefixSupplier); } public void setValueEncoder(Function<Object, byte[]> valueEncoder){ getConfig().setValueEncoder(valueEncoder); } public void setValueDecoder(Function<byte[], Object> valueDecoder){ getConfig().setValueDecoder(valueDecoder); } }
if (config == null) { config = new ExternalCacheConfig(); } return (ExternalCacheConfig) config;
518
35
553
<methods>public non-sealed void <init>() ,public T addMonitor(com.alicp.jetcache.CacheMonitor) ,public final Cache<K,V> build() ,public final Cache<K,V> buildCache() ,public T buildFunc(Function<CacheConfig#RAW,Cache#RAW>) ,public T cacheNullValue(boolean) ,public T cachePenetrateProtect(boolean) ,public java.lang.Object clone() ,public T expireAfterAccess(long, java.util.concurrent.TimeUnit) ,public T expireAfterWrite(long, java.util.concurrent.TimeUnit) ,public abstract CacheConfig#RAW getConfig() ,public T keyConvertor(Function<java.lang.Object,java.lang.Object>) ,public T loader(CacheLoader<K,V>) ,public T refreshPolicy(com.alicp.jetcache.RefreshPolicy) ,public void setCacheNullValue(boolean) ,public void setCachePenetrateProtect(boolean) ,public void setExpireAfterAccessInMillis(long) ,public void setExpireAfterWriteInMillis(long) ,public void setKeyConvertor(Function<java.lang.Object,java.lang.Object>) ,public void setLoader(CacheLoader<K,V>) ,public void setMonitors(List<com.alicp.jetcache.CacheMonitor>) ,public void setRefreshPolicy(com.alicp.jetcache.RefreshPolicy) <variables>private Function<CacheConfig#RAW,Cache#RAW> buildFunc,protected CacheConfig#RAW config
alibaba_jetcache
jetcache/jetcache-core/src/main/java/com/alicp/jetcache/external/ExternalKeyUtil.java
ExternalKeyUtil
buildKeyAfterConvert
class ExternalKeyUtil { public static byte[] buildKeyAfterConvert(Object newKey, String prefix) throws IOException {<FILL_FUNCTION_BODY>} }
if (newKey == null) { throw new NullPointerException("key can't be null"); } byte[] keyBytesWithOutPrefix; if (newKey instanceof String) { keyBytesWithOutPrefix = newKey.toString().getBytes(StandardCharsets.UTF_8); } else if (newKey instanceof byte[]) { keyBytesWithOutPrefix = (byte[]) newKey; } else if (newKey instanceof Number) { keyBytesWithOutPrefix = (newKey.getClass().getSimpleName() + newKey).getBytes(StandardCharsets.UTF_8); } else if (newKey instanceof Date) { SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss,SSS"); keyBytesWithOutPrefix = (newKey.getClass().getSimpleName() + sdf.format(newKey)).getBytes(); } else if (newKey instanceof Boolean) { keyBytesWithOutPrefix = newKey.toString().getBytes(StandardCharsets.UTF_8); } else if (newKey instanceof Serializable) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream os = new ObjectOutputStream(bos); os.writeObject(newKey); os.close(); bos.close(); keyBytesWithOutPrefix = bos.toByteArray(); } else { throw new CacheException("can't convert key of class: " + newKey.getClass()); } byte[] prefixBytes = prefix.getBytes(StandardCharsets.UTF_8); byte[] rt = new byte[prefixBytes.length + keyBytesWithOutPrefix.length]; System.arraycopy(prefixBytes, 0, rt, 0, prefixBytes.length); System.arraycopy(keyBytesWithOutPrefix, 0, rt, prefixBytes.length, keyBytesWithOutPrefix.length); return rt;
42
462
504
<no_super_class>
alibaba_jetcache
jetcache/jetcache-core/src/main/java/com/alicp/jetcache/external/MockRemoteCache.java
MockRemoteCache
do_GET
class MockRemoteCache<K, V> extends AbstractExternalCache<K, V> { private Cache<ByteBuffer, byte[]> cache; private ExternalCacheConfig<K, V> config; public MockRemoteCache(MockRemoteCacheConfig<K, V> config) { super(config); this.config = config; cache = LinkedHashMapCacheBuilder.createLinkedHashMapCacheBuilder() .limit(config.getLimit()) .expireAfterWrite(config.getExpireAfterWriteInMillis(), TimeUnit.MILLISECONDS) .buildCache(); } @Override public CacheConfig<K, V> config() { return config; } private ByteBuffer genKey(K key) { return ByteBuffer.wrap(buildKey(key)); } //------------------------------- @Override public <T> T unwrap(Class<T> clazz) { return cache.unwrap(clazz); } private static Method getHolder; static { try { getHolder = CacheGetResult.class.getDeclaredMethod("getHolder"); getHolder.setAccessible(true); } catch (NoSuchMethodException e) { throw new CacheException(e); } } private CacheGetResult convertCacheGetResult(CacheGetResult originResult) { try { CacheValueHolder originHolder = (CacheValueHolder) getHolder.invoke(originResult); LinkedList<CacheValueHolder> list = new LinkedList<>(); while (originHolder != null) { CacheValueHolder h = new CacheValueHolder(); if (list.size() > 0) { list.getLast().setValue(h); } list.add(h); h.setAccessTime(originHolder.getAccessTime()); h.setExpireTime(originHolder.getExpireTime()); Object v = originHolder.getValue(); if (v != null && !(v instanceof CacheValueHolder)) { h.setValue(config.getValueDecoder().apply((byte[]) v)); break; } else if (originHolder.getValue() == null) { originHolder = (CacheValueHolder) originHolder.getValue(); } } return new CacheGetResult(originResult.getResultCode(), originResult.getMessage(), list.peekFirst()); } catch (Exception e) { throw new CacheException(e); } } public CacheValueHolder getHolder(K key) { try { CacheGetResult<V> r = GET(key); return (CacheValueHolder) getHolder.invoke(r); } catch (Exception e) { throw new CacheException(e); } } @Override protected CacheGetResult<V> do_GET(K key) {<FILL_FUNCTION_BODY>} @Override protected MultiGetResult<K, V> do_GET_ALL(Set<? extends K> keys) { ArrayList<K> keyList = new ArrayList<>(keys.size()); ArrayList<ByteBuffer> newKeyList = new ArrayList<>(keys.size()); keys.stream().forEach((k) -> { ByteBuffer newKey = genKey(k); keyList.add(k); newKeyList.add(newKey); }); MultiGetResult<ByteBuffer, byte[]> result = cache.GET_ALL(new HashSet(newKeyList)); Map<ByteBuffer, CacheGetResult<byte[]>> resultMap = result.getValues(); if (resultMap != null) { Map<K, CacheGetResult<V>> returnMap = new HashMap<>(); for (int i = 0; i < keyList.size(); i++) { K key = keyList.get(i); ByteBuffer newKey = newKeyList.get(i); CacheGetResult r = resultMap.get(newKey); if (r.getValue() != null) { r = convertCacheGetResult(r); } returnMap.put(key, r); } result = new MultiGetResult<ByteBuffer, byte[]>(result.getResultCode(), null, (Map) returnMap); } return (MultiGetResult) result; } @Override protected CacheResult do_PUT(K key, V value, long expireAfterWrite, TimeUnit timeUnit) { return cache.PUT(genKey(key), config.getValueEncoder().apply(value), expireAfterWrite, timeUnit); } @Override protected CacheResult do_PUT_ALL(Map<? extends K, ? extends V> map, long expireAfterWrite, TimeUnit timeUnit) { Map<ByteBuffer, byte[]> newMap = new HashMap<>(); map.entrySet().forEach((e) -> newMap.put(genKey(e.getKey()), config.getValueEncoder().apply(e.getValue()))); return cache.PUT_ALL(newMap, expireAfterWrite, timeUnit); } @Override protected CacheResult do_REMOVE(K key) { return cache.REMOVE(genKey(key)); } @Override protected CacheResult do_REMOVE_ALL(Set<? extends K> keys) { return cache.REMOVE_ALL(keys.stream().map((k) -> genKey(k)).collect(Collectors.toSet())); } @Override protected CacheResult do_PUT_IF_ABSENT(K key, V value, long expireAfterWrite, TimeUnit timeUnit) { return cache.PUT_IF_ABSENT(genKey(key), config.getValueEncoder().apply(value), expireAfterWrite, timeUnit); } }
CacheGetResult r = cache.GET(genKey(key)); if (r.isSuccess()) { r = convertCacheGetResult(r); } return r;
1,426
48
1,474
<methods>public void <init>(ExternalCacheConfig<K,V>) ,public byte[] buildKey(K) <variables>private ExternalCacheConfig<K,V> config
alibaba_jetcache
jetcache/jetcache-core/src/main/java/com/alicp/jetcache/external/MockRemoteCacheBuilder.java
MockRemoteCacheBuilderImpl
createBroadcastManager
class MockRemoteCacheBuilderImpl extends MockRemoteCacheBuilder<MockRemoteCacheBuilderImpl> { } public static MockRemoteCacheBuilderImpl createMockRemoteCacheBuilder() { return new MockRemoteCacheBuilderImpl(); } @Override public MockRemoteCacheConfig getConfig() { if (config == null) { config = new MockRemoteCacheConfig(); } return (MockRemoteCacheConfig) config; } @Override public boolean supportBroadcast() { return true; } @Override public BroadcastManager createBroadcastManager(CacheManager cacheManager) {<FILL_FUNCTION_BODY>
return new BroadcastManager(cacheManager) { @Override public CacheResult publish(CacheMessage cacheMessage) { lastPublishMessage = cacheMessage; return CacheResult.SUCCESS_WITHOUT_MSG; } @Override public void startSubscribe() { subscribeStart = true; } };
162
88
250
<methods>public non-sealed void <init>() ,public T broadcastChannel(java.lang.String) ,public com.alicp.jetcache.support.BroadcastManager createBroadcastManager(com.alicp.jetcache.CacheManager) ,public ExternalCacheConfig#RAW getConfig() ,public T keyPrefix(java.lang.String) ,public T keyPrefixSupplier(Supplier<java.lang.String>) ,public void setBroadcastChannel(java.lang.String) ,public void setKeyPrefix(java.lang.String) ,public void setKeyPrefixSupplier(Supplier<java.lang.String>) ,public void setValueDecoder(Function<byte[],java.lang.Object>) ,public void setValueEncoder(Function<java.lang.Object,byte[]>) ,public boolean supportBroadcast() ,public T valueDecoder(Function<byte[],java.lang.Object>) ,public T valueEncoder(Function<java.lang.Object,byte[]>) <variables>
alibaba_jetcache
jetcache/jetcache-core/src/main/java/com/alicp/jetcache/support/AbstractJsonDecoder.java
AbstractJsonDecoder
doApply
class AbstractJsonDecoder extends AbstractValueDecoder { public AbstractJsonDecoder(boolean useIdentityNumber) { super(useIdentityNumber); } @Override protected Object doApply(byte[] buffer) throws Exception {<FILL_FUNCTION_BODY>} private int readInt(byte[] buf, int index) { int x = buf[index] & 0xFF; x = (x << 8) | (buf[index + 1] & 0xFF); x = (x << 8) | (buf[index + 2] & 0xFF); x = (x << 8) | (buf[index + 3] & 0xFF); return x; } private short readShort(byte[] buf, int index) { int x = buf[index] & 0xFF; x = (x << 8) | (buf[index + 1] & 0xFF); return (short) x; } private Object readObject(byte[] buf, int[] indexHolder) throws Exception { int index = indexHolder[0]; short classNameLen = readShort(buf, index); index += 2; if (classNameLen < 0) { indexHolder[0] = index; return null; } else { String className = new String(buf, index, classNameLen, StandardCharsets.UTF_8); index += classNameLen; Class<?> clazz = Class.forName(className); int size = readInt(buf, index); index += 4; Object obj = parseObject(buf, index, size, clazz); index += size; indexHolder[0] = index; return obj; } } protected abstract Object parseObject(byte[] buffer, int index, int len, Class clazz); }
int[] indexHolder = new int[1]; indexHolder[0] = isUseIdentityNumber() ? 4 : 0; short objCount = readShort(buffer, indexHolder[0]); indexHolder[0] = indexHolder[0] + 2; if (objCount < 0) { return null; } Object obj = readObject(buffer, indexHolder); if (obj == null) { return null; } if (obj instanceof CacheValueHolder) { CacheValueHolder h = (CacheValueHolder) obj; h.setValue(readObject(buffer, indexHolder)); return h; } else if (obj instanceof CacheMessage) { CacheMessage cm = (CacheMessage) obj; if (objCount > 1) { Object[] keys = new Object[objCount - 1]; for (int i = 0; i < objCount - 1; i++) { keys[i] = readObject(buffer, indexHolder); } cm.setKeys(keys); } return cm; } else { return obj; }
454
278
732
<methods>public void <init>(boolean) ,public java.lang.Object apply(byte[]) ,public boolean isUseIdentityNumber() ,public void setDecoderMap(com.alicp.jetcache.support.DecoderMap) <variables>private com.alicp.jetcache.support.DecoderMap decoderMap,protected boolean useIdentityNumber
alibaba_jetcache
jetcache/jetcache-core/src/main/java/com/alicp/jetcache/support/AbstractJsonEncoder.java
AbstractJsonEncoder
encode
class AbstractJsonEncoder extends AbstractValueEncoder { public AbstractJsonEncoder(boolean useIdentityNumber) { super(useIdentityNumber); } protected abstract byte[] encodeSingleValue(Object value); @Override public byte[] apply(Object value) { try { JsonData[] data = encode(value); int len = len(data); byte[] buffer = useIdentityNumber ? new byte[len + 4] : new byte[len]; int index = 0; if (useIdentityNumber) { index = writeInt(buffer, index, SerialPolicy.IDENTITY_NUMBER_FASTJSON2); } if (data == null) { writeShort(buffer, index, -1); } else { index = writeShort(buffer, index, data.length); for (JsonData d : data) { if (d == null) { index = writeShort(buffer, index, -1); } else { index = writeShort(buffer, index, d.getClassName().length); index = writeBytes(buffer, index, d.getClassName()); index = writeInt(buffer, index, d.getData().length); index = writeBytes(buffer, index, d.getData()); } } } return buffer; } catch (Throwable e) { StringBuilder sb = new StringBuilder("Fastjson Encode error. "); sb.append("msg=").append(e.getMessage()); throw new CacheEncodeException(sb.toString(), e); } } private int len(JsonData[] data) { if (data == null) { return 2; } int x = 2; for (JsonData d : data) { if (d == null) { x += 2; } else { x += 2 + d.getClassName().length + 4 + d.getData().length; } } return x; } private int writeInt(byte[] buf, int index, int value) { buf[index] = (byte) (value >> 24 & 0xFF); buf[index + 1] = (byte) (value >> 16 & 0xFF); buf[index + 2] = (byte) (value >> 8 & 0xFF); buf[index + 3] = (byte) (value & 0xFF); return index + 4; } private int writeShort(byte[] buf, int index, int value) { buf[index] = (byte) (value >> 8 & 0xFF); buf[index + 1] = (byte) (value & 0xFF); return index + 2; } private int writeBytes(byte[] buf, int index, byte[] data) { System.arraycopy(data, 0, buf, index, data.length); return index + data.length; } private JsonData[] encode(Object value) {<FILL_FUNCTION_BODY>} private JsonData encodeJsonData(Object value) { if (value == null) { return null; } JsonData jsonData = new JsonData(); jsonData.setClassName(value.getClass().getName().getBytes(StandardCharsets.UTF_8)); jsonData.setData(encodeSingleValue(value)); return jsonData; } private static class JsonData { private byte[] className; private byte[] data; public byte[] getClassName() { return className; } public void setClassName(byte[] className) { this.className = className; } public byte[] getData() { return data; } public void setData(byte[] data) { this.data = data; } } }
if (value == null) { return null; } if (value instanceof CacheValueHolder) { CacheValueHolder h = (CacheValueHolder) value; Object bizObject = h.getValue(); h.setValue(null); JsonData[] result = new JsonData[2]; result[0] = encodeJsonData(h); result[1] = encodeJsonData(bizObject); h.setValue(bizObject); return result; } else if (value instanceof CacheMessage) { CacheMessage cm = (CacheMessage) value; Object[] keys = cm.getKeys(); cm.setKeys(null); JsonData[] result = keys == null ? new JsonData[1] : new JsonData[keys.length + 1]; result[0] = encodeJsonData(cm); if (keys != null) { for (int i = 0; i < keys.length; i++) { result[i + 1] = encodeJsonData(keys[i]); } } cm.setKeys(keys); return result; } else { return new JsonData[]{encodeJsonData(value)}; }
962
295
1,257
<methods>public void <init>(boolean) ,public boolean isUseIdentityNumber() <variables>protected boolean useIdentityNumber
alibaba_jetcache
jetcache/jetcache-core/src/main/java/com/alicp/jetcache/support/AbstractLifecycle.java
AbstractLifecycle
init
class AbstractLifecycle { private boolean init; private boolean shutdown; final ReentrantLock reentrantLock = new ReentrantLock(); public final void init() {<FILL_FUNCTION_BODY>} protected void doInit() { } public final void shutdown() { reentrantLock.lock(); try { if (init && !shutdown) { doShutdown(); init = false; shutdown = true; } }finally { reentrantLock.unlock(); } } protected void doShutdown() { } }
reentrantLock.lock(); try { if (!init) { doInit(); init = true; } }finally { reentrantLock.unlock(); }
162
55
217
<no_super_class>
alibaba_jetcache
jetcache/jetcache-core/src/main/java/com/alicp/jetcache/support/AbstractValueDecoder.java
AbstractValueDecoder
apply
class AbstractValueDecoder implements Function<byte[], Object>, ValueEncoders { protected boolean useIdentityNumber; private DecoderMap decoderMap = DecoderMap.defaultInstance(); public AbstractValueDecoder(boolean useIdentityNumber) { this.useIdentityNumber = useIdentityNumber; } protected int parseHeader(byte[] buf) { int x = 0; x = x | (buf[0] & 0xFF); x <<= 8; x = x | (buf[1] & 0xFF); x <<= 8; x = x | (buf[2] & 0xFF); x <<= 8; x = x | (buf[3] & 0xFF); return x; } protected abstract Object doApply(byte[] buffer) throws Exception; @Override public Object apply(byte[] buffer) {<FILL_FUNCTION_BODY>} public boolean isUseIdentityNumber() { return useIdentityNumber; } public void setDecoderMap(DecoderMap decoderMap) { this.decoderMap = decoderMap; } }
try { if (useIdentityNumber) { decoderMap.initDefaultDecoder(); int identityNumber = parseHeader(buffer); AbstractValueDecoder decoder = decoderMap.getDecoder(identityNumber); Objects.requireNonNull(decoder, "no decoder for identity number:" + identityNumber); return decoder.doApply(buffer); } else { return doApply(buffer); } } catch (Throwable e) { throw new CacheEncodeException("decode error", e); }
294
136
430
<no_super_class>
alibaba_jetcache
jetcache/jetcache-core/src/main/java/com/alicp/jetcache/support/BroadcastManager.java
BroadcastManager
processNotification
class BroadcastManager implements AutoCloseable { private static Logger logger = LoggerFactory.getLogger(BroadcastManager.class); private final String sourceId = UUID.randomUUID().toString(); private final CacheManager cacheManager; public BroadcastManager(CacheManager cacheManager) { this.cacheManager = cacheManager; } protected void checkConfig(ExternalCacheConfig config) { if (config.getBroadcastChannel() == null) { throw new CacheConfigException("BroadcastChannel not set"); } if (config.getValueEncoder() == null) { throw new CacheConfigException("no value encoder"); } if (config.getValueDecoder() == null) { throw new CacheConfigException("no value decoder"); } } public abstract CacheResult publish(CacheMessage cacheMessage); public abstract void startSubscribe(); @Override public void close() throws Exception { } public String getSourceId() { return sourceId; } public CacheManager getCacheManager() { return cacheManager; } protected void processNotification(byte[] message, Function<byte[], Object> decoder) {<FILL_FUNCTION_BODY>} private void processCacheMessage(CacheMessage cacheMessage) { if (sourceId.equals(cacheMessage.getSourceId())) { return; } Cache cache = cacheManager.getCache(cacheMessage.getArea(), cacheMessage.getCacheName()); if (cache == null) { logger.warn("Cache instance not exists: {},{}", cacheMessage.getArea(), cacheMessage.getCacheName()); return; } Cache absCache = CacheUtil.getAbstractCache(cache); if (!(absCache instanceof MultiLevelCache)) { logger.warn("Cache instance is not MultiLevelCache: {},{}", cacheMessage.getArea(), cacheMessage.getCacheName()); return; } Cache[] caches = ((MultiLevelCache) absCache).caches(); Set<Object> keys = Stream.of(cacheMessage.getKeys()).collect(Collectors.toSet()); for (Cache c : caches) { Cache localCache = CacheUtil.getAbstractCache(c); if (localCache instanceof AbstractEmbeddedCache) { ((AbstractEmbeddedCache) localCache).__removeAll(keys); } else { break; } } } }
try { if (message == null) { logger.error("notify message is null"); return; } Object value = decoder.apply(message); if (value == null) { logger.error("notify message is null"); return; } if (value instanceof CacheMessage) { processCacheMessage((CacheMessage) value); } else { logger.error("the message is not instance of CacheMessage, class={}", value.getClass()); } } catch (Throwable e) { SquashedLogger.getLogger(logger).error("receive cache notify error", e); }
605
161
766
<no_super_class>
alibaba_jetcache
jetcache/jetcache-core/src/main/java/com/alicp/jetcache/support/CacheNotifyMonitor.java
CacheNotifyMonitor
afterOperation
class CacheNotifyMonitor implements CacheMonitor { private final BroadcastManager broadcastManager; private final String area; private final String cacheName; private final String sourceId; public CacheNotifyMonitor(CacheManager cacheManager, String area, String cacheName) { this.broadcastManager = cacheManager.getBroadcastManager(area); this.area = area; this.cacheName = cacheName; if (broadcastManager != null) { this.sourceId = broadcastManager.getSourceId(); } else { this.sourceId = null; } } public CacheNotifyMonitor(CacheManager cacheManager, String cacheName) { this(cacheManager, CacheConsts.DEFAULT_AREA, cacheName); } private Object convertKey(Object key, AbstractEmbeddedCache localCache) { Function keyConvertor = localCache.config().getKeyConvertor(); if (keyConvertor == null) { return key; } else { return keyConvertor.apply(key); } } private AbstractEmbeddedCache getLocalCache(AbstractCache absCache) { if (!(absCache instanceof MultiLevelCache)) { return null; } for (Cache c : ((MultiLevelCache) absCache).caches()) { if (c instanceof AbstractEmbeddedCache) { return (AbstractEmbeddedCache) c; } } return null; } @Override public void afterOperation(CacheEvent event) {<FILL_FUNCTION_BODY>} }
if (this.broadcastManager == null) { return; } AbstractCache absCache = CacheUtil.getAbstractCache(event.getCache()); if (absCache.isClosed()) { return; } AbstractEmbeddedCache localCache = getLocalCache(absCache); if (localCache == null) { return; } if (event instanceof CachePutEvent) { CacheMessage m = new CacheMessage(); m.setArea(area); m.setCacheName(cacheName); m.setSourceId(sourceId); CachePutEvent e = (CachePutEvent) event; m.setType(CacheMessage.TYPE_PUT); m.setKeys(new Object[]{convertKey(e.getKey(), localCache)}); broadcastManager.publish(m); } else if (event instanceof CacheRemoveEvent) { CacheMessage m = new CacheMessage(); m.setArea(area); m.setCacheName(cacheName); m.setSourceId(sourceId); CacheRemoveEvent e = (CacheRemoveEvent) event; m.setType(CacheMessage.TYPE_REMOVE); m.setKeys(new Object[]{convertKey(e.getKey(), localCache)}); broadcastManager.publish(m); } else if (event instanceof CachePutAllEvent) { CacheMessage m = new CacheMessage(); m.setArea(area); m.setCacheName(cacheName); m.setSourceId(sourceId); CachePutAllEvent e = (CachePutAllEvent) event; m.setType(CacheMessage.TYPE_PUT_ALL); if (e.getMap() != null) { m.setKeys(e.getMap().keySet().stream().map(k -> convertKey(k, localCache)).toArray()); } broadcastManager.publish(m); } else if (event instanceof CacheRemoveAllEvent) { CacheMessage m = new CacheMessage(); m.setArea(area); m.setCacheName(cacheName); m.setSourceId(sourceId); CacheRemoveAllEvent e = (CacheRemoveAllEvent) event; m.setType(CacheMessage.TYPE_REMOVE_ALL); if (e.getKeys() != null) { m.setKeys(e.getKeys().stream().map(k -> convertKey(k, localCache)).toArray()); } broadcastManager.publish(m); }
399
621
1,020
<no_super_class>
alibaba_jetcache
jetcache/jetcache-core/src/main/java/com/alicp/jetcache/support/DecoderMap.java
DecoderMap
initDefaultDecoder
class DecoderMap { private final ConcurrentHashMap<Integer, AbstractValueDecoder> decoderMap = new ConcurrentHashMap<>(); private volatile boolean inited = false; private final ReentrantLock reentrantLock = new ReentrantLock(); private static final DecoderMap instance = new DecoderMap(); public DecoderMap() { } public static DecoderMap defaultInstance() { return instance; } public AbstractValueDecoder getDecoder(int identityNumber) { return decoderMap.get(identityNumber); } public void register(int identityNumber, AbstractValueDecoder decoder) { decoderMap.put(identityNumber, decoder); } public void clear() { decoderMap.clear(); } public ReentrantLock getLock() { return reentrantLock; } public void setInited(boolean inited) { this.inited = inited; } public void initDefaultDecoder() {<FILL_FUNCTION_BODY>} public static JavaValueDecoder defaultJavaValueDecoder() { try { Class.forName("org.springframework.core.ConfigurableObjectInputStream"); return SpringJavaValueDecoder.INSTANCE; } catch (ClassNotFoundException e) { return JavaValueDecoder.INSTANCE; } } }
if (inited) { return; } reentrantLock.lock(); try { if (inited) { return; } register(SerialPolicy.IDENTITY_NUMBER_JAVA, defaultJavaValueDecoder()); register(SerialPolicy.IDENTITY_NUMBER_KRYO4, KryoValueDecoder.INSTANCE); register(SerialPolicy.IDENTITY_NUMBER_KRYO5, Kryo5ValueDecoder.INSTANCE); // register(SerialPolicy.IDENTITY_NUMBER_FASTJSON2, Fastjson2ValueDecoder.INSTANCE); inited = true; } finally { reentrantLock.unlock(); }
353
181
534
<no_super_class>
alibaba_jetcache
jetcache/jetcache-core/src/main/java/com/alicp/jetcache/support/DefaultMetricsManager.java
DefaultMetricsManager
firstDelay
class DefaultMetricsManager { private static final Logger logger = LoggerFactory.getLogger(DefaultMetricsManager.class); protected final CopyOnWriteArrayList<DefaultCacheMonitor> monitorList = new CopyOnWriteArrayList(); private ScheduledFuture<?> future; private final int resetTime; private final TimeUnit resetTimeUnit; private final Consumer<StatInfo> metricsCallback; private final ReentrantLock reentrantLock = new ReentrantLock(); public DefaultMetricsManager(int resetTime, TimeUnit resetTimeUnit, Consumer<StatInfo> metricsCallback) { this.resetTime = resetTime; this.resetTimeUnit = resetTimeUnit; this.metricsCallback = metricsCallback; } public DefaultMetricsManager(int resetTime, TimeUnit resetTimeUnit) { this(resetTime, resetTimeUnit, false); } public DefaultMetricsManager(int resetTime, TimeUnit resetTimeUnit, boolean verboseLog) { this.resetTime = resetTime; this.resetTimeUnit = resetTimeUnit; this.metricsCallback = new StatInfoLogger(verboseLog); } final Runnable cmd = new Runnable() { private long time = System.currentTimeMillis(); @Override public void run() { try { List<CacheStat> stats = monitorList.stream().map((m) -> { CacheStat stat = m.getCacheStat(); m.resetStat(); return stat; }).collect(Collectors.toList()); long endTime = System.currentTimeMillis(); StatInfo statInfo = new StatInfo(); statInfo.setStartTime(time); statInfo.setEndTime(endTime); statInfo.setStats(stats); time = endTime; metricsCallback.accept(statInfo); } catch (Exception e) { logger.error("jetcache DefaultMetricsManager error", e); } } }; public void start() { reentrantLock.lock(); try { if (future != null) { return; } long delay = firstDelay(resetTime, resetTimeUnit); future = JetCacheExecutor.defaultExecutor().scheduleAtFixedRate( cmd, delay, resetTimeUnit.toMillis(resetTime), TimeUnit.MILLISECONDS); logger.info("cache stat period at " + resetTime + " " + resetTimeUnit); }finally { reentrantLock.unlock(); } } public void stop() { reentrantLock.lock(); try { future.cancel(false); logger.info("cache stat canceled"); future = null; }finally { reentrantLock.unlock(); } } public void add(DefaultCacheMonitor... monitors) { monitorList.addAll(Arrays.asList(monitors)); } public void clear() { monitorList.clear(); } protected static long firstDelay(int resetTime, TimeUnit resetTimeUnit) {<FILL_FUNCTION_BODY>} protected static LocalDateTime computeFirstResetTime(LocalDateTime baseTime, int time, TimeUnit unit) { if (unit != TimeUnit.SECONDS && unit != TimeUnit.MINUTES && unit != TimeUnit.HOURS && unit != TimeUnit.DAYS) { throw new IllegalArgumentException(); } LocalDateTime t = baseTime; switch (unit) { case DAYS: t = t.plusDays(1).withHour(0).withMinute(0).withSecond(0).withNano(0); break; case HOURS: if (24 % time == 0) { t = t.plusHours(time - t.getHour() % time); } else { t = t.plusHours(1); } t = t.withMinute(0).withSecond(0).withNano(0); break; case MINUTES: if (60 % time == 0) { t = t.plusMinutes(time - t.getMinute() % time); } else { t = t.plusMinutes(1); } t = t.withSecond(0).withNano(0); break; case SECONDS: if (60 % time == 0) { t = t.plusSeconds(time - t.getSecond() % time); } else { t = t.plusSeconds(1); } t = t.withNano(0); break; } return t; } }
LocalDateTime firstResetTime = computeFirstResetTime(LocalDateTime.now(), resetTime, resetTimeUnit); return firstResetTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli() - System.currentTimeMillis();
1,182
62
1,244
<no_super_class>
alibaba_jetcache
jetcache/jetcache-core/src/main/java/com/alicp/jetcache/support/Fastjson2KeyConvertor.java
Fastjson2KeyConvertor
apply
class Fastjson2KeyConvertor implements Function<Object, Object> { public static final Fastjson2KeyConvertor INSTANCE = new Fastjson2KeyConvertor(); @Override public Object apply(Object originalKey) {<FILL_FUNCTION_BODY>} }
if (originalKey == null) { return null; } if (originalKey instanceof String) { return originalKey; } return JSON.toJSONString(originalKey);
71
52
123
<no_super_class>
alibaba_jetcache
jetcache/jetcache-core/src/main/java/com/alicp/jetcache/support/Fastjson2ValueDecoder.java
Fastjson2ValueDecoder
parseObject
class Fastjson2ValueDecoder extends AbstractJsonDecoder { public static final Fastjson2ValueDecoder INSTANCE = new Fastjson2ValueDecoder(true); public Fastjson2ValueDecoder(boolean useIdentityNumber) { super(useIdentityNumber); } @Override protected Object parseObject(byte[] buffer, int index, int len, Class clazz) {<FILL_FUNCTION_BODY>} }
String s = new String(buffer, index, len, StandardCharsets.UTF_8); return JSON.parseObject(s, clazz);
109
38
147
<methods>public void <init>(boolean) <variables>
alibaba_jetcache
jetcache/jetcache-core/src/main/java/com/alicp/jetcache/support/FastjsonKeyConvertor.java
FastjsonKeyConvertor
apply
class FastjsonKeyConvertor implements Function<Object, Object> { public static final FastjsonKeyConvertor INSTANCE = new FastjsonKeyConvertor(); @Override public Object apply(Object originalKey) {<FILL_FUNCTION_BODY>} }
if (originalKey == null) { return null; } if (originalKey instanceof String) { return originalKey; } return JSON.toJSONString(originalKey);
68
52
120
<no_super_class>
alibaba_jetcache
jetcache/jetcache-core/src/main/java/com/alicp/jetcache/support/JacksonKeyConvertor.java
JacksonKeyConvertor
apply
class JacksonKeyConvertor implements Function<Object, Object> { public static final JacksonKeyConvertor INSTANCE = new JacksonKeyConvertor(); private static ObjectMapper objectMapper = new ObjectMapper(); @Override public Object apply(Object originalKey) {<FILL_FUNCTION_BODY>} }
if (originalKey == null) { return null; } if (originalKey instanceof CharSequence) { return originalKey.toString(); } try { return objectMapper.writeValueAsString(originalKey); } catch (JsonProcessingException e) { throw new CacheEncodeException("jackson key convert fail", e); }
79
93
172
<no_super_class>
alibaba_jetcache
jetcache/jetcache-core/src/main/java/com/alicp/jetcache/support/JavaValueDecoder.java
JavaValueDecoder
doApply
class JavaValueDecoder extends AbstractValueDecoder { public static final JavaValueDecoder INSTANCE = new JavaValueDecoder(true); public JavaValueDecoder(boolean useIdentityNumber) { super(useIdentityNumber); } @Override public Object doApply(byte[] buffer) throws Exception {<FILL_FUNCTION_BODY>} protected ObjectInputStream buildObjectInputStream(ByteArrayInputStream in) throws IOException { return new ObjectInputStream(in); } }
ByteArrayInputStream in; if (useIdentityNumber) { in = new ByteArrayInputStream(buffer, 4, buffer.length - 4); } else { in = new ByteArrayInputStream(buffer); } ObjectInputStream ois = buildObjectInputStream(in); return ois.readObject();
123
81
204
<methods>public void <init>(boolean) ,public java.lang.Object apply(byte[]) ,public boolean isUseIdentityNumber() ,public void setDecoderMap(com.alicp.jetcache.support.DecoderMap) <variables>private com.alicp.jetcache.support.DecoderMap decoderMap,protected boolean useIdentityNumber
alibaba_jetcache
jetcache/jetcache-core/src/main/java/com/alicp/jetcache/support/JavaValueEncoder.java
JavaValueEncoder
apply
class JavaValueEncoder extends AbstractValueEncoder { public static final JavaValueEncoder INSTANCE = new JavaValueEncoder(true); private static final int INIT_BUF_SIZE = 2048; public JavaValueEncoder(boolean useIdentityNumber) { super(useIdentityNumber); } static ObjectPool<ByteArrayOutputStream> bosPool = new ObjectPool<>(16, new ObjectPool.ObjectFactory<ByteArrayOutputStream>() { @Override public ByteArrayOutputStream create() { return new ByteArrayOutputStream(INIT_BUF_SIZE); } @Override public void reset(ByteArrayOutputStream obj) { obj.reset(); } }); @Override public byte[] apply(Object value) {<FILL_FUNCTION_BODY>} }
ByteArrayOutputStream bos = null; try { bos = bosPool.borrowObject(); if (useIdentityNumber) { bos.write((SerialPolicy.IDENTITY_NUMBER_JAVA >> 24) & 0xFF); bos.write((SerialPolicy.IDENTITY_NUMBER_JAVA >> 16) & 0xFF); bos.write((SerialPolicy.IDENTITY_NUMBER_JAVA >> 8) & 0xFF); bos.write(SerialPolicy.IDENTITY_NUMBER_JAVA & 0xFF); } ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(value); oos.flush(); return bos.toByteArray(); } catch (IOException e) { StringBuilder sb = new StringBuilder("Java Encode error. "); sb.append("msg=").append(e.getMessage()); throw new CacheEncodeException(sb.toString(), e); } finally { if (bos != null) { bosPool.returnObject(bos); } }
206
277
483
<methods>public void <init>(boolean) ,public boolean isUseIdentityNumber() <variables>protected boolean useIdentityNumber
alibaba_jetcache
jetcache/jetcache-core/src/main/java/com/alicp/jetcache/support/JetCacheExecutor.java
JetCacheExecutor
defaultExecutor
class JetCacheExecutor { protected volatile static ScheduledExecutorService defaultExecutor; protected volatile static ScheduledExecutorService heavyIOExecutor; private static final ReentrantLock reentrantLock = new ReentrantLock(); private static AtomicInteger threadCount = new AtomicInteger(0); static { Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { if (defaultExecutor != null) { defaultExecutor.shutdownNow(); } if (heavyIOExecutor != null) { heavyIOExecutor.shutdownNow(); } } }); } public static ScheduledExecutorService defaultExecutor() {<FILL_FUNCTION_BODY>} public static ScheduledExecutorService heavyIOExecutor() { if (heavyIOExecutor != null) { return heavyIOExecutor; } reentrantLock.lock(); try { if (heavyIOExecutor == null) { ThreadFactory tf = r -> { Thread t = new Thread(r, "JetCacheHeavyIOExecutor" + threadCount.getAndIncrement()); t.setDaemon(true); return t; }; heavyIOExecutor = new ScheduledThreadPoolExecutor( 10, tf, new ThreadPoolExecutor.DiscardPolicy()); } }finally { reentrantLock.unlock(); } return heavyIOExecutor; } public static void setDefaultExecutor(ScheduledExecutorService executor) { JetCacheExecutor.defaultExecutor = executor; } public static void setHeavyIOExecutor(ScheduledExecutorService heavyIOExecutor) { JetCacheExecutor.heavyIOExecutor = heavyIOExecutor; } }
if (defaultExecutor != null) { return defaultExecutor; } reentrantLock.lock(); try{ if (defaultExecutor == null) { ThreadFactory tf = r -> { Thread t = new Thread(r, "JetCacheDefaultExecutor"); t.setDaemon(true); return t; }; defaultExecutor = new ScheduledThreadPoolExecutor( 1, tf, new ThreadPoolExecutor.DiscardPolicy()); } }finally { reentrantLock.unlock(); } return defaultExecutor;
447
148
595
<no_super_class>
alibaba_jetcache
jetcache/jetcache-core/src/main/java/com/alicp/jetcache/support/Kryo5ValueDecoder.java
Kryo5ValueDecoder
doApply
class Kryo5ValueDecoder extends AbstractValueDecoder { public static final Kryo5ValueDecoder INSTANCE = new Kryo5ValueDecoder(true); public Kryo5ValueDecoder(boolean useIdentityNumber) { super(useIdentityNumber); } @Override public Object doApply(byte[] buffer) {<FILL_FUNCTION_BODY>} }
ByteArrayInputStream in; if (useIdentityNumber) { in = new ByteArrayInputStream(buffer, 4, buffer.length - 4); } else { in = new ByteArrayInputStream(buffer); } Input input = new Input(in); Kryo5ValueEncoder.Kryo5Cache kryoCache = null; try { kryoCache = Kryo5ValueEncoder.kryoCacheObjectPool.borrowObject(); Kryo kryo = kryoCache.getKryo(); ClassLoader classLoader = Kryo5ValueDecoder.class.getClassLoader(); Thread t = Thread.currentThread(); if (t != null) { ClassLoader ctxClassLoader = t.getContextClassLoader(); if (ctxClassLoader != null) { classLoader = ctxClassLoader; } } kryo.setClassLoader(classLoader); return kryo.readClassAndObject(input); }finally { if(kryoCache != null){ Kryo5ValueEncoder.kryoCacheObjectPool.returnObject(kryoCache); } }
103
299
402
<methods>public void <init>(boolean) ,public java.lang.Object apply(byte[]) ,public boolean isUseIdentityNumber() ,public void setDecoderMap(com.alicp.jetcache.support.DecoderMap) <variables>private com.alicp.jetcache.support.DecoderMap decoderMap,protected boolean useIdentityNumber
alibaba_jetcache
jetcache/jetcache-core/src/main/java/com/alicp/jetcache/support/Kryo5ValueEncoder.java
Kryo5Cache
apply
class Kryo5Cache { final Output output; final Kryo kryo; public Kryo5Cache(){ kryo = new Kryo(); kryo.setDefaultSerializer(CompatibleFieldSerializer.class); kryo.setRegistrationRequired(false); output = new Output(INIT_BUFFER_SIZE, -1); } public Output getOutput(){ return output; } public Kryo getKryo(){ return kryo; } } public Kryo5ValueEncoder(boolean useIdentityNumber) { super(useIdentityNumber); } @Override public byte[] apply(Object value) {<FILL_FUNCTION_BODY>
Kryo5Cache kryoCache = null; try { kryoCache = kryoCacheObjectPool.borrowObject(); if (useIdentityNumber) { writeInt(kryoCache.getOutput(), SerialPolicy.IDENTITY_NUMBER_KRYO5); } kryoCache.getKryo().writeClassAndObject(kryoCache.getOutput(), value); return kryoCache.getOutput().toBytes(); } catch (Exception e) { StringBuilder sb = new StringBuilder("Kryo Encode error. "); sb.append("msg=").append(e.getMessage()); throw new CacheEncodeException(sb.toString(), e); } finally { if (kryoCache != null) { kryoCacheObjectPool.returnObject(kryoCache); } }
193
218
411
<methods>public void <init>(boolean) ,public boolean isUseIdentityNumber() <variables>protected boolean useIdentityNumber
alibaba_jetcache
jetcache/jetcache-core/src/main/java/com/alicp/jetcache/support/KryoValueDecoder.java
KryoValueDecoder
doApply
class KryoValueDecoder extends AbstractValueDecoder { public static final KryoValueDecoder INSTANCE = new KryoValueDecoder(true); public KryoValueDecoder(boolean useIdentityNumber) { super(useIdentityNumber); } @Override public Object doApply(byte[] buffer) {<FILL_FUNCTION_BODY>} }
ByteArrayInputStream in; if (useIdentityNumber) { in = new ByteArrayInputStream(buffer, 4, buffer.length - 4); } else { in = new ByteArrayInputStream(buffer); } Input input = new Input(in); KryoValueEncoder.KryoCache kryoCache = null; try { kryoCache = KryoValueEncoder.kryoCacheObjectPool.borrowObject(); Kryo kryo = kryoCache.getKryo(); ClassLoader classLoader = KryoValueDecoder.class.getClassLoader(); Thread t = Thread.currentThread(); if (t != null) { ClassLoader ctxClassLoader = t.getContextClassLoader(); if (ctxClassLoader != null) { classLoader = ctxClassLoader; } } kryo.setClassLoader(classLoader); return kryo.readClassAndObject(input); }finally { if(kryoCache != null){ KryoValueEncoder.kryoCacheObjectPool.returnObject(kryoCache); } }
99
294
393
<methods>public void <init>(boolean) ,public java.lang.Object apply(byte[]) ,public boolean isUseIdentityNumber() ,public void setDecoderMap(com.alicp.jetcache.support.DecoderMap) <variables>private com.alicp.jetcache.support.DecoderMap decoderMap,protected boolean useIdentityNumber
alibaba_jetcache
jetcache/jetcache-core/src/main/java/com/alicp/jetcache/support/KryoValueEncoder.java
KryoCache
apply
class KryoCache { final Output output; final Kryo kryo; public KryoCache(){ kryo = new Kryo(); kryo.setDefaultSerializer(CompatibleFieldSerializer.class); byte[] buffer = new byte[INIT_BUFFER_SIZE]; output = new Output(buffer, -1); } public Output getOutput(){ return output; } public Kryo getKryo(){ return kryo; } } public KryoValueEncoder(boolean useIdentityNumber) { super(useIdentityNumber); } @Override public byte[] apply(Object value) {<FILL_FUNCTION_BODY>
KryoCache kryoCache = null; try { kryoCache = kryoCacheObjectPool.borrowObject(); // Output output = new Output(kryoCache.getBuffer(), -1); // output.clear(); Output output = kryoCache.getOutput(); if (useIdentityNumber) { writeInt(output, SerialPolicy.IDENTITY_NUMBER_KRYO4); } kryoCache.getKryo().writeClassAndObject(output, value); return output.toBytes(); } catch (Exception e) { StringBuilder sb = new StringBuilder("Kryo Encode error. "); sb.append("msg=").append(e.getMessage()); throw new CacheEncodeException(sb.toString(), e); } finally { if (kryoCache != null) { kryoCacheObjectPool.returnObject(kryoCache); } }
186
239
425
<methods>public void <init>(boolean) ,public boolean isUseIdentityNumber() <variables>protected boolean useIdentityNumber
alibaba_jetcache
jetcache/jetcache-core/src/main/java/com/alicp/jetcache/support/ObjectPool.java
ObjectPool
returnObject
class ObjectPool<T> { private final ArrayBlockingQueue<T> queue; private final int size; private final ObjectFactory<T> factory; private static final Logger logger = LoggerFactory.getLogger(ObjectPool.class); public ObjectPool(int size, ObjectFactory<T> factory) { this.size = size; this.factory = factory; queue = new ArrayBlockingQueue<>(size); for (int i = 0; i < size; i++) { queue.add(factory.create()); } logger.debug("Init the object pool with size {}", size); } public T borrowObject() { T t = queue.poll(); if(t == null) { logger.debug("The pool is not enough, create a new object"); return factory.create(); } return t; } public void returnObject(T obj) {<FILL_FUNCTION_BODY>} public interface ObjectFactory<T> { T create(); void reset(T obj); } }
if (obj == null) { return; } factory.reset(obj); queue.offer(obj);
272
36
308
<no_super_class>
alibaba_jetcache
jetcache/jetcache-core/src/main/java/com/alicp/jetcache/support/SquashedLogger.java
SquashedLogger
error
class SquashedLogger { private static final int DEFAULT_INTERVAL_SECONDS = 10; private static final ConcurrentHashMap<Logger, SquashedLogger> MAP = new ConcurrentHashMap<>(); private final Logger logger; private final long interval; private volatile AtomicLong lastLogTime; private SquashedLogger(Logger logger, int intervalSeconds) { this.logger = logger; this.lastLogTime = new AtomicLong(0); this.interval = Duration.ofSeconds(intervalSeconds).toNanos(); } public static SquashedLogger getLogger(Logger target, int intervalSeconds) { SquashedLogger result = MAP.get(target); if (result == null) { result = MAP.computeIfAbsent(target, k -> new SquashedLogger(k, intervalSeconds)); } return result; } public static SquashedLogger getLogger(Logger target) { return getLogger(target, DEFAULT_INTERVAL_SECONDS); } private boolean shouldLogEx() { long now = System.nanoTime(); long last = lastLogTime.get(); if (Math.abs(now - last) > interval) { return lastLogTime.compareAndSet(last, now); } else { return false; } } public void error(CharSequence msg, Throwable e) {<FILL_FUNCTION_BODY>} }
if (shouldLogEx()) { logger.error(msg.toString(), e); } else { StringBuilder sb; if (msg instanceof StringBuilder) { sb = (StringBuilder) msg; } else { sb = new StringBuilder(msg.length() + 256); sb.append(msg); } sb.append(' '); while (e != null) { sb.append(e); e = e.getCause(); if (e != null) { sb.append("\ncause by "); } } logger.error(msg.toString()); }
377
163
540
<no_super_class>
alibaba_jetcache
jetcache/jetcache-core/src/main/java/com/alicp/jetcache/template/CacheBuilderTemplate.java
CacheBuilderTemplate
getCacheBuilder
class CacheBuilderTemplate { private final boolean penetrationProtect; private final Map<String, CacheBuilder>[] cacheBuilders; private final List<CacheMonitorInstaller> cacheMonitorInstallers = new ArrayList<>(); @SafeVarargs public CacheBuilderTemplate(boolean penetrationProtect, Map<String, CacheBuilder>... cacheBuilders) { this.penetrationProtect = penetrationProtect; this.cacheBuilders = cacheBuilders; } public boolean isPenetrationProtect() { return penetrationProtect; } public CacheBuilder getCacheBuilder(int level, String area) {<FILL_FUNCTION_BODY>} public List<CacheMonitorInstaller> getCacheMonitorInstallers() { return cacheMonitorInstallers; } }
CacheBuilder cb = cacheBuilders[level].get(area); if (cb instanceof AbstractCacheBuilder) { return (CacheBuilder) ((AbstractCacheBuilder<?>) cb).clone(); } else { return cb; }
200
62
262
<no_super_class>
alibaba_jetcache
jetcache/jetcache-core/src/main/java/com/alicp/jetcache/template/MetricsMonitorInstaller.java
MetricsMonitorInstaller
addMonitors
class MetricsMonitorInstaller extends AbstractLifecycle implements CacheMonitorInstaller { private final Consumer<StatInfo> metricsCallback; private final Duration interval; private DefaultMetricsManager metricsManager; public MetricsMonitorInstaller(Consumer<StatInfo> metricsCallback, Duration interval) { this.metricsCallback = metricsCallback; this.interval = interval; } @Override protected void doInit() { if (metricsCallback != null && interval != null) { metricsManager = new DefaultMetricsManager((int) interval.toMinutes(), TimeUnit.MINUTES, metricsCallback); metricsManager.start(); } } @Override protected void doShutdown() { if (metricsManager != null) { metricsManager.stop(); metricsManager.clear(); metricsManager = null; } } @Override public void addMonitors(CacheManager cacheManager, Cache cache, QuickConfig quickConfig) {<FILL_FUNCTION_BODY>} }
if (metricsManager == null) { return; } cache = CacheUtil.getAbstractCache(cache); if (cache instanceof MultiLevelCache) { MultiLevelCache mc = (MultiLevelCache) cache; if (mc.caches().length == 2) { Cache local = mc.caches()[0]; Cache remote = mc.caches()[1]; DefaultCacheMonitor localMonitor = new DefaultCacheMonitor(quickConfig.getName() + "_local"); local.config().getMonitors().add(localMonitor); DefaultCacheMonitor remoteMonitor = new DefaultCacheMonitor(quickConfig.getName() + "_remote"); remote.config().getMonitors().add(remoteMonitor); metricsManager.add(localMonitor, remoteMonitor); } } DefaultCacheMonitor monitor = new DefaultCacheMonitor(quickConfig.getName()); cache.config().getMonitors().add(monitor); metricsManager.add(monitor);
263
236
499
<methods>public non-sealed void <init>() ,public final void init() ,public final void shutdown() <variables>private boolean init,final java.util.concurrent.locks.ReentrantLock reentrantLock,private boolean shutdown
alibaba_jetcache
jetcache/jetcache-core/src/main/java/com/alicp/jetcache/template/NotifyMonitorInstaller.java
NotifyMonitorInstaller
addMonitors
class NotifyMonitorInstaller implements CacheMonitorInstaller { private final Function<String, CacheBuilder> remoteBuilderTemplate; public NotifyMonitorInstaller(Function<String, CacheBuilder> remoteBuilderTemplate) { this.remoteBuilderTemplate = remoteBuilderTemplate; } @Override public void addMonitors(CacheManager cacheManager, Cache cache, QuickConfig quickConfig) {<FILL_FUNCTION_BODY>} }
if (quickConfig.getSyncLocal() == null || !quickConfig.getSyncLocal()) { return; } if (!(CacheUtil.getAbstractCache(cache) instanceof MultiLevelCache)) { return; } String area = quickConfig.getArea(); final ExternalCacheBuilder cacheBuilder = (ExternalCacheBuilder) remoteBuilderTemplate.apply(area); if (cacheBuilder == null || !cacheBuilder.supportBroadcast() || cacheBuilder.getConfig().getBroadcastChannel() == null) { return; } if (cacheManager.getBroadcastManager(area) == null) { BroadcastManager cm = cacheBuilder.createBroadcastManager(cacheManager); if (cm != null) { cm.startSubscribe(); cacheManager.putBroadcastManager(area, cm); } } CacheMonitor monitor = new CacheNotifyMonitor(cacheManager, area, quickConfig.getName()); cache.config().getMonitors().add(monitor);
107
253
360
<no_super_class>
alibaba_jetcache
jetcache/jetcache-core/src/main/java/com/alicp/jetcache/template/QuickConfig.java
Builder
build
class Builder { private String area = CacheConsts.DEFAULT_AREA; private final String name; private Duration expire; private Duration localExpire; private Integer localLimit; private CacheType cacheType; private Boolean syncLocal; private Function<Object, Object> keyConvertor; private Function<Object, byte[]> valueEncoder; private Function<byte[], Object> valueDecoder; private Boolean cacheNullValue; private Boolean useAreaInPrefix; private Boolean penetrationProtect; private Duration penetrationProtectTimeout; private RefreshPolicy refreshPolicy; private CacheLoader<? extends Object, ? extends Object> loader; Builder(String name) { Objects.requireNonNull(name); this.name = name; } Builder(String area, String name) { Objects.requireNonNull(area); Objects.requireNonNull(name); this.area = area; this.name = name; } public QuickConfig build() {<FILL_FUNCTION_BODY>} public Builder expire(Duration expire) { this.expire = expire; return this; } public Builder localExpire(Duration localExpire) { this.localExpire = localExpire; return this; } public Builder localLimit(Integer localLimit) { this.localLimit = localLimit; return this; } public Builder cacheType(CacheType cacheType) { this.cacheType = cacheType; return this; } public Builder syncLocal(Boolean syncLocal) { this.syncLocal = syncLocal; return this; } public Builder keyConvertor(Function<Object, Object> keyConvertor) { this.keyConvertor = keyConvertor; return this; } public Builder valueEncoder(Function<Object, byte[]> valueEncoder) { this.valueEncoder = valueEncoder; return this; } public Builder valueDecoder(Function<byte[], Object> valueDecoder) { this.valueDecoder = valueDecoder; return this; } public Builder cacheNullValue(Boolean cacheNullValue) { this.cacheNullValue = cacheNullValue; return this; } public Builder useAreaInPrefix(Boolean useAreaInPrefix) { this.useAreaInPrefix = useAreaInPrefix; return this; } public Builder penetrationProtect(Boolean penetrationProtect) { this.penetrationProtect = penetrationProtect; return this; } public Builder penetrationProtectTimeout(Duration penetrationProtectTimeout) { this.penetrationProtectTimeout = penetrationProtectTimeout; return this; } public Builder refreshPolicy(RefreshPolicy refreshPolicy) { this.refreshPolicy = refreshPolicy; return this; } public <K, V> Builder loader(CacheLoader<K, V> loader) { this.loader = loader; return this; } }
QuickConfig c = new QuickConfig(); c.area = area; c.name = name; c.expire = expire; c.localExpire = localExpire; c.localLimit = localLimit; c.cacheType = cacheType; c.syncLocal = syncLocal; c.keyConvertor = keyConvertor; c.valueEncoder = valueEncoder; c.valueDecoder = valueDecoder; c.cacheNullValue = cacheNullValue; c.useAreaInPrefix = useAreaInPrefix; c.penetrationProtect = penetrationProtect; c.penetrationProtectTimeout = penetrationProtectTimeout; c.refreshPolicy = refreshPolicy; c.loader = loader; return c;
788
199
987
<no_super_class>
alibaba_jetcache
jetcache/jetcache-starter/jetcache-autoconfigure/src/main/java/com/alicp/jetcache/autoconfigure/AbstractCacheAutoInit.java
AbstractCacheAutoInit
afterPropertiesSet
class AbstractCacheAutoInit implements InitializingBean { private static Logger logger = LoggerFactory.getLogger(AbstractCacheAutoInit.class); @Autowired protected ConfigurableEnvironment environment; @Autowired protected AutoConfigureBeans autoConfigureBeans; private final ReentrantLock reentrantLock = new ReentrantLock(); protected String[] typeNames; private volatile boolean inited = false; public AbstractCacheAutoInit(String... cacheTypes) { Objects.requireNonNull(cacheTypes,"cacheTypes can't be null"); Assert.isTrue(cacheTypes.length > 0, "cacheTypes length is 0"); this.typeNames = cacheTypes; } @Override public void afterPropertiesSet() {<FILL_FUNCTION_BODY>} private void process(String prefix, Map cacheBuilders, boolean local) { ConfigTree resolver = new ConfigTree(environment, prefix); Map<String, Object> m = resolver.getProperties(); Set<String> cacheAreaNames = resolver.directChildrenKeys(); for (String cacheArea : cacheAreaNames) { final Object configType = m.get(cacheArea + ".type"); boolean match = Arrays.stream(typeNames).anyMatch((tn) -> tn.equals(configType)); if (!match) { continue; } ConfigTree ct = resolver.subTree(cacheArea + "."); logger.info("init cache area {} , type= {}", cacheArea, typeNames[0]); CacheBuilder c = initCache(ct, local ? "local." + cacheArea : "remote." + cacheArea); cacheBuilders.put(cacheArea, c); } } protected void parseGeneralConfig(CacheBuilder builder, ConfigTree ct) { AbstractCacheBuilder acb = (AbstractCacheBuilder) builder; acb.keyConvertor(new ParserFunction(ct.getProperty("keyConvertor", KeyConvertor.FASTJSON2))); String expireAfterWriteInMillis = ct.getProperty("expireAfterWriteInMillis"); if (expireAfterWriteInMillis == null) { // compatible with 2.1 expireAfterWriteInMillis = ct.getProperty("defaultExpireInMillis"); } if (expireAfterWriteInMillis != null) { acb.setExpireAfterWriteInMillis(Long.parseLong(expireAfterWriteInMillis)); } String expireAfterAccessInMillis = ct.getProperty("expireAfterAccessInMillis"); if (expireAfterAccessInMillis != null) { acb.setExpireAfterAccessInMillis(Long.parseLong(expireAfterAccessInMillis)); } } protected abstract CacheBuilder initCache(ConfigTree ct, String cacheAreaWithPrefix); }
if (!inited) { reentrantLock.lock(); try{ if (!inited) { process("jetcache.local.", autoConfigureBeans.getLocalCacheBuilders(), true); process("jetcache.remote.", autoConfigureBeans.getRemoteCacheBuilders(), false); inited = true; } }finally { reentrantLock.unlock(); } }
719
111
830
<no_super_class>
alibaba_jetcache
jetcache/jetcache-starter/jetcache-autoconfigure/src/main/java/com/alicp/jetcache/autoconfigure/BeanDependencyManager.java
BeanDependencyManager
postProcessBeanFactory
class BeanDependencyManager implements BeanFactoryPostProcessor { @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {<FILL_FUNCTION_BODY>} }
String[] autoInitBeanNames = beanFactory.getBeanNamesForType(AbstractCacheAutoInit.class, false, false); if (autoInitBeanNames != null) { BeanDefinition bd = beanFactory.getBeanDefinition(JetCacheAutoConfiguration.GLOBAL_CACHE_CONFIG_NAME); String[] dependsOn = bd.getDependsOn(); if (dependsOn == null) { dependsOn = new String[0]; } int oldLen = dependsOn.length; dependsOn = Arrays.copyOf(dependsOn, dependsOn.length + autoInitBeanNames.length); System.arraycopy(autoInitBeanNames,0, dependsOn, oldLen, autoInitBeanNames.length); bd.setDependsOn(dependsOn); }
56
199
255
<no_super_class>
alibaba_jetcache
jetcache/jetcache-starter/jetcache-autoconfigure/src/main/java/com/alicp/jetcache/autoconfigure/ConfigTree.java
ConfigTree
getProperties
class ConfigTree { private ConfigurableEnvironment environment; private String prefix; public ConfigTree(ConfigurableEnvironment environment, String prefix) { Assert.notNull(environment, "environment is required"); Assert.notNull(prefix, "prefix is required"); this.environment = environment; this.prefix = prefix; } public ConfigTree subTree(String prefix) { return new ConfigTree(environment, fullPrefixOrKey(prefix)); } private String fullPrefixOrKey(String prefixOrKey) { return this.prefix + prefixOrKey; } public Map<String, Object> getProperties() {<FILL_FUNCTION_BODY>} public boolean containsProperty(String key) { key = fullPrefixOrKey(key); return environment.containsProperty(key); } public String getProperty(String key) { key = fullPrefixOrKey(key); return environment.getProperty(key); } public String getProperty(String key, String defaultValue) { if (containsProperty(key)) { return getProperty(key); } else { return defaultValue; } } public boolean getProperty(String key, boolean defaultValue) { if (containsProperty(key)) { return Boolean.parseBoolean(getProperty(key)); } else { return defaultValue; } } public int getProperty(String key, int defaultValue) { if (containsProperty(key)) { return Integer.parseInt(getProperty(key)); } else { return defaultValue; } } public long getProperty(String key, long defaultValue) { if (containsProperty(key)) { return Long.parseLong(getProperty(key)); } else { return defaultValue; } } public String getPrefix() { return prefix; } public Set<String> directChildrenKeys() { Map<String, Object> m = getProperties(); return m.keySet().stream().map( s -> s.indexOf('.') >= 0 ? s.substring(0, s.indexOf('.')) : null) .filter(s -> s != null) .collect(Collectors.toSet()); } }
Map<String, Object> m = new HashMap<>(); for (PropertySource<?> source : environment.getPropertySources()) { if (source instanceof EnumerablePropertySource) { for (String name : ((EnumerablePropertySource<?>) source) .getPropertyNames()) { if (name != null && name.startsWith(prefix)) { String subKey = name.substring(prefix.length()); m.put(subKey, environment.getProperty(name)); } } } } return m;
574
141
715
<no_super_class>
alibaba_jetcache
jetcache/jetcache-starter/jetcache-autoconfigure/src/main/java/com/alicp/jetcache/autoconfigure/EmbeddedCacheAutoInit.java
EmbeddedCacheAutoInit
parseGeneralConfig
class EmbeddedCacheAutoInit extends AbstractCacheAutoInit { public EmbeddedCacheAutoInit(String... cacheTypes) { super(cacheTypes); } @Override protected void parseGeneralConfig(CacheBuilder builder, ConfigTree ct) {<FILL_FUNCTION_BODY>} }
super.parseGeneralConfig(builder, ct); EmbeddedCacheBuilder ecb = (EmbeddedCacheBuilder) builder; ecb.limit(Integer.parseInt(ct.getProperty("limit", String.valueOf(CacheConsts.DEFAULT_LOCAL_LIMIT))));
78
74
152
<methods>public transient void <init>(java.lang.String[]) ,public void afterPropertiesSet() <variables>protected com.alicp.jetcache.autoconfigure.AutoConfigureBeans autoConfigureBeans,protected ConfigurableEnvironment environment,private volatile boolean inited,private static Logger logger,private final java.util.concurrent.locks.ReentrantLock reentrantLock,protected java.lang.String[] typeNames
alibaba_jetcache
jetcache/jetcache-starter/jetcache-autoconfigure/src/main/java/com/alicp/jetcache/autoconfigure/ExternalCacheAutoInit.java
ExternalCacheAutoInit
parseBroadcastChannel
class ExternalCacheAutoInit extends AbstractCacheAutoInit { public ExternalCacheAutoInit(String... cacheTypes) { super(cacheTypes); } @Override protected void parseGeneralConfig(CacheBuilder builder, ConfigTree ct) { super.parseGeneralConfig(builder, ct); ExternalCacheBuilder ecb = (ExternalCacheBuilder) builder; ecb.setKeyPrefix(ct.getProperty("keyPrefix")); ecb.setBroadcastChannel(parseBroadcastChannel(ct)); ecb.setValueEncoder(new ParserFunction(ct.getProperty("valueEncoder", CacheConsts.DEFAULT_SERIAL_POLICY))); ecb.setValueDecoder(new ParserFunction(ct.getProperty("valueDecoder", CacheConsts.DEFAULT_SERIAL_POLICY))); } protected String parseBroadcastChannel(ConfigTree ct) {<FILL_FUNCTION_BODY>} }
String broadcastChannel = ct.getProperty("broadcastChannel"); if (broadcastChannel != null && !"".equals(broadcastChannel.trim())) { return broadcastChannel.trim(); } else { return null; }
236
66
302
<methods>public transient void <init>(java.lang.String[]) ,public void afterPropertiesSet() <variables>protected com.alicp.jetcache.autoconfigure.AutoConfigureBeans autoConfigureBeans,protected ConfigurableEnvironment environment,private volatile boolean inited,private static Logger logger,private final java.util.concurrent.locks.ReentrantLock reentrantLock,protected java.lang.String[] typeNames
alibaba_jetcache
jetcache/jetcache-starter/jetcache-autoconfigure/src/main/java/com/alicp/jetcache/autoconfigure/JedisFactory.java
JedisFactory
getObject
class JedisFactory implements FactoryBean<UnifiedJedis> { private String key; private Class<?> poolClass; @Autowired private AutoConfigureBeans autoConfigureBeans; private boolean inited; private UnifiedJedis unifiedJedis; public JedisFactory(String key, Class<? extends UnifiedJedis> poolClass){ this.key = key; this.poolClass = poolClass; } public String getKey() { return key; } @Override public UnifiedJedis getObject() throws Exception {<FILL_FUNCTION_BODY>} @Override public Class<?> getObjectType() { return poolClass; } @Override public boolean isSingleton() { return true; } }
if (!inited) { unifiedJedis = (UnifiedJedis) autoConfigureBeans.getCustomContainer().get("jedis." + key); inited = true; } return unifiedJedis;
220
64
284
<no_super_class>
alibaba_jetcache
jetcache/jetcache-starter/jetcache-autoconfigure/src/main/java/com/alicp/jetcache/autoconfigure/JedisPoolFactory.java
JedisPoolFactory
getObject
class JedisPoolFactory implements FactoryBean<Pool<Jedis>> { private String key; private Class<?> poolClass; @Autowired private AutoConfigureBeans autoConfigureBeans; private boolean inited; private Pool<Jedis> jedisPool; public JedisPoolFactory(String key, Class<? extends Pool<Jedis>> poolClass){ this.key = key; this.poolClass = poolClass; } public String getKey() { return key; } @Override public Pool<Jedis> getObject() throws Exception {<FILL_FUNCTION_BODY>} @Override public Class<?> getObjectType() { return poolClass; } @Override public boolean isSingleton() { return true; } }
if (!inited) { jedisPool = (Pool<Jedis>) autoConfigureBeans.getCustomContainer().get("jedisPool." + key); inited = true; } return jedisPool;
223
64
287
<no_super_class>
alibaba_jetcache
jetcache/jetcache-starter/jetcache-autoconfigure/src/main/java/com/alicp/jetcache/autoconfigure/JetCacheAutoConfiguration.java
JetCacheAutoConfiguration
globalCacheConfig
class JetCacheAutoConfiguration { public static final String GLOBAL_CACHE_CONFIG_NAME = "globalCacheConfig"; @Bean(destroyMethod = "shutdown") @ConditionalOnMissingBean public SpringConfigProvider springConfigProvider( @Autowired ApplicationContext applicationContext, @Autowired GlobalCacheConfig globalCacheConfig, @Autowired(required = false) EncoderParser encoderParser, @Autowired(required = false) KeyConvertorParser keyConvertorParser, @Autowired(required = false) Consumer<StatInfo> metricsCallback) { return new JetCacheBaseBeans().springConfigProvider(applicationContext, globalCacheConfig, encoderParser, keyConvertorParser, metricsCallback); } @Bean(name = "jcCacheManager",destroyMethod = "close") @ConditionalOnMissingBean public SimpleCacheManager cacheManager(@Autowired SpringConfigProvider springConfigProvider) { SimpleCacheManager cacheManager = new SimpleCacheManager(); cacheManager.setCacheBuilderTemplate(springConfigProvider.getCacheBuilderTemplate()); return cacheManager; } @Bean @ConditionalOnMissingBean public AutoConfigureBeans autoConfigureBeans() { return new AutoConfigureBeans(); } @Bean public static BeanDependencyManager beanDependencyManager() { return new BeanDependencyManager(); } @Bean(name = GLOBAL_CACHE_CONFIG_NAME) public GlobalCacheConfig globalCacheConfig(AutoConfigureBeans autoConfigureBeans, JetCacheProperties props) {<FILL_FUNCTION_BODY>} }
GlobalCacheConfig _globalCacheConfig = new GlobalCacheConfig(); _globalCacheConfig.setHiddenPackages(props.getHiddenPackages()); _globalCacheConfig.setStatIntervalMinutes(props.getStatIntervalMinutes()); _globalCacheConfig.setAreaInCacheName(props.isAreaInCacheName()); _globalCacheConfig.setPenetrationProtect(props.isPenetrationProtect()); _globalCacheConfig.setEnableMethodCache(props.isEnableMethodCache()); _globalCacheConfig.setLocalCacheBuilders(autoConfigureBeans.getLocalCacheBuilders()); _globalCacheConfig.setRemoteCacheBuilders(autoConfigureBeans.getRemoteCacheBuilders()); return _globalCacheConfig;
406
183
589
<no_super_class>
alibaba_jetcache
jetcache/jetcache-starter/jetcache-autoconfigure/src/main/java/com/alicp/jetcache/autoconfigure/JetCacheCondition.java
JetCacheCondition
match
class JetCacheCondition extends SpringBootCondition { private String[] cacheTypes; protected JetCacheCondition(String... cacheTypes) { Objects.requireNonNull(cacheTypes, "cacheTypes can't be null"); Assert.isTrue(cacheTypes.length > 0, "cacheTypes length is 0"); this.cacheTypes = cacheTypes; } @Override public ConditionOutcome getMatchOutcome(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) { ConfigTree ct = new ConfigTree((ConfigurableEnvironment) conditionContext.getEnvironment(), "jetcache."); if (match(ct, "local.") || match(ct, "remote.")) { return ConditionOutcome.match(); } else { return ConditionOutcome.noMatch("no match for " + cacheTypes[0]); } } private boolean match(ConfigTree ct, String prefix) {<FILL_FUNCTION_BODY>} }
Map<String, Object> m = ct.subTree(prefix).getProperties(); Set<String> cacheAreaNames = m.keySet().stream().map((s) -> s.substring(0, s.indexOf('.'))).collect(Collectors.toSet()); final List<String> cacheTypesList = Arrays.asList(cacheTypes); return cacheAreaNames.stream().anyMatch((s) -> cacheTypesList.contains(m.get(s + ".type")));
240
121
361
<no_super_class>
alibaba_jetcache
jetcache/jetcache-starter/jetcache-autoconfigure/src/main/java/com/alicp/jetcache/autoconfigure/LettuceFactory.java
LettuceFactory
init
class LettuceFactory implements FactoryBean { @Autowired private AutoConfigureBeans autoConfigureBeans; private boolean inited; private Object obj; private Class<?> clazz; private String key; // for unit test LettuceFactory(AutoConfigureBeans autoConfigureBeans, String key, Class<?> clazz) { this(key, clazz); this.autoConfigureBeans = autoConfigureBeans; } public LettuceFactory(String key, Class<?> clazz) { this.clazz = clazz; if (AbstractRedisClient.class.isAssignableFrom(clazz)) { key += ".client"; } else if (StatefulConnection.class.isAssignableFrom(clazz)) { key += ".connection"; } else if (RedisClusterCommands.class.isAssignableFrom(clazz)) { // RedisCommands extends RedisClusterCommands key += ".commands"; } else if (RedisClusterAsyncCommands.class.isAssignableFrom(clazz)) { // RedisAsyncCommands extends RedisClusterAsyncCommands key += ".asyncCommands"; } else if (RedisClusterReactiveCommands.class.isAssignableFrom(clazz)) { // RedisReactiveCommands extends RedisClusterReactiveCommands key += ".reactiveCommands"; } else { throw new IllegalArgumentException(clazz.getName()); } this.key = key; } private void init() {<FILL_FUNCTION_BODY>} @Override public Object getObject() throws Exception { init(); return obj; } @Override public Class<?> getObjectType() { return clazz; } @Override public boolean isSingleton() { return true; } }
if (!inited) { obj = autoConfigureBeans.getCustomContainer().get(key); inited = true; }
487
39
526
<no_super_class>