id int32 0 165k | repo stringlengths 7 58 | path stringlengths 12 218 | func_name stringlengths 3 140 | original_string stringlengths 73 34.1k | language stringclasses 1 value | code stringlengths 73 34.1k | code_tokens list | docstring stringlengths 3 16k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 105 339 |
|---|---|---|---|---|---|---|---|---|---|---|---|
28,500 | TakahikoKawasaki/nv-websocket-client | src/main/java/com/neovisionaries/ws/client/WebSocket.java | WebSocket.sendFrame | public WebSocket sendFrame(WebSocketFrame frame)
{
if (frame == null)
{
return this;
}
synchronized (mStateManager)
{
WebSocketState state = mStateManager.getState();
if (state != OPEN && state != CLOSING)
{
return this;
}
}
// The current state is either OPEN or CLOSING. Or, CLOSED.
// Get the reference to the writing thread.
WritingThread wt = mWritingThread;
// Some applications call sendFrame() without waiting for the
// notification of WebSocketListener.onConnected() (Issue #23),
// and/or even after the connection is closed. That is, there
// are chances that sendFrame() is called when mWritingThread
// is null. So, it should be checked whether an instance of
// WritingThread is available or not before calling queueFrame().
if (wt == null)
{
// An instance of WritingThread is not available.
return this;
}
// Split the frame into multiple frames if necessary.
List<WebSocketFrame> frames = splitIfNecessary(frame);
// Queue the frame or the frames. Even if the current state is
// CLOSED, queueing won't be a big issue.
// If the frame was not split.
if (frames == null)
{
// Queue the frame.
wt.queueFrame(frame);
}
else
{
for (WebSocketFrame f : frames)
{
// Queue the frame.
wt.queueFrame(f);
}
}
return this;
} | java | public WebSocket sendFrame(WebSocketFrame frame)
{
if (frame == null)
{
return this;
}
synchronized (mStateManager)
{
WebSocketState state = mStateManager.getState();
if (state != OPEN && state != CLOSING)
{
return this;
}
}
// The current state is either OPEN or CLOSING. Or, CLOSED.
// Get the reference to the writing thread.
WritingThread wt = mWritingThread;
// Some applications call sendFrame() without waiting for the
// notification of WebSocketListener.onConnected() (Issue #23),
// and/or even after the connection is closed. That is, there
// are chances that sendFrame() is called when mWritingThread
// is null. So, it should be checked whether an instance of
// WritingThread is available or not before calling queueFrame().
if (wt == null)
{
// An instance of WritingThread is not available.
return this;
}
// Split the frame into multiple frames if necessary.
List<WebSocketFrame> frames = splitIfNecessary(frame);
// Queue the frame or the frames. Even if the current state is
// CLOSED, queueing won't be a big issue.
// If the frame was not split.
if (frames == null)
{
// Queue the frame.
wt.queueFrame(frame);
}
else
{
for (WebSocketFrame f : frames)
{
// Queue the frame.
wt.queueFrame(f);
}
}
return this;
} | [
"public",
"WebSocket",
"sendFrame",
"(",
"WebSocketFrame",
"frame",
")",
"{",
"if",
"(",
"frame",
"==",
"null",
")",
"{",
"return",
"this",
";",
"}",
"synchronized",
"(",
"mStateManager",
")",
"{",
"WebSocketState",
"state",
"=",
"mStateManager",
".",
"getState",
"(",
")",
";",
"if",
"(",
"state",
"!=",
"OPEN",
"&&",
"state",
"!=",
"CLOSING",
")",
"{",
"return",
"this",
";",
"}",
"}",
"// The current state is either OPEN or CLOSING. Or, CLOSED.",
"// Get the reference to the writing thread.",
"WritingThread",
"wt",
"=",
"mWritingThread",
";",
"// Some applications call sendFrame() without waiting for the",
"// notification of WebSocketListener.onConnected() (Issue #23),",
"// and/or even after the connection is closed. That is, there",
"// are chances that sendFrame() is called when mWritingThread",
"// is null. So, it should be checked whether an instance of",
"// WritingThread is available or not before calling queueFrame().",
"if",
"(",
"wt",
"==",
"null",
")",
"{",
"// An instance of WritingThread is not available.",
"return",
"this",
";",
"}",
"// Split the frame into multiple frames if necessary.",
"List",
"<",
"WebSocketFrame",
">",
"frames",
"=",
"splitIfNecessary",
"(",
"frame",
")",
";",
"// Queue the frame or the frames. Even if the current state is",
"// CLOSED, queueing won't be a big issue.",
"// If the frame was not split.",
"if",
"(",
"frames",
"==",
"null",
")",
"{",
"// Queue the frame.",
"wt",
".",
"queueFrame",
"(",
"frame",
")",
";",
"}",
"else",
"{",
"for",
"(",
"WebSocketFrame",
"f",
":",
"frames",
")",
"{",
"// Queue the frame.",
"wt",
".",
"queueFrame",
"(",
"f",
")",
";",
"}",
"}",
"return",
"this",
";",
"}"
] | Send a WebSocket frame to the server.
<p>
This method just queues the given frame. Actual transmission
is performed asynchronously.
</p>
<p>
When the current state of this WebSocket is not {@link
WebSocketState#OPEN OPEN}, this method does not accept
the frame.
</p>
<p>
Sending a <a href="https://tools.ietf.org/html/rfc6455#section-5.5.1"
>close frame</a> changes the state to {@link WebSocketState#CLOSING
CLOSING} (if the current state is neither {@link WebSocketState#CLOSING
CLOSING} nor {@link WebSocketState#CLOSED CLOSED}).
</p>
<p>
Note that the validity of the give frame is not checked.
For example, even if the payload length of a given frame
is greater than 125 and the opcode indicates that the
frame is a control frame, this method accepts the given
frame.
</p>
@param frame
A WebSocket frame to be sent to the server.
If {@code null} is given, nothing is done.
@return
{@code this} object. | [
"Send",
"a",
"WebSocket",
"frame",
"to",
"the",
"server",
"."
] | efaec21181d740ad3808313acf679313179e0825 | https://github.com/TakahikoKawasaki/nv-websocket-client/blob/efaec21181d740ad3808313acf679313179e0825/src/main/java/com/neovisionaries/ws/client/WebSocket.java#L2697-L2753 |
28,501 | TakahikoKawasaki/nv-websocket-client | src/main/java/com/neovisionaries/ws/client/WebSocket.java | WebSocket.sendContinuation | public WebSocket sendContinuation(String payload, boolean fin)
{
return sendFrame(WebSocketFrame.createContinuationFrame(payload).setFin(fin));
} | java | public WebSocket sendContinuation(String payload, boolean fin)
{
return sendFrame(WebSocketFrame.createContinuationFrame(payload).setFin(fin));
} | [
"public",
"WebSocket",
"sendContinuation",
"(",
"String",
"payload",
",",
"boolean",
"fin",
")",
"{",
"return",
"sendFrame",
"(",
"WebSocketFrame",
".",
"createContinuationFrame",
"(",
"payload",
")",
".",
"setFin",
"(",
"fin",
")",
")",
";",
"}"
] | Send a continuation frame to the server.
<p>
This method is an alias of {@link #sendFrame(WebSocketFrame)
sendFrame}{@code (WebSocketFrame.}{@link
WebSocketFrame#createContinuationFrame(String)
createContinuationFrame}{@code (payload).}{@link
WebSocketFrame#setFin(boolean) setFin}{@code (fin))}.
</p>
@param payload
The payload of a continuation frame.
@param fin
The FIN bit value.
@return
{@code this} object. | [
"Send",
"a",
"continuation",
"frame",
"to",
"the",
"server",
"."
] | efaec21181d740ad3808313acf679313179e0825 | https://github.com/TakahikoKawasaki/nv-websocket-client/blob/efaec21181d740ad3808313acf679313179e0825/src/main/java/com/neovisionaries/ws/client/WebSocket.java#L2859-L2862 |
28,502 | TakahikoKawasaki/nv-websocket-client | src/main/java/com/neovisionaries/ws/client/WebSocket.java | WebSocket.sendText | public WebSocket sendText(String payload, boolean fin)
{
return sendFrame(WebSocketFrame.createTextFrame(payload).setFin(fin));
} | java | public WebSocket sendText(String payload, boolean fin)
{
return sendFrame(WebSocketFrame.createTextFrame(payload).setFin(fin));
} | [
"public",
"WebSocket",
"sendText",
"(",
"String",
"payload",
",",
"boolean",
"fin",
")",
"{",
"return",
"sendFrame",
"(",
"WebSocketFrame",
".",
"createTextFrame",
"(",
"payload",
")",
".",
"setFin",
"(",
"fin",
")",
")",
";",
"}"
] | Send a text frame to the server.
<p>
This method is an alias of {@link #sendFrame(WebSocketFrame)
sendFrame}{@code (WebSocketFrame.}{@link
WebSocketFrame#createTextFrame(String)
createTextFrame}{@code (payload).}{@link
WebSocketFrame#setFin(boolean) setFin}{@code (fin))}.
</p>
@param payload
The payload of a text frame.
@param fin
The FIN bit value.
@return
{@code this} object. | [
"Send",
"a",
"text",
"frame",
"to",
"the",
"server",
"."
] | efaec21181d740ad3808313acf679313179e0825 | https://github.com/TakahikoKawasaki/nv-websocket-client/blob/efaec21181d740ad3808313acf679313179e0825/src/main/java/com/neovisionaries/ws/client/WebSocket.java#L2968-L2971 |
28,503 | TakahikoKawasaki/nv-websocket-client | src/main/java/com/neovisionaries/ws/client/WebSocket.java | WebSocket.sendBinary | public WebSocket sendBinary(byte[] payload, boolean fin)
{
return sendFrame(WebSocketFrame.createBinaryFrame(payload).setFin(fin));
} | java | public WebSocket sendBinary(byte[] payload, boolean fin)
{
return sendFrame(WebSocketFrame.createBinaryFrame(payload).setFin(fin));
} | [
"public",
"WebSocket",
"sendBinary",
"(",
"byte",
"[",
"]",
"payload",
",",
"boolean",
"fin",
")",
"{",
"return",
"sendFrame",
"(",
"WebSocketFrame",
".",
"createBinaryFrame",
"(",
"payload",
")",
".",
"setFin",
"(",
"fin",
")",
")",
";",
"}"
] | Send a binary frame to the server.
<p>
This method is an alias of {@link #sendFrame(WebSocketFrame)
sendFrame}{@code (WebSocketFrame.}{@link
WebSocketFrame#createBinaryFrame(byte[])
createBinaryFrame}{@code (payload).}{@link
WebSocketFrame#setFin(boolean) setFin}{@code (fin))}.
</p>
@param payload
The payload of a binary frame.
@param fin
The FIN bit value.
@return
{@code this} object. | [
"Send",
"a",
"binary",
"frame",
"to",
"the",
"server",
"."
] | efaec21181d740ad3808313acf679313179e0825 | https://github.com/TakahikoKawasaki/nv-websocket-client/blob/efaec21181d740ad3808313acf679313179e0825/src/main/java/com/neovisionaries/ws/client/WebSocket.java#L3022-L3025 |
28,504 | TakahikoKawasaki/nv-websocket-client | src/main/java/com/neovisionaries/ws/client/WebSocket.java | WebSocket.sendClose | public WebSocket sendClose(int closeCode, String reason)
{
return sendFrame(WebSocketFrame.createCloseFrame(closeCode, reason));
} | java | public WebSocket sendClose(int closeCode, String reason)
{
return sendFrame(WebSocketFrame.createCloseFrame(closeCode, reason));
} | [
"public",
"WebSocket",
"sendClose",
"(",
"int",
"closeCode",
",",
"String",
"reason",
")",
"{",
"return",
"sendFrame",
"(",
"WebSocketFrame",
".",
"createCloseFrame",
"(",
"closeCode",
",",
"reason",
")",
")",
";",
"}"
] | Send a close frame to the server.
<p>
This method is an alias of {@link #sendFrame(WebSocketFrame)
sendFrame}{@code (WebSocketFrame.}{@link
WebSocketFrame#createCloseFrame(int, String)
createCloseFrame}{@code (closeCode, reason))}.
</p>
@param closeCode
The close code.
@param reason
The close reason.
Note that a control frame's payload length must be 125 bytes or less
(RFC 6455, <a href="https://tools.ietf.org/html/rfc6455#section-5.5"
>5.5. Control Frames</a>).
@return
{@code this} object.
@see WebSocketCloseCode | [
"Send",
"a",
"close",
"frame",
"to",
"the",
"server",
"."
] | efaec21181d740ad3808313acf679313179e0825 | https://github.com/TakahikoKawasaki/nv-websocket-client/blob/efaec21181d740ad3808313acf679313179e0825/src/main/java/com/neovisionaries/ws/client/WebSocket.java#L3094-L3097 |
28,505 | TakahikoKawasaki/nv-websocket-client | src/main/java/com/neovisionaries/ws/client/WebSocket.java | WebSocket.shakeHands | private Map<String, List<String>> shakeHands() throws WebSocketException
{
// The raw socket created by WebSocketFactory.
Socket socket = mSocketConnector.getSocket();
// Get the input stream of the socket.
WebSocketInputStream input = openInputStream(socket);
// Get the output stream of the socket.
WebSocketOutputStream output = openOutputStream(socket);
// Generate a value for Sec-WebSocket-Key.
String key = generateWebSocketKey();
// Send an opening handshake to the server.
writeHandshake(output, key);
// Read the response from the server.
Map<String, List<String>> headers = readHandshake(input, key);
// Keep the input stream and the output stream to pass them
// to the reading thread and the writing thread later.
mInput = input;
mOutput = output;
// The handshake succeeded.
return headers;
} | java | private Map<String, List<String>> shakeHands() throws WebSocketException
{
// The raw socket created by WebSocketFactory.
Socket socket = mSocketConnector.getSocket();
// Get the input stream of the socket.
WebSocketInputStream input = openInputStream(socket);
// Get the output stream of the socket.
WebSocketOutputStream output = openOutputStream(socket);
// Generate a value for Sec-WebSocket-Key.
String key = generateWebSocketKey();
// Send an opening handshake to the server.
writeHandshake(output, key);
// Read the response from the server.
Map<String, List<String>> headers = readHandshake(input, key);
// Keep the input stream and the output stream to pass them
// to the reading thread and the writing thread later.
mInput = input;
mOutput = output;
// The handshake succeeded.
return headers;
} | [
"private",
"Map",
"<",
"String",
",",
"List",
"<",
"String",
">",
">",
"shakeHands",
"(",
")",
"throws",
"WebSocketException",
"{",
"// The raw socket created by WebSocketFactory.",
"Socket",
"socket",
"=",
"mSocketConnector",
".",
"getSocket",
"(",
")",
";",
"// Get the input stream of the socket.",
"WebSocketInputStream",
"input",
"=",
"openInputStream",
"(",
"socket",
")",
";",
"// Get the output stream of the socket.",
"WebSocketOutputStream",
"output",
"=",
"openOutputStream",
"(",
"socket",
")",
";",
"// Generate a value for Sec-WebSocket-Key.",
"String",
"key",
"=",
"generateWebSocketKey",
"(",
")",
";",
"// Send an opening handshake to the server.",
"writeHandshake",
"(",
"output",
",",
"key",
")",
";",
"// Read the response from the server.",
"Map",
"<",
"String",
",",
"List",
"<",
"String",
">",
">",
"headers",
"=",
"readHandshake",
"(",
"input",
",",
"key",
")",
";",
"// Keep the input stream and the output stream to pass them",
"// to the reading thread and the writing thread later.",
"mInput",
"=",
"input",
";",
"mOutput",
"=",
"output",
";",
"// The handshake succeeded.",
"return",
"headers",
";",
"}"
] | Perform the opening handshake. | [
"Perform",
"the",
"opening",
"handshake",
"."
] | efaec21181d740ad3808313acf679313179e0825 | https://github.com/TakahikoKawasaki/nv-websocket-client/blob/efaec21181d740ad3808313acf679313179e0825/src/main/java/com/neovisionaries/ws/client/WebSocket.java#L3260-L3287 |
28,506 | TakahikoKawasaki/nv-websocket-client | src/main/java/com/neovisionaries/ws/client/WebSocket.java | WebSocket.openInputStream | private WebSocketInputStream openInputStream(Socket socket) throws WebSocketException
{
try
{
// Get the input stream of the raw socket through which
// this client receives data from the server.
return new WebSocketInputStream(
new BufferedInputStream(socket.getInputStream()));
}
catch (IOException e)
{
// Failed to get the input stream of the raw socket.
throw new WebSocketException(
WebSocketError.SOCKET_INPUT_STREAM_FAILURE,
"Failed to get the input stream of the raw socket: " + e.getMessage(), e);
}
} | java | private WebSocketInputStream openInputStream(Socket socket) throws WebSocketException
{
try
{
// Get the input stream of the raw socket through which
// this client receives data from the server.
return new WebSocketInputStream(
new BufferedInputStream(socket.getInputStream()));
}
catch (IOException e)
{
// Failed to get the input stream of the raw socket.
throw new WebSocketException(
WebSocketError.SOCKET_INPUT_STREAM_FAILURE,
"Failed to get the input stream of the raw socket: " + e.getMessage(), e);
}
} | [
"private",
"WebSocketInputStream",
"openInputStream",
"(",
"Socket",
"socket",
")",
"throws",
"WebSocketException",
"{",
"try",
"{",
"// Get the input stream of the raw socket through which",
"// this client receives data from the server.",
"return",
"new",
"WebSocketInputStream",
"(",
"new",
"BufferedInputStream",
"(",
"socket",
".",
"getInputStream",
"(",
")",
")",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"// Failed to get the input stream of the raw socket.",
"throw",
"new",
"WebSocketException",
"(",
"WebSocketError",
".",
"SOCKET_INPUT_STREAM_FAILURE",
",",
"\"Failed to get the input stream of the raw socket: \"",
"+",
"e",
".",
"getMessage",
"(",
")",
",",
"e",
")",
";",
"}",
"}"
] | Open the input stream of the WebSocket connection.
The stream is used by the reading thread. | [
"Open",
"the",
"input",
"stream",
"of",
"the",
"WebSocket",
"connection",
".",
"The",
"stream",
"is",
"used",
"by",
"the",
"reading",
"thread",
"."
] | efaec21181d740ad3808313acf679313179e0825 | https://github.com/TakahikoKawasaki/nv-websocket-client/blob/efaec21181d740ad3808313acf679313179e0825/src/main/java/com/neovisionaries/ws/client/WebSocket.java#L3294-L3310 |
28,507 | TakahikoKawasaki/nv-websocket-client | src/main/java/com/neovisionaries/ws/client/WebSocket.java | WebSocket.openOutputStream | private WebSocketOutputStream openOutputStream(Socket socket) throws WebSocketException
{
try
{
// Get the output stream of the socket through which
// this client sends data to the server.
return new WebSocketOutputStream(
new BufferedOutputStream(socket.getOutputStream()));
}
catch (IOException e)
{
// Failed to get the output stream from the raw socket.
throw new WebSocketException(
WebSocketError.SOCKET_OUTPUT_STREAM_FAILURE,
"Failed to get the output stream from the raw socket: " + e.getMessage(), e);
}
} | java | private WebSocketOutputStream openOutputStream(Socket socket) throws WebSocketException
{
try
{
// Get the output stream of the socket through which
// this client sends data to the server.
return new WebSocketOutputStream(
new BufferedOutputStream(socket.getOutputStream()));
}
catch (IOException e)
{
// Failed to get the output stream from the raw socket.
throw new WebSocketException(
WebSocketError.SOCKET_OUTPUT_STREAM_FAILURE,
"Failed to get the output stream from the raw socket: " + e.getMessage(), e);
}
} | [
"private",
"WebSocketOutputStream",
"openOutputStream",
"(",
"Socket",
"socket",
")",
"throws",
"WebSocketException",
"{",
"try",
"{",
"// Get the output stream of the socket through which",
"// this client sends data to the server.",
"return",
"new",
"WebSocketOutputStream",
"(",
"new",
"BufferedOutputStream",
"(",
"socket",
".",
"getOutputStream",
"(",
")",
")",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"// Failed to get the output stream from the raw socket.",
"throw",
"new",
"WebSocketException",
"(",
"WebSocketError",
".",
"SOCKET_OUTPUT_STREAM_FAILURE",
",",
"\"Failed to get the output stream from the raw socket: \"",
"+",
"e",
".",
"getMessage",
"(",
")",
",",
"e",
")",
";",
"}",
"}"
] | Open the output stream of the WebSocket connection.
The stream is used by the writing thread. | [
"Open",
"the",
"output",
"stream",
"of",
"the",
"WebSocket",
"connection",
".",
"The",
"stream",
"is",
"used",
"by",
"the",
"writing",
"thread",
"."
] | efaec21181d740ad3808313acf679313179e0825 | https://github.com/TakahikoKawasaki/nv-websocket-client/blob/efaec21181d740ad3808313acf679313179e0825/src/main/java/com/neovisionaries/ws/client/WebSocket.java#L3317-L3333 |
28,508 | TakahikoKawasaki/nv-websocket-client | src/main/java/com/neovisionaries/ws/client/WebSocket.java | WebSocket.writeHandshake | private void writeHandshake(WebSocketOutputStream output, String key) throws WebSocketException
{
// Generate an opening handshake sent to the server from this client.
mHandshakeBuilder.setKey(key);
String requestLine = mHandshakeBuilder.buildRequestLine();
List<String[]> headers = mHandshakeBuilder.buildHeaders();
String handshake = HandshakeBuilder.build(requestLine, headers);
// Call onSendingHandshake() method of listeners.
mListenerManager.callOnSendingHandshake(requestLine, headers);
try
{
// Send the opening handshake to the server.
output.write(handshake);
output.flush();
}
catch (IOException e)
{
// Failed to send an opening handshake request to the server.
throw new WebSocketException(
WebSocketError.OPENING_HAHDSHAKE_REQUEST_FAILURE,
"Failed to send an opening handshake request to the server: " + e.getMessage(), e);
}
} | java | private void writeHandshake(WebSocketOutputStream output, String key) throws WebSocketException
{
// Generate an opening handshake sent to the server from this client.
mHandshakeBuilder.setKey(key);
String requestLine = mHandshakeBuilder.buildRequestLine();
List<String[]> headers = mHandshakeBuilder.buildHeaders();
String handshake = HandshakeBuilder.build(requestLine, headers);
// Call onSendingHandshake() method of listeners.
mListenerManager.callOnSendingHandshake(requestLine, headers);
try
{
// Send the opening handshake to the server.
output.write(handshake);
output.flush();
}
catch (IOException e)
{
// Failed to send an opening handshake request to the server.
throw new WebSocketException(
WebSocketError.OPENING_HAHDSHAKE_REQUEST_FAILURE,
"Failed to send an opening handshake request to the server: " + e.getMessage(), e);
}
} | [
"private",
"void",
"writeHandshake",
"(",
"WebSocketOutputStream",
"output",
",",
"String",
"key",
")",
"throws",
"WebSocketException",
"{",
"// Generate an opening handshake sent to the server from this client.",
"mHandshakeBuilder",
".",
"setKey",
"(",
"key",
")",
";",
"String",
"requestLine",
"=",
"mHandshakeBuilder",
".",
"buildRequestLine",
"(",
")",
";",
"List",
"<",
"String",
"[",
"]",
">",
"headers",
"=",
"mHandshakeBuilder",
".",
"buildHeaders",
"(",
")",
";",
"String",
"handshake",
"=",
"HandshakeBuilder",
".",
"build",
"(",
"requestLine",
",",
"headers",
")",
";",
"// Call onSendingHandshake() method of listeners.",
"mListenerManager",
".",
"callOnSendingHandshake",
"(",
"requestLine",
",",
"headers",
")",
";",
"try",
"{",
"// Send the opening handshake to the server.",
"output",
".",
"write",
"(",
"handshake",
")",
";",
"output",
".",
"flush",
"(",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"// Failed to send an opening handshake request to the server.",
"throw",
"new",
"WebSocketException",
"(",
"WebSocketError",
".",
"OPENING_HAHDSHAKE_REQUEST_FAILURE",
",",
"\"Failed to send an opening handshake request to the server: \"",
"+",
"e",
".",
"getMessage",
"(",
")",
",",
"e",
")",
";",
"}",
"}"
] | Send an opening handshake request to the WebSocket server. | [
"Send",
"an",
"opening",
"handshake",
"request",
"to",
"the",
"WebSocket",
"server",
"."
] | efaec21181d740ad3808313acf679313179e0825 | https://github.com/TakahikoKawasaki/nv-websocket-client/blob/efaec21181d740ad3808313acf679313179e0825/src/main/java/com/neovisionaries/ws/client/WebSocket.java#L3367-L3391 |
28,509 | TakahikoKawasaki/nv-websocket-client | src/main/java/com/neovisionaries/ws/client/WebSocket.java | WebSocket.readHandshake | private Map<String, List<String>> readHandshake(WebSocketInputStream input, String key) throws WebSocketException
{
return new HandshakeReader(this).readHandshake(input, key);
} | java | private Map<String, List<String>> readHandshake(WebSocketInputStream input, String key) throws WebSocketException
{
return new HandshakeReader(this).readHandshake(input, key);
} | [
"private",
"Map",
"<",
"String",
",",
"List",
"<",
"String",
">",
">",
"readHandshake",
"(",
"WebSocketInputStream",
"input",
",",
"String",
"key",
")",
"throws",
"WebSocketException",
"{",
"return",
"new",
"HandshakeReader",
"(",
"this",
")",
".",
"readHandshake",
"(",
"input",
",",
"key",
")",
";",
"}"
] | Receive an opening handshake response from the WebSocket server. | [
"Receive",
"an",
"opening",
"handshake",
"response",
"from",
"the",
"WebSocket",
"server",
"."
] | efaec21181d740ad3808313acf679313179e0825 | https://github.com/TakahikoKawasaki/nv-websocket-client/blob/efaec21181d740ad3808313acf679313179e0825/src/main/java/com/neovisionaries/ws/client/WebSocket.java#L3397-L3400 |
28,510 | TakahikoKawasaki/nv-websocket-client | src/main/java/com/neovisionaries/ws/client/WebSocket.java | WebSocket.startThreads | private void startThreads()
{
ReadingThread readingThread = new ReadingThread(this);
WritingThread writingThread = new WritingThread(this);
synchronized (mThreadsLock)
{
mReadingThread = readingThread;
mWritingThread = writingThread;
}
// Execute onThreadCreated of the listeners.
readingThread.callOnThreadCreated();
writingThread.callOnThreadCreated();
readingThread.start();
writingThread.start();
} | java | private void startThreads()
{
ReadingThread readingThread = new ReadingThread(this);
WritingThread writingThread = new WritingThread(this);
synchronized (mThreadsLock)
{
mReadingThread = readingThread;
mWritingThread = writingThread;
}
// Execute onThreadCreated of the listeners.
readingThread.callOnThreadCreated();
writingThread.callOnThreadCreated();
readingThread.start();
writingThread.start();
} | [
"private",
"void",
"startThreads",
"(",
")",
"{",
"ReadingThread",
"readingThread",
"=",
"new",
"ReadingThread",
"(",
"this",
")",
";",
"WritingThread",
"writingThread",
"=",
"new",
"WritingThread",
"(",
"this",
")",
";",
"synchronized",
"(",
"mThreadsLock",
")",
"{",
"mReadingThread",
"=",
"readingThread",
";",
"mWritingThread",
"=",
"writingThread",
";",
"}",
"// Execute onThreadCreated of the listeners.",
"readingThread",
".",
"callOnThreadCreated",
"(",
")",
";",
"writingThread",
".",
"callOnThreadCreated",
"(",
")",
";",
"readingThread",
".",
"start",
"(",
")",
";",
"writingThread",
".",
"start",
"(",
")",
";",
"}"
] | Start both the reading thread and the writing thread.
<p>
The reading thread will call {@link #onReadingThreadStarted()}
as its first step. Likewise, the writing thread will call
{@link #onWritingThreadStarted()} as its first step. After
both the threads have started, {@link #onThreadsStarted()} is
called.
</p> | [
"Start",
"both",
"the",
"reading",
"thread",
"and",
"the",
"writing",
"thread",
"."
] | efaec21181d740ad3808313acf679313179e0825 | https://github.com/TakahikoKawasaki/nv-websocket-client/blob/efaec21181d740ad3808313acf679313179e0825/src/main/java/com/neovisionaries/ws/client/WebSocket.java#L3414-L3431 |
28,511 | TakahikoKawasaki/nv-websocket-client | src/main/java/com/neovisionaries/ws/client/WebSocket.java | WebSocket.stopThreads | private void stopThreads(long closeDelay)
{
ReadingThread readingThread;
WritingThread writingThread;
synchronized (mThreadsLock)
{
readingThread = mReadingThread;
writingThread = mWritingThread;
mReadingThread = null;
mWritingThread = null;
}
if (readingThread != null)
{
readingThread.requestStop(closeDelay);
}
if (writingThread != null)
{
writingThread.requestStop();
}
} | java | private void stopThreads(long closeDelay)
{
ReadingThread readingThread;
WritingThread writingThread;
synchronized (mThreadsLock)
{
readingThread = mReadingThread;
writingThread = mWritingThread;
mReadingThread = null;
mWritingThread = null;
}
if (readingThread != null)
{
readingThread.requestStop(closeDelay);
}
if (writingThread != null)
{
writingThread.requestStop();
}
} | [
"private",
"void",
"stopThreads",
"(",
"long",
"closeDelay",
")",
"{",
"ReadingThread",
"readingThread",
";",
"WritingThread",
"writingThread",
";",
"synchronized",
"(",
"mThreadsLock",
")",
"{",
"readingThread",
"=",
"mReadingThread",
";",
"writingThread",
"=",
"mWritingThread",
";",
"mReadingThread",
"=",
"null",
";",
"mWritingThread",
"=",
"null",
";",
"}",
"if",
"(",
"readingThread",
"!=",
"null",
")",
"{",
"readingThread",
".",
"requestStop",
"(",
"closeDelay",
")",
";",
"}",
"if",
"(",
"writingThread",
"!=",
"null",
")",
"{",
"writingThread",
".",
"requestStop",
"(",
")",
";",
"}",
"}"
] | Stop both the reading thread and the writing thread.
<p>
The reading thread will call {@link #onReadingThreadFinished(WebSocketFrame)}
as its last step. Likewise, the writing thread will call {@link
#onWritingThreadFinished(WebSocketFrame)} as its last step.
After both the threads have stopped, {@link #onThreadsFinished()}
is called.
</p> | [
"Stop",
"both",
"the",
"reading",
"thread",
"and",
"the",
"writing",
"thread",
"."
] | efaec21181d740ad3808313acf679313179e0825 | https://github.com/TakahikoKawasaki/nv-websocket-client/blob/efaec21181d740ad3808313acf679313179e0825/src/main/java/com/neovisionaries/ws/client/WebSocket.java#L3445-L3468 |
28,512 | TakahikoKawasaki/nv-websocket-client | src/main/java/com/neovisionaries/ws/client/WebSocket.java | WebSocket.onReadingThreadStarted | void onReadingThreadStarted()
{
boolean bothStarted = false;
synchronized (mThreadsLock)
{
mReadingThreadStarted = true;
if (mWritingThreadStarted)
{
// Both the reading thread and the writing thread have started.
bothStarted = true;
}
}
// Call onConnected() method of listeners if not called yet.
callOnConnectedIfNotYet();
// If both the reading thread and the writing thread have started.
if (bothStarted)
{
onThreadsStarted();
}
} | java | void onReadingThreadStarted()
{
boolean bothStarted = false;
synchronized (mThreadsLock)
{
mReadingThreadStarted = true;
if (mWritingThreadStarted)
{
// Both the reading thread and the writing thread have started.
bothStarted = true;
}
}
// Call onConnected() method of listeners if not called yet.
callOnConnectedIfNotYet();
// If both the reading thread and the writing thread have started.
if (bothStarted)
{
onThreadsStarted();
}
} | [
"void",
"onReadingThreadStarted",
"(",
")",
"{",
"boolean",
"bothStarted",
"=",
"false",
";",
"synchronized",
"(",
"mThreadsLock",
")",
"{",
"mReadingThreadStarted",
"=",
"true",
";",
"if",
"(",
"mWritingThreadStarted",
")",
"{",
"// Both the reading thread and the writing thread have started.",
"bothStarted",
"=",
"true",
";",
"}",
"}",
"// Call onConnected() method of listeners if not called yet.",
"callOnConnectedIfNotYet",
"(",
")",
";",
"// If both the reading thread and the writing thread have started.",
"if",
"(",
"bothStarted",
")",
"{",
"onThreadsStarted",
"(",
")",
";",
"}",
"}"
] | Called by the reading thread as its first step. | [
"Called",
"by",
"the",
"reading",
"thread",
"as",
"its",
"first",
"step",
"."
] | efaec21181d740ad3808313acf679313179e0825 | https://github.com/TakahikoKawasaki/nv-websocket-client/blob/efaec21181d740ad3808313acf679313179e0825/src/main/java/com/neovisionaries/ws/client/WebSocket.java#L3537-L3560 |
28,513 | TakahikoKawasaki/nv-websocket-client | src/main/java/com/neovisionaries/ws/client/WebSocket.java | WebSocket.onReadingThreadFinished | void onReadingThreadFinished(WebSocketFrame closeFrame)
{
synchronized (mThreadsLock)
{
mReadingThreadFinished = true;
mServerCloseFrame = closeFrame;
if (mWritingThreadFinished == false)
{
// Wait for the writing thread to finish.
return;
}
}
// Both the reading thread and the writing thread have finished.
onThreadsFinished();
} | java | void onReadingThreadFinished(WebSocketFrame closeFrame)
{
synchronized (mThreadsLock)
{
mReadingThreadFinished = true;
mServerCloseFrame = closeFrame;
if (mWritingThreadFinished == false)
{
// Wait for the writing thread to finish.
return;
}
}
// Both the reading thread and the writing thread have finished.
onThreadsFinished();
} | [
"void",
"onReadingThreadFinished",
"(",
"WebSocketFrame",
"closeFrame",
")",
"{",
"synchronized",
"(",
"mThreadsLock",
")",
"{",
"mReadingThreadFinished",
"=",
"true",
";",
"mServerCloseFrame",
"=",
"closeFrame",
";",
"if",
"(",
"mWritingThreadFinished",
"==",
"false",
")",
"{",
"// Wait for the writing thread to finish.",
"return",
";",
"}",
"}",
"// Both the reading thread and the writing thread have finished.",
"onThreadsFinished",
"(",
")",
";",
"}"
] | Called by the reading thread as its last step. | [
"Called",
"by",
"the",
"reading",
"thread",
"as",
"its",
"last",
"step",
"."
] | efaec21181d740ad3808313acf679313179e0825 | https://github.com/TakahikoKawasaki/nv-websocket-client/blob/efaec21181d740ad3808313acf679313179e0825/src/main/java/com/neovisionaries/ws/client/WebSocket.java#L3635-L3651 |
28,514 | TakahikoKawasaki/nv-websocket-client | src/main/java/com/neovisionaries/ws/client/WebSocket.java | WebSocket.onWritingThreadFinished | void onWritingThreadFinished(WebSocketFrame closeFrame)
{
synchronized (mThreadsLock)
{
mWritingThreadFinished = true;
mClientCloseFrame = closeFrame;
if (mReadingThreadFinished == false)
{
// Wait for the reading thread to finish.
return;
}
}
// Both the reading thread and the writing thread have finished.
onThreadsFinished();
} | java | void onWritingThreadFinished(WebSocketFrame closeFrame)
{
synchronized (mThreadsLock)
{
mWritingThreadFinished = true;
mClientCloseFrame = closeFrame;
if (mReadingThreadFinished == false)
{
// Wait for the reading thread to finish.
return;
}
}
// Both the reading thread and the writing thread have finished.
onThreadsFinished();
} | [
"void",
"onWritingThreadFinished",
"(",
"WebSocketFrame",
"closeFrame",
")",
"{",
"synchronized",
"(",
"mThreadsLock",
")",
"{",
"mWritingThreadFinished",
"=",
"true",
";",
"mClientCloseFrame",
"=",
"closeFrame",
";",
"if",
"(",
"mReadingThreadFinished",
"==",
"false",
")",
"{",
"// Wait for the reading thread to finish.",
"return",
";",
"}",
"}",
"// Both the reading thread and the writing thread have finished.",
"onThreadsFinished",
"(",
")",
";",
"}"
] | Called by the writing thread as its last step. | [
"Called",
"by",
"the",
"writing",
"thread",
"as",
"its",
"last",
"step",
"."
] | efaec21181d740ad3808313acf679313179e0825 | https://github.com/TakahikoKawasaki/nv-websocket-client/blob/efaec21181d740ad3808313acf679313179e0825/src/main/java/com/neovisionaries/ws/client/WebSocket.java#L3657-L3673 |
28,515 | TakahikoKawasaki/nv-websocket-client | src/main/java/com/neovisionaries/ws/client/WebSocket.java | WebSocket.findAgreedPerMessageCompressionExtension | private PerMessageCompressionExtension findAgreedPerMessageCompressionExtension()
{
if (mAgreedExtensions == null)
{
return null;
}
for (WebSocketExtension extension : mAgreedExtensions)
{
if (extension instanceof PerMessageCompressionExtension)
{
return (PerMessageCompressionExtension)extension;
}
}
return null;
} | java | private PerMessageCompressionExtension findAgreedPerMessageCompressionExtension()
{
if (mAgreedExtensions == null)
{
return null;
}
for (WebSocketExtension extension : mAgreedExtensions)
{
if (extension instanceof PerMessageCompressionExtension)
{
return (PerMessageCompressionExtension)extension;
}
}
return null;
} | [
"private",
"PerMessageCompressionExtension",
"findAgreedPerMessageCompressionExtension",
"(",
")",
"{",
"if",
"(",
"mAgreedExtensions",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"for",
"(",
"WebSocketExtension",
"extension",
":",
"mAgreedExtensions",
")",
"{",
"if",
"(",
"extension",
"instanceof",
"PerMessageCompressionExtension",
")",
"{",
"return",
"(",
"PerMessageCompressionExtension",
")",
"extension",
";",
"}",
"}",
"return",
"null",
";",
"}"
] | Find a per-message compression extension from among the agreed extensions. | [
"Find",
"a",
"per",
"-",
"message",
"compression",
"extension",
"from",
"among",
"the",
"agreed",
"extensions",
"."
] | efaec21181d740ad3808313acf679313179e0825 | https://github.com/TakahikoKawasaki/nv-websocket-client/blob/efaec21181d740ad3808313acf679313179e0825/src/main/java/com/neovisionaries/ws/client/WebSocket.java#L3735-L3751 |
28,516 | TakahikoKawasaki/nv-websocket-client | src/main/java/com/neovisionaries/ws/client/Misc.java | Misc.getBytesUTF8 | public static byte[] getBytesUTF8(String string)
{
if (string == null)
{
return null;
}
try
{
return string.getBytes("UTF-8");
}
catch (UnsupportedEncodingException e)
{
// This never happens.
return null;
}
} | java | public static byte[] getBytesUTF8(String string)
{
if (string == null)
{
return null;
}
try
{
return string.getBytes("UTF-8");
}
catch (UnsupportedEncodingException e)
{
// This never happens.
return null;
}
} | [
"public",
"static",
"byte",
"[",
"]",
"getBytesUTF8",
"(",
"String",
"string",
")",
"{",
"if",
"(",
"string",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"try",
"{",
"return",
"string",
".",
"getBytes",
"(",
"\"UTF-8\"",
")",
";",
"}",
"catch",
"(",
"UnsupportedEncodingException",
"e",
")",
"{",
"// This never happens.",
"return",
"null",
";",
"}",
"}"
] | Get a UTF-8 byte array representation of the given string. | [
"Get",
"a",
"UTF",
"-",
"8",
"byte",
"array",
"representation",
"of",
"the",
"given",
"string",
"."
] | efaec21181d740ad3808313acf679313179e0825 | https://github.com/TakahikoKawasaki/nv-websocket-client/blob/efaec21181d740ad3808313acf679313179e0825/src/main/java/com/neovisionaries/ws/client/Misc.java#L51-L67 |
28,517 | TakahikoKawasaki/nv-websocket-client | src/main/java/com/neovisionaries/ws/client/Misc.java | Misc.toOpcodeName | public static String toOpcodeName(int opcode)
{
switch (opcode)
{
case CONTINUATION:
return "CONTINUATION";
case TEXT:
return "TEXT";
case BINARY:
return "BINARY";
case CLOSE:
return "CLOSE";
case PING:
return "PING";
case PONG:
return "PONG";
default:
break;
}
if (0x1 <= opcode && opcode <= 0x7)
{
return String.format("DATA(0x%X)", opcode);
}
if (0x8 <= opcode && opcode <= 0xF)
{
return String.format("CONTROL(0x%X)", opcode);
}
return String.format("0x%X", opcode);
} | java | public static String toOpcodeName(int opcode)
{
switch (opcode)
{
case CONTINUATION:
return "CONTINUATION";
case TEXT:
return "TEXT";
case BINARY:
return "BINARY";
case CLOSE:
return "CLOSE";
case PING:
return "PING";
case PONG:
return "PONG";
default:
break;
}
if (0x1 <= opcode && opcode <= 0x7)
{
return String.format("DATA(0x%X)", opcode);
}
if (0x8 <= opcode && opcode <= 0xF)
{
return String.format("CONTROL(0x%X)", opcode);
}
return String.format("0x%X", opcode);
} | [
"public",
"static",
"String",
"toOpcodeName",
"(",
"int",
"opcode",
")",
"{",
"switch",
"(",
"opcode",
")",
"{",
"case",
"CONTINUATION",
":",
"return",
"\"CONTINUATION\"",
";",
"case",
"TEXT",
":",
"return",
"\"TEXT\"",
";",
"case",
"BINARY",
":",
"return",
"\"BINARY\"",
";",
"case",
"CLOSE",
":",
"return",
"\"CLOSE\"",
";",
"case",
"PING",
":",
"return",
"\"PING\"",
";",
"case",
"PONG",
":",
"return",
"\"PONG\"",
";",
"default",
":",
"break",
";",
"}",
"if",
"(",
"0x1",
"<=",
"opcode",
"&&",
"opcode",
"<=",
"0x7",
")",
"{",
"return",
"String",
".",
"format",
"(",
"\"DATA(0x%X)\"",
",",
"opcode",
")",
";",
"}",
"if",
"(",
"0x8",
"<=",
"opcode",
"&&",
"opcode",
"<=",
"0xF",
")",
"{",
"return",
"String",
".",
"format",
"(",
"\"CONTROL(0x%X)\"",
",",
"opcode",
")",
";",
"}",
"return",
"String",
".",
"format",
"(",
"\"0x%X\"",
",",
"opcode",
")",
";",
"}"
] | Convert a WebSocket opcode into a string representation. | [
"Convert",
"a",
"WebSocket",
"opcode",
"into",
"a",
"string",
"representation",
"."
] | efaec21181d740ad3808313acf679313179e0825 | https://github.com/TakahikoKawasaki/nv-websocket-client/blob/efaec21181d740ad3808313acf679313179e0825/src/main/java/com/neovisionaries/ws/client/Misc.java#L135-L172 |
28,518 | TakahikoKawasaki/nv-websocket-client | src/main/java/com/neovisionaries/ws/client/Misc.java | Misc.readLine | public static String readLine(InputStream in, String charset) throws IOException
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while (true)
{
// Read one byte from the stream.
int b = in.read();
// If the end of the stream was reached.
if (b == -1)
{
if (baos.size() == 0)
{
// No more line.
return null;
}
else
{
// The end of the line was reached.
break;
}
}
if (b == '\n')
{
// The end of the line was reached.
break;
}
if (b != '\r')
{
// Normal character.
baos.write(b);
continue;
}
// Read one more byte.
int b2 = in.read();
// If the end of the stream was reached.
if (b2 == -1)
{
// Treat the '\r' as a normal character.
baos.write(b);
// The end of the line was reached.
break;
}
// If '\n' follows the '\r'.
if (b2 == '\n')
{
// The end of the line was reached.
break;
}
// Treat the '\r' as a normal character.
baos.write(b);
// Append the byte which follows the '\r'.
baos.write(b2);
}
// Convert the byte array to a string.
return baos.toString(charset);
} | java | public static String readLine(InputStream in, String charset) throws IOException
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while (true)
{
// Read one byte from the stream.
int b = in.read();
// If the end of the stream was reached.
if (b == -1)
{
if (baos.size() == 0)
{
// No more line.
return null;
}
else
{
// The end of the line was reached.
break;
}
}
if (b == '\n')
{
// The end of the line was reached.
break;
}
if (b != '\r')
{
// Normal character.
baos.write(b);
continue;
}
// Read one more byte.
int b2 = in.read();
// If the end of the stream was reached.
if (b2 == -1)
{
// Treat the '\r' as a normal character.
baos.write(b);
// The end of the line was reached.
break;
}
// If '\n' follows the '\r'.
if (b2 == '\n')
{
// The end of the line was reached.
break;
}
// Treat the '\r' as a normal character.
baos.write(b);
// Append the byte which follows the '\r'.
baos.write(b2);
}
// Convert the byte array to a string.
return baos.toString(charset);
} | [
"public",
"static",
"String",
"readLine",
"(",
"InputStream",
"in",
",",
"String",
"charset",
")",
"throws",
"IOException",
"{",
"ByteArrayOutputStream",
"baos",
"=",
"new",
"ByteArrayOutputStream",
"(",
")",
";",
"while",
"(",
"true",
")",
"{",
"// Read one byte from the stream.",
"int",
"b",
"=",
"in",
".",
"read",
"(",
")",
";",
"// If the end of the stream was reached.",
"if",
"(",
"b",
"==",
"-",
"1",
")",
"{",
"if",
"(",
"baos",
".",
"size",
"(",
")",
"==",
"0",
")",
"{",
"// No more line.",
"return",
"null",
";",
"}",
"else",
"{",
"// The end of the line was reached.",
"break",
";",
"}",
"}",
"if",
"(",
"b",
"==",
"'",
"'",
")",
"{",
"// The end of the line was reached.",
"break",
";",
"}",
"if",
"(",
"b",
"!=",
"'",
"'",
")",
"{",
"// Normal character.",
"baos",
".",
"write",
"(",
"b",
")",
";",
"continue",
";",
"}",
"// Read one more byte.",
"int",
"b2",
"=",
"in",
".",
"read",
"(",
")",
";",
"// If the end of the stream was reached.",
"if",
"(",
"b2",
"==",
"-",
"1",
")",
"{",
"// Treat the '\\r' as a normal character.",
"baos",
".",
"write",
"(",
"b",
")",
";",
"// The end of the line was reached.",
"break",
";",
"}",
"// If '\\n' follows the '\\r'.",
"if",
"(",
"b2",
"==",
"'",
"'",
")",
"{",
"// The end of the line was reached.",
"break",
";",
"}",
"// Treat the '\\r' as a normal character.",
"baos",
".",
"write",
"(",
"b",
")",
";",
"// Append the byte which follows the '\\r'.",
"baos",
".",
"write",
"(",
"b2",
")",
";",
"}",
"// Convert the byte array to a string.",
"return",
"baos",
".",
"toString",
"(",
"charset",
")",
";",
"}"
] | Read a line from the given stream. | [
"Read",
"a",
"line",
"from",
"the",
"given",
"stream",
"."
] | efaec21181d740ad3808313acf679313179e0825 | https://github.com/TakahikoKawasaki/nv-websocket-client/blob/efaec21181d740ad3808313acf679313179e0825/src/main/java/com/neovisionaries/ws/client/Misc.java#L178-L244 |
28,519 | TakahikoKawasaki/nv-websocket-client | src/main/java/com/neovisionaries/ws/client/Misc.java | Misc.min | public static int min(int[] values)
{
int min = Integer.MAX_VALUE;
for (int i = 0; i < values.length; ++i)
{
if (values[i] < min)
{
min = values[i];
}
}
return min;
} | java | public static int min(int[] values)
{
int min = Integer.MAX_VALUE;
for (int i = 0; i < values.length; ++i)
{
if (values[i] < min)
{
min = values[i];
}
}
return min;
} | [
"public",
"static",
"int",
"min",
"(",
"int",
"[",
"]",
"values",
")",
"{",
"int",
"min",
"=",
"Integer",
".",
"MAX_VALUE",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"values",
".",
"length",
";",
"++",
"i",
")",
"{",
"if",
"(",
"values",
"[",
"i",
"]",
"<",
"min",
")",
"{",
"min",
"=",
"values",
"[",
"i",
"]",
";",
"}",
"}",
"return",
"min",
";",
"}"
] | Find the minimum value from the given array. | [
"Find",
"the",
"minimum",
"value",
"from",
"the",
"given",
"array",
"."
] | efaec21181d740ad3808313acf679313179e0825 | https://github.com/TakahikoKawasaki/nv-websocket-client/blob/efaec21181d740ad3808313acf679313179e0825/src/main/java/com/neovisionaries/ws/client/Misc.java#L250-L263 |
28,520 | TakahikoKawasaki/nv-websocket-client | src/main/java/com/neovisionaries/ws/client/Misc.java | Misc.max | public static int max(int[] values)
{
int max = Integer.MIN_VALUE;
for (int i = 0; i < values.length; ++i)
{
if (max < values[i])
{
max = values[i];
}
}
return max;
} | java | public static int max(int[] values)
{
int max = Integer.MIN_VALUE;
for (int i = 0; i < values.length; ++i)
{
if (max < values[i])
{
max = values[i];
}
}
return max;
} | [
"public",
"static",
"int",
"max",
"(",
"int",
"[",
"]",
"values",
")",
"{",
"int",
"max",
"=",
"Integer",
".",
"MIN_VALUE",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"values",
".",
"length",
";",
"++",
"i",
")",
"{",
"if",
"(",
"max",
"<",
"values",
"[",
"i",
"]",
")",
"{",
"max",
"=",
"values",
"[",
"i",
"]",
";",
"}",
"}",
"return",
"max",
";",
"}"
] | Find the maximum value from the given array. | [
"Find",
"the",
"maximum",
"value",
"from",
"the",
"given",
"array",
"."
] | efaec21181d740ad3808313acf679313179e0825 | https://github.com/TakahikoKawasaki/nv-websocket-client/blob/efaec21181d740ad3808313acf679313179e0825/src/main/java/com/neovisionaries/ws/client/Misc.java#L269-L282 |
28,521 | TakahikoKawasaki/nv-websocket-client | src/main/java/com/neovisionaries/ws/client/Huffman.java | Huffman.createIntArray | private static int[] createIntArray(int size, int initialValue)
{
int[] array = new int[size];
for (int i = 0; i < size; ++i)
{
array[i] = initialValue;
}
return array;
} | java | private static int[] createIntArray(int size, int initialValue)
{
int[] array = new int[size];
for (int i = 0; i < size; ++i)
{
array[i] = initialValue;
}
return array;
} | [
"private",
"static",
"int",
"[",
"]",
"createIntArray",
"(",
"int",
"size",
",",
"int",
"initialValue",
")",
"{",
"int",
"[",
"]",
"array",
"=",
"new",
"int",
"[",
"size",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"size",
";",
"++",
"i",
")",
"{",
"array",
"[",
"i",
"]",
"=",
"initialValue",
";",
"}",
"return",
"array",
";",
"}"
] | Create an array whose elements have the given initial value. | [
"Create",
"an",
"array",
"whose",
"elements",
"have",
"the",
"given",
"initial",
"value",
"."
] | efaec21181d740ad3808313acf679313179e0825 | https://github.com/TakahikoKawasaki/nv-websocket-client/blob/efaec21181d740ad3808313acf679313179e0825/src/main/java/com/neovisionaries/ws/client/Huffman.java#L54-L64 |
28,522 | jhipster/jhipster | jhipster-framework/src/main/java/io/github/jhipster/service/QueryService.java | QueryService.equalsSpecification | protected <X> Specification<ENTITY> equalsSpecification(Function<Root<ENTITY>, Expression<X>> metaclassFunction, final X value) {
return (root, query, builder) -> builder.equal(metaclassFunction.apply(root), value);
} | java | protected <X> Specification<ENTITY> equalsSpecification(Function<Root<ENTITY>, Expression<X>> metaclassFunction, final X value) {
return (root, query, builder) -> builder.equal(metaclassFunction.apply(root), value);
} | [
"protected",
"<",
"X",
">",
"Specification",
"<",
"ENTITY",
">",
"equalsSpecification",
"(",
"Function",
"<",
"Root",
"<",
"ENTITY",
">",
",",
"Expression",
"<",
"X",
">",
">",
"metaclassFunction",
",",
"final",
"X",
"value",
")",
"{",
"return",
"(",
"root",
",",
"query",
",",
"builder",
")",
"->",
"builder",
".",
"equal",
"(",
"metaclassFunction",
".",
"apply",
"(",
"root",
")",
",",
"value",
")",
";",
"}"
] | Generic method, which based on a Root<ENTITY> returns an Expression which type is the same as the given 'value' type.
@param metaclassFunction function which returns the column which is used for filtering.
@param value the actual value to filter for.
@param <X> The type of the attribute which is filtered.
@return a Specification. | [
"Generic",
"method",
"which",
"based",
"on",
"a",
"Root<",
";",
"ENTITY>",
";",
"returns",
"an",
"Expression",
"which",
"type",
"is",
"the",
"same",
"as",
"the",
"given",
"value",
"type",
"."
] | 5dcf4239c7cc035e188ef02447d3c628fac5c5d9 | https://github.com/jhipster/jhipster/blob/5dcf4239c7cc035e188ef02447d3c628fac5c5d9/jhipster-framework/src/main/java/io/github/jhipster/service/QueryService.java#L338-L340 |
28,523 | jhipster/jhipster | jhipster-framework/src/main/java/io/github/jhipster/security/PersistentTokenCache.java | PersistentTokenCache.get | public T get(String key) {
purge();
final Value val = map.get(key);
final long time = System.currentTimeMillis();
return val != null && time < val.expire ? val.token : null;
} | java | public T get(String key) {
purge();
final Value val = map.get(key);
final long time = System.currentTimeMillis();
return val != null && time < val.expire ? val.token : null;
} | [
"public",
"T",
"get",
"(",
"String",
"key",
")",
"{",
"purge",
"(",
")",
";",
"final",
"Value",
"val",
"=",
"map",
".",
"get",
"(",
"key",
")",
";",
"final",
"long",
"time",
"=",
"System",
".",
"currentTimeMillis",
"(",
")",
";",
"return",
"val",
"!=",
"null",
"&&",
"time",
"<",
"val",
".",
"expire",
"?",
"val",
".",
"token",
":",
"null",
";",
"}"
] | Get a token from the cache.
@param key The key to look for.
@return The token, if present and not yet expired, or null otherwise. | [
"Get",
"a",
"token",
"from",
"the",
"cache",
"."
] | 5dcf4239c7cc035e188ef02447d3c628fac5c5d9 | https://github.com/jhipster/jhipster/blob/5dcf4239c7cc035e188ef02447d3c628fac5c5d9/jhipster-framework/src/main/java/io/github/jhipster/security/PersistentTokenCache.java#L61-L66 |
28,524 | jhipster/jhipster | jhipster-framework/src/main/java/io/github/jhipster/security/PersistentTokenCache.java | PersistentTokenCache.put | public void put(String key, T token) {
purge();
if (map.containsKey(key)) {
map.remove(key);
}
final long time = System.currentTimeMillis();
map.put(key, new Value(token, time + expireMillis));
latestWriteTime = time;
} | java | public void put(String key, T token) {
purge();
if (map.containsKey(key)) {
map.remove(key);
}
final long time = System.currentTimeMillis();
map.put(key, new Value(token, time + expireMillis));
latestWriteTime = time;
} | [
"public",
"void",
"put",
"(",
"String",
"key",
",",
"T",
"token",
")",
"{",
"purge",
"(",
")",
";",
"if",
"(",
"map",
".",
"containsKey",
"(",
"key",
")",
")",
"{",
"map",
".",
"remove",
"(",
"key",
")",
";",
"}",
"final",
"long",
"time",
"=",
"System",
".",
"currentTimeMillis",
"(",
")",
";",
"map",
".",
"put",
"(",
"key",
",",
"new",
"Value",
"(",
"token",
",",
"time",
"+",
"expireMillis",
")",
")",
";",
"latestWriteTime",
"=",
"time",
";",
"}"
] | Put a token in the cache.
If a token already exists for the given key, it is replaced.
@param key The key to insert for.
@param token The token to insert. | [
"Put",
"a",
"token",
"in",
"the",
"cache",
".",
"If",
"a",
"token",
"already",
"exists",
"for",
"the",
"given",
"key",
"it",
"is",
"replaced",
"."
] | 5dcf4239c7cc035e188ef02447d3c628fac5c5d9 | https://github.com/jhipster/jhipster/blob/5dcf4239c7cc035e188ef02447d3c628fac5c5d9/jhipster-framework/src/main/java/io/github/jhipster/security/PersistentTokenCache.java#L75-L83 |
28,525 | jhipster/jhipster | jhipster-framework/src/main/java/io/github/jhipster/config/apidoc/PageableParameterBuilderPlugin.java | PageableParameterBuilderPlugin.createPageParameter | protected Parameter createPageParameter(ParameterContext context) {
ModelReference intModel = createModelRefFactory(context).apply(resolver.resolve(Integer.TYPE));
return new ParameterBuilder()
.name(getPageName())
.parameterType(PAGE_TYPE)
.modelRef(intModel)
.description(PAGE_DESCRIPTION)
.build();
} | java | protected Parameter createPageParameter(ParameterContext context) {
ModelReference intModel = createModelRefFactory(context).apply(resolver.resolve(Integer.TYPE));
return new ParameterBuilder()
.name(getPageName())
.parameterType(PAGE_TYPE)
.modelRef(intModel)
.description(PAGE_DESCRIPTION)
.build();
} | [
"protected",
"Parameter",
"createPageParameter",
"(",
"ParameterContext",
"context",
")",
"{",
"ModelReference",
"intModel",
"=",
"createModelRefFactory",
"(",
"context",
")",
".",
"apply",
"(",
"resolver",
".",
"resolve",
"(",
"Integer",
".",
"TYPE",
")",
")",
";",
"return",
"new",
"ParameterBuilder",
"(",
")",
".",
"name",
"(",
"getPageName",
"(",
")",
")",
".",
"parameterType",
"(",
"PAGE_TYPE",
")",
".",
"modelRef",
"(",
"intModel",
")",
".",
"description",
"(",
"PAGE_DESCRIPTION",
")",
".",
"build",
"(",
")",
";",
"}"
] | Create a page parameter.
Override it if needed. Set a default value for example.
@param context {@link Pageable} parameter context
@return The page parameter | [
"Create",
"a",
"page",
"parameter",
".",
"Override",
"it",
"if",
"needed",
".",
"Set",
"a",
"default",
"value",
"for",
"example",
"."
] | 5dcf4239c7cc035e188ef02447d3c628fac5c5d9 | https://github.com/jhipster/jhipster/blob/5dcf4239c7cc035e188ef02447d3c628fac5c5d9/jhipster-framework/src/main/java/io/github/jhipster/config/apidoc/PageableParameterBuilderPlugin.java#L136-L144 |
28,526 | jhipster/jhipster | jhipster-framework/src/main/java/io/github/jhipster/config/apidoc/PageableParameterBuilderPlugin.java | PageableParameterBuilderPlugin.createSizeParameter | protected Parameter createSizeParameter(ParameterContext context) {
ModelReference intModel = createModelRefFactory(context).apply(resolver.resolve(Integer.TYPE));
return new ParameterBuilder()
.name(getSizeName())
.parameterType(SIZE_TYPE)
.modelRef(intModel)
.description(SIZE_DESCRIPTION)
.build();
} | java | protected Parameter createSizeParameter(ParameterContext context) {
ModelReference intModel = createModelRefFactory(context).apply(resolver.resolve(Integer.TYPE));
return new ParameterBuilder()
.name(getSizeName())
.parameterType(SIZE_TYPE)
.modelRef(intModel)
.description(SIZE_DESCRIPTION)
.build();
} | [
"protected",
"Parameter",
"createSizeParameter",
"(",
"ParameterContext",
"context",
")",
"{",
"ModelReference",
"intModel",
"=",
"createModelRefFactory",
"(",
"context",
")",
".",
"apply",
"(",
"resolver",
".",
"resolve",
"(",
"Integer",
".",
"TYPE",
")",
")",
";",
"return",
"new",
"ParameterBuilder",
"(",
")",
".",
"name",
"(",
"getSizeName",
"(",
")",
")",
".",
"parameterType",
"(",
"SIZE_TYPE",
")",
".",
"modelRef",
"(",
"intModel",
")",
".",
"description",
"(",
"SIZE_DESCRIPTION",
")",
".",
"build",
"(",
")",
";",
"}"
] | Create a size parameter.
Override it if needed. Set a default value for example.
@param context {@link Pageable} parameter context
@return The size parameter | [
"Create",
"a",
"size",
"parameter",
".",
"Override",
"it",
"if",
"needed",
".",
"Set",
"a",
"default",
"value",
"for",
"example",
"."
] | 5dcf4239c7cc035e188ef02447d3c628fac5c5d9 | https://github.com/jhipster/jhipster/blob/5dcf4239c7cc035e188ef02447d3c628fac5c5d9/jhipster-framework/src/main/java/io/github/jhipster/config/apidoc/PageableParameterBuilderPlugin.java#L153-L161 |
28,527 | jhipster/jhipster | jhipster-framework/src/main/java/io/github/jhipster/config/apidoc/PageableParameterBuilderPlugin.java | PageableParameterBuilderPlugin.createSortParameter | protected Parameter createSortParameter(ParameterContext context) {
ModelReference stringModel = createModelRefFactory(context).apply(resolver.resolve(List.class, String.class));
return new ParameterBuilder()
.name(getSortName())
.parameterType(SORT_TYPE)
.modelRef(stringModel)
.allowMultiple(true)
.description(SORT_DESCRIPTION)
.build();
} | java | protected Parameter createSortParameter(ParameterContext context) {
ModelReference stringModel = createModelRefFactory(context).apply(resolver.resolve(List.class, String.class));
return new ParameterBuilder()
.name(getSortName())
.parameterType(SORT_TYPE)
.modelRef(stringModel)
.allowMultiple(true)
.description(SORT_DESCRIPTION)
.build();
} | [
"protected",
"Parameter",
"createSortParameter",
"(",
"ParameterContext",
"context",
")",
"{",
"ModelReference",
"stringModel",
"=",
"createModelRefFactory",
"(",
"context",
")",
".",
"apply",
"(",
"resolver",
".",
"resolve",
"(",
"List",
".",
"class",
",",
"String",
".",
"class",
")",
")",
";",
"return",
"new",
"ParameterBuilder",
"(",
")",
".",
"name",
"(",
"getSortName",
"(",
")",
")",
".",
"parameterType",
"(",
"SORT_TYPE",
")",
".",
"modelRef",
"(",
"stringModel",
")",
".",
"allowMultiple",
"(",
"true",
")",
".",
"description",
"(",
"SORT_DESCRIPTION",
")",
".",
"build",
"(",
")",
";",
"}"
] | Create a sort parameter.
Override it if needed. Set a default value or further description for example.
@param context {@link Pageable} parameter context
@return The sort parameter | [
"Create",
"a",
"sort",
"parameter",
".",
"Override",
"it",
"if",
"needed",
".",
"Set",
"a",
"default",
"value",
"or",
"further",
"description",
"for",
"example",
"."
] | 5dcf4239c7cc035e188ef02447d3c628fac5c5d9 | https://github.com/jhipster/jhipster/blob/5dcf4239c7cc035e188ef02447d3c628fac5c5d9/jhipster-framework/src/main/java/io/github/jhipster/config/apidoc/PageableParameterBuilderPlugin.java#L170-L179 |
28,528 | alexxiyang/shiro-redis | src/main/java/org/crazycake/shiro/RedisCache.java | RedisCache.get | @Override
public V get(K key) throws CacheException {
logger.debug("get key [" + key + "]");
if (key == null) {
return null;
}
try {
Object redisCacheKey = getRedisCacheKey(key);
byte[] rawValue = redisManager.get(keySerializer.serialize(redisCacheKey));
if (rawValue == null) {
return null;
}
V value = (V) valueSerializer.deserialize(rawValue);
return value;
} catch (SerializationException e) {
throw new CacheException(e);
}
} | java | @Override
public V get(K key) throws CacheException {
logger.debug("get key [" + key + "]");
if (key == null) {
return null;
}
try {
Object redisCacheKey = getRedisCacheKey(key);
byte[] rawValue = redisManager.get(keySerializer.serialize(redisCacheKey));
if (rawValue == null) {
return null;
}
V value = (V) valueSerializer.deserialize(rawValue);
return value;
} catch (SerializationException e) {
throw new CacheException(e);
}
} | [
"@",
"Override",
"public",
"V",
"get",
"(",
"K",
"key",
")",
"throws",
"CacheException",
"{",
"logger",
".",
"debug",
"(",
"\"get key [\"",
"+",
"key",
"+",
"\"]\"",
")",
";",
"if",
"(",
"key",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"try",
"{",
"Object",
"redisCacheKey",
"=",
"getRedisCacheKey",
"(",
"key",
")",
";",
"byte",
"[",
"]",
"rawValue",
"=",
"redisManager",
".",
"get",
"(",
"keySerializer",
".",
"serialize",
"(",
"redisCacheKey",
")",
")",
";",
"if",
"(",
"rawValue",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"V",
"value",
"=",
"(",
"V",
")",
"valueSerializer",
".",
"deserialize",
"(",
"rawValue",
")",
";",
"return",
"value",
";",
"}",
"catch",
"(",
"SerializationException",
"e",
")",
"{",
"throw",
"new",
"CacheException",
"(",
"e",
")",
";",
"}",
"}"
] | get shiro authorization redis key-value
@param key key
@return value
@throws CacheException get cache exception | [
"get",
"shiro",
"authorization",
"redis",
"key",
"-",
"value"
] | a9b1a4b44fcd2f2926d0e84fabeb331013825ebb | https://github.com/alexxiyang/shiro-redis/blob/a9b1a4b44fcd2f2926d0e84fabeb331013825ebb/src/main/java/org/crazycake/shiro/RedisCache.java#L69-L88 |
28,529 | alexxiyang/shiro-redis | src/main/java/org/crazycake/shiro/RedisCache.java | RedisCache.size | @Override
public int size() {
Long longSize = 0L;
try {
longSize = new Long(redisManager.dbSize(keySerializer.serialize(this.keyPrefix + "*")));
} catch (SerializationException e) {
logger.error("get keys error", e);
}
return longSize.intValue();
} | java | @Override
public int size() {
Long longSize = 0L;
try {
longSize = new Long(redisManager.dbSize(keySerializer.serialize(this.keyPrefix + "*")));
} catch (SerializationException e) {
logger.error("get keys error", e);
}
return longSize.intValue();
} | [
"@",
"Override",
"public",
"int",
"size",
"(",
")",
"{",
"Long",
"longSize",
"=",
"0L",
";",
"try",
"{",
"longSize",
"=",
"new",
"Long",
"(",
"redisManager",
".",
"dbSize",
"(",
"keySerializer",
".",
"serialize",
"(",
"this",
".",
"keyPrefix",
"+",
"\"*\"",
")",
")",
")",
";",
"}",
"catch",
"(",
"SerializationException",
"e",
")",
"{",
"logger",
".",
"error",
"(",
"\"get keys error\"",
",",
"e",
")",
";",
"}",
"return",
"longSize",
".",
"intValue",
"(",
")",
";",
"}"
] | get all authorization key-value quantity
@return key-value size | [
"get",
"all",
"authorization",
"key",
"-",
"value",
"quantity"
] | a9b1a4b44fcd2f2926d0e84fabeb331013825ebb | https://github.com/alexxiyang/shiro-redis/blob/a9b1a4b44fcd2f2926d0e84fabeb331013825ebb/src/main/java/org/crazycake/shiro/RedisCache.java#L208-L217 |
28,530 | alexxiyang/shiro-redis | src/main/java/org/crazycake/shiro/WorkAloneRedisManager.java | WorkAloneRedisManager.del | @Override
public void del(byte[] key) {
if (key == null) {
return;
}
Jedis jedis = getJedis();
try {
jedis.del(key);
} finally {
jedis.close();
}
} | java | @Override
public void del(byte[] key) {
if (key == null) {
return;
}
Jedis jedis = getJedis();
try {
jedis.del(key);
} finally {
jedis.close();
}
} | [
"@",
"Override",
"public",
"void",
"del",
"(",
"byte",
"[",
"]",
"key",
")",
"{",
"if",
"(",
"key",
"==",
"null",
")",
"{",
"return",
";",
"}",
"Jedis",
"jedis",
"=",
"getJedis",
"(",
")",
";",
"try",
"{",
"jedis",
".",
"del",
"(",
"key",
")",
";",
"}",
"finally",
"{",
"jedis",
".",
"close",
"(",
")",
";",
"}",
"}"
] | Delete a key-value pair.
@param key key | [
"Delete",
"a",
"key",
"-",
"value",
"pair",
"."
] | a9b1a4b44fcd2f2926d0e84fabeb331013825ebb | https://github.com/alexxiyang/shiro-redis/blob/a9b1a4b44fcd2f2926d0e84fabeb331013825ebb/src/main/java/org/crazycake/shiro/WorkAloneRedisManager.java#L88-L99 |
28,531 | alexxiyang/shiro-redis | src/main/java/org/crazycake/shiro/WorkAloneRedisManager.java | WorkAloneRedisManager.dbSize | @Override
public Long dbSize(byte[] pattern) {
long dbSize = 0L;
Jedis jedis = getJedis();
try {
ScanParams params = new ScanParams();
params.count(count);
params.match(pattern);
byte[] cursor = ScanParams.SCAN_POINTER_START_BINARY;
ScanResult<byte[]> scanResult;
do {
scanResult = jedis.scan(cursor, params);
List<byte[]> results = scanResult.getResult();
for (byte[] result : results) {
dbSize++;
}
cursor = scanResult.getCursorAsBytes();
} while (scanResult.getStringCursor().compareTo(ScanParams.SCAN_POINTER_START) > 0);
} finally {
jedis.close();
}
return dbSize;
} | java | @Override
public Long dbSize(byte[] pattern) {
long dbSize = 0L;
Jedis jedis = getJedis();
try {
ScanParams params = new ScanParams();
params.count(count);
params.match(pattern);
byte[] cursor = ScanParams.SCAN_POINTER_START_BINARY;
ScanResult<byte[]> scanResult;
do {
scanResult = jedis.scan(cursor, params);
List<byte[]> results = scanResult.getResult();
for (byte[] result : results) {
dbSize++;
}
cursor = scanResult.getCursorAsBytes();
} while (scanResult.getStringCursor().compareTo(ScanParams.SCAN_POINTER_START) > 0);
} finally {
jedis.close();
}
return dbSize;
} | [
"@",
"Override",
"public",
"Long",
"dbSize",
"(",
"byte",
"[",
"]",
"pattern",
")",
"{",
"long",
"dbSize",
"=",
"0L",
";",
"Jedis",
"jedis",
"=",
"getJedis",
"(",
")",
";",
"try",
"{",
"ScanParams",
"params",
"=",
"new",
"ScanParams",
"(",
")",
";",
"params",
".",
"count",
"(",
"count",
")",
";",
"params",
".",
"match",
"(",
"pattern",
")",
";",
"byte",
"[",
"]",
"cursor",
"=",
"ScanParams",
".",
"SCAN_POINTER_START_BINARY",
";",
"ScanResult",
"<",
"byte",
"[",
"]",
">",
"scanResult",
";",
"do",
"{",
"scanResult",
"=",
"jedis",
".",
"scan",
"(",
"cursor",
",",
"params",
")",
";",
"List",
"<",
"byte",
"[",
"]",
">",
"results",
"=",
"scanResult",
".",
"getResult",
"(",
")",
";",
"for",
"(",
"byte",
"[",
"]",
"result",
":",
"results",
")",
"{",
"dbSize",
"++",
";",
"}",
"cursor",
"=",
"scanResult",
".",
"getCursorAsBytes",
"(",
")",
";",
"}",
"while",
"(",
"scanResult",
".",
"getStringCursor",
"(",
")",
".",
"compareTo",
"(",
"ScanParams",
".",
"SCAN_POINTER_START",
")",
">",
"0",
")",
";",
"}",
"finally",
"{",
"jedis",
".",
"close",
"(",
")",
";",
"}",
"return",
"dbSize",
";",
"}"
] | Return the size of redis db.
@param pattern key pattern
@return key-value size | [
"Return",
"the",
"size",
"of",
"redis",
"db",
"."
] | a9b1a4b44fcd2f2926d0e84fabeb331013825ebb | https://github.com/alexxiyang/shiro-redis/blob/a9b1a4b44fcd2f2926d0e84fabeb331013825ebb/src/main/java/org/crazycake/shiro/WorkAloneRedisManager.java#L106-L128 |
28,532 | alexxiyang/shiro-redis | src/main/java/org/crazycake/shiro/WorkAloneRedisManager.java | WorkAloneRedisManager.keys | public Set<byte[]> keys(byte[] pattern) {
Set<byte[]> keys = new HashSet<byte[]>();
Jedis jedis = getJedis();
try {
ScanParams params = new ScanParams();
params.count(count);
params.match(pattern);
byte[] cursor = ScanParams.SCAN_POINTER_START_BINARY;
ScanResult<byte[]> scanResult;
do {
scanResult = jedis.scan(cursor, params);
keys.addAll(scanResult.getResult());
cursor = scanResult.getCursorAsBytes();
} while (scanResult.getStringCursor().compareTo(ScanParams.SCAN_POINTER_START) > 0);
} finally {
jedis.close();
}
return keys;
} | java | public Set<byte[]> keys(byte[] pattern) {
Set<byte[]> keys = new HashSet<byte[]>();
Jedis jedis = getJedis();
try {
ScanParams params = new ScanParams();
params.count(count);
params.match(pattern);
byte[] cursor = ScanParams.SCAN_POINTER_START_BINARY;
ScanResult<byte[]> scanResult;
do {
scanResult = jedis.scan(cursor, params);
keys.addAll(scanResult.getResult());
cursor = scanResult.getCursorAsBytes();
} while (scanResult.getStringCursor().compareTo(ScanParams.SCAN_POINTER_START) > 0);
} finally {
jedis.close();
}
return keys;
} | [
"public",
"Set",
"<",
"byte",
"[",
"]",
">",
"keys",
"(",
"byte",
"[",
"]",
"pattern",
")",
"{",
"Set",
"<",
"byte",
"[",
"]",
">",
"keys",
"=",
"new",
"HashSet",
"<",
"byte",
"[",
"]",
">",
"(",
")",
";",
"Jedis",
"jedis",
"=",
"getJedis",
"(",
")",
";",
"try",
"{",
"ScanParams",
"params",
"=",
"new",
"ScanParams",
"(",
")",
";",
"params",
".",
"count",
"(",
"count",
")",
";",
"params",
".",
"match",
"(",
"pattern",
")",
";",
"byte",
"[",
"]",
"cursor",
"=",
"ScanParams",
".",
"SCAN_POINTER_START_BINARY",
";",
"ScanResult",
"<",
"byte",
"[",
"]",
">",
"scanResult",
";",
"do",
"{",
"scanResult",
"=",
"jedis",
".",
"scan",
"(",
"cursor",
",",
"params",
")",
";",
"keys",
".",
"addAll",
"(",
"scanResult",
".",
"getResult",
"(",
")",
")",
";",
"cursor",
"=",
"scanResult",
".",
"getCursorAsBytes",
"(",
")",
";",
"}",
"while",
"(",
"scanResult",
".",
"getStringCursor",
"(",
")",
".",
"compareTo",
"(",
"ScanParams",
".",
"SCAN_POINTER_START",
")",
">",
"0",
")",
";",
"}",
"finally",
"{",
"jedis",
".",
"close",
"(",
")",
";",
"}",
"return",
"keys",
";",
"}"
] | Return all the keys of Redis db. Filtered by pattern.
@param pattern key pattern
@return key set | [
"Return",
"all",
"the",
"keys",
"of",
"Redis",
"db",
".",
"Filtered",
"by",
"pattern",
"."
] | a9b1a4b44fcd2f2926d0e84fabeb331013825ebb | https://github.com/alexxiyang/shiro-redis/blob/a9b1a4b44fcd2f2926d0e84fabeb331013825ebb/src/main/java/org/crazycake/shiro/WorkAloneRedisManager.java#L135-L155 |
28,533 | Netflix/Turbine | turbine-core/src/main/java/com/netflix/turbine/aggregator/NumberList.java | NumberList.delta | public static NumberList delta(Map<String, Object> currentMap, Map<String, Object> previousMap) {
LinkedHashMap<String, Long> values = new LinkedHashMap<String, Long>(currentMap.size());
if(currentMap.size() != previousMap.size()) {
throw new IllegalArgumentException("Maps must have the same keys");
}
for (Entry<String, Object> k : currentMap.entrySet()) {
Object v = k.getValue();
Number current = getNumber(v);
Object p = previousMap.get(k.getKey());
Number previous = null;
if (p == null) {
previous = 0;
} else {
previous = getNumber(p);
}
long d = (current.longValue() - previous.longValue());
values.put(k.getKey(), d);
}
return new NumberList(values);
} | java | public static NumberList delta(Map<String, Object> currentMap, Map<String, Object> previousMap) {
LinkedHashMap<String, Long> values = new LinkedHashMap<String, Long>(currentMap.size());
if(currentMap.size() != previousMap.size()) {
throw new IllegalArgumentException("Maps must have the same keys");
}
for (Entry<String, Object> k : currentMap.entrySet()) {
Object v = k.getValue();
Number current = getNumber(v);
Object p = previousMap.get(k.getKey());
Number previous = null;
if (p == null) {
previous = 0;
} else {
previous = getNumber(p);
}
long d = (current.longValue() - previous.longValue());
values.put(k.getKey(), d);
}
return new NumberList(values);
} | [
"public",
"static",
"NumberList",
"delta",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"currentMap",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"previousMap",
")",
"{",
"LinkedHashMap",
"<",
"String",
",",
"Long",
">",
"values",
"=",
"new",
"LinkedHashMap",
"<",
"String",
",",
"Long",
">",
"(",
"currentMap",
".",
"size",
"(",
")",
")",
";",
"if",
"(",
"currentMap",
".",
"size",
"(",
")",
"!=",
"previousMap",
".",
"size",
"(",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Maps must have the same keys\"",
")",
";",
"}",
"for",
"(",
"Entry",
"<",
"String",
",",
"Object",
">",
"k",
":",
"currentMap",
".",
"entrySet",
"(",
")",
")",
"{",
"Object",
"v",
"=",
"k",
".",
"getValue",
"(",
")",
";",
"Number",
"current",
"=",
"getNumber",
"(",
"v",
")",
";",
"Object",
"p",
"=",
"previousMap",
".",
"get",
"(",
"k",
".",
"getKey",
"(",
")",
")",
";",
"Number",
"previous",
"=",
"null",
";",
"if",
"(",
"p",
"==",
"null",
")",
"{",
"previous",
"=",
"0",
";",
"}",
"else",
"{",
"previous",
"=",
"getNumber",
"(",
"p",
")",
";",
"}",
"long",
"d",
"=",
"(",
"current",
".",
"longValue",
"(",
")",
"-",
"previous",
".",
"longValue",
"(",
")",
")",
";",
"values",
".",
"put",
"(",
"k",
".",
"getKey",
"(",
")",
",",
"d",
")",
";",
"}",
"return",
"new",
"NumberList",
"(",
"values",
")",
";",
"}"
] | This assumes both maps contain the same keys. If they don't then keys will be lost.
@param currentMap
@param previousMap
@return | [
"This",
"assumes",
"both",
"maps",
"contain",
"the",
"same",
"keys",
".",
"If",
"they",
"don",
"t",
"then",
"keys",
"will",
"be",
"lost",
"."
] | 0e924058aa4d1d526310206a51dcf82f65274d58 | https://github.com/Netflix/Turbine/blob/0e924058aa4d1d526310206a51dcf82f65274d58/turbine-core/src/main/java/com/netflix/turbine/aggregator/NumberList.java#L65-L86 |
28,534 | Netflix/Turbine | turbine-core/src/main/java/com/netflix/turbine/aggregator/NumberList.java | NumberList.deltaInverse | public static NumberList deltaInverse(Map<String, Object> map) {
LinkedHashMap<String, Long> values = new LinkedHashMap<String, Long>(map.size());
for (Entry<String, Object> k : map.entrySet()) {
Object v = k.getValue();
Number current = getNumber(v);
long d = -current.longValue();
values.put(k.getKey(), d);
}
return new NumberList(values);
} | java | public static NumberList deltaInverse(Map<String, Object> map) {
LinkedHashMap<String, Long> values = new LinkedHashMap<String, Long>(map.size());
for (Entry<String, Object> k : map.entrySet()) {
Object v = k.getValue();
Number current = getNumber(v);
long d = -current.longValue();
values.put(k.getKey(), d);
}
return new NumberList(values);
} | [
"public",
"static",
"NumberList",
"deltaInverse",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"map",
")",
"{",
"LinkedHashMap",
"<",
"String",
",",
"Long",
">",
"values",
"=",
"new",
"LinkedHashMap",
"<",
"String",
",",
"Long",
">",
"(",
"map",
".",
"size",
"(",
")",
")",
";",
"for",
"(",
"Entry",
"<",
"String",
",",
"Object",
">",
"k",
":",
"map",
".",
"entrySet",
"(",
")",
")",
"{",
"Object",
"v",
"=",
"k",
".",
"getValue",
"(",
")",
";",
"Number",
"current",
"=",
"getNumber",
"(",
"v",
")",
";",
"long",
"d",
"=",
"-",
"current",
".",
"longValue",
"(",
")",
";",
"values",
".",
"put",
"(",
"k",
".",
"getKey",
"(",
")",
",",
"d",
")",
";",
"}",
"return",
"new",
"NumberList",
"(",
"values",
")",
";",
"}"
] | Return a NubmerList with the inverse of the given values. | [
"Return",
"a",
"NubmerList",
"with",
"the",
"inverse",
"of",
"the",
"given",
"values",
"."
] | 0e924058aa4d1d526310206a51dcf82f65274d58 | https://github.com/Netflix/Turbine/blob/0e924058aa4d1d526310206a51dcf82f65274d58/turbine-core/src/main/java/com/netflix/turbine/aggregator/NumberList.java#L91-L101 |
28,535 | Netflix/Turbine | turbine-core/src/main/java/com/netflix/turbine/aggregator/StreamAggregator.java | StreamAggregator.aggregateUsingFlattenedGroupBy | @SuppressWarnings("unused")
private static Observable<GroupedObservable<TypeAndNameKey, Map<String, Object>>> aggregateUsingFlattenedGroupBy(Observable<GroupedObservable<InstanceKey, Map<String, Object>>> stream) {
Observable<Map<String, Object>> allData = stream.flatMap(instanceStream -> {
return instanceStream
.map((Map<String, Object> event) -> {
event.put("InstanceKey", instanceStream.getKey());
event.put("TypeAndName", TypeAndNameKey.from(String.valueOf(event.get("type")), String.valueOf(event.get("name"))));
return event;
})
.compose(is -> {
return tombstone(is, instanceStream.getKey());
});
});
Observable<GroupedObservable<TypeAndNameKey, Map<String, Object>>> byCommand = allData
.groupBy((Map<String, Object> event) -> {
return (TypeAndNameKey) event.get("TypeAndName");
});
return byCommand
.map(commandGroup -> {
Observable<Map<String, Object>> sumOfDeltasForAllInstancesForCommand = commandGroup
.groupBy((Map<String, Object> json) -> {
return json.get("InstanceKey");
}).flatMap(instanceGroup -> {
// calculate and output deltas for each instance stream per command
return instanceGroup
.takeUntil(d -> d.containsKey("tombstone"))
.startWith(Collections.<String, Object> emptyMap())
.map(data -> {
if (data.containsKey("tombstone")) {
return Collections.<String, Object> emptyMap();
} else {
return data;
}
})
.buffer(2, 1)
.filter(list -> list.size() == 2)
.map(StreamAggregator::previousAndCurrentToDelta)
.filter(data -> data != null && !data.isEmpty());
})
// we now have all instance deltas merged into a single stream per command
// and sum them into a single stream of aggregate values
.scan(new HashMap<String, Object>(), StreamAggregator::sumOfDelta)
.skip(1);
// we artificially wrap in a GroupedObservable that communicates the CommandKey this stream represents
return GroupedObservable.from(commandGroup.getKey(), sumOfDeltasForAllInstancesForCommand);
});
} | java | @SuppressWarnings("unused")
private static Observable<GroupedObservable<TypeAndNameKey, Map<String, Object>>> aggregateUsingFlattenedGroupBy(Observable<GroupedObservable<InstanceKey, Map<String, Object>>> stream) {
Observable<Map<String, Object>> allData = stream.flatMap(instanceStream -> {
return instanceStream
.map((Map<String, Object> event) -> {
event.put("InstanceKey", instanceStream.getKey());
event.put("TypeAndName", TypeAndNameKey.from(String.valueOf(event.get("type")), String.valueOf(event.get("name"))));
return event;
})
.compose(is -> {
return tombstone(is, instanceStream.getKey());
});
});
Observable<GroupedObservable<TypeAndNameKey, Map<String, Object>>> byCommand = allData
.groupBy((Map<String, Object> event) -> {
return (TypeAndNameKey) event.get("TypeAndName");
});
return byCommand
.map(commandGroup -> {
Observable<Map<String, Object>> sumOfDeltasForAllInstancesForCommand = commandGroup
.groupBy((Map<String, Object> json) -> {
return json.get("InstanceKey");
}).flatMap(instanceGroup -> {
// calculate and output deltas for each instance stream per command
return instanceGroup
.takeUntil(d -> d.containsKey("tombstone"))
.startWith(Collections.<String, Object> emptyMap())
.map(data -> {
if (data.containsKey("tombstone")) {
return Collections.<String, Object> emptyMap();
} else {
return data;
}
})
.buffer(2, 1)
.filter(list -> list.size() == 2)
.map(StreamAggregator::previousAndCurrentToDelta)
.filter(data -> data != null && !data.isEmpty());
})
// we now have all instance deltas merged into a single stream per command
// and sum them into a single stream of aggregate values
.scan(new HashMap<String, Object>(), StreamAggregator::sumOfDelta)
.skip(1);
// we artificially wrap in a GroupedObservable that communicates the CommandKey this stream represents
return GroupedObservable.from(commandGroup.getKey(), sumOfDeltasForAllInstancesForCommand);
});
} | [
"@",
"SuppressWarnings",
"(",
"\"unused\"",
")",
"private",
"static",
"Observable",
"<",
"GroupedObservable",
"<",
"TypeAndNameKey",
",",
"Map",
"<",
"String",
",",
"Object",
">",
">",
">",
"aggregateUsingFlattenedGroupBy",
"(",
"Observable",
"<",
"GroupedObservable",
"<",
"InstanceKey",
",",
"Map",
"<",
"String",
",",
"Object",
">",
">",
">",
"stream",
")",
"{",
"Observable",
"<",
"Map",
"<",
"String",
",",
"Object",
">",
">",
"allData",
"=",
"stream",
".",
"flatMap",
"(",
"instanceStream",
"->",
"{",
"return",
"instanceStream",
".",
"map",
"(",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"event",
")",
"->",
"{",
"event",
".",
"put",
"(",
"\"InstanceKey\"",
",",
"instanceStream",
".",
"getKey",
"(",
")",
")",
";",
"event",
".",
"put",
"(",
"\"TypeAndName\"",
",",
"TypeAndNameKey",
".",
"from",
"(",
"String",
".",
"valueOf",
"(",
"event",
".",
"get",
"(",
"\"type\"",
")",
")",
",",
"String",
".",
"valueOf",
"(",
"event",
".",
"get",
"(",
"\"name\"",
")",
")",
")",
")",
";",
"return",
"event",
";",
"}",
")",
".",
"compose",
"(",
"is",
"->",
"{",
"return",
"tombstone",
"(",
"is",
",",
"instanceStream",
".",
"getKey",
"(",
")",
")",
";",
"}",
")",
";",
"}",
")",
";",
"Observable",
"<",
"GroupedObservable",
"<",
"TypeAndNameKey",
",",
"Map",
"<",
"String",
",",
"Object",
">",
">",
">",
"byCommand",
"=",
"allData",
".",
"groupBy",
"(",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"event",
")",
"->",
"{",
"return",
"(",
"TypeAndNameKey",
")",
"event",
".",
"get",
"(",
"\"TypeAndName\"",
")",
";",
"}",
")",
";",
"return",
"byCommand",
".",
"map",
"(",
"commandGroup",
"->",
"{",
"Observable",
"<",
"Map",
"<",
"String",
",",
"Object",
">",
">",
"sumOfDeltasForAllInstancesForCommand",
"=",
"commandGroup",
".",
"groupBy",
"(",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"json",
")",
"->",
"{",
"return",
"json",
".",
"get",
"(",
"\"InstanceKey\"",
")",
";",
"}",
")",
".",
"flatMap",
"(",
"instanceGroup",
"->",
"{",
"// calculate and output deltas for each instance stream per command",
"return",
"instanceGroup",
".",
"takeUntil",
"(",
"d",
"->",
"d",
".",
"containsKey",
"(",
"\"tombstone\"",
")",
")",
".",
"startWith",
"(",
"Collections",
".",
"<",
"String",
",",
"Object",
">",
"emptyMap",
"(",
")",
")",
".",
"map",
"(",
"data",
"->",
"{",
"if",
"(",
"data",
".",
"containsKey",
"(",
"\"tombstone\"",
")",
")",
"{",
"return",
"Collections",
".",
"<",
"String",
",",
"Object",
">",
"emptyMap",
"(",
")",
";",
"}",
"else",
"{",
"return",
"data",
";",
"}",
"}",
")",
".",
"buffer",
"(",
"2",
",",
"1",
")",
".",
"filter",
"(",
"list",
"->",
"list",
".",
"size",
"(",
")",
"==",
"2",
")",
".",
"map",
"(",
"StreamAggregator",
"::",
"previousAndCurrentToDelta",
")",
".",
"filter",
"(",
"data",
"->",
"data",
"!=",
"null",
"&&",
"!",
"data",
".",
"isEmpty",
"(",
")",
")",
";",
"}",
")",
"// we now have all instance deltas merged into a single stream per command",
"// and sum them into a single stream of aggregate values",
".",
"scan",
"(",
"new",
"HashMap",
"<",
"String",
",",
"Object",
">",
"(",
")",
",",
"StreamAggregator",
"::",
"sumOfDelta",
")",
".",
"skip",
"(",
"1",
")",
";",
"// we artificially wrap in a GroupedObservable that communicates the CommandKey this stream represents",
"return",
"GroupedObservable",
".",
"from",
"(",
"commandGroup",
".",
"getKey",
"(",
")",
",",
"sumOfDeltasForAllInstancesForCommand",
")",
";",
"}",
")",
";",
"}"
] | Flatten the stream and then do nested groupBy. This matches the mental model and is simple but
serializes the stream to a single thread which is bad for performance.
TODO: Add a version like this but with a ParallelObservable
@param stream
@return | [
"Flatten",
"the",
"stream",
"and",
"then",
"do",
"nested",
"groupBy",
".",
"This",
"matches",
"the",
"mental",
"model",
"and",
"is",
"simple",
"but",
"serializes",
"the",
"stream",
"to",
"a",
"single",
"thread",
"which",
"is",
"bad",
"for",
"performance",
"."
] | 0e924058aa4d1d526310206a51dcf82f65274d58 | https://github.com/Netflix/Turbine/blob/0e924058aa4d1d526310206a51dcf82f65274d58/turbine-core/src/main/java/com/netflix/turbine/aggregator/StreamAggregator.java#L47-L96 |
28,536 | Netflix/Turbine | turbine-core/src/main/java/com/netflix/turbine/aggregator/StreamAggregator.java | StreamAggregator.tombstone | private static Observable<Map<String, Object>> tombstone(Observable<Map<String, Object>> instanceStream, InstanceKey instanceKey) {
return instanceStream.publish(is -> {
Observable<Map<String, Object>> tombstone = is
// collect all unique "TypeAndName" keys
.collect(() -> new HashSet<TypeAndNameKey>(), (listOfTypeAndName, event) -> {
listOfTypeAndName.add((TypeAndNameKey) event.get("TypeAndName"));
})
// when instanceStream completes, emit a "tombstone" for each "TypeAndName" in the HashSet collected above
.flatMap(listOfTypeAndName -> {
return Observable.from(listOfTypeAndName)
.map(typeAndName -> {
Map<String, Object> tombstoneForTypeAndName = new LinkedHashMap<>();
tombstoneForTypeAndName.put("tombstone", "true");
tombstoneForTypeAndName.put("InstanceKey", instanceKey);
tombstoneForTypeAndName.put("TypeAndName", typeAndName);
tombstoneForTypeAndName.put("name", typeAndName.getName());
tombstoneForTypeAndName.put("type", typeAndName.getType());
return tombstoneForTypeAndName;
});
});
// concat the tombstone events to the end of the original stream
return is.mergeWith(tombstone);
});
} | java | private static Observable<Map<String, Object>> tombstone(Observable<Map<String, Object>> instanceStream, InstanceKey instanceKey) {
return instanceStream.publish(is -> {
Observable<Map<String, Object>> tombstone = is
// collect all unique "TypeAndName" keys
.collect(() -> new HashSet<TypeAndNameKey>(), (listOfTypeAndName, event) -> {
listOfTypeAndName.add((TypeAndNameKey) event.get("TypeAndName"));
})
// when instanceStream completes, emit a "tombstone" for each "TypeAndName" in the HashSet collected above
.flatMap(listOfTypeAndName -> {
return Observable.from(listOfTypeAndName)
.map(typeAndName -> {
Map<String, Object> tombstoneForTypeAndName = new LinkedHashMap<>();
tombstoneForTypeAndName.put("tombstone", "true");
tombstoneForTypeAndName.put("InstanceKey", instanceKey);
tombstoneForTypeAndName.put("TypeAndName", typeAndName);
tombstoneForTypeAndName.put("name", typeAndName.getName());
tombstoneForTypeAndName.put("type", typeAndName.getType());
return tombstoneForTypeAndName;
});
});
// concat the tombstone events to the end of the original stream
return is.mergeWith(tombstone);
});
} | [
"private",
"static",
"Observable",
"<",
"Map",
"<",
"String",
",",
"Object",
">",
">",
"tombstone",
"(",
"Observable",
"<",
"Map",
"<",
"String",
",",
"Object",
">",
">",
"instanceStream",
",",
"InstanceKey",
"instanceKey",
")",
"{",
"return",
"instanceStream",
".",
"publish",
"(",
"is",
"->",
"{",
"Observable",
"<",
"Map",
"<",
"String",
",",
"Object",
">",
">",
"tombstone",
"=",
"is",
"// collect all unique \"TypeAndName\" keys",
".",
"collect",
"(",
"(",
")",
"->",
"new",
"HashSet",
"<",
"TypeAndNameKey",
">",
"(",
")",
",",
"(",
"listOfTypeAndName",
",",
"event",
")",
"->",
"{",
"listOfTypeAndName",
".",
"add",
"(",
"(",
"TypeAndNameKey",
")",
"event",
".",
"get",
"(",
"\"TypeAndName\"",
")",
")",
";",
"}",
")",
"// when instanceStream completes, emit a \"tombstone\" for each \"TypeAndName\" in the HashSet collected above",
".",
"flatMap",
"(",
"listOfTypeAndName",
"->",
"{",
"return",
"Observable",
".",
"from",
"(",
"listOfTypeAndName",
")",
".",
"map",
"(",
"typeAndName",
"->",
"{",
"Map",
"<",
"String",
",",
"Object",
">",
"tombstoneForTypeAndName",
"=",
"new",
"LinkedHashMap",
"<>",
"(",
")",
";",
"tombstoneForTypeAndName",
".",
"put",
"(",
"\"tombstone\"",
",",
"\"true\"",
")",
";",
"tombstoneForTypeAndName",
".",
"put",
"(",
"\"InstanceKey\"",
",",
"instanceKey",
")",
";",
"tombstoneForTypeAndName",
".",
"put",
"(",
"\"TypeAndName\"",
",",
"typeAndName",
")",
";",
"tombstoneForTypeAndName",
".",
"put",
"(",
"\"name\"",
",",
"typeAndName",
".",
"getName",
"(",
")",
")",
";",
"tombstoneForTypeAndName",
".",
"put",
"(",
"\"type\"",
",",
"typeAndName",
".",
"getType",
"(",
")",
")",
";",
"return",
"tombstoneForTypeAndName",
";",
"}",
")",
";",
"}",
")",
";",
"// concat the tombstone events to the end of the original stream",
"return",
"is",
".",
"mergeWith",
"(",
"tombstone",
")",
";",
"}",
")",
";",
"}"
] | Append tombstone events to each instanceStream when they terminate so that the last values from the stream
will be removed from all aggregates down stream.
@param instanceStream
@param instanceKey | [
"Append",
"tombstone",
"events",
"to",
"each",
"instanceStream",
"when",
"they",
"terminate",
"so",
"that",
"the",
"last",
"values",
"from",
"the",
"stream",
"will",
"be",
"removed",
"from",
"all",
"aggregates",
"down",
"stream",
"."
] | 0e924058aa4d1d526310206a51dcf82f65274d58 | https://github.com/Netflix/Turbine/blob/0e924058aa4d1d526310206a51dcf82f65274d58/turbine-core/src/main/java/com/netflix/turbine/aggregator/StreamAggregator.java#L105-L129 |
28,537 | soabase/exhibitor | exhibitor-core/src/main/java/com/netflix/exhibitor/core/config/DefaultProperties.java | DefaultProperties.getFromInstanceConfig | public static Properties getFromInstanceConfig(InstanceConfig defaultInstanceConfig)
{
PropertyBasedInstanceConfig config = new PropertyBasedInstanceConfig(new ConfigCollectionImpl(defaultInstanceConfig, null));
return config.getProperties();
} | java | public static Properties getFromInstanceConfig(InstanceConfig defaultInstanceConfig)
{
PropertyBasedInstanceConfig config = new PropertyBasedInstanceConfig(new ConfigCollectionImpl(defaultInstanceConfig, null));
return config.getProperties();
} | [
"public",
"static",
"Properties",
"getFromInstanceConfig",
"(",
"InstanceConfig",
"defaultInstanceConfig",
")",
"{",
"PropertyBasedInstanceConfig",
"config",
"=",
"new",
"PropertyBasedInstanceConfig",
"(",
"new",
"ConfigCollectionImpl",
"(",
"defaultInstanceConfig",
",",
"null",
")",
")",
";",
"return",
"config",
".",
"getProperties",
"(",
")",
";",
"}"
] | Return the default properties given an instance config
@param defaultInstanceConfig the default properties as an object
@return default properties | [
"Return",
"the",
"default",
"properties",
"given",
"an",
"instance",
"config"
] | d345d2d45c75b0694b562b6c346f8594f3a5d166 | https://github.com/soabase/exhibitor/blob/d345d2d45c75b0694b562b6c346f8594f3a5d166/exhibitor-core/src/main/java/com/netflix/exhibitor/core/config/DefaultProperties.java#L58-L62 |
28,538 | soabase/exhibitor | exhibitor-core/src/main/java/com/netflix/exhibitor/core/config/DefaultProperties.java | DefaultProperties.newDefaultInstanceConfig | public static InstanceConfig newDefaultInstanceConfig(BackupProvider provider)
{
List<EncodedConfigParser.FieldValue> backupDefaultValues = Lists.newArrayList();
if ( provider != null )
{
for ( BackupConfigSpec spec : provider.getConfigs() )
{
backupDefaultValues.add(new EncodedConfigParser.FieldValue(spec.getKey(), spec.getDefaultValue()));
}
}
final String backupExtraValue = new EncodedConfigParser(backupDefaultValues).toEncoded();
return new InstanceConfig()
{
@Override
public String getString(StringConfigs config)
{
switch ( config )
{
case ZOO_CFG_EXTRA:
{
return "syncLimit=5&tickTime=2000&initLimit=10";
}
case BACKUP_EXTRA:
{
return backupExtraValue;
}
}
return "";
}
@Override
public int getInt(IntConfigs config)
{
switch ( config )
{
case CLIENT_PORT:
{
return 2181;
}
case CONNECT_PORT:
{
return 2888;
}
case ELECTION_PORT:
{
return 3888;
}
case CHECK_MS:
{
return (int)TimeUnit.MILLISECONDS.convert(30, TimeUnit.SECONDS);
}
case CLEANUP_PERIOD_MS:
{
return (int)TimeUnit.MILLISECONDS.convert(12, TimeUnit.HOURS);
}
case CLEANUP_MAX_FILES:
{
return 3;
}
case BACKUP_PERIOD_MS:
{
return (int)TimeUnit.MILLISECONDS.convert(1, TimeUnit.MINUTES);
}
case BACKUP_MAX_STORE_MS:
{
return (int)TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS);
}
case AUTO_MANAGE_INSTANCES_SETTLING_PERIOD_MS:
{
return (int)TimeUnit.MILLISECONDS.convert(3, TimeUnit.MINUTES);
}
case OBSERVER_THRESHOLD:
{
return 999;
}
case AUTO_MANAGE_INSTANCES_APPLY_ALL_AT_ONCE:
{
return 1;
}
}
return 0;
}
};
} | java | public static InstanceConfig newDefaultInstanceConfig(BackupProvider provider)
{
List<EncodedConfigParser.FieldValue> backupDefaultValues = Lists.newArrayList();
if ( provider != null )
{
for ( BackupConfigSpec spec : provider.getConfigs() )
{
backupDefaultValues.add(new EncodedConfigParser.FieldValue(spec.getKey(), spec.getDefaultValue()));
}
}
final String backupExtraValue = new EncodedConfigParser(backupDefaultValues).toEncoded();
return new InstanceConfig()
{
@Override
public String getString(StringConfigs config)
{
switch ( config )
{
case ZOO_CFG_EXTRA:
{
return "syncLimit=5&tickTime=2000&initLimit=10";
}
case BACKUP_EXTRA:
{
return backupExtraValue;
}
}
return "";
}
@Override
public int getInt(IntConfigs config)
{
switch ( config )
{
case CLIENT_PORT:
{
return 2181;
}
case CONNECT_PORT:
{
return 2888;
}
case ELECTION_PORT:
{
return 3888;
}
case CHECK_MS:
{
return (int)TimeUnit.MILLISECONDS.convert(30, TimeUnit.SECONDS);
}
case CLEANUP_PERIOD_MS:
{
return (int)TimeUnit.MILLISECONDS.convert(12, TimeUnit.HOURS);
}
case CLEANUP_MAX_FILES:
{
return 3;
}
case BACKUP_PERIOD_MS:
{
return (int)TimeUnit.MILLISECONDS.convert(1, TimeUnit.MINUTES);
}
case BACKUP_MAX_STORE_MS:
{
return (int)TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS);
}
case AUTO_MANAGE_INSTANCES_SETTLING_PERIOD_MS:
{
return (int)TimeUnit.MILLISECONDS.convert(3, TimeUnit.MINUTES);
}
case OBSERVER_THRESHOLD:
{
return 999;
}
case AUTO_MANAGE_INSTANCES_APPLY_ALL_AT_ONCE:
{
return 1;
}
}
return 0;
}
};
} | [
"public",
"static",
"InstanceConfig",
"newDefaultInstanceConfig",
"(",
"BackupProvider",
"provider",
")",
"{",
"List",
"<",
"EncodedConfigParser",
".",
"FieldValue",
">",
"backupDefaultValues",
"=",
"Lists",
".",
"newArrayList",
"(",
")",
";",
"if",
"(",
"provider",
"!=",
"null",
")",
"{",
"for",
"(",
"BackupConfigSpec",
"spec",
":",
"provider",
".",
"getConfigs",
"(",
")",
")",
"{",
"backupDefaultValues",
".",
"add",
"(",
"new",
"EncodedConfigParser",
".",
"FieldValue",
"(",
"spec",
".",
"getKey",
"(",
")",
",",
"spec",
".",
"getDefaultValue",
"(",
")",
")",
")",
";",
"}",
"}",
"final",
"String",
"backupExtraValue",
"=",
"new",
"EncodedConfigParser",
"(",
"backupDefaultValues",
")",
".",
"toEncoded",
"(",
")",
";",
"return",
"new",
"InstanceConfig",
"(",
")",
"{",
"@",
"Override",
"public",
"String",
"getString",
"(",
"StringConfigs",
"config",
")",
"{",
"switch",
"(",
"config",
")",
"{",
"case",
"ZOO_CFG_EXTRA",
":",
"{",
"return",
"\"syncLimit=5&tickTime=2000&initLimit=10\"",
";",
"}",
"case",
"BACKUP_EXTRA",
":",
"{",
"return",
"backupExtraValue",
";",
"}",
"}",
"return",
"\"\"",
";",
"}",
"@",
"Override",
"public",
"int",
"getInt",
"(",
"IntConfigs",
"config",
")",
"{",
"switch",
"(",
"config",
")",
"{",
"case",
"CLIENT_PORT",
":",
"{",
"return",
"2181",
";",
"}",
"case",
"CONNECT_PORT",
":",
"{",
"return",
"2888",
";",
"}",
"case",
"ELECTION_PORT",
":",
"{",
"return",
"3888",
";",
"}",
"case",
"CHECK_MS",
":",
"{",
"return",
"(",
"int",
")",
"TimeUnit",
".",
"MILLISECONDS",
".",
"convert",
"(",
"30",
",",
"TimeUnit",
".",
"SECONDS",
")",
";",
"}",
"case",
"CLEANUP_PERIOD_MS",
":",
"{",
"return",
"(",
"int",
")",
"TimeUnit",
".",
"MILLISECONDS",
".",
"convert",
"(",
"12",
",",
"TimeUnit",
".",
"HOURS",
")",
";",
"}",
"case",
"CLEANUP_MAX_FILES",
":",
"{",
"return",
"3",
";",
"}",
"case",
"BACKUP_PERIOD_MS",
":",
"{",
"return",
"(",
"int",
")",
"TimeUnit",
".",
"MILLISECONDS",
".",
"convert",
"(",
"1",
",",
"TimeUnit",
".",
"MINUTES",
")",
";",
"}",
"case",
"BACKUP_MAX_STORE_MS",
":",
"{",
"return",
"(",
"int",
")",
"TimeUnit",
".",
"MILLISECONDS",
".",
"convert",
"(",
"1",
",",
"TimeUnit",
".",
"DAYS",
")",
";",
"}",
"case",
"AUTO_MANAGE_INSTANCES_SETTLING_PERIOD_MS",
":",
"{",
"return",
"(",
"int",
")",
"TimeUnit",
".",
"MILLISECONDS",
".",
"convert",
"(",
"3",
",",
"TimeUnit",
".",
"MINUTES",
")",
";",
"}",
"case",
"OBSERVER_THRESHOLD",
":",
"{",
"return",
"999",
";",
"}",
"case",
"AUTO_MANAGE_INSTANCES_APPLY_ALL_AT_ONCE",
":",
"{",
"return",
"1",
";",
"}",
"}",
"return",
"0",
";",
"}",
"}",
";",
"}"
] | Return the standard default properties as an instance config
@param provider backup provider or null
@return default properties instance | [
"Return",
"the",
"standard",
"default",
"properties",
"as",
"an",
"instance",
"config"
] | d345d2d45c75b0694b562b6c346f8594f3a5d166 | https://github.com/soabase/exhibitor/blob/d345d2d45c75b0694b562b6c346f8594f3a5d166/exhibitor-core/src/main/java/com/netflix/exhibitor/core/config/DefaultProperties.java#L70-L166 |
28,539 | soabase/exhibitor | exhibitor-core/src/main/java/com/netflix/exhibitor/core/activity/ActivityLog.java | ActivityLog.toDisplayList | public List<String> toDisplayList(final String separator, ExhibitorArguments.LogDirection logDirection)
{
Iterable<String> transformed = Iterables.transform
(
queue,
new Function<Message, String>()
{
public String apply(Message message)
{
return message.date + separator + message.type + separator + message.text;
}
}
);
ImmutableList<String> list = ImmutableList.copyOf(transformed);
return (logDirection == ExhibitorArguments.LogDirection.NATURAL) ? list : Lists.reverse(list);
} | java | public List<String> toDisplayList(final String separator, ExhibitorArguments.LogDirection logDirection)
{
Iterable<String> transformed = Iterables.transform
(
queue,
new Function<Message, String>()
{
public String apply(Message message)
{
return message.date + separator + message.type + separator + message.text;
}
}
);
ImmutableList<String> list = ImmutableList.copyOf(transformed);
return (logDirection == ExhibitorArguments.LogDirection.NATURAL) ? list : Lists.reverse(list);
} | [
"public",
"List",
"<",
"String",
">",
"toDisplayList",
"(",
"final",
"String",
"separator",
",",
"ExhibitorArguments",
".",
"LogDirection",
"logDirection",
")",
"{",
"Iterable",
"<",
"String",
">",
"transformed",
"=",
"Iterables",
".",
"transform",
"(",
"queue",
",",
"new",
"Function",
"<",
"Message",
",",
"String",
">",
"(",
")",
"{",
"public",
"String",
"apply",
"(",
"Message",
"message",
")",
"{",
"return",
"message",
".",
"date",
"+",
"separator",
"+",
"message",
".",
"type",
"+",
"separator",
"+",
"message",
".",
"text",
";",
"}",
"}",
")",
";",
"ImmutableList",
"<",
"String",
">",
"list",
"=",
"ImmutableList",
".",
"copyOf",
"(",
"transformed",
")",
";",
"return",
"(",
"logDirection",
"==",
"ExhibitorArguments",
".",
"LogDirection",
".",
"NATURAL",
")",
"?",
"list",
":",
"Lists",
".",
"reverse",
"(",
"list",
")",
";",
"}"
] | Return the current window lines
@param separator line separator
@param logDirection display direction
@return lines | [
"Return",
"the",
"current",
"window",
"lines"
] | d345d2d45c75b0694b562b6c346f8594f3a5d166 | https://github.com/soabase/exhibitor/blob/d345d2d45c75b0694b562b6c346f8594f3a5d166/exhibitor-core/src/main/java/com/netflix/exhibitor/core/activity/ActivityLog.java#L73-L88 |
28,540 | soabase/exhibitor | exhibitor-core/src/main/java/com/netflix/exhibitor/core/activity/ActivityLog.java | ActivityLog.add | public void add(Type type, String message, Throwable exception)
{
String queueMessage = message;
if ( (type == Type.ERROR) && (exception != null) )
{
queueMessage += " (" + getExceptionMessage(exception) + ")";
}
if ( type.addToUI() )
{
while ( queue.size() > windowSizeLines ) // NOTE: due to concurrency, this may make the queue shorter than MAX - that's OK (and in some cases longer)
{
queue.remove();
}
queue.add(new Message(queueMessage, type));
}
type.log(message, exception);
} | java | public void add(Type type, String message, Throwable exception)
{
String queueMessage = message;
if ( (type == Type.ERROR) && (exception != null) )
{
queueMessage += " (" + getExceptionMessage(exception) + ")";
}
if ( type.addToUI() )
{
while ( queue.size() > windowSizeLines ) // NOTE: due to concurrency, this may make the queue shorter than MAX - that's OK (and in some cases longer)
{
queue.remove();
}
queue.add(new Message(queueMessage, type));
}
type.log(message, exception);
} | [
"public",
"void",
"add",
"(",
"Type",
"type",
",",
"String",
"message",
",",
"Throwable",
"exception",
")",
"{",
"String",
"queueMessage",
"=",
"message",
";",
"if",
"(",
"(",
"type",
"==",
"Type",
".",
"ERROR",
")",
"&&",
"(",
"exception",
"!=",
"null",
")",
")",
"{",
"queueMessage",
"+=",
"\" (\"",
"+",
"getExceptionMessage",
"(",
"exception",
")",
"+",
"\")\"",
";",
"}",
"if",
"(",
"type",
".",
"addToUI",
"(",
")",
")",
"{",
"while",
"(",
"queue",
".",
"size",
"(",
")",
">",
"windowSizeLines",
")",
"// NOTE: due to concurrency, this may make the queue shorter than MAX - that's OK (and in some cases longer)",
"{",
"queue",
".",
"remove",
"(",
")",
";",
"}",
"queue",
".",
"add",
"(",
"new",
"Message",
"(",
"queueMessage",
",",
"type",
")",
")",
";",
"}",
"type",
".",
"log",
"(",
"message",
",",
"exception",
")",
";",
"}"
] | Add a log message with an exception
@param type message type
@param message the messqage
@param exception the exception | [
"Add",
"a",
"log",
"message",
"with",
"an",
"exception"
] | d345d2d45c75b0694b562b6c346f8594f3a5d166 | https://github.com/soabase/exhibitor/blob/d345d2d45c75b0694b562b6c346f8594f3a5d166/exhibitor-core/src/main/java/com/netflix/exhibitor/core/activity/ActivityLog.java#L186-L203 |
28,541 | soabase/exhibitor | exhibitor-core/src/main/java/com/netflix/exhibitor/core/activity/ActivityLog.java | ActivityLog.getExceptionMessage | public static String getExceptionMessage(Throwable exception)
{
StringWriter out = new StringWriter();
exception.printStackTrace(new PrintWriter(out));
BufferedReader in = new BufferedReader(new StringReader(out.toString()));
try
{
StringBuilder str = new StringBuilder();
for(;;)
{
String line = in.readLine();
if ( line == null )
{
break;
}
if ( str.length() > 0 )
{
str.append(", ");
}
str.append(line);
}
return str.toString();
}
catch ( IOException e )
{
// ignore
}
return "n/a";
} | java | public static String getExceptionMessage(Throwable exception)
{
StringWriter out = new StringWriter();
exception.printStackTrace(new PrintWriter(out));
BufferedReader in = new BufferedReader(new StringReader(out.toString()));
try
{
StringBuilder str = new StringBuilder();
for(;;)
{
String line = in.readLine();
if ( line == null )
{
break;
}
if ( str.length() > 0 )
{
str.append(", ");
}
str.append(line);
}
return str.toString();
}
catch ( IOException e )
{
// ignore
}
return "n/a";
} | [
"public",
"static",
"String",
"getExceptionMessage",
"(",
"Throwable",
"exception",
")",
"{",
"StringWriter",
"out",
"=",
"new",
"StringWriter",
"(",
")",
";",
"exception",
".",
"printStackTrace",
"(",
"new",
"PrintWriter",
"(",
"out",
")",
")",
";",
"BufferedReader",
"in",
"=",
"new",
"BufferedReader",
"(",
"new",
"StringReader",
"(",
"out",
".",
"toString",
"(",
")",
")",
")",
";",
"try",
"{",
"StringBuilder",
"str",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"for",
"(",
";",
";",
")",
"{",
"String",
"line",
"=",
"in",
".",
"readLine",
"(",
")",
";",
"if",
"(",
"line",
"==",
"null",
")",
"{",
"break",
";",
"}",
"if",
"(",
"str",
".",
"length",
"(",
")",
">",
"0",
")",
"{",
"str",
".",
"append",
"(",
"\", \"",
")",
";",
"}",
"str",
".",
"append",
"(",
"line",
")",
";",
"}",
"return",
"str",
".",
"toString",
"(",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"// ignore",
"}",
"return",
"\"n/a\"",
";",
"}"
] | Convert an exception into a log message
@param exception the exception
@return message | [
"Convert",
"an",
"exception",
"into",
"a",
"log",
"message"
] | d345d2d45c75b0694b562b6c346f8594f3a5d166 | https://github.com/soabase/exhibitor/blob/d345d2d45c75b0694b562b6c346f8594f3a5d166/exhibitor-core/src/main/java/com/netflix/exhibitor/core/activity/ActivityLog.java#L211-L239 |
28,542 | soabase/exhibitor | exhibitor-core/src/main/java/com/netflix/exhibitor/core/config/EncodedConfigParser.java | EncodedConfigParser.getValue | public String getValue(final String field)
{
FieldValue fieldValue = Iterables.find
(
fieldValues,
new Predicate<FieldValue>()
{
@Override
public boolean apply(FieldValue fv)
{
return fv.getField().equals(field);
}
},
null
);
return (fieldValue != null) ? fieldValue.getValue() : null;
} | java | public String getValue(final String field)
{
FieldValue fieldValue = Iterables.find
(
fieldValues,
new Predicate<FieldValue>()
{
@Override
public boolean apply(FieldValue fv)
{
return fv.getField().equals(field);
}
},
null
);
return (fieldValue != null) ? fieldValue.getValue() : null;
} | [
"public",
"String",
"getValue",
"(",
"final",
"String",
"field",
")",
"{",
"FieldValue",
"fieldValue",
"=",
"Iterables",
".",
"find",
"(",
"fieldValues",
",",
"new",
"Predicate",
"<",
"FieldValue",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"boolean",
"apply",
"(",
"FieldValue",
"fv",
")",
"{",
"return",
"fv",
".",
"getField",
"(",
")",
".",
"equals",
"(",
"field",
")",
";",
"}",
"}",
",",
"null",
")",
";",
"return",
"(",
"fieldValue",
"!=",
"null",
")",
"?",
"fieldValue",
".",
"getValue",
"(",
")",
":",
"null",
";",
"}"
] | Return the value for the given field or null
@param field field to check
@return value or null | [
"Return",
"the",
"value",
"for",
"the",
"given",
"field",
"or",
"null"
] | d345d2d45c75b0694b562b6c346f8594f3a5d166 | https://github.com/soabase/exhibitor/blob/d345d2d45c75b0694b562b6c346f8594f3a5d166/exhibitor-core/src/main/java/com/netflix/exhibitor/core/config/EncodedConfigParser.java#L202-L218 |
28,543 | soabase/exhibitor | exhibitor-core/src/main/java/com/netflix/exhibitor/core/rest/jersey/JerseySupport.java | JerseySupport.newApplicationConfig | public static DefaultResourceConfig newApplicationConfig(UIContext context)
{
final Set<Object> singletons = getSingletons(context);
final Set<Class<?>> classes = getClasses();
return new DefaultResourceConfig()
{
@Override
public Set<Class<?>> getClasses()
{
return classes;
}
@Override
public Set<Object> getSingletons()
{
return singletons;
}
};
} | java | public static DefaultResourceConfig newApplicationConfig(UIContext context)
{
final Set<Object> singletons = getSingletons(context);
final Set<Class<?>> classes = getClasses();
return new DefaultResourceConfig()
{
@Override
public Set<Class<?>> getClasses()
{
return classes;
}
@Override
public Set<Object> getSingletons()
{
return singletons;
}
};
} | [
"public",
"static",
"DefaultResourceConfig",
"newApplicationConfig",
"(",
"UIContext",
"context",
")",
"{",
"final",
"Set",
"<",
"Object",
">",
"singletons",
"=",
"getSingletons",
"(",
"context",
")",
";",
"final",
"Set",
"<",
"Class",
"<",
"?",
">",
">",
"classes",
"=",
"getClasses",
"(",
")",
";",
"return",
"new",
"DefaultResourceConfig",
"(",
")",
"{",
"@",
"Override",
"public",
"Set",
"<",
"Class",
"<",
"?",
">",
">",
"getClasses",
"(",
")",
"{",
"return",
"classes",
";",
"}",
"@",
"Override",
"public",
"Set",
"<",
"Object",
">",
"getSingletons",
"(",
")",
"{",
"return",
"singletons",
";",
"}",
"}",
";",
"}"
] | Return a new Jersey config instance that correctly supplies all needed Exhibitor
objects
@param context the UIContext
@return new config | [
"Return",
"a",
"new",
"Jersey",
"config",
"instance",
"that",
"correctly",
"supplies",
"all",
"needed",
"Exhibitor",
"objects"
] | d345d2d45c75b0694b562b6c346f8594f3a5d166 | https://github.com/soabase/exhibitor/blob/d345d2d45c75b0694b562b6c346f8594f3a5d166/exhibitor-core/src/main/java/com/netflix/exhibitor/core/rest/jersey/JerseySupport.java#L51-L70 |
28,544 | soabase/exhibitor | exhibitor-core/src/main/java/com/netflix/exhibitor/core/state/ServerList.java | ServerList.filterOutObservers | public ServerList filterOutObservers()
{
Iterable<ServerSpec> filtered = Iterables.filter
(
specs,
new Predicate<ServerSpec>()
{
@Override
public boolean apply(ServerSpec spec)
{
return spec.getServerType() != ServerType.OBSERVER;
}
}
);
return new ServerList(Lists.newArrayList(filtered));
} | java | public ServerList filterOutObservers()
{
Iterable<ServerSpec> filtered = Iterables.filter
(
specs,
new Predicate<ServerSpec>()
{
@Override
public boolean apply(ServerSpec spec)
{
return spec.getServerType() != ServerType.OBSERVER;
}
}
);
return new ServerList(Lists.newArrayList(filtered));
} | [
"public",
"ServerList",
"filterOutObservers",
"(",
")",
"{",
"Iterable",
"<",
"ServerSpec",
">",
"filtered",
"=",
"Iterables",
".",
"filter",
"(",
"specs",
",",
"new",
"Predicate",
"<",
"ServerSpec",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"boolean",
"apply",
"(",
"ServerSpec",
"spec",
")",
"{",
"return",
"spec",
".",
"getServerType",
"(",
")",
"!=",
"ServerType",
".",
"OBSERVER",
";",
"}",
"}",
")",
";",
"return",
"new",
"ServerList",
"(",
"Lists",
".",
"newArrayList",
"(",
"filtered",
")",
")",
";",
"}"
] | Return this server list with any observers removed
@return filtered list | [
"Return",
"this",
"server",
"list",
"with",
"any",
"observers",
"removed"
] | d345d2d45c75b0694b562b6c346f8594f3a5d166 | https://github.com/soabase/exhibitor/blob/d345d2d45c75b0694b562b6c346f8594f3a5d166/exhibitor-core/src/main/java/com/netflix/exhibitor/core/state/ServerList.java#L194-L209 |
28,545 | soabase/exhibitor | exhibitor-core/src/main/java/com/netflix/exhibitor/core/activity/ActivityQueue.java | ActivityQueue.start | public void start()
{
for ( QueueGroups group : QueueGroups.values() )
{
final DelayQueue<ActivityHolder> thisQueue = queues.get(group);
service.submit
(
new Runnable()
{
@Override
public void run()
{
try
{
while ( !Thread.currentThread().isInterrupted() )
{
ActivityHolder holder = thisQueue.take();
try
{
Boolean result = holder.activity.call();
holder.activity.completed((result != null) && result);
}
catch ( Throwable e )
{
log.error("Unhandled exception in background task", e);
}
}
}
catch ( InterruptedException dummy )
{
Thread.currentThread().interrupt();
}
}
}
);
}
} | java | public void start()
{
for ( QueueGroups group : QueueGroups.values() )
{
final DelayQueue<ActivityHolder> thisQueue = queues.get(group);
service.submit
(
new Runnable()
{
@Override
public void run()
{
try
{
while ( !Thread.currentThread().isInterrupted() )
{
ActivityHolder holder = thisQueue.take();
try
{
Boolean result = holder.activity.call();
holder.activity.completed((result != null) && result);
}
catch ( Throwable e )
{
log.error("Unhandled exception in background task", e);
}
}
}
catch ( InterruptedException dummy )
{
Thread.currentThread().interrupt();
}
}
}
);
}
} | [
"public",
"void",
"start",
"(",
")",
"{",
"for",
"(",
"QueueGroups",
"group",
":",
"QueueGroups",
".",
"values",
"(",
")",
")",
"{",
"final",
"DelayQueue",
"<",
"ActivityHolder",
">",
"thisQueue",
"=",
"queues",
".",
"get",
"(",
"group",
")",
";",
"service",
".",
"submit",
"(",
"new",
"Runnable",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"run",
"(",
")",
"{",
"try",
"{",
"while",
"(",
"!",
"Thread",
".",
"currentThread",
"(",
")",
".",
"isInterrupted",
"(",
")",
")",
"{",
"ActivityHolder",
"holder",
"=",
"thisQueue",
".",
"take",
"(",
")",
";",
"try",
"{",
"Boolean",
"result",
"=",
"holder",
".",
"activity",
".",
"call",
"(",
")",
";",
"holder",
".",
"activity",
".",
"completed",
"(",
"(",
"result",
"!=",
"null",
")",
"&&",
"result",
")",
";",
"}",
"catch",
"(",
"Throwable",
"e",
")",
"{",
"log",
".",
"error",
"(",
"\"Unhandled exception in background task\"",
",",
"e",
")",
";",
"}",
"}",
"}",
"catch",
"(",
"InterruptedException",
"dummy",
")",
"{",
"Thread",
".",
"currentThread",
"(",
")",
".",
"interrupt",
"(",
")",
";",
"}",
"}",
"}",
")",
";",
"}",
"}"
] | The queue must be started | [
"The",
"queue",
"must",
"be",
"started"
] | d345d2d45c75b0694b562b6c346f8594f3a5d166 | https://github.com/soabase/exhibitor/blob/d345d2d45c75b0694b562b6c346f8594f3a5d166/exhibitor-core/src/main/java/com/netflix/exhibitor/core/activity/ActivityQueue.java#L107-L143 |
28,546 | soabase/exhibitor | exhibitor-core/src/main/java/com/netflix/exhibitor/core/activity/ActivityQueue.java | ActivityQueue.add | public synchronized void add(QueueGroups group, Activity activity)
{
add(group, activity, 0, TimeUnit.MILLISECONDS);
} | java | public synchronized void add(QueueGroups group, Activity activity)
{
add(group, activity, 0, TimeUnit.MILLISECONDS);
} | [
"public",
"synchronized",
"void",
"add",
"(",
"QueueGroups",
"group",
",",
"Activity",
"activity",
")",
"{",
"add",
"(",
"group",
",",
"activity",
",",
"0",
",",
"TimeUnit",
".",
"MILLISECONDS",
")",
";",
"}"
] | Add an activity to the given queue
@param group the queue - all activities within a queue are executed serially
@param activity the activity | [
"Add",
"an",
"activity",
"to",
"the",
"given",
"queue"
] | d345d2d45c75b0694b562b6c346f8594f3a5d166 | https://github.com/soabase/exhibitor/blob/d345d2d45c75b0694b562b6c346f8594f3a5d166/exhibitor-core/src/main/java/com/netflix/exhibitor/core/activity/ActivityQueue.java#L151-L154 |
28,547 | soabase/exhibitor | exhibitor-core/src/main/java/com/netflix/exhibitor/core/activity/ActivityQueue.java | ActivityQueue.add | public synchronized void add(QueueGroups group, Activity activity, long delay, TimeUnit unit)
{
ActivityHolder holder = new ActivityHolder(activity, TimeUnit.MILLISECONDS.convert(delay, unit));
queues.get(group).offer(holder);
} | java | public synchronized void add(QueueGroups group, Activity activity, long delay, TimeUnit unit)
{
ActivityHolder holder = new ActivityHolder(activity, TimeUnit.MILLISECONDS.convert(delay, unit));
queues.get(group).offer(holder);
} | [
"public",
"synchronized",
"void",
"add",
"(",
"QueueGroups",
"group",
",",
"Activity",
"activity",
",",
"long",
"delay",
",",
"TimeUnit",
"unit",
")",
"{",
"ActivityHolder",
"holder",
"=",
"new",
"ActivityHolder",
"(",
"activity",
",",
"TimeUnit",
".",
"MILLISECONDS",
".",
"convert",
"(",
"delay",
",",
"unit",
")",
")",
";",
"queues",
".",
"get",
"(",
"group",
")",
".",
"offer",
"(",
"holder",
")",
";",
"}"
] | Add an activity to the given queue that executes after a specified delay
@param group the queue - all activities within a queue are executed serially
@param activity the activity
@param delay the delay
@param unit the delay unit | [
"Add",
"an",
"activity",
"to",
"the",
"given",
"queue",
"that",
"executes",
"after",
"a",
"specified",
"delay"
] | d345d2d45c75b0694b562b6c346f8594f3a5d166 | https://github.com/soabase/exhibitor/blob/d345d2d45c75b0694b562b6c346f8594f3a5d166/exhibitor-core/src/main/java/com/netflix/exhibitor/core/activity/ActivityQueue.java#L164-L168 |
28,548 | soabase/exhibitor | exhibitor-core/src/main/java/com/netflix/exhibitor/core/activity/ActivityQueue.java | ActivityQueue.replace | public synchronized void replace(QueueGroups group, Activity activity)
{
replace(group, activity, 0, TimeUnit.MILLISECONDS);
} | java | public synchronized void replace(QueueGroups group, Activity activity)
{
replace(group, activity, 0, TimeUnit.MILLISECONDS);
} | [
"public",
"synchronized",
"void",
"replace",
"(",
"QueueGroups",
"group",
",",
"Activity",
"activity",
")",
"{",
"replace",
"(",
"group",
",",
"activity",
",",
"0",
",",
"TimeUnit",
".",
"MILLISECONDS",
")",
";",
"}"
] | Replace the given activity in the given queue. If not in the queue, adds it to the queue.
@param group the queue - all activities within a queue are executed serially
@param activity the activity | [
"Replace",
"the",
"given",
"activity",
"in",
"the",
"given",
"queue",
".",
"If",
"not",
"in",
"the",
"queue",
"adds",
"it",
"to",
"the",
"queue",
"."
] | d345d2d45c75b0694b562b6c346f8594f3a5d166 | https://github.com/soabase/exhibitor/blob/d345d2d45c75b0694b562b6c346f8594f3a5d166/exhibitor-core/src/main/java/com/netflix/exhibitor/core/activity/ActivityQueue.java#L182-L185 |
28,549 | soabase/exhibitor | exhibitor-core/src/main/java/com/netflix/exhibitor/core/Exhibitor.java | Exhibitor.getHostname | public static String getHostname()
{
String host = "unknown";
try
{
return InetAddress.getLocalHost().getHostName();
}
catch ( UnknownHostException e )
{
// ignore
}
return host;
} | java | public static String getHostname()
{
String host = "unknown";
try
{
return InetAddress.getLocalHost().getHostName();
}
catch ( UnknownHostException e )
{
// ignore
}
return host;
} | [
"public",
"static",
"String",
"getHostname",
"(",
")",
"{",
"String",
"host",
"=",
"\"unknown\"",
";",
"try",
"{",
"return",
"InetAddress",
".",
"getLocalHost",
"(",
")",
".",
"getHostName",
"(",
")",
";",
"}",
"catch",
"(",
"UnknownHostException",
"e",
")",
"{",
"// ignore",
"}",
"return",
"host",
";",
"}"
] | Return this VM's hostname if possible
@return hostname | [
"Return",
"this",
"VM",
"s",
"hostname",
"if",
"possible"
] | d345d2d45c75b0694b562b6c346f8594f3a5d166 | https://github.com/soabase/exhibitor/blob/d345d2d45c75b0694b562b6c346f8594f3a5d166/exhibitor-core/src/main/java/com/netflix/exhibitor/core/Exhibitor.java#L102-L114 |
28,550 | soabase/exhibitor | exhibitor-core/src/main/java/com/netflix/exhibitor/core/Exhibitor.java | Exhibitor.start | public void start() throws Exception
{
Preconditions.checkState(state.compareAndSet(State.LATENT, State.STARTED));
//Try to restore data from backup before zookeeper will be started
backupManager.restoreAll();
activityQueue.start();
configManager.start();
monitorRunningInstance.start();
cleanupManager.start();
backupManager.start();
autoInstanceManagement.start();
if ( servoMonitoring != null )
{
servoMonitoring.start();
}
configManager.addConfigListener
(
new ConfigListener()
{
@Override
public void configUpdated()
{
try
{
resetLocalConnection();
}
catch ( IOException e )
{
log.add(ActivityLog.Type.ERROR, "Resetting connection", e);
}
}
}
);
} | java | public void start() throws Exception
{
Preconditions.checkState(state.compareAndSet(State.LATENT, State.STARTED));
//Try to restore data from backup before zookeeper will be started
backupManager.restoreAll();
activityQueue.start();
configManager.start();
monitorRunningInstance.start();
cleanupManager.start();
backupManager.start();
autoInstanceManagement.start();
if ( servoMonitoring != null )
{
servoMonitoring.start();
}
configManager.addConfigListener
(
new ConfigListener()
{
@Override
public void configUpdated()
{
try
{
resetLocalConnection();
}
catch ( IOException e )
{
log.add(ActivityLog.Type.ERROR, "Resetting connection", e);
}
}
}
);
} | [
"public",
"void",
"start",
"(",
")",
"throws",
"Exception",
"{",
"Preconditions",
".",
"checkState",
"(",
"state",
".",
"compareAndSet",
"(",
"State",
".",
"LATENT",
",",
"State",
".",
"STARTED",
")",
")",
";",
"//Try to restore data from backup before zookeeper will be started",
"backupManager",
".",
"restoreAll",
"(",
")",
";",
"activityQueue",
".",
"start",
"(",
")",
";",
"configManager",
".",
"start",
"(",
")",
";",
"monitorRunningInstance",
".",
"start",
"(",
")",
";",
"cleanupManager",
".",
"start",
"(",
")",
";",
"backupManager",
".",
"start",
"(",
")",
";",
"autoInstanceManagement",
".",
"start",
"(",
")",
";",
"if",
"(",
"servoMonitoring",
"!=",
"null",
")",
"{",
"servoMonitoring",
".",
"start",
"(",
")",
";",
"}",
"configManager",
".",
"addConfigListener",
"(",
"new",
"ConfigListener",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"configUpdated",
"(",
")",
"{",
"try",
"{",
"resetLocalConnection",
"(",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"log",
".",
"add",
"(",
"ActivityLog",
".",
"Type",
".",
"ERROR",
",",
"\"Resetting connection\"",
",",
"e",
")",
";",
"}",
"}",
"}",
")",
";",
"}"
] | Start the app
@throws Exception errors | [
"Start",
"the",
"app"
] | d345d2d45c75b0694b562b6c346f8594f3a5d166 | https://github.com/soabase/exhibitor/blob/d345d2d45c75b0694b562b6c346f8594f3a5d166/exhibitor-core/src/main/java/com/netflix/exhibitor/core/Exhibitor.java#L175-L211 |
28,551 | soabase/exhibitor | exhibitor-core/src/main/java/com/netflix/exhibitor/core/backup/BackupManager.java | BackupManager.getAvailableBackups | public List<BackupMetaData> getAvailableBackups() throws Exception
{
Map<String, String> config = getBackupConfig();
return backupProvider.get().getAvailableBackups(exhibitor, config);
} | java | public List<BackupMetaData> getAvailableBackups() throws Exception
{
Map<String, String> config = getBackupConfig();
return backupProvider.get().getAvailableBackups(exhibitor, config);
} | [
"public",
"List",
"<",
"BackupMetaData",
">",
"getAvailableBackups",
"(",
")",
"throws",
"Exception",
"{",
"Map",
"<",
"String",
",",
"String",
">",
"config",
"=",
"getBackupConfig",
"(",
")",
";",
"return",
"backupProvider",
".",
"get",
"(",
")",
".",
"getAvailableBackups",
"(",
"exhibitor",
",",
"config",
")",
";",
"}"
] | Return list of available backups
@return backups
@throws Exception errors | [
"Return",
"list",
"of",
"available",
"backups"
] | d345d2d45c75b0694b562b6c346f8594f3a5d166 | https://github.com/soabase/exhibitor/blob/d345d2d45c75b0694b562b6c346f8594f3a5d166/exhibitor-core/src/main/java/com/netflix/exhibitor/core/backup/BackupManager.java#L146-L150 |
28,552 | soabase/exhibitor | exhibitor-core/src/main/java/com/netflix/exhibitor/core/backup/BackupManager.java | BackupManager.getBackupStream | public BackupStream getBackupStream(BackupMetaData metaData) throws Exception
{
return backupProvider.get().getBackupStream(exhibitor, metaData, getBackupConfig());
} | java | public BackupStream getBackupStream(BackupMetaData metaData) throws Exception
{
return backupProvider.get().getBackupStream(exhibitor, metaData, getBackupConfig());
} | [
"public",
"BackupStream",
"getBackupStream",
"(",
"BackupMetaData",
"metaData",
")",
"throws",
"Exception",
"{",
"return",
"backupProvider",
".",
"get",
"(",
")",
".",
"getBackupStream",
"(",
"exhibitor",
",",
"metaData",
",",
"getBackupConfig",
"(",
")",
")",
";",
"}"
] | Return a stream for the specified backup
@param metaData the backup to get
@return the stream or null if the stream doesn't exist
@throws Exception errors | [
"Return",
"a",
"stream",
"for",
"the",
"specified",
"backup"
] | d345d2d45c75b0694b562b6c346f8594f3a5d166 | https://github.com/soabase/exhibitor/blob/d345d2d45c75b0694b562b6c346f8594f3a5d166/exhibitor-core/src/main/java/com/netflix/exhibitor/core/backup/BackupManager.java#L159-L162 |
28,553 | soabase/exhibitor | exhibitor-core/src/main/java/com/netflix/exhibitor/core/backup/BackupManager.java | BackupManager.restoreAll | public void restoreAll() throws Exception
{
if (!backupProvider.isPresent()) {
log.info("No backup provider configured. Skipping restore.");
return;
}
ZooKeeperLogFiles logFiles = new ZooKeeperLogFiles(exhibitor);
log.info("Restoring log files from backup.");
if (!logFiles.isValid()) {
log.error("Backup path invalid. Skipping restore.");
return;
}
if (logFiles.getPaths().isEmpty()) {
log.info("Backup path(s) empty. Skipping restore.");
return;
}
File dataDir = ZooKeeperLogFiles.getDataDir(exhibitor);
for (BackupMetaData data : getAvailableBackups()) {
String fileName = data.getName();
log.info(String.format("Restoring file: %s", fileName));
File file = new File(dataDir, fileName);
restore(data, file);
}
log.info("Restoring logs from backup done.");
} | java | public void restoreAll() throws Exception
{
if (!backupProvider.isPresent()) {
log.info("No backup provider configured. Skipping restore.");
return;
}
ZooKeeperLogFiles logFiles = new ZooKeeperLogFiles(exhibitor);
log.info("Restoring log files from backup.");
if (!logFiles.isValid()) {
log.error("Backup path invalid. Skipping restore.");
return;
}
if (logFiles.getPaths().isEmpty()) {
log.info("Backup path(s) empty. Skipping restore.");
return;
}
File dataDir = ZooKeeperLogFiles.getDataDir(exhibitor);
for (BackupMetaData data : getAvailableBackups()) {
String fileName = data.getName();
log.info(String.format("Restoring file: %s", fileName));
File file = new File(dataDir, fileName);
restore(data, file);
}
log.info("Restoring logs from backup done.");
} | [
"public",
"void",
"restoreAll",
"(",
")",
"throws",
"Exception",
"{",
"if",
"(",
"!",
"backupProvider",
".",
"isPresent",
"(",
")",
")",
"{",
"log",
".",
"info",
"(",
"\"No backup provider configured. Skipping restore.\"",
")",
";",
"return",
";",
"}",
"ZooKeeperLogFiles",
"logFiles",
"=",
"new",
"ZooKeeperLogFiles",
"(",
"exhibitor",
")",
";",
"log",
".",
"info",
"(",
"\"Restoring log files from backup.\"",
")",
";",
"if",
"(",
"!",
"logFiles",
".",
"isValid",
"(",
")",
")",
"{",
"log",
".",
"error",
"(",
"\"Backup path invalid. Skipping restore.\"",
")",
";",
"return",
";",
"}",
"if",
"(",
"logFiles",
".",
"getPaths",
"(",
")",
".",
"isEmpty",
"(",
")",
")",
"{",
"log",
".",
"info",
"(",
"\"Backup path(s) empty. Skipping restore.\"",
")",
";",
"return",
";",
"}",
"File",
"dataDir",
"=",
"ZooKeeperLogFiles",
".",
"getDataDir",
"(",
"exhibitor",
")",
";",
"for",
"(",
"BackupMetaData",
"data",
":",
"getAvailableBackups",
"(",
")",
")",
"{",
"String",
"fileName",
"=",
"data",
".",
"getName",
"(",
")",
";",
"log",
".",
"info",
"(",
"String",
".",
"format",
"(",
"\"Restoring file: %s\"",
",",
"fileName",
")",
")",
";",
"File",
"file",
"=",
"new",
"File",
"(",
"dataDir",
",",
"fileName",
")",
";",
"restore",
"(",
"data",
",",
"file",
")",
";",
"}",
"log",
".",
"info",
"(",
"\"Restoring logs from backup done.\"",
")",
";",
"}"
] | Restore all known logs | [
"Restore",
"all",
"known",
"logs"
] | d345d2d45c75b0694b562b6c346f8594f3a5d166 | https://github.com/soabase/exhibitor/blob/d345d2d45c75b0694b562b6c346f8594f3a5d166/exhibitor-core/src/main/java/com/netflix/exhibitor/core/backup/BackupManager.java#L187-L213 |
28,554 | soabase/exhibitor | exhibitor-core/src/main/java/com/netflix/exhibitor/core/backup/BackupManager.java | BackupManager.restore | public void restore(BackupMetaData backup, File destinationFile) throws Exception
{
File tempFile = File.createTempFile("exhibitor-backup", ".tmp");
OutputStream out = new FileOutputStream(tempFile);
InputStream in = null;
try {
backupProvider.get().downloadBackup(exhibitor, backup, out, getBackupConfig());
CloseableUtils.closeQuietly(out);
out = null;
out = new FileOutputStream(destinationFile);
in = new GZIPInputStream(new FileInputStream(tempFile));
ByteStreams.copy(in, out);
}
finally {
CloseableUtils.closeQuietly(in);
CloseableUtils.closeQuietly(out);
if (!tempFile.delete()) {
exhibitor.getLog().add(ActivityLog.Type.ERROR, "Could not delete temp file (for restore): " + tempFile);
}
}
} | java | public void restore(BackupMetaData backup, File destinationFile) throws Exception
{
File tempFile = File.createTempFile("exhibitor-backup", ".tmp");
OutputStream out = new FileOutputStream(tempFile);
InputStream in = null;
try {
backupProvider.get().downloadBackup(exhibitor, backup, out, getBackupConfig());
CloseableUtils.closeQuietly(out);
out = null;
out = new FileOutputStream(destinationFile);
in = new GZIPInputStream(new FileInputStream(tempFile));
ByteStreams.copy(in, out);
}
finally {
CloseableUtils.closeQuietly(in);
CloseableUtils.closeQuietly(out);
if (!tempFile.delete()) {
exhibitor.getLog().add(ActivityLog.Type.ERROR, "Could not delete temp file (for restore): " + tempFile);
}
}
} | [
"public",
"void",
"restore",
"(",
"BackupMetaData",
"backup",
",",
"File",
"destinationFile",
")",
"throws",
"Exception",
"{",
"File",
"tempFile",
"=",
"File",
".",
"createTempFile",
"(",
"\"exhibitor-backup\"",
",",
"\".tmp\"",
")",
";",
"OutputStream",
"out",
"=",
"new",
"FileOutputStream",
"(",
"tempFile",
")",
";",
"InputStream",
"in",
"=",
"null",
";",
"try",
"{",
"backupProvider",
".",
"get",
"(",
")",
".",
"downloadBackup",
"(",
"exhibitor",
",",
"backup",
",",
"out",
",",
"getBackupConfig",
"(",
")",
")",
";",
"CloseableUtils",
".",
"closeQuietly",
"(",
"out",
")",
";",
"out",
"=",
"null",
";",
"out",
"=",
"new",
"FileOutputStream",
"(",
"destinationFile",
")",
";",
"in",
"=",
"new",
"GZIPInputStream",
"(",
"new",
"FileInputStream",
"(",
"tempFile",
")",
")",
";",
"ByteStreams",
".",
"copy",
"(",
"in",
",",
"out",
")",
";",
"}",
"finally",
"{",
"CloseableUtils",
".",
"closeQuietly",
"(",
"in",
")",
";",
"CloseableUtils",
".",
"closeQuietly",
"(",
"out",
")",
";",
"if",
"(",
"!",
"tempFile",
".",
"delete",
"(",
")",
")",
"{",
"exhibitor",
".",
"getLog",
"(",
")",
".",
"add",
"(",
"ActivityLog",
".",
"Type",
".",
"ERROR",
",",
"\"Could not delete temp file (for restore): \"",
"+",
"tempFile",
")",
";",
"}",
"}",
"}"
] | Restore the given key to the given file
@param backup the backup to pull down
@param destinationFile the file
@throws Exception errors | [
"Restore",
"the",
"given",
"key",
"to",
"the",
"given",
"file"
] | d345d2d45c75b0694b562b6c346f8594f3a5d166 | https://github.com/soabase/exhibitor/blob/d345d2d45c75b0694b562b6c346f8594f3a5d166/exhibitor-core/src/main/java/com/netflix/exhibitor/core/backup/BackupManager.java#L222-L244 |
28,555 | selenide/selenide | src/main/java/com/codeborne/selenide/Selectors.java | Selectors.byAttribute | public static By byAttribute(String attributeName, String attributeValue) {
return By.cssSelector(String.format("[%s='%s']", attributeName, attributeValue));
} | java | public static By byAttribute(String attributeName, String attributeValue) {
return By.cssSelector(String.format("[%s='%s']", attributeName, attributeValue));
} | [
"public",
"static",
"By",
"byAttribute",
"(",
"String",
"attributeName",
",",
"String",
"attributeValue",
")",
"{",
"return",
"By",
".",
"cssSelector",
"(",
"String",
".",
"format",
"(",
"\"[%s='%s']\"",
",",
"attributeName",
",",
"attributeValue",
")",
")",
";",
"}"
] | Find elements having attribute with given value.
Examples:
{@code <div binding="fieldValue"></div>}
Find element with attribute 'binding' EXACTLY containing text 'fieldValue' , use:
byAttribute("binding", "fieldValue")
For finding difficult/generated data attribute which contains some value:
{@code <div binding="userName17fk5n6kc2Ds45F40d0fieldValue_promoLanding word"></div>}
Find element with attribute 'binding' CONTAINING text 'fieldValue', use symbol '*' with attribute name:
byAttribute("binding*", "fieldValue") it same as By.cssSelector("[binding*='fieldValue']")
Find element whose attribute 'binding' BEGINS with 'userName', use symbol '^' with attribute name:
byAttribute("binding^", "fieldValue")
Find element whose attribute 'binding' ENDS with 'promoLanding', use symbol '$' with attribute name:
byAttribute("binding$", "promoLanding")
Find element whose attribute 'binding' CONTAINING WORD 'word':
byAttribute("binding~", "word")
Seems to work incorrectly if attribute name contains dash, for example: {@code <option data-mailServerId="123"></option>}
@param attributeName name of attribute, should not be empty or null
@param attributeValue value of attribute, should not contain both apostrophes and quotes
@return standard selenium By cssSelector criteria | [
"Find",
"elements",
"having",
"attribute",
"with",
"given",
"value",
"."
] | b867baf171942cf07725d83a985237428569883f | https://github.com/selenide/selenide/blob/b867baf171942cf07725d83a985237428569883f/src/main/java/com/codeborne/selenide/Selectors.java#L64-L66 |
28,556 | selenide/selenide | src/main/java/com/codeborne/selenide/ElementsCollection.java | ElementsCollection.texts | public static List<String> texts(Collection<WebElement> elements) {
return elements.stream().map(ElementsCollection::getText).collect(toList());
} | java | public static List<String> texts(Collection<WebElement> elements) {
return elements.stream().map(ElementsCollection::getText).collect(toList());
} | [
"public",
"static",
"List",
"<",
"String",
">",
"texts",
"(",
"Collection",
"<",
"WebElement",
">",
"elements",
")",
"{",
"return",
"elements",
".",
"stream",
"(",
")",
".",
"map",
"(",
"ElementsCollection",
"::",
"getText",
")",
".",
"collect",
"(",
"toList",
"(",
")",
")",
";",
"}"
] | Fail-safe method for retrieving texts of given elements.
@param elements Any collection of WebElements
@return Array of texts (or exceptions in case of any WebDriverExceptions) | [
"Fail",
"-",
"safe",
"method",
"for",
"retrieving",
"texts",
"of",
"given",
"elements",
"."
] | b867baf171942cf07725d83a985237428569883f | https://github.com/selenide/selenide/blob/b867baf171942cf07725d83a985237428569883f/src/main/java/com/codeborne/selenide/ElementsCollection.java#L252-L254 |
28,557 | selenide/selenide | src/main/java/com/codeborne/selenide/ElementsCollection.java | ElementsCollection.elementsToString | public static String elementsToString(Driver driver, Collection<WebElement> elements) {
if (elements == null) {
return "[not loaded yet...]";
}
if (elements.isEmpty()) {
return "[]";
}
StringBuilder sb = new StringBuilder(256);
sb.append("[\n\t");
for (WebElement element : elements) {
if (sb.length() > 4) {
sb.append(",\n\t");
}
sb.append(Describe.describe(driver, element));
}
sb.append("\n]");
return sb.toString();
} | java | public static String elementsToString(Driver driver, Collection<WebElement> elements) {
if (elements == null) {
return "[not loaded yet...]";
}
if (elements.isEmpty()) {
return "[]";
}
StringBuilder sb = new StringBuilder(256);
sb.append("[\n\t");
for (WebElement element : elements) {
if (sb.length() > 4) {
sb.append(",\n\t");
}
sb.append(Describe.describe(driver, element));
}
sb.append("\n]");
return sb.toString();
} | [
"public",
"static",
"String",
"elementsToString",
"(",
"Driver",
"driver",
",",
"Collection",
"<",
"WebElement",
">",
"elements",
")",
"{",
"if",
"(",
"elements",
"==",
"null",
")",
"{",
"return",
"\"[not loaded yet...]\"",
";",
"}",
"if",
"(",
"elements",
".",
"isEmpty",
"(",
")",
")",
"{",
"return",
"\"[]\"",
";",
"}",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
"256",
")",
";",
"sb",
".",
"append",
"(",
"\"[\\n\\t\"",
")",
";",
"for",
"(",
"WebElement",
"element",
":",
"elements",
")",
"{",
"if",
"(",
"sb",
".",
"length",
"(",
")",
">",
"4",
")",
"{",
"sb",
".",
"append",
"(",
"\",\\n\\t\"",
")",
";",
"}",
"sb",
".",
"append",
"(",
"Describe",
".",
"describe",
"(",
"driver",
",",
"element",
")",
")",
";",
"}",
"sb",
".",
"append",
"(",
"\"\\n]\"",
")",
";",
"return",
"sb",
".",
"toString",
"(",
")",
";",
"}"
] | Outputs string presentation of the element's collection
@param elements
@return String | [
"Outputs",
"string",
"presentation",
"of",
"the",
"element",
"s",
"collection"
] | b867baf171942cf07725d83a985237428569883f | https://github.com/selenide/selenide/blob/b867baf171942cf07725d83a985237428569883f/src/main/java/com/codeborne/selenide/ElementsCollection.java#L269-L288 |
28,558 | selenide/selenide | src/main/java/com/codeborne/selenide/proxy/SelenideProxyServer.java | SelenideProxyServer.start | public void start() {
proxy.setTrustAllServers(true);
if (outsideProxy != null) {
proxy.setChainedProxy(getProxyAddress(outsideProxy));
}
addRequestFilter("authentication", new AuthenticationFilter());
addRequestFilter("requestSizeWatchdog", new RequestSizeWatchdog());
addResponseFilter("responseSizeWatchdog", new ResponseSizeWatchdog());
addResponseFilter("download", new FileDownloadFilter(config));
proxy.start(config.proxyPort());
port = proxy.getPort();
} | java | public void start() {
proxy.setTrustAllServers(true);
if (outsideProxy != null) {
proxy.setChainedProxy(getProxyAddress(outsideProxy));
}
addRequestFilter("authentication", new AuthenticationFilter());
addRequestFilter("requestSizeWatchdog", new RequestSizeWatchdog());
addResponseFilter("responseSizeWatchdog", new ResponseSizeWatchdog());
addResponseFilter("download", new FileDownloadFilter(config));
proxy.start(config.proxyPort());
port = proxy.getPort();
} | [
"public",
"void",
"start",
"(",
")",
"{",
"proxy",
".",
"setTrustAllServers",
"(",
"true",
")",
";",
"if",
"(",
"outsideProxy",
"!=",
"null",
")",
"{",
"proxy",
".",
"setChainedProxy",
"(",
"getProxyAddress",
"(",
"outsideProxy",
")",
")",
";",
"}",
"addRequestFilter",
"(",
"\"authentication\"",
",",
"new",
"AuthenticationFilter",
"(",
")",
")",
";",
"addRequestFilter",
"(",
"\"requestSizeWatchdog\"",
",",
"new",
"RequestSizeWatchdog",
"(",
")",
")",
";",
"addResponseFilter",
"(",
"\"responseSizeWatchdog\"",
",",
"new",
"ResponseSizeWatchdog",
"(",
")",
")",
";",
"addResponseFilter",
"(",
"\"download\"",
",",
"new",
"FileDownloadFilter",
"(",
"config",
")",
")",
";",
"proxy",
".",
"start",
"(",
"config",
".",
"proxyPort",
"(",
")",
")",
";",
"port",
"=",
"proxy",
".",
"getPort",
"(",
")",
";",
"}"
] | Start the server
It automatically adds one response filter "download" that can intercept downloaded files. | [
"Start",
"the",
"server"
] | b867baf171942cf07725d83a985237428569883f | https://github.com/selenide/selenide/blob/b867baf171942cf07725d83a985237428569883f/src/main/java/com/codeborne/selenide/proxy/SelenideProxyServer.java#L53-L66 |
28,559 | selenide/selenide | src/main/java/com/codeborne/selenide/proxy/SelenideProxyServer.java | SelenideProxyServer.createSeleniumProxy | public Proxy createSeleniumProxy() {
return isEmpty(config.proxyHost())
? ClientUtil.createSeleniumProxy(proxy)
: ClientUtil.createSeleniumProxy(proxy, inetAddressResolver.getInetAddressByName(config.proxyHost()));
} | java | public Proxy createSeleniumProxy() {
return isEmpty(config.proxyHost())
? ClientUtil.createSeleniumProxy(proxy)
: ClientUtil.createSeleniumProxy(proxy, inetAddressResolver.getInetAddressByName(config.proxyHost()));
} | [
"public",
"Proxy",
"createSeleniumProxy",
"(",
")",
"{",
"return",
"isEmpty",
"(",
"config",
".",
"proxyHost",
"(",
")",
")",
"?",
"ClientUtil",
".",
"createSeleniumProxy",
"(",
"proxy",
")",
":",
"ClientUtil",
".",
"createSeleniumProxy",
"(",
"proxy",
",",
"inetAddressResolver",
".",
"getInetAddressByName",
"(",
"config",
".",
"proxyHost",
"(",
")",
")",
")",
";",
"}"
] | Converts this proxy to a "selenium" proxy that can be used by webdriver | [
"Converts",
"this",
"proxy",
"to",
"a",
"selenium",
"proxy",
"that",
"can",
"be",
"used",
"by",
"webdriver"
] | b867baf171942cf07725d83a985237428569883f | https://github.com/selenide/selenide/blob/b867baf171942cf07725d83a985237428569883f/src/main/java/com/codeborne/selenide/proxy/SelenideProxyServer.java#L114-L118 |
28,560 | selenide/selenide | src/main/java/com/codeborne/selenide/proxy/SelenideProxyServer.java | SelenideProxyServer.requestFilter | @SuppressWarnings("unchecked")
public <T extends RequestFilter> T requestFilter(String name) {
return (T) requestFilters.get(name);
} | java | @SuppressWarnings("unchecked")
public <T extends RequestFilter> T requestFilter(String name) {
return (T) requestFilters.get(name);
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"<",
"T",
"extends",
"RequestFilter",
">",
"T",
"requestFilter",
"(",
"String",
"name",
")",
"{",
"return",
"(",
"T",
")",
"requestFilters",
".",
"get",
"(",
"name",
")",
";",
"}"
] | Get request filter by name | [
"Get",
"request",
"filter",
"by",
"name"
] | b867baf171942cf07725d83a985237428569883f | https://github.com/selenide/selenide/blob/b867baf171942cf07725d83a985237428569883f/src/main/java/com/codeborne/selenide/proxy/SelenideProxyServer.java#L150-L153 |
28,561 | selenide/selenide | src/main/java/com/codeborne/selenide/proxy/SelenideProxyServer.java | SelenideProxyServer.responseFilter | @SuppressWarnings("unchecked")
public <T extends ResponseFilter> T responseFilter(String name) {
return (T) responseFilters.get(name);
} | java | @SuppressWarnings("unchecked")
public <T extends ResponseFilter> T responseFilter(String name) {
return (T) responseFilters.get(name);
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"<",
"T",
"extends",
"ResponseFilter",
">",
"T",
"responseFilter",
"(",
"String",
"name",
")",
"{",
"return",
"(",
"T",
")",
"responseFilters",
".",
"get",
"(",
"name",
")",
";",
"}"
] | Get response filter by name
By default, the only one filter "download" is available. | [
"Get",
"response",
"filter",
"by",
"name"
] | b867baf171942cf07725d83a985237428569883f | https://github.com/selenide/selenide/blob/b867baf171942cf07725d83a985237428569883f/src/main/java/com/codeborne/selenide/proxy/SelenideProxyServer.java#L160-L163 |
28,562 | selenide/selenide | src/main/java/com/codeborne/selenide/Condition.java | Condition.value | public static Condition value(final String expectedValue) {
return new Condition("value") {
@Override
public boolean apply(Driver driver, WebElement element) {
return Html.text.contains(getAttributeValue(element, "value"), expectedValue);
}
@Override
public String toString() {
return name + " '" + expectedValue + "'";
}
};
} | java | public static Condition value(final String expectedValue) {
return new Condition("value") {
@Override
public boolean apply(Driver driver, WebElement element) {
return Html.text.contains(getAttributeValue(element, "value"), expectedValue);
}
@Override
public String toString() {
return name + " '" + expectedValue + "'";
}
};
} | [
"public",
"static",
"Condition",
"value",
"(",
"final",
"String",
"expectedValue",
")",
"{",
"return",
"new",
"Condition",
"(",
"\"value\"",
")",
"{",
"@",
"Override",
"public",
"boolean",
"apply",
"(",
"Driver",
"driver",
",",
"WebElement",
"element",
")",
"{",
"return",
"Html",
".",
"text",
".",
"contains",
"(",
"getAttributeValue",
"(",
"element",
",",
"\"value\"",
")",
",",
"expectedValue",
")",
";",
"}",
"@",
"Override",
"public",
"String",
"toString",
"(",
")",
"{",
"return",
"name",
"+",
"\" '\"",
"+",
"expectedValue",
"+",
"\"'\"",
";",
"}",
"}",
";",
"}"
] | Assert that element has given "value" attribute as substring
NB! Ignores difference in non-visible characters like spaces, non-breakable spaces, tabs, newlines etc.
<p>Sample: <code>$("input").shouldHave(value("12345 666 77"));</code></p>
@param expectedValue expected value of "value" attribute | [
"Assert",
"that",
"element",
"has",
"given",
"value",
"attribute",
"as",
"substring",
"NB!",
"Ignores",
"difference",
"in",
"non",
"-",
"visible",
"characters",
"like",
"spaces",
"non",
"-",
"breakable",
"spaces",
"tabs",
"newlines",
"etc",
"."
] | b867baf171942cf07725d83a985237428569883f | https://github.com/selenide/selenide/blob/b867baf171942cf07725d83a985237428569883f/src/main/java/com/codeborne/selenide/Condition.java#L156-L168 |
28,563 | selenide/selenide | src/main/java/com/codeborne/selenide/Condition.java | Condition.matchText | public static Condition matchText(final String regex) {
return new Condition("match text") {
@Override
public boolean apply(Driver driver, WebElement element) {
return Html.text.matches(element.getText(), regex);
}
@Override
public String toString() {
return name + " '" + regex + '\'';
}
};
} | java | public static Condition matchText(final String regex) {
return new Condition("match text") {
@Override
public boolean apply(Driver driver, WebElement element) {
return Html.text.matches(element.getText(), regex);
}
@Override
public String toString() {
return name + " '" + regex + '\'';
}
};
} | [
"public",
"static",
"Condition",
"matchText",
"(",
"final",
"String",
"regex",
")",
"{",
"return",
"new",
"Condition",
"(",
"\"match text\"",
")",
"{",
"@",
"Override",
"public",
"boolean",
"apply",
"(",
"Driver",
"driver",
",",
"WebElement",
"element",
")",
"{",
"return",
"Html",
".",
"text",
".",
"matches",
"(",
"element",
".",
"getText",
"(",
")",
",",
"regex",
")",
";",
"}",
"@",
"Override",
"public",
"String",
"toString",
"(",
")",
"{",
"return",
"name",
"+",
"\" '\"",
"+",
"regex",
"+",
"'",
"'",
";",
"}",
"}",
";",
"}"
] | Assert that given element's text matches given regular expression
<p>Sample: <code>$("h1").should(matchText("Hello\s*John"))</code></p>
@param regex e.g. Kicked.*Chuck Norris - in this case ".*" can contain any characters including spaces, tabs, CR etc. | [
"Assert",
"that",
"given",
"element",
"s",
"text",
"matches",
"given",
"regular",
"expression"
] | b867baf171942cf07725d83a985237428569883f | https://github.com/selenide/selenide/blob/b867baf171942cf07725d83a985237428569883f/src/main/java/com/codeborne/selenide/Condition.java#L231-L243 |
28,564 | selenide/selenide | src/main/java/com/codeborne/selenide/Condition.java | Condition.selectedText | public static Condition selectedText(final String expectedText) {
return new Condition("selectedText") {
String actualResult = "";
@Override
public boolean apply(Driver driver, WebElement element) {
actualResult = driver.executeJavaScript(
"return arguments[0].value.substring(arguments[0].selectionStart, arguments[0].selectionEnd);", element);
return actualResult.equals(expectedText);
}
@Override
public String actualValue(Driver driver, WebElement element) {
return "'" + actualResult + "'";
}
@Override
public String toString() {
return name + " '" + expectedText + '\'';
}
};
} | java | public static Condition selectedText(final String expectedText) {
return new Condition("selectedText") {
String actualResult = "";
@Override
public boolean apply(Driver driver, WebElement element) {
actualResult = driver.executeJavaScript(
"return arguments[0].value.substring(arguments[0].selectionStart, arguments[0].selectionEnd);", element);
return actualResult.equals(expectedText);
}
@Override
public String actualValue(Driver driver, WebElement element) {
return "'" + actualResult + "'";
}
@Override
public String toString() {
return name + " '" + expectedText + '\'';
}
};
} | [
"public",
"static",
"Condition",
"selectedText",
"(",
"final",
"String",
"expectedText",
")",
"{",
"return",
"new",
"Condition",
"(",
"\"selectedText\"",
")",
"{",
"String",
"actualResult",
"=",
"\"\"",
";",
"@",
"Override",
"public",
"boolean",
"apply",
"(",
"Driver",
"driver",
",",
"WebElement",
"element",
")",
"{",
"actualResult",
"=",
"driver",
".",
"executeJavaScript",
"(",
"\"return arguments[0].value.substring(arguments[0].selectionStart, arguments[0].selectionEnd);\"",
",",
"element",
")",
";",
"return",
"actualResult",
".",
"equals",
"(",
"expectedText",
")",
";",
"}",
"@",
"Override",
"public",
"String",
"actualValue",
"(",
"Driver",
"driver",
",",
"WebElement",
"element",
")",
"{",
"return",
"\"'\"",
"+",
"actualResult",
"+",
"\"'\"",
";",
"}",
"@",
"Override",
"public",
"String",
"toString",
"(",
")",
"{",
"return",
"name",
"+",
"\" '\"",
"+",
"expectedText",
"+",
"'",
"'",
";",
"}",
"}",
";",
"}"
] | Checks for selected text on a given input web element
<p>Sample: {@code $("input").shouldHave(selectedText("Text"))}</p>
<p>NB! Case sensitive</p>
@param expectedText expected selected text of the element | [
"Checks",
"for",
"selected",
"text",
"on",
"a",
"given",
"input",
"web",
"element"
] | b867baf171942cf07725d83a985237428569883f | https://github.com/selenide/selenide/blob/b867baf171942cf07725d83a985237428569883f/src/main/java/com/codeborne/selenide/Condition.java#L267-L288 |
28,565 | selenide/selenide | src/main/java/com/codeborne/selenide/Condition.java | Condition.and | public static Condition and(String name, final Condition... condition) {
return new Condition(name) {
private Condition lastFailedCondition;
@Override
public boolean apply(Driver driver, WebElement element) {
for (Condition c : condition) {
if (!c.apply(driver, element)) {
lastFailedCondition = c;
return false;
}
}
return true;
}
@Override
public String actualValue(Driver driver, WebElement element) {
return lastFailedCondition == null ? null : lastFailedCondition.actualValue(driver, element);
}
@Override
public String toString() {
return lastFailedCondition == null ? super.toString() : lastFailedCondition.toString();
}
};
} | java | public static Condition and(String name, final Condition... condition) {
return new Condition(name) {
private Condition lastFailedCondition;
@Override
public boolean apply(Driver driver, WebElement element) {
for (Condition c : condition) {
if (!c.apply(driver, element)) {
lastFailedCondition = c;
return false;
}
}
return true;
}
@Override
public String actualValue(Driver driver, WebElement element) {
return lastFailedCondition == null ? null : lastFailedCondition.actualValue(driver, element);
}
@Override
public String toString() {
return lastFailedCondition == null ? super.toString() : lastFailedCondition.toString();
}
};
} | [
"public",
"static",
"Condition",
"and",
"(",
"String",
"name",
",",
"final",
"Condition",
"...",
"condition",
")",
"{",
"return",
"new",
"Condition",
"(",
"name",
")",
"{",
"private",
"Condition",
"lastFailedCondition",
";",
"@",
"Override",
"public",
"boolean",
"apply",
"(",
"Driver",
"driver",
",",
"WebElement",
"element",
")",
"{",
"for",
"(",
"Condition",
"c",
":",
"condition",
")",
"{",
"if",
"(",
"!",
"c",
".",
"apply",
"(",
"driver",
",",
"element",
")",
")",
"{",
"lastFailedCondition",
"=",
"c",
";",
"return",
"false",
";",
"}",
"}",
"return",
"true",
";",
"}",
"@",
"Override",
"public",
"String",
"actualValue",
"(",
"Driver",
"driver",
",",
"WebElement",
"element",
")",
"{",
"return",
"lastFailedCondition",
"==",
"null",
"?",
"null",
":",
"lastFailedCondition",
".",
"actualValue",
"(",
"driver",
",",
"element",
")",
";",
"}",
"@",
"Override",
"public",
"String",
"toString",
"(",
")",
"{",
"return",
"lastFailedCondition",
"==",
"null",
"?",
"super",
".",
"toString",
"(",
")",
":",
"lastFailedCondition",
".",
"toString",
"(",
")",
";",
"}",
"}",
";",
"}"
] | Check if element matches ALL given conditions.
@param name Name of this condition, like "empty" (meaning e.g. empty text AND empty value).
@param condition Conditions to match.
@return logical AND for given conditions. | [
"Check",
"if",
"element",
"matches",
"ALL",
"given",
"conditions",
"."
] | b867baf171942cf07725d83a985237428569883f | https://github.com/selenide/selenide/blob/b867baf171942cf07725d83a985237428569883f/src/main/java/com/codeborne/selenide/Condition.java#L540-L565 |
28,566 | selenide/selenide | src/main/java/com/codeborne/selenide/webdriver/ChromeDriverFactory.java | ChromeDriverFactory.convertStringToNearestObjectType | private Object convertStringToNearestObjectType(String value) {
switch (value) {
case "true":
return true;
case "false":
return false;
default: {
if (NumberUtils.isParsable(value)) {
return Integer.parseInt(value);
}
return value;
}
}
} | java | private Object convertStringToNearestObjectType(String value) {
switch (value) {
case "true":
return true;
case "false":
return false;
default: {
if (NumberUtils.isParsable(value)) {
return Integer.parseInt(value);
}
return value;
}
}
} | [
"private",
"Object",
"convertStringToNearestObjectType",
"(",
"String",
"value",
")",
"{",
"switch",
"(",
"value",
")",
"{",
"case",
"\"true\"",
":",
"return",
"true",
";",
"case",
"\"false\"",
":",
"return",
"false",
";",
"default",
":",
"{",
"if",
"(",
"NumberUtils",
".",
"isParsable",
"(",
"value",
")",
")",
"{",
"return",
"Integer",
".",
"parseInt",
"(",
"value",
")",
";",
"}",
"return",
"value",
";",
"}",
"}",
"}"
] | Converts String to Boolean\Integer or returns original String.
@param value string to convert
@return string's object representation | [
"Converts",
"String",
"to",
"Boolean",
"\\",
"Integer",
"or",
"returns",
"original",
"String",
"."
] | b867baf171942cf07725d83a985237428569883f | https://github.com/selenide/selenide/blob/b867baf171942cf07725d83a985237428569883f/src/main/java/com/codeborne/selenide/webdriver/ChromeDriverFactory.java#L111-L124 |
28,567 | SundeepK/CompactCalendarView | library/src/main/java/com/github/sundeepk/compactcalendarview/CompactCalendarController.java | CompactCalendarController.isScrolling | private boolean isScrolling() {
float scrolledX = Math.abs(accumulatedScrollOffset.x);
int expectedScrollX = Math.abs(width * monthsScrolledSoFar);
return scrolledX < expectedScrollX - 5 || scrolledX > expectedScrollX + 5;
} | java | private boolean isScrolling() {
float scrolledX = Math.abs(accumulatedScrollOffset.x);
int expectedScrollX = Math.abs(width * monthsScrolledSoFar);
return scrolledX < expectedScrollX - 5 || scrolledX > expectedScrollX + 5;
} | [
"private",
"boolean",
"isScrolling",
"(",
")",
"{",
"float",
"scrolledX",
"=",
"Math",
".",
"abs",
"(",
"accumulatedScrollOffset",
".",
"x",
")",
";",
"int",
"expectedScrollX",
"=",
"Math",
".",
"abs",
"(",
"width",
"*",
"monthsScrolledSoFar",
")",
";",
"return",
"scrolledX",
"<",
"expectedScrollX",
"-",
"5",
"||",
"scrolledX",
">",
"expectedScrollX",
"+",
"5",
";",
"}"
] | as it maybe off by a few pixels | [
"as",
"it",
"maybe",
"off",
"by",
"a",
"few",
"pixels"
] | e74e0eeb913744bdcaea6e9df53268441f9dbf8d | https://github.com/SundeepK/CompactCalendarView/blob/e74e0eeb913744bdcaea6e9df53268441f9dbf8d/library/src/main/java/com/github/sundeepk/compactcalendarview/CompactCalendarController.java#L499-L503 |
28,568 | SundeepK/CompactCalendarView | library/src/main/java/com/github/sundeepk/compactcalendarview/CompactCalendarController.java | CompactCalendarController.drawEventsWithPlus | private void drawEventsWithPlus(Canvas canvas, float xPosition, float yPosition, List<Event> eventsList) {
// k = size() - 1, but since we don't want to draw more than 2 indicators, we just stop after 2 iterations so we can just hard k = -2 instead
// we can use the below loop to draw arbitrary eventsByMonthAndYearMap based on the current screen size, for example, larger screens should be able to
// display more than 2 evens before displaying plus indicator, but don't draw more than 3 indicators for now
for (int j = 0, k = -2; j < 3; j++, k += 2) {
Event event = eventsList.get(j);
float xStartPosition = xPosition + (xIndicatorOffset * k);
if (j == 2) {
dayPaint.setColor(multiEventIndicatorColor);
dayPaint.setStrokeWidth(multiDayIndicatorStrokeWidth);
canvas.drawLine(xStartPosition - smallIndicatorRadius, yPosition, xStartPosition + smallIndicatorRadius, yPosition, dayPaint);
canvas.drawLine(xStartPosition, yPosition - smallIndicatorRadius, xStartPosition, yPosition + smallIndicatorRadius, dayPaint);
dayPaint.setStrokeWidth(0);
} else {
drawEventIndicatorCircle(canvas, xStartPosition, yPosition, event.getColor());
}
}
} | java | private void drawEventsWithPlus(Canvas canvas, float xPosition, float yPosition, List<Event> eventsList) {
// k = size() - 1, but since we don't want to draw more than 2 indicators, we just stop after 2 iterations so we can just hard k = -2 instead
// we can use the below loop to draw arbitrary eventsByMonthAndYearMap based on the current screen size, for example, larger screens should be able to
// display more than 2 evens before displaying plus indicator, but don't draw more than 3 indicators for now
for (int j = 0, k = -2; j < 3; j++, k += 2) {
Event event = eventsList.get(j);
float xStartPosition = xPosition + (xIndicatorOffset * k);
if (j == 2) {
dayPaint.setColor(multiEventIndicatorColor);
dayPaint.setStrokeWidth(multiDayIndicatorStrokeWidth);
canvas.drawLine(xStartPosition - smallIndicatorRadius, yPosition, xStartPosition + smallIndicatorRadius, yPosition, dayPaint);
canvas.drawLine(xStartPosition, yPosition - smallIndicatorRadius, xStartPosition, yPosition + smallIndicatorRadius, dayPaint);
dayPaint.setStrokeWidth(0);
} else {
drawEventIndicatorCircle(canvas, xStartPosition, yPosition, event.getColor());
}
}
} | [
"private",
"void",
"drawEventsWithPlus",
"(",
"Canvas",
"canvas",
",",
"float",
"xPosition",
",",
"float",
"yPosition",
",",
"List",
"<",
"Event",
">",
"eventsList",
")",
"{",
"// k = size() - 1, but since we don't want to draw more than 2 indicators, we just stop after 2 iterations so we can just hard k = -2 instead",
"// we can use the below loop to draw arbitrary eventsByMonthAndYearMap based on the current screen size, for example, larger screens should be able to",
"// display more than 2 evens before displaying plus indicator, but don't draw more than 3 indicators for now",
"for",
"(",
"int",
"j",
"=",
"0",
",",
"k",
"=",
"-",
"2",
";",
"j",
"<",
"3",
";",
"j",
"++",
",",
"k",
"+=",
"2",
")",
"{",
"Event",
"event",
"=",
"eventsList",
".",
"get",
"(",
"j",
")",
";",
"float",
"xStartPosition",
"=",
"xPosition",
"+",
"(",
"xIndicatorOffset",
"*",
"k",
")",
";",
"if",
"(",
"j",
"==",
"2",
")",
"{",
"dayPaint",
".",
"setColor",
"(",
"multiEventIndicatorColor",
")",
";",
"dayPaint",
".",
"setStrokeWidth",
"(",
"multiDayIndicatorStrokeWidth",
")",
";",
"canvas",
".",
"drawLine",
"(",
"xStartPosition",
"-",
"smallIndicatorRadius",
",",
"yPosition",
",",
"xStartPosition",
"+",
"smallIndicatorRadius",
",",
"yPosition",
",",
"dayPaint",
")",
";",
"canvas",
".",
"drawLine",
"(",
"xStartPosition",
",",
"yPosition",
"-",
"smallIndicatorRadius",
",",
"xStartPosition",
",",
"yPosition",
"+",
"smallIndicatorRadius",
",",
"dayPaint",
")",
";",
"dayPaint",
".",
"setStrokeWidth",
"(",
"0",
")",
";",
"}",
"else",
"{",
"drawEventIndicatorCircle",
"(",
"canvas",
",",
"xStartPosition",
",",
"yPosition",
",",
"event",
".",
"getColor",
"(",
")",
")",
";",
"}",
"}",
"}"
] | draw 2 eventsByMonthAndYearMap followed by plus indicator to show there are more than 2 eventsByMonthAndYearMap | [
"draw",
"2",
"eventsByMonthAndYearMap",
"followed",
"by",
"plus",
"indicator",
"to",
"show",
"there",
"are",
"more",
"than",
"2",
"eventsByMonthAndYearMap"
] | e74e0eeb913744bdcaea6e9df53268441f9dbf8d | https://github.com/SundeepK/CompactCalendarView/blob/e74e0eeb913744bdcaea6e9df53268441f9dbf8d/library/src/main/java/com/github/sundeepk/compactcalendarview/CompactCalendarController.java#L845-L862 |
28,569 | SundeepK/CompactCalendarView | library/src/main/java/com/github/sundeepk/compactcalendarview/CompactCalendarController.java | CompactCalendarController.getDayOfWeek | int getDayOfWeek(Calendar calendar) {
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK) - firstDayOfWeekToDraw;
dayOfWeek = dayOfWeek < 0 ? 7 + dayOfWeek: dayOfWeek;
return dayOfWeek;
} | java | int getDayOfWeek(Calendar calendar) {
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK) - firstDayOfWeekToDraw;
dayOfWeek = dayOfWeek < 0 ? 7 + dayOfWeek: dayOfWeek;
return dayOfWeek;
} | [
"int",
"getDayOfWeek",
"(",
"Calendar",
"calendar",
")",
"{",
"int",
"dayOfWeek",
"=",
"calendar",
".",
"get",
"(",
"Calendar",
".",
"DAY_OF_WEEK",
")",
"-",
"firstDayOfWeekToDraw",
";",
"dayOfWeek",
"=",
"dayOfWeek",
"<",
"0",
"?",
"7",
"+",
"dayOfWeek",
":",
"dayOfWeek",
";",
"return",
"dayOfWeek",
";",
"}"
] | it returns 0-6 where 0 is Sunday instead of 1 | [
"it",
"returns",
"0",
"-",
"6",
"where",
"0",
"is",
"Sunday",
"instead",
"of",
"1"
] | e74e0eeb913744bdcaea6e9df53268441f9dbf8d | https://github.com/SundeepK/CompactCalendarView/blob/e74e0eeb913744bdcaea6e9df53268441f9dbf8d/library/src/main/java/com/github/sundeepk/compactcalendarview/CompactCalendarController.java#L866-L870 |
28,570 | SundeepK/CompactCalendarView | library/src/main/java/com/github/sundeepk/compactcalendarview/CompactCalendarController.java | CompactCalendarController.drawCircle | private void drawCircle(Canvas canvas, float x, float y, int color, float circleScale) {
dayPaint.setColor(color);
if (animationStatus == ANIMATE_INDICATORS) {
float maxRadius = circleScale * bigCircleIndicatorRadius * 1.4f;
drawCircle(canvas, growfactorIndicator > maxRadius ? maxRadius: growfactorIndicator, x, y - (textHeight / 6));
} else {
drawCircle(canvas, circleScale * bigCircleIndicatorRadius, x, y - (textHeight / 6));
}
} | java | private void drawCircle(Canvas canvas, float x, float y, int color, float circleScale) {
dayPaint.setColor(color);
if (animationStatus == ANIMATE_INDICATORS) {
float maxRadius = circleScale * bigCircleIndicatorRadius * 1.4f;
drawCircle(canvas, growfactorIndicator > maxRadius ? maxRadius: growfactorIndicator, x, y - (textHeight / 6));
} else {
drawCircle(canvas, circleScale * bigCircleIndicatorRadius, x, y - (textHeight / 6));
}
} | [
"private",
"void",
"drawCircle",
"(",
"Canvas",
"canvas",
",",
"float",
"x",
",",
"float",
"y",
",",
"int",
"color",
",",
"float",
"circleScale",
")",
"{",
"dayPaint",
".",
"setColor",
"(",
"color",
")",
";",
"if",
"(",
"animationStatus",
"==",
"ANIMATE_INDICATORS",
")",
"{",
"float",
"maxRadius",
"=",
"circleScale",
"*",
"bigCircleIndicatorRadius",
"*",
"1.4f",
";",
"drawCircle",
"(",
"canvas",
",",
"growfactorIndicator",
">",
"maxRadius",
"?",
"maxRadius",
":",
"growfactorIndicator",
",",
"x",
",",
"y",
"-",
"(",
"textHeight",
"/",
"6",
")",
")",
";",
"}",
"else",
"{",
"drawCircle",
"(",
"canvas",
",",
"circleScale",
"*",
"bigCircleIndicatorRadius",
",",
"x",
",",
"y",
"-",
"(",
"textHeight",
"/",
"6",
")",
")",
";",
"}",
"}"
] | Draw Circle on certain days to highlight them | [
"Draw",
"Circle",
"on",
"certain",
"days",
"to",
"highlight",
"them"
] | e74e0eeb913744bdcaea6e9df53268441f9dbf8d | https://github.com/SundeepK/CompactCalendarView/blob/e74e0eeb913744bdcaea6e9df53268441f9dbf8d/library/src/main/java/com/github/sundeepk/compactcalendarview/CompactCalendarController.java#L974-L982 |
28,571 | SundeepK/CompactCalendarView | library/src/main/java/com/github/sundeepk/compactcalendarview/EventsContainer.java | EventsContainer.getKeyForCalendarEvent | private String getKeyForCalendarEvent(Calendar cal) {
return cal.get(Calendar.YEAR) + "_" + cal.get(Calendar.MONTH);
} | java | private String getKeyForCalendarEvent(Calendar cal) {
return cal.get(Calendar.YEAR) + "_" + cal.get(Calendar.MONTH);
} | [
"private",
"String",
"getKeyForCalendarEvent",
"(",
"Calendar",
"cal",
")",
"{",
"return",
"cal",
".",
"get",
"(",
"Calendar",
".",
"YEAR",
")",
"+",
"\"_\"",
"+",
"cal",
".",
"get",
"(",
"Calendar",
".",
"MONTH",
")",
";",
"}"
] | E.g. 4 2016 becomes 2016_4 | [
"E",
".",
"g",
".",
"4",
"2016",
"becomes",
"2016_4"
] | e74e0eeb913744bdcaea6e9df53268441f9dbf8d | https://github.com/SundeepK/CompactCalendarView/blob/e74e0eeb913744bdcaea6e9df53268441f9dbf8d/library/src/main/java/com/github/sundeepk/compactcalendarview/EventsContainer.java#L154-L156 |
28,572 | square/android-times-square | library/src/main/java/com/squareup/timessquare/CalendarPickerView.java | CalendarPickerView.unfixDialogDimens | public void unfixDialogDimens() {
Logr.d("Reset the fixed dimensions to allow for re-measurement");
// Fix the layout height/width after the dialog has been shown.
getLayoutParams().height = LayoutParams.MATCH_PARENT;
getLayoutParams().width = LayoutParams.MATCH_PARENT;
requestLayout();
} | java | public void unfixDialogDimens() {
Logr.d("Reset the fixed dimensions to allow for re-measurement");
// Fix the layout height/width after the dialog has been shown.
getLayoutParams().height = LayoutParams.MATCH_PARENT;
getLayoutParams().width = LayoutParams.MATCH_PARENT;
requestLayout();
} | [
"public",
"void",
"unfixDialogDimens",
"(",
")",
"{",
"Logr",
".",
"d",
"(",
"\"Reset the fixed dimensions to allow for re-measurement\"",
")",
";",
"// Fix the layout height/width after the dialog has been shown.",
"getLayoutParams",
"(",
")",
".",
"height",
"=",
"LayoutParams",
".",
"MATCH_PARENT",
";",
"getLayoutParams",
"(",
")",
".",
"width",
"=",
"LayoutParams",
".",
"MATCH_PARENT",
";",
"requestLayout",
"(",
")",
";",
"}"
] | This method should only be called if the calendar is contained in a dialog, and it should only
be called when the screen has been rotated and the dialog should be re-measured. | [
"This",
"method",
"should",
"only",
"be",
"called",
"if",
"the",
"calendar",
"is",
"contained",
"in",
"a",
"dialog",
"and",
"it",
"should",
"only",
"be",
"called",
"when",
"the",
"screen",
"has",
"been",
"rotated",
"and",
"the",
"dialog",
"should",
"be",
"re",
"-",
"measured",
"."
] | 83b08e7cc220d587845054cd1471a604d17721f6 | https://github.com/square/android-times-square/blob/83b08e7cc220d587845054cd1471a604d17721f6/library/src/main/java/com/squareup/timessquare/CalendarPickerView.java#L525-L531 |
28,573 | Netflix/spectator | spectator-ext-ipc/src/main/java/com/netflix/spectator/ipc/IpcLogger.java | IpcLogger.inflightRequests | AtomicInteger inflightRequests(Id id) {
return Utils.computeIfAbsent(inflightRequests, id, i -> new AtomicInteger());
} | java | AtomicInteger inflightRequests(Id id) {
return Utils.computeIfAbsent(inflightRequests, id, i -> new AtomicInteger());
} | [
"AtomicInteger",
"inflightRequests",
"(",
"Id",
"id",
")",
"{",
"return",
"Utils",
".",
"computeIfAbsent",
"(",
"inflightRequests",
",",
"id",
",",
"i",
"->",
"new",
"AtomicInteger",
"(",
")",
")",
";",
"}"
] | Return the number of inflight requests associated with the given id. | [
"Return",
"the",
"number",
"of",
"inflight",
"requests",
"associated",
"with",
"the",
"given",
"id",
"."
] | 259318252770de3bad581b85adff187d8f2c6537 | https://github.com/Netflix/spectator/blob/259318252770de3bad581b85adff187d8f2c6537/spectator-ext-ipc/src/main/java/com/netflix/spectator/ipc/IpcLogger.java#L78-L80 |
28,574 | Netflix/spectator | spectator-ext-ipc/src/main/java/com/netflix/spectator/ipc/IpcLogger.java | IpcLogger.limiterForKey | Function<String, String> limiterForKey(String key) {
return Utils.computeIfAbsent(limiters, key, k -> CardinalityLimiters.rollup(25));
} | java | Function<String, String> limiterForKey(String key) {
return Utils.computeIfAbsent(limiters, key, k -> CardinalityLimiters.rollup(25));
} | [
"Function",
"<",
"String",
",",
"String",
">",
"limiterForKey",
"(",
"String",
"key",
")",
"{",
"return",
"Utils",
".",
"computeIfAbsent",
"(",
"limiters",
",",
"key",
",",
"k",
"->",
"CardinalityLimiters",
".",
"rollup",
"(",
"25",
")",
")",
";",
"}"
] | Return the cardinality limiter for a given key. This is used to protect the metrics
backend from a metrics explosion if some dimensions have a high cardinality. | [
"Return",
"the",
"cardinality",
"limiter",
"for",
"a",
"given",
"key",
".",
"This",
"is",
"used",
"to",
"protect",
"the",
"metrics",
"backend",
"from",
"a",
"metrics",
"explosion",
"if",
"some",
"dimensions",
"have",
"a",
"high",
"cardinality",
"."
] | 259318252770de3bad581b85adff187d8f2c6537 | https://github.com/Netflix/spectator/blob/259318252770de3bad581b85adff187d8f2c6537/spectator-ext-ipc/src/main/java/com/netflix/spectator/ipc/IpcLogger.java#L86-L88 |
28,575 | Netflix/spectator | spectator-ext-ipc/src/main/java/com/netflix/spectator/ipc/IpcLogger.java | IpcLogger.log | void log(IpcLogEntry entry) {
Level level = entry.getLevel();
Predicate<Marker> enabled;
BiConsumer<Marker, String> log;
switch (level) {
case TRACE:
enabled = logger::isTraceEnabled;
log = logger::trace;
break;
case DEBUG:
enabled = logger::isDebugEnabled;
log = logger::debug;
break;
case INFO:
enabled = logger::isInfoEnabled;
log = logger::info;
break;
case WARN:
enabled = logger::isWarnEnabled;
log = logger::warn;
break;
case ERROR:
enabled = logger::isErrorEnabled;
log = logger::error;
break;
default:
enabled = logger::isDebugEnabled;
log = logger::debug;
break;
}
if (enabled.test(entry.getMarker())) {
log.accept(entry.getMarker(), entry.toString());
}
// For successful responses we can reuse the entry to avoid additional allocations. Failed
// requests might have retries so we just reset the response portion to avoid incorrectly
// having state bleed through from one request to the next.
if (entry.isSuccessful()) {
entry.reset();
entries.offer(entry);
} else {
entry.resetForRetry();
}
} | java | void log(IpcLogEntry entry) {
Level level = entry.getLevel();
Predicate<Marker> enabled;
BiConsumer<Marker, String> log;
switch (level) {
case TRACE:
enabled = logger::isTraceEnabled;
log = logger::trace;
break;
case DEBUG:
enabled = logger::isDebugEnabled;
log = logger::debug;
break;
case INFO:
enabled = logger::isInfoEnabled;
log = logger::info;
break;
case WARN:
enabled = logger::isWarnEnabled;
log = logger::warn;
break;
case ERROR:
enabled = logger::isErrorEnabled;
log = logger::error;
break;
default:
enabled = logger::isDebugEnabled;
log = logger::debug;
break;
}
if (enabled.test(entry.getMarker())) {
log.accept(entry.getMarker(), entry.toString());
}
// For successful responses we can reuse the entry to avoid additional allocations. Failed
// requests might have retries so we just reset the response portion to avoid incorrectly
// having state bleed through from one request to the next.
if (entry.isSuccessful()) {
entry.reset();
entries.offer(entry);
} else {
entry.resetForRetry();
}
} | [
"void",
"log",
"(",
"IpcLogEntry",
"entry",
")",
"{",
"Level",
"level",
"=",
"entry",
".",
"getLevel",
"(",
")",
";",
"Predicate",
"<",
"Marker",
">",
"enabled",
";",
"BiConsumer",
"<",
"Marker",
",",
"String",
">",
"log",
";",
"switch",
"(",
"level",
")",
"{",
"case",
"TRACE",
":",
"enabled",
"=",
"logger",
"::",
"isTraceEnabled",
";",
"log",
"=",
"logger",
"::",
"trace",
";",
"break",
";",
"case",
"DEBUG",
":",
"enabled",
"=",
"logger",
"::",
"isDebugEnabled",
";",
"log",
"=",
"logger",
"::",
"debug",
";",
"break",
";",
"case",
"INFO",
":",
"enabled",
"=",
"logger",
"::",
"isInfoEnabled",
";",
"log",
"=",
"logger",
"::",
"info",
";",
"break",
";",
"case",
"WARN",
":",
"enabled",
"=",
"logger",
"::",
"isWarnEnabled",
";",
"log",
"=",
"logger",
"::",
"warn",
";",
"break",
";",
"case",
"ERROR",
":",
"enabled",
"=",
"logger",
"::",
"isErrorEnabled",
";",
"log",
"=",
"logger",
"::",
"error",
";",
"break",
";",
"default",
":",
"enabled",
"=",
"logger",
"::",
"isDebugEnabled",
";",
"log",
"=",
"logger",
"::",
"debug",
";",
"break",
";",
"}",
"if",
"(",
"enabled",
".",
"test",
"(",
"entry",
".",
"getMarker",
"(",
")",
")",
")",
"{",
"log",
".",
"accept",
"(",
"entry",
".",
"getMarker",
"(",
")",
",",
"entry",
".",
"toString",
"(",
")",
")",
";",
"}",
"// For successful responses we can reuse the entry to avoid additional allocations. Failed",
"// requests might have retries so we just reset the response portion to avoid incorrectly",
"// having state bleed through from one request to the next.",
"if",
"(",
"entry",
".",
"isSuccessful",
"(",
")",
")",
"{",
"entry",
".",
"reset",
"(",
")",
";",
"entries",
".",
"offer",
"(",
"entry",
")",
";",
"}",
"else",
"{",
"entry",
".",
"resetForRetry",
"(",
")",
";",
"}",
"}"
] | Called by the entry to log the request. | [
"Called",
"by",
"the",
"entry",
"to",
"log",
"the",
"request",
"."
] | 259318252770de3bad581b85adff187d8f2c6537 | https://github.com/Netflix/spectator/blob/259318252770de3bad581b85adff187d8f2c6537/spectator-ext-ipc/src/main/java/com/netflix/spectator/ipc/IpcLogger.java#L122-L166 |
28,576 | Netflix/spectator | spectator-ext-ipc/src/jmh/java/com/netflix/spectator/ipc/SeqServerGroup.java | SeqServerGroup.parse | public static SeqServerGroup parse(String asg) {
int d1 = asg.indexOf('-');
int d2 = asg.indexOf('-', d1 + 1);
int dN = asg.lastIndexOf('-');
if (dN < 0 || !isSequence(asg, dN)) {
dN = asg.length();
}
return new SeqServerGroup(asg, d1, d2, dN);
} | java | public static SeqServerGroup parse(String asg) {
int d1 = asg.indexOf('-');
int d2 = asg.indexOf('-', d1 + 1);
int dN = asg.lastIndexOf('-');
if (dN < 0 || !isSequence(asg, dN)) {
dN = asg.length();
}
return new SeqServerGroup(asg, d1, d2, dN);
} | [
"public",
"static",
"SeqServerGroup",
"parse",
"(",
"String",
"asg",
")",
"{",
"int",
"d1",
"=",
"asg",
".",
"indexOf",
"(",
"'",
"'",
")",
";",
"int",
"d2",
"=",
"asg",
".",
"indexOf",
"(",
"'",
"'",
",",
"d1",
"+",
"1",
")",
";",
"int",
"dN",
"=",
"asg",
".",
"lastIndexOf",
"(",
"'",
"'",
")",
";",
"if",
"(",
"dN",
"<",
"0",
"||",
"!",
"isSequence",
"(",
"asg",
",",
"dN",
")",
")",
"{",
"dN",
"=",
"asg",
".",
"length",
"(",
")",
";",
"}",
"return",
"new",
"SeqServerGroup",
"(",
"asg",
",",
"d1",
",",
"d2",
",",
"dN",
")",
";",
"}"
] | Create a new instance of a server group object by parsing the group name. | [
"Create",
"a",
"new",
"instance",
"of",
"a",
"server",
"group",
"object",
"by",
"parsing",
"the",
"group",
"name",
"."
] | 259318252770de3bad581b85adff187d8f2c6537 | https://github.com/Netflix/spectator/blob/259318252770de3bad581b85adff187d8f2c6537/spectator-ext-ipc/src/jmh/java/com/netflix/spectator/ipc/SeqServerGroup.java#L34-L42 |
28,577 | Netflix/spectator | spectator-ext-ipc/src/jmh/java/com/netflix/spectator/ipc/SeqServerGroup.java | SeqServerGroup.substr | private static CharSequence substr(CharSequence str, int s, int e) {
return (s >= e) ? null : CharBuffer.wrap(str, s, e);
} | java | private static CharSequence substr(CharSequence str, int s, int e) {
return (s >= e) ? null : CharBuffer.wrap(str, s, e);
} | [
"private",
"static",
"CharSequence",
"substr",
"(",
"CharSequence",
"str",
",",
"int",
"s",
",",
"int",
"e",
")",
"{",
"return",
"(",
"s",
">=",
"e",
")",
"?",
"null",
":",
"CharBuffer",
".",
"wrap",
"(",
"str",
",",
"s",
",",
"e",
")",
";",
"}"
] | The substring method will create a copy of the substring in JDK 8 and probably newer
versions. To reduce the number of allocations we use a char buffer to return a view
with just that subset. | [
"The",
"substring",
"method",
"will",
"create",
"a",
"copy",
"of",
"the",
"substring",
"in",
"JDK",
"8",
"and",
"probably",
"newer",
"versions",
".",
"To",
"reduce",
"the",
"number",
"of",
"allocations",
"we",
"use",
"a",
"char",
"buffer",
"to",
"return",
"a",
"view",
"with",
"just",
"that",
"subset",
"."
] | 259318252770de3bad581b85adff187d8f2c6537 | https://github.com/Netflix/spectator/blob/259318252770de3bad581b85adff187d8f2c6537/spectator-ext-ipc/src/jmh/java/com/netflix/spectator/ipc/SeqServerGroup.java#L65-L67 |
28,578 | Netflix/spectator | spectator-api/src/main/java/com/netflix/spectator/api/histogram/PercentileDistributionSummary.java | PercentileDistributionSummary.builder | public static IdBuilder<Builder> builder(Registry registry) {
return new IdBuilder<Builder>(registry) {
@Override protected Builder createTypeBuilder(Id id) {
return new Builder(registry, id);
}
};
} | java | public static IdBuilder<Builder> builder(Registry registry) {
return new IdBuilder<Builder>(registry) {
@Override protected Builder createTypeBuilder(Id id) {
return new Builder(registry, id);
}
};
} | [
"public",
"static",
"IdBuilder",
"<",
"Builder",
">",
"builder",
"(",
"Registry",
"registry",
")",
"{",
"return",
"new",
"IdBuilder",
"<",
"Builder",
">",
"(",
"registry",
")",
"{",
"@",
"Override",
"protected",
"Builder",
"createTypeBuilder",
"(",
"Id",
"id",
")",
"{",
"return",
"new",
"Builder",
"(",
"registry",
",",
"id",
")",
";",
"}",
"}",
";",
"}"
] | Return a builder for configuring and retrieving and instance of a percentile distribution
summary. If the distribution summary has dynamic dimensions, then the builder can be used
with the new dimensions. If the id is the same as an existing distribution summary, then it
will update the same underlying distribution summaries in the registry. | [
"Return",
"a",
"builder",
"for",
"configuring",
"and",
"retrieving",
"and",
"instance",
"of",
"a",
"percentile",
"distribution",
"summary",
".",
"If",
"the",
"distribution",
"summary",
"has",
"dynamic",
"dimensions",
"then",
"the",
"builder",
"can",
"be",
"used",
"with",
"the",
"new",
"dimensions",
".",
"If",
"the",
"id",
"is",
"the",
"same",
"as",
"an",
"existing",
"distribution",
"summary",
"then",
"it",
"will",
"update",
"the",
"same",
"underlying",
"distribution",
"summaries",
"in",
"the",
"registry",
"."
] | 259318252770de3bad581b85adff187d8f2c6537 | https://github.com/Netflix/spectator/blob/259318252770de3bad581b85adff187d8f2c6537/spectator-api/src/main/java/com/netflix/spectator/api/histogram/PercentileDistributionSummary.java#L101-L107 |
28,579 | Netflix/spectator | spectator-api/src/main/java/com/netflix/spectator/api/histogram/PercentileDistributionSummary.java | PercentileDistributionSummary.counterFor | private Counter counterFor(int i) {
Counter c = counters.get(i);
if (c == null) {
Id counterId = id.withTags(Statistic.percentile, new BasicTag("percentile", TAG_VALUES[i]));
c = registry.counter(counterId);
counters.set(i, c);
}
return c;
} | java | private Counter counterFor(int i) {
Counter c = counters.get(i);
if (c == null) {
Id counterId = id.withTags(Statistic.percentile, new BasicTag("percentile", TAG_VALUES[i]));
c = registry.counter(counterId);
counters.set(i, c);
}
return c;
} | [
"private",
"Counter",
"counterFor",
"(",
"int",
"i",
")",
"{",
"Counter",
"c",
"=",
"counters",
".",
"get",
"(",
"i",
")",
";",
"if",
"(",
"c",
"==",
"null",
")",
"{",
"Id",
"counterId",
"=",
"id",
".",
"withTags",
"(",
"Statistic",
".",
"percentile",
",",
"new",
"BasicTag",
"(",
"\"percentile\"",
",",
"TAG_VALUES",
"[",
"i",
"]",
")",
")",
";",
"c",
"=",
"registry",
".",
"counter",
"(",
"counterId",
")",
";",
"counters",
".",
"set",
"(",
"i",
",",
"c",
")",
";",
"}",
"return",
"c",
";",
"}"
] | accessed for a distribution summary. | [
"accessed",
"for",
"a",
"distribution",
"summary",
"."
] | 259318252770de3bad581b85adff187d8f2c6537 | https://github.com/Netflix/spectator/blob/259318252770de3bad581b85adff187d8f2c6537/spectator-api/src/main/java/com/netflix/spectator/api/histogram/PercentileDistributionSummary.java#L211-L219 |
28,580 | Netflix/spectator | spectator-api/src/main/java/com/netflix/spectator/api/histogram/PercentileDistributionSummary.java | PercentileDistributionSummary.percentile | public double percentile(double p) {
long[] counts = new long[PercentileBuckets.length()];
for (int i = 0; i < counts.length; ++i) {
counts[i] = counterFor(i).count();
}
return PercentileBuckets.percentile(counts, p);
} | java | public double percentile(double p) {
long[] counts = new long[PercentileBuckets.length()];
for (int i = 0; i < counts.length; ++i) {
counts[i] = counterFor(i).count();
}
return PercentileBuckets.percentile(counts, p);
} | [
"public",
"double",
"percentile",
"(",
"double",
"p",
")",
"{",
"long",
"[",
"]",
"counts",
"=",
"new",
"long",
"[",
"PercentileBuckets",
".",
"length",
"(",
")",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"counts",
".",
"length",
";",
"++",
"i",
")",
"{",
"counts",
"[",
"i",
"]",
"=",
"counterFor",
"(",
"i",
")",
".",
"count",
"(",
")",
";",
"}",
"return",
"PercentileBuckets",
".",
"percentile",
"(",
"counts",
",",
"p",
")",
";",
"}"
] | Computes the specified percentile for this distribution summary.
@param p
Percentile to compute, value must be {@code 0.0 <= p <= 100.0}.
@return
An approximation of the {@code p}`th percentile in seconds. | [
"Computes",
"the",
"specified",
"percentile",
"for",
"this",
"distribution",
"summary",
"."
] | 259318252770de3bad581b85adff187d8f2c6537 | https://github.com/Netflix/spectator/blob/259318252770de3bad581b85adff187d8f2c6537/spectator-api/src/main/java/com/netflix/spectator/api/histogram/PercentileDistributionSummary.java#L241-L247 |
28,581 | Netflix/spectator | spectator-api/src/main/java/com/netflix/spectator/impl/AtomicDouble.java | AtomicDouble.max | public void max(double v) {
if (Double.isFinite(v)) {
double max = get();
while (isGreaterThan(v, max) && !compareAndSet(max, v)) {
max = value.get();
}
}
} | java | public void max(double v) {
if (Double.isFinite(v)) {
double max = get();
while (isGreaterThan(v, max) && !compareAndSet(max, v)) {
max = value.get();
}
}
} | [
"public",
"void",
"max",
"(",
"double",
"v",
")",
"{",
"if",
"(",
"Double",
".",
"isFinite",
"(",
"v",
")",
")",
"{",
"double",
"max",
"=",
"get",
"(",
")",
";",
"while",
"(",
"isGreaterThan",
"(",
"v",
",",
"max",
")",
"&&",
"!",
"compareAndSet",
"(",
"max",
",",
"v",
")",
")",
"{",
"max",
"=",
"value",
".",
"get",
"(",
")",
";",
"}",
"}",
"}"
] | Set the current value to the maximum of the current value or the provided value. | [
"Set",
"the",
"current",
"value",
"to",
"the",
"maximum",
"of",
"the",
"current",
"value",
"or",
"the",
"provided",
"value",
"."
] | 259318252770de3bad581b85adff187d8f2c6537 | https://github.com/Netflix/spectator/blob/259318252770de3bad581b85adff187d8f2c6537/spectator-api/src/main/java/com/netflix/spectator/impl/AtomicDouble.java#L103-L110 |
28,582 | Netflix/spectator | spectator-reg-stateless/src/main/java/com/netflix/spectator/stateless/JsonUtils.java | JsonUtils.encode | static byte[] encode(
Map<String, String> commonTags,
List<Measurement> measurements) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
JsonGenerator gen = FACTORY.createGenerator(baos);
gen.writeStartArray();
Map<String, Integer> strings = buildStringTable(gen, commonTags, measurements);
for (Measurement m : measurements) {
appendMeasurement(gen, strings, commonTags, m.id(), m.value());
}
gen.writeEndArray();
gen.close();
return baos.toByteArray();
} | java | static byte[] encode(
Map<String, String> commonTags,
List<Measurement> measurements) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
JsonGenerator gen = FACTORY.createGenerator(baos);
gen.writeStartArray();
Map<String, Integer> strings = buildStringTable(gen, commonTags, measurements);
for (Measurement m : measurements) {
appendMeasurement(gen, strings, commonTags, m.id(), m.value());
}
gen.writeEndArray();
gen.close();
return baos.toByteArray();
} | [
"static",
"byte",
"[",
"]",
"encode",
"(",
"Map",
"<",
"String",
",",
"String",
">",
"commonTags",
",",
"List",
"<",
"Measurement",
">",
"measurements",
")",
"throws",
"IOException",
"{",
"ByteArrayOutputStream",
"baos",
"=",
"new",
"ByteArrayOutputStream",
"(",
")",
";",
"JsonGenerator",
"gen",
"=",
"FACTORY",
".",
"createGenerator",
"(",
"baos",
")",
";",
"gen",
".",
"writeStartArray",
"(",
")",
";",
"Map",
"<",
"String",
",",
"Integer",
">",
"strings",
"=",
"buildStringTable",
"(",
"gen",
",",
"commonTags",
",",
"measurements",
")",
";",
"for",
"(",
"Measurement",
"m",
":",
"measurements",
")",
"{",
"appendMeasurement",
"(",
"gen",
",",
"strings",
",",
"commonTags",
",",
"m",
".",
"id",
"(",
")",
",",
"m",
".",
"value",
"(",
")",
")",
";",
"}",
"gen",
".",
"writeEndArray",
"(",
")",
";",
"gen",
".",
"close",
"(",
")",
";",
"return",
"baos",
".",
"toByteArray",
"(",
")",
";",
"}"
] | Encode the measurements to a JSON payload that can be sent to the aggregator. | [
"Encode",
"the",
"measurements",
"to",
"a",
"JSON",
"payload",
"that",
"can",
"be",
"sent",
"to",
"the",
"aggregator",
"."
] | 259318252770de3bad581b85adff187d8f2c6537 | https://github.com/Netflix/spectator/blob/259318252770de3bad581b85adff187d8f2c6537/spectator-reg-stateless/src/main/java/com/netflix/spectator/stateless/JsonUtils.java#L54-L68 |
28,583 | Netflix/spectator | spectator-ext-spark/src/main/java/com/netflix/spectator/spark/SparkValueFunction.java | SparkValueFunction.fromConfig | public static SparkValueFunction fromConfig(Config config, String key) {
return fromPatternList(config.getConfigList(key));
} | java | public static SparkValueFunction fromConfig(Config config, String key) {
return fromPatternList(config.getConfigList(key));
} | [
"public",
"static",
"SparkValueFunction",
"fromConfig",
"(",
"Config",
"config",
",",
"String",
"key",
")",
"{",
"return",
"fromPatternList",
"(",
"config",
".",
"getConfigList",
"(",
"key",
")",
")",
";",
"}"
] | Create a value function based on a config. | [
"Create",
"a",
"value",
"function",
"based",
"on",
"a",
"config",
"."
] | 259318252770de3bad581b85adff187d8f2c6537 | https://github.com/Netflix/spectator/blob/259318252770de3bad581b85adff187d8f2c6537/spectator-ext-spark/src/main/java/com/netflix/spectator/spark/SparkValueFunction.java#L40-L42 |
28,584 | Netflix/spectator | spectator-api/src/main/java/com/netflix/spectator/api/AbstractRegistry.java | AbstractRegistry.getOrCreate | @SuppressWarnings("unchecked")
protected <T extends Meter> T getOrCreate(Id id, Class<T> cls, T dflt, Function<Id, T> factory) {
try {
Preconditions.checkNotNull(id, "id");
Meter m = Utils.computeIfAbsent(meters, id, i -> compute(factory.apply(i), dflt));
if (!cls.isAssignableFrom(m.getClass())) {
logTypeError(id, cls, m.getClass());
m = dflt;
}
return (T) m;
} catch (Exception e) {
propagate(e);
return dflt;
}
} | java | @SuppressWarnings("unchecked")
protected <T extends Meter> T getOrCreate(Id id, Class<T> cls, T dflt, Function<Id, T> factory) {
try {
Preconditions.checkNotNull(id, "id");
Meter m = Utils.computeIfAbsent(meters, id, i -> compute(factory.apply(i), dflt));
if (!cls.isAssignableFrom(m.getClass())) {
logTypeError(id, cls, m.getClass());
m = dflt;
}
return (T) m;
} catch (Exception e) {
propagate(e);
return dflt;
}
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"protected",
"<",
"T",
"extends",
"Meter",
">",
"T",
"getOrCreate",
"(",
"Id",
"id",
",",
"Class",
"<",
"T",
">",
"cls",
",",
"T",
"dflt",
",",
"Function",
"<",
"Id",
",",
"T",
">",
"factory",
")",
"{",
"try",
"{",
"Preconditions",
".",
"checkNotNull",
"(",
"id",
",",
"\"id\"",
")",
";",
"Meter",
"m",
"=",
"Utils",
".",
"computeIfAbsent",
"(",
"meters",
",",
"id",
",",
"i",
"->",
"compute",
"(",
"factory",
".",
"apply",
"(",
"i",
")",
",",
"dflt",
")",
")",
";",
"if",
"(",
"!",
"cls",
".",
"isAssignableFrom",
"(",
"m",
".",
"getClass",
"(",
")",
")",
")",
"{",
"logTypeError",
"(",
"id",
",",
"cls",
",",
"m",
".",
"getClass",
"(",
")",
")",
";",
"m",
"=",
"dflt",
";",
"}",
"return",
"(",
"T",
")",
"m",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"propagate",
"(",
"e",
")",
";",
"return",
"dflt",
";",
"}",
"}"
] | Helper used to get or create an instance of a core meter type. This is mostly used
internally to this implementation, but may be useful in rare cases for creating
customizations based on a core type in a sub-class.
@param id
Identifier used to lookup this meter in the registry.
@param cls
Type of the meter.
@param dflt
Default value used if there is a failure during the lookup and it is not configured
to propagate.
@param factory
Function for creating a new instance of the meter type if one is not already available
in the registry.
@return
Instance of the meter. | [
"Helper",
"used",
"to",
"get",
"or",
"create",
"an",
"instance",
"of",
"a",
"core",
"meter",
"type",
".",
"This",
"is",
"mostly",
"used",
"internally",
"to",
"this",
"implementation",
"but",
"may",
"be",
"useful",
"in",
"rare",
"cases",
"for",
"creating",
"customizations",
"based",
"on",
"a",
"core",
"type",
"in",
"a",
"sub",
"-",
"class",
"."
] | 259318252770de3bad581b85adff187d8f2c6537 | https://github.com/Netflix/spectator/blob/259318252770de3bad581b85adff187d8f2c6537/spectator-api/src/main/java/com/netflix/spectator/api/AbstractRegistry.java#L203-L217 |
28,585 | Netflix/spectator | spectator-api/src/main/java/com/netflix/spectator/api/AbstractRegistry.java | AbstractRegistry.removeExpiredMeters | protected void removeExpiredMeters() {
int total = 0;
int expired = 0;
Iterator<Map.Entry<Id, Meter>> it = meters.entrySet().iterator();
while (it.hasNext()) {
++total;
Map.Entry<Id, Meter> entry = it.next();
Meter m = entry.getValue();
if (m.hasExpired()) {
++expired;
it.remove();
}
}
logger.debug("removed {} expired meters out of {} total", expired, total);
cleanupCachedState();
} | java | protected void removeExpiredMeters() {
int total = 0;
int expired = 0;
Iterator<Map.Entry<Id, Meter>> it = meters.entrySet().iterator();
while (it.hasNext()) {
++total;
Map.Entry<Id, Meter> entry = it.next();
Meter m = entry.getValue();
if (m.hasExpired()) {
++expired;
it.remove();
}
}
logger.debug("removed {} expired meters out of {} total", expired, total);
cleanupCachedState();
} | [
"protected",
"void",
"removeExpiredMeters",
"(",
")",
"{",
"int",
"total",
"=",
"0",
";",
"int",
"expired",
"=",
"0",
";",
"Iterator",
"<",
"Map",
".",
"Entry",
"<",
"Id",
",",
"Meter",
">",
">",
"it",
"=",
"meters",
".",
"entrySet",
"(",
")",
".",
"iterator",
"(",
")",
";",
"while",
"(",
"it",
".",
"hasNext",
"(",
")",
")",
"{",
"++",
"total",
";",
"Map",
".",
"Entry",
"<",
"Id",
",",
"Meter",
">",
"entry",
"=",
"it",
".",
"next",
"(",
")",
";",
"Meter",
"m",
"=",
"entry",
".",
"getValue",
"(",
")",
";",
"if",
"(",
"m",
".",
"hasExpired",
"(",
")",
")",
"{",
"++",
"expired",
";",
"it",
".",
"remove",
"(",
")",
";",
"}",
"}",
"logger",
".",
"debug",
"(",
"\"removed {} expired meters out of {} total\"",
",",
"expired",
",",
"total",
")",
";",
"cleanupCachedState",
"(",
")",
";",
"}"
] | Can be called by sub-classes to remove expired meters from the internal map.
The SwapMeter types that are returned will lookup a new copy on the next access. | [
"Can",
"be",
"called",
"by",
"sub",
"-",
"classes",
"to",
"remove",
"expired",
"meters",
"from",
"the",
"internal",
"map",
".",
"The",
"SwapMeter",
"types",
"that",
"are",
"returned",
"will",
"lookup",
"a",
"new",
"copy",
"on",
"the",
"next",
"access",
"."
] | 259318252770de3bad581b85adff187d8f2c6537 | https://github.com/Netflix/spectator/blob/259318252770de3bad581b85adff187d8f2c6537/spectator-api/src/main/java/com/netflix/spectator/api/AbstractRegistry.java#L231-L246 |
28,586 | Netflix/spectator | spectator-api/src/main/java/com/netflix/spectator/api/AbstractRegistry.java | AbstractRegistry.cleanupCachedState | private void cleanupCachedState() {
int total = 0;
int expired = 0;
Iterator<Map.Entry<Id, Object>> it = state.entrySet().iterator();
while (it.hasNext()) {
++total;
Map.Entry<Id, Object> entry = it.next();
Object obj = entry.getValue();
if (obj instanceof Meter && ((Meter) obj).hasExpired()) {
++expired;
it.remove();
}
}
logger.debug("removed {} expired entries from cache out of {} total", expired, total);
} | java | private void cleanupCachedState() {
int total = 0;
int expired = 0;
Iterator<Map.Entry<Id, Object>> it = state.entrySet().iterator();
while (it.hasNext()) {
++total;
Map.Entry<Id, Object> entry = it.next();
Object obj = entry.getValue();
if (obj instanceof Meter && ((Meter) obj).hasExpired()) {
++expired;
it.remove();
}
}
logger.debug("removed {} expired entries from cache out of {} total", expired, total);
} | [
"private",
"void",
"cleanupCachedState",
"(",
")",
"{",
"int",
"total",
"=",
"0",
";",
"int",
"expired",
"=",
"0",
";",
"Iterator",
"<",
"Map",
".",
"Entry",
"<",
"Id",
",",
"Object",
">",
">",
"it",
"=",
"state",
".",
"entrySet",
"(",
")",
".",
"iterator",
"(",
")",
";",
"while",
"(",
"it",
".",
"hasNext",
"(",
")",
")",
"{",
"++",
"total",
";",
"Map",
".",
"Entry",
"<",
"Id",
",",
"Object",
">",
"entry",
"=",
"it",
".",
"next",
"(",
")",
";",
"Object",
"obj",
"=",
"entry",
".",
"getValue",
"(",
")",
";",
"if",
"(",
"obj",
"instanceof",
"Meter",
"&&",
"(",
"(",
"Meter",
")",
"obj",
")",
".",
"hasExpired",
"(",
")",
")",
"{",
"++",
"expired",
";",
"it",
".",
"remove",
"(",
")",
";",
"}",
"}",
"logger",
".",
"debug",
"(",
"\"removed {} expired entries from cache out of {} total\"",
",",
"expired",
",",
"total",
")",
";",
"}"
] | Cleanup any expired meter patterns stored in the state. It should only be used as
a cache so the entry should get recreated if needed. | [
"Cleanup",
"any",
"expired",
"meter",
"patterns",
"stored",
"in",
"the",
"state",
".",
"It",
"should",
"only",
"be",
"used",
"as",
"a",
"cache",
"so",
"the",
"entry",
"should",
"get",
"recreated",
"if",
"needed",
"."
] | 259318252770de3bad581b85adff187d8f2c6537 | https://github.com/Netflix/spectator/blob/259318252770de3bad581b85adff187d8f2c6537/spectator-api/src/main/java/com/netflix/spectator/api/AbstractRegistry.java#L252-L266 |
28,587 | Netflix/spectator | spectator-ext-sandbox/src/main/java/com/netflix/spectator/sandbox/BucketDistributionSummary.java | BucketDistributionSummary.get | public static BucketDistributionSummary get(Id id, BucketFunction f) {
return get(Spectator.globalRegistry(), id, f);
} | java | public static BucketDistributionSummary get(Id id, BucketFunction f) {
return get(Spectator.globalRegistry(), id, f);
} | [
"public",
"static",
"BucketDistributionSummary",
"get",
"(",
"Id",
"id",
",",
"BucketFunction",
"f",
")",
"{",
"return",
"get",
"(",
"Spectator",
".",
"globalRegistry",
"(",
")",
",",
"id",
",",
"f",
")",
";",
"}"
] | Creates a distribution summary object that manages a set of distribution summaries based on
the bucket function supplied. Calling record will be mapped to the record on the appropriate
distribution summary.
@param id
Identifier for the metric being registered.
@param f
Function to map values to buckets.
@return
Distribution summary that manages sub-counters based on the bucket function. | [
"Creates",
"a",
"distribution",
"summary",
"object",
"that",
"manages",
"a",
"set",
"of",
"distribution",
"summaries",
"based",
"on",
"the",
"bucket",
"function",
"supplied",
".",
"Calling",
"record",
"will",
"be",
"mapped",
"to",
"the",
"record",
"on",
"the",
"appropriate",
"distribution",
"summary",
"."
] | 259318252770de3bad581b85adff187d8f2c6537 | https://github.com/Netflix/spectator/blob/259318252770de3bad581b85adff187d8f2c6537/spectator-ext-sandbox/src/main/java/com/netflix/spectator/sandbox/BucketDistributionSummary.java#L44-L46 |
28,588 | Netflix/spectator | spectator-ext-ipcservlet/src/main/java/com/netflix/spectator/ipcservlet/ServletPathHack.java | ServletPathHack.getServletPath | static String getServletPath(HttpServletRequest request) {
String servletPath = request.getServletPath();
if (hackWorks && PACKAGE.equals(request.getClass().getPackage().getName())) {
try {
Object outer = get(request, "this$0");
Object servletPipeline = get(outer, "servletPipeline");
Object servletDefs = get(servletPipeline, "servletDefinitions");
int length = Array.getLength(servletDefs);
for (int i = 0; i < length; ++i) {
Object pattern = get(Array.get(servletDefs, i), "patternMatcher");
if (matches(pattern, servletPath)) {
servletPath = extractPath(pattern, servletPath);
break;
}
}
} catch (Exception e) {
hackWorks = false;
}
}
return servletPath;
} | java | static String getServletPath(HttpServletRequest request) {
String servletPath = request.getServletPath();
if (hackWorks && PACKAGE.equals(request.getClass().getPackage().getName())) {
try {
Object outer = get(request, "this$0");
Object servletPipeline = get(outer, "servletPipeline");
Object servletDefs = get(servletPipeline, "servletDefinitions");
int length = Array.getLength(servletDefs);
for (int i = 0; i < length; ++i) {
Object pattern = get(Array.get(servletDefs, i), "patternMatcher");
if (matches(pattern, servletPath)) {
servletPath = extractPath(pattern, servletPath);
break;
}
}
} catch (Exception e) {
hackWorks = false;
}
}
return servletPath;
} | [
"static",
"String",
"getServletPath",
"(",
"HttpServletRequest",
"request",
")",
"{",
"String",
"servletPath",
"=",
"request",
".",
"getServletPath",
"(",
")",
";",
"if",
"(",
"hackWorks",
"&&",
"PACKAGE",
".",
"equals",
"(",
"request",
".",
"getClass",
"(",
")",
".",
"getPackage",
"(",
")",
".",
"getName",
"(",
")",
")",
")",
"{",
"try",
"{",
"Object",
"outer",
"=",
"get",
"(",
"request",
",",
"\"this$0\"",
")",
";",
"Object",
"servletPipeline",
"=",
"get",
"(",
"outer",
",",
"\"servletPipeline\"",
")",
";",
"Object",
"servletDefs",
"=",
"get",
"(",
"servletPipeline",
",",
"\"servletDefinitions\"",
")",
";",
"int",
"length",
"=",
"Array",
".",
"getLength",
"(",
"servletDefs",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"length",
";",
"++",
"i",
")",
"{",
"Object",
"pattern",
"=",
"get",
"(",
"Array",
".",
"get",
"(",
"servletDefs",
",",
"i",
")",
",",
"\"patternMatcher\"",
")",
";",
"if",
"(",
"matches",
"(",
"pattern",
",",
"servletPath",
")",
")",
"{",
"servletPath",
"=",
"extractPath",
"(",
"pattern",
",",
"servletPath",
")",
";",
"break",
";",
"}",
"}",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"hackWorks",
"=",
"false",
";",
"}",
"}",
"return",
"servletPath",
";",
"}"
] | Helper to get the servlet path for the request. | [
"Helper",
"to",
"get",
"the",
"servlet",
"path",
"for",
"the",
"request",
"."
] | 259318252770de3bad581b85adff187d8f2c6537 | https://github.com/Netflix/spectator/blob/259318252770de3bad581b85adff187d8f2c6537/spectator-ext-ipcservlet/src/main/java/com/netflix/spectator/ipcservlet/ServletPathHack.java#L56-L76 |
28,589 | Netflix/spectator | spectator-api/src/main/java/com/netflix/spectator/api/patterns/TagsBuilder.java | TagsBuilder.withTag | public <E extends Enum<E>> T withTag(String k, Enum<E> v) {
return withTag(k, v.name());
} | java | public <E extends Enum<E>> T withTag(String k, Enum<E> v) {
return withTag(k, v.name());
} | [
"public",
"<",
"E",
"extends",
"Enum",
"<",
"E",
">",
">",
"T",
"withTag",
"(",
"String",
"k",
",",
"Enum",
"<",
"E",
">",
"v",
")",
"{",
"return",
"withTag",
"(",
"k",
",",
"v",
".",
"name",
"(",
")",
")",
";",
"}"
] | Add an additional tag value based on the name of the enum. | [
"Add",
"an",
"additional",
"tag",
"value",
"based",
"on",
"the",
"name",
"of",
"the",
"enum",
"."
] | 259318252770de3bad581b85adff187d8f2c6537 | https://github.com/Netflix/spectator/blob/259318252770de3bad581b85adff187d8f2c6537/spectator-api/src/main/java/com/netflix/spectator/api/patterns/TagsBuilder.java#L55-L57 |
28,590 | Netflix/spectator | spectator-ext-ipc/src/main/java/com/netflix/spectator/ipc/IpcLogEntry.java | IpcLogEntry.withException | public IpcLogEntry withException(Throwable exception) {
this.exception = exception;
if (statusDetail == null) {
statusDetail = exception.getClass().getSimpleName();
}
if (status == null) {
status = IpcStatus.forException(exception);
}
return this;
} | java | public IpcLogEntry withException(Throwable exception) {
this.exception = exception;
if (statusDetail == null) {
statusDetail = exception.getClass().getSimpleName();
}
if (status == null) {
status = IpcStatus.forException(exception);
}
return this;
} | [
"public",
"IpcLogEntry",
"withException",
"(",
"Throwable",
"exception",
")",
"{",
"this",
".",
"exception",
"=",
"exception",
";",
"if",
"(",
"statusDetail",
"==",
"null",
")",
"{",
"statusDetail",
"=",
"exception",
".",
"getClass",
"(",
")",
".",
"getSimpleName",
"(",
")",
";",
"}",
"if",
"(",
"status",
"==",
"null",
")",
"{",
"status",
"=",
"IpcStatus",
".",
"forException",
"(",
"exception",
")",
";",
"}",
"return",
"this",
";",
"}"
] | Set the exception that was thrown while trying to execute the request. This will be
logged and can be used to fill in the error reason. | [
"Set",
"the",
"exception",
"that",
"was",
"thrown",
"while",
"trying",
"to",
"execute",
"the",
"request",
".",
"This",
"will",
"be",
"logged",
"and",
"can",
"be",
"used",
"to",
"fill",
"in",
"the",
"error",
"reason",
"."
] | 259318252770de3bad581b85adff187d8f2c6537 | https://github.com/Netflix/spectator/blob/259318252770de3bad581b85adff187d8f2c6537/spectator-ext-ipc/src/main/java/com/netflix/spectator/ipc/IpcLogEntry.java#L253-L262 |
28,591 | Netflix/spectator | spectator-ext-ipc/src/main/java/com/netflix/spectator/ipc/IpcLogEntry.java | IpcLogEntry.withUri | public IpcLogEntry withUri(String uri, String path) {
this.uri = uri;
this.path = path;
return this;
} | java | public IpcLogEntry withUri(String uri, String path) {
this.uri = uri;
this.path = path;
return this;
} | [
"public",
"IpcLogEntry",
"withUri",
"(",
"String",
"uri",
",",
"String",
"path",
")",
"{",
"this",
".",
"uri",
"=",
"uri",
";",
"this",
".",
"path",
"=",
"path",
";",
"return",
"this",
";",
"}"
] | Set the URI and path for the request. | [
"Set",
"the",
"URI",
"and",
"path",
"for",
"the",
"request",
"."
] | 259318252770de3bad581b85adff187d8f2c6537 | https://github.com/Netflix/spectator/blob/259318252770de3bad581b85adff187d8f2c6537/spectator-ext-ipc/src/main/java/com/netflix/spectator/ipc/IpcLogEntry.java#L484-L488 |
28,592 | Netflix/spectator | spectator-ext-ipc/src/main/java/com/netflix/spectator/ipc/IpcLogEntry.java | IpcLogEntry.log | public void log() {
if (logger != null) {
if (registry != null) {
if (isClient()) {
recordClientMetrics();
} else {
recordServerMetrics();
}
}
if (inflightId != null) {
logger.inflightRequests(inflightId).decrementAndGet();
}
logger.log(this);
} else {
reset();
}
} | java | public void log() {
if (logger != null) {
if (registry != null) {
if (isClient()) {
recordClientMetrics();
} else {
recordServerMetrics();
}
}
if (inflightId != null) {
logger.inflightRequests(inflightId).decrementAndGet();
}
logger.log(this);
} else {
reset();
}
} | [
"public",
"void",
"log",
"(",
")",
"{",
"if",
"(",
"logger",
"!=",
"null",
")",
"{",
"if",
"(",
"registry",
"!=",
"null",
")",
"{",
"if",
"(",
"isClient",
"(",
")",
")",
"{",
"recordClientMetrics",
"(",
")",
";",
"}",
"else",
"{",
"recordServerMetrics",
"(",
")",
";",
"}",
"}",
"if",
"(",
"inflightId",
"!=",
"null",
")",
"{",
"logger",
".",
"inflightRequests",
"(",
"inflightId",
")",
".",
"decrementAndGet",
"(",
")",
";",
"}",
"logger",
".",
"log",
"(",
"this",
")",
";",
"}",
"else",
"{",
"reset",
"(",
")",
";",
"}",
"}"
] | Log the request. This entry will potentially be reused after this is called. The user
should not attempt any further modifications to the state of this entry. | [
"Log",
"the",
"request",
".",
"This",
"entry",
"will",
"potentially",
"be",
"reused",
"after",
"this",
"is",
"called",
".",
"The",
"user",
"should",
"not",
"attempt",
"any",
"further",
"modifications",
"to",
"the",
"state",
"of",
"this",
"entry",
"."
] | 259318252770de3bad581b85adff187d8f2c6537 | https://github.com/Netflix/spectator/blob/259318252770de3bad581b85adff187d8f2c6537/spectator-ext-ipc/src/main/java/com/netflix/spectator/ipc/IpcLogEntry.java#L707-L724 |
28,593 | Netflix/spectator | spectator-ext-ipc/src/main/java/com/netflix/spectator/ipc/IpcLogEntry.java | IpcLogEntry.reset | void reset() {
logger = null;
level = Level.DEBUG;
marker = null;
startTime = -1L;
startNanos = -1L;
latency = -1L;
owner = null;
result = null;
protocol = null;
status = null;
statusDetail = null;
exception = null;
attempt = null;
attemptFinal = null;
vip = null;
endpoint = null;
clientRegion = null;
clientZone = null;
clientApp = null;
clientCluster = null;
clientAsg = null;
clientNode = null;
serverRegion = null;
serverZone = null;
serverApp = null;
serverCluster = null;
serverAsg = null;
serverNode = null;
httpMethod = null;
httpStatus = -1;
uri = null;
path = null;
requestHeaders.clear();
responseHeaders.clear();
remoteAddress = null;
remotePort = -1;
additionalTags.clear();
builder.delete(0, builder.length());
inflightId = null;
} | java | void reset() {
logger = null;
level = Level.DEBUG;
marker = null;
startTime = -1L;
startNanos = -1L;
latency = -1L;
owner = null;
result = null;
protocol = null;
status = null;
statusDetail = null;
exception = null;
attempt = null;
attemptFinal = null;
vip = null;
endpoint = null;
clientRegion = null;
clientZone = null;
clientApp = null;
clientCluster = null;
clientAsg = null;
clientNode = null;
serverRegion = null;
serverZone = null;
serverApp = null;
serverCluster = null;
serverAsg = null;
serverNode = null;
httpMethod = null;
httpStatus = -1;
uri = null;
path = null;
requestHeaders.clear();
responseHeaders.clear();
remoteAddress = null;
remotePort = -1;
additionalTags.clear();
builder.delete(0, builder.length());
inflightId = null;
} | [
"void",
"reset",
"(",
")",
"{",
"logger",
"=",
"null",
";",
"level",
"=",
"Level",
".",
"DEBUG",
";",
"marker",
"=",
"null",
";",
"startTime",
"=",
"-",
"1L",
";",
"startNanos",
"=",
"-",
"1L",
";",
"latency",
"=",
"-",
"1L",
";",
"owner",
"=",
"null",
";",
"result",
"=",
"null",
";",
"protocol",
"=",
"null",
";",
"status",
"=",
"null",
";",
"statusDetail",
"=",
"null",
";",
"exception",
"=",
"null",
";",
"attempt",
"=",
"null",
";",
"attemptFinal",
"=",
"null",
";",
"vip",
"=",
"null",
";",
"endpoint",
"=",
"null",
";",
"clientRegion",
"=",
"null",
";",
"clientZone",
"=",
"null",
";",
"clientApp",
"=",
"null",
";",
"clientCluster",
"=",
"null",
";",
"clientAsg",
"=",
"null",
";",
"clientNode",
"=",
"null",
";",
"serverRegion",
"=",
"null",
";",
"serverZone",
"=",
"null",
";",
"serverApp",
"=",
"null",
";",
"serverCluster",
"=",
"null",
";",
"serverAsg",
"=",
"null",
";",
"serverNode",
"=",
"null",
";",
"httpMethod",
"=",
"null",
";",
"httpStatus",
"=",
"-",
"1",
";",
"uri",
"=",
"null",
";",
"path",
"=",
"null",
";",
"requestHeaders",
".",
"clear",
"(",
")",
";",
"responseHeaders",
".",
"clear",
"(",
")",
";",
"remoteAddress",
"=",
"null",
";",
"remotePort",
"=",
"-",
"1",
";",
"additionalTags",
".",
"clear",
"(",
")",
";",
"builder",
".",
"delete",
"(",
"0",
",",
"builder",
".",
"length",
"(",
")",
")",
";",
"inflightId",
"=",
"null",
";",
"}"
] | Resets this log entry so the instance can be reused. This helps to reduce allocations. | [
"Resets",
"this",
"log",
"entry",
"so",
"the",
"instance",
"can",
"be",
"reused",
".",
"This",
"helps",
"to",
"reduce",
"allocations",
"."
] | 259318252770de3bad581b85adff187d8f2c6537 | https://github.com/Netflix/spectator/blob/259318252770de3bad581b85adff187d8f2c6537/spectator-ext-ipc/src/main/java/com/netflix/spectator/ipc/IpcLogEntry.java#L828-L868 |
28,594 | Netflix/spectator | spectator-ext-ipc/src/main/java/com/netflix/spectator/ipc/IpcLogEntry.java | IpcLogEntry.resetForRetry | void resetForRetry() {
startTime = -1L;
startNanos = -1L;
latency = -1L;
result = null;
status = null;
statusDetail = null;
exception = null;
attempt = null;
attemptFinal = null;
vip = null;
serverRegion = null;
serverZone = null;
serverApp = null;
serverCluster = null;
serverAsg = null;
serverNode = null;
httpStatus = -1;
requestHeaders.clear();
responseHeaders.clear();
remoteAddress = null;
remotePort = -1;
builder.delete(0, builder.length());
inflightId = null;
} | java | void resetForRetry() {
startTime = -1L;
startNanos = -1L;
latency = -1L;
result = null;
status = null;
statusDetail = null;
exception = null;
attempt = null;
attemptFinal = null;
vip = null;
serverRegion = null;
serverZone = null;
serverApp = null;
serverCluster = null;
serverAsg = null;
serverNode = null;
httpStatus = -1;
requestHeaders.clear();
responseHeaders.clear();
remoteAddress = null;
remotePort = -1;
builder.delete(0, builder.length());
inflightId = null;
} | [
"void",
"resetForRetry",
"(",
")",
"{",
"startTime",
"=",
"-",
"1L",
";",
"startNanos",
"=",
"-",
"1L",
";",
"latency",
"=",
"-",
"1L",
";",
"result",
"=",
"null",
";",
"status",
"=",
"null",
";",
"statusDetail",
"=",
"null",
";",
"exception",
"=",
"null",
";",
"attempt",
"=",
"null",
";",
"attemptFinal",
"=",
"null",
";",
"vip",
"=",
"null",
";",
"serverRegion",
"=",
"null",
";",
"serverZone",
"=",
"null",
";",
"serverApp",
"=",
"null",
";",
"serverCluster",
"=",
"null",
";",
"serverAsg",
"=",
"null",
";",
"serverNode",
"=",
"null",
";",
"httpStatus",
"=",
"-",
"1",
";",
"requestHeaders",
".",
"clear",
"(",
")",
";",
"responseHeaders",
".",
"clear",
"(",
")",
";",
"remoteAddress",
"=",
"null",
";",
"remotePort",
"=",
"-",
"1",
";",
"builder",
".",
"delete",
"(",
"0",
",",
"builder",
".",
"length",
"(",
")",
")",
";",
"inflightId",
"=",
"null",
";",
"}"
] | Partially reset this log entry so it can be used for another request attempt. Any
attributes that can change for a given request need to be cleared. | [
"Partially",
"reset",
"this",
"log",
"entry",
"so",
"it",
"can",
"be",
"used",
"for",
"another",
"request",
"attempt",
".",
"Any",
"attributes",
"that",
"can",
"change",
"for",
"a",
"given",
"request",
"need",
"to",
"be",
"cleared",
"."
] | 259318252770de3bad581b85adff187d8f2c6537 | https://github.com/Netflix/spectator/blob/259318252770de3bad581b85adff187d8f2c6537/spectator-ext-ipc/src/main/java/com/netflix/spectator/ipc/IpcLogEntry.java#L874-L898 |
28,595 | Netflix/spectator | spectator-api/src/main/java/com/netflix/spectator/impl/matcher/PatternUtils.java | PatternUtils.compile | public static PatternMatcher compile(String pattern) {
String p = pattern;
boolean ignoreCase = false;
if (p.startsWith("(?i)")) {
ignoreCase = true;
p = pattern.substring(4);
}
if (p.length() > 0) {
p = "^.*(" + p + ").*$";
}
Parser parser = new Parser(PatternUtils.expandEscapedChars(p));
Matcher m = Optimizer.optimize(parser.parse());
return ignoreCase ? m.ignoreCase() : m;
} | java | public static PatternMatcher compile(String pattern) {
String p = pattern;
boolean ignoreCase = false;
if (p.startsWith("(?i)")) {
ignoreCase = true;
p = pattern.substring(4);
}
if (p.length() > 0) {
p = "^.*(" + p + ").*$";
}
Parser parser = new Parser(PatternUtils.expandEscapedChars(p));
Matcher m = Optimizer.optimize(parser.parse());
return ignoreCase ? m.ignoreCase() : m;
} | [
"public",
"static",
"PatternMatcher",
"compile",
"(",
"String",
"pattern",
")",
"{",
"String",
"p",
"=",
"pattern",
";",
"boolean",
"ignoreCase",
"=",
"false",
";",
"if",
"(",
"p",
".",
"startsWith",
"(",
"\"(?i)\"",
")",
")",
"{",
"ignoreCase",
"=",
"true",
";",
"p",
"=",
"pattern",
".",
"substring",
"(",
"4",
")",
";",
"}",
"if",
"(",
"p",
".",
"length",
"(",
")",
">",
"0",
")",
"{",
"p",
"=",
"\"^.*(\"",
"+",
"p",
"+",
"\").*$\"",
";",
"}",
"Parser",
"parser",
"=",
"new",
"Parser",
"(",
"PatternUtils",
".",
"expandEscapedChars",
"(",
"p",
")",
")",
";",
"Matcher",
"m",
"=",
"Optimizer",
".",
"optimize",
"(",
"parser",
".",
"parse",
"(",
")",
")",
";",
"return",
"ignoreCase",
"?",
"m",
".",
"ignoreCase",
"(",
")",
":",
"m",
";",
"}"
] | Compile a pattern string and return a matcher that can be used to check if string values
match the pattern. Pattern matchers are can be reused many times and are thread safe. | [
"Compile",
"a",
"pattern",
"string",
"and",
"return",
"a",
"matcher",
"that",
"can",
"be",
"used",
"to",
"check",
"if",
"string",
"values",
"match",
"the",
"pattern",
".",
"Pattern",
"matchers",
"are",
"can",
"be",
"reused",
"many",
"times",
"and",
"are",
"thread",
"safe",
"."
] | 259318252770de3bad581b85adff187d8f2c6537 | https://github.com/Netflix/spectator/blob/259318252770de3bad581b85adff187d8f2c6537/spectator-api/src/main/java/com/netflix/spectator/impl/matcher/PatternUtils.java#L37-L50 |
28,596 | Netflix/spectator | spectator-api/src/main/java/com/netflix/spectator/impl/matcher/PatternUtils.java | PatternUtils.error | static IllegalArgumentException error(String message, String str, int pos) {
return new IllegalArgumentException(message + "\n" + context(str, pos));
} | java | static IllegalArgumentException error(String message, String str, int pos) {
return new IllegalArgumentException(message + "\n" + context(str, pos));
} | [
"static",
"IllegalArgumentException",
"error",
"(",
"String",
"message",
",",
"String",
"str",
",",
"int",
"pos",
")",
"{",
"return",
"new",
"IllegalArgumentException",
"(",
"message",
"+",
"\"\\n\"",
"+",
"context",
"(",
"str",
",",
"pos",
")",
")",
";",
"}"
] | Create an IllegalArgumentException with a message including context based
on the position. | [
"Create",
"an",
"IllegalArgumentException",
"with",
"a",
"message",
"including",
"context",
"based",
"on",
"the",
"position",
"."
] | 259318252770de3bad581b85adff187d8f2c6537 | https://github.com/Netflix/spectator/blob/259318252770de3bad581b85adff187d8f2c6537/spectator-api/src/main/java/com/netflix/spectator/impl/matcher/PatternUtils.java#L65-L67 |
28,597 | Netflix/spectator | spectator-api/src/main/java/com/netflix/spectator/impl/matcher/PatternUtils.java | PatternUtils.unsupported | static UnsupportedOperationException unsupported(String message, String str, int pos) {
return new UnsupportedOperationException(message + "\n" + context(str, pos));
} | java | static UnsupportedOperationException unsupported(String message, String str, int pos) {
return new UnsupportedOperationException(message + "\n" + context(str, pos));
} | [
"static",
"UnsupportedOperationException",
"unsupported",
"(",
"String",
"message",
",",
"String",
"str",
",",
"int",
"pos",
")",
"{",
"return",
"new",
"UnsupportedOperationException",
"(",
"message",
"+",
"\"\\n\"",
"+",
"context",
"(",
"str",
",",
"pos",
")",
")",
";",
"}"
] | Create an UnsupportedOperationException with a message including context based
on the position. | [
"Create",
"an",
"UnsupportedOperationException",
"with",
"a",
"message",
"including",
"context",
"based",
"on",
"the",
"position",
"."
] | 259318252770de3bad581b85adff187d8f2c6537 | https://github.com/Netflix/spectator/blob/259318252770de3bad581b85adff187d8f2c6537/spectator-api/src/main/java/com/netflix/spectator/impl/matcher/PatternUtils.java#L73-L75 |
28,598 | Netflix/spectator | spectator-api/src/main/java/com/netflix/spectator/impl/matcher/PatternUtils.java | PatternUtils.expandEscapedChars | @SuppressWarnings("PMD.NcssCount")
static String expandEscapedChars(String str) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < str.length(); ++i) {
char c = str.charAt(i);
if (c == '\\') {
++i;
if (i >= str.length()) {
throw error("dangling escape", str, i);
}
c = str.charAt(i);
switch (c) {
case 't': builder.append('\t'); break;
case 'n': builder.append('\n'); break;
case 'r': builder.append('\r'); break;
case 'f': builder.append('\f'); break;
case 'a': builder.append('\u0007'); break;
case 'e': builder.append('\u001B'); break;
case '0':
int numDigits = 0;
for (int j = i + 1; j < Math.min(i + 4, str.length()); ++j) {
c = str.charAt(j);
if (c >= '0' && c <= '7') {
++numDigits;
} else {
break;
}
}
if (numDigits < 1 || numDigits > 3) {
throw error("invalid octal escape sequence", str, i);
}
c = parse(str.substring(i + 1, i + numDigits + 1), 8, "octal", str, i);
builder.append(c);
i += numDigits;
break;
case 'x':
if (i + 3 > str.length()) {
throw error("invalid hexadecimal escape sequence", str, i);
}
c = parse(str.substring(i + 1, i + 3), 16, "hexadecimal", str, i);
builder.append(c);
i += 2;
break;
case 'u':
if (i + 5 > str.length()) {
throw error("invalid unicode escape sequence", str, i);
}
c = parse(str.substring(i + 1, i + 5), 16, "unicode", str, i);
builder.append(c);
i += 4;
break;
default:
builder.append('\\').append(c);
break;
}
} else {
builder.append(c);
}
}
return builder.toString();
} | java | @SuppressWarnings("PMD.NcssCount")
static String expandEscapedChars(String str) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < str.length(); ++i) {
char c = str.charAt(i);
if (c == '\\') {
++i;
if (i >= str.length()) {
throw error("dangling escape", str, i);
}
c = str.charAt(i);
switch (c) {
case 't': builder.append('\t'); break;
case 'n': builder.append('\n'); break;
case 'r': builder.append('\r'); break;
case 'f': builder.append('\f'); break;
case 'a': builder.append('\u0007'); break;
case 'e': builder.append('\u001B'); break;
case '0':
int numDigits = 0;
for (int j = i + 1; j < Math.min(i + 4, str.length()); ++j) {
c = str.charAt(j);
if (c >= '0' && c <= '7') {
++numDigits;
} else {
break;
}
}
if (numDigits < 1 || numDigits > 3) {
throw error("invalid octal escape sequence", str, i);
}
c = parse(str.substring(i + 1, i + numDigits + 1), 8, "octal", str, i);
builder.append(c);
i += numDigits;
break;
case 'x':
if (i + 3 > str.length()) {
throw error("invalid hexadecimal escape sequence", str, i);
}
c = parse(str.substring(i + 1, i + 3), 16, "hexadecimal", str, i);
builder.append(c);
i += 2;
break;
case 'u':
if (i + 5 > str.length()) {
throw error("invalid unicode escape sequence", str, i);
}
c = parse(str.substring(i + 1, i + 5), 16, "unicode", str, i);
builder.append(c);
i += 4;
break;
default:
builder.append('\\').append(c);
break;
}
} else {
builder.append(c);
}
}
return builder.toString();
} | [
"@",
"SuppressWarnings",
"(",
"\"PMD.NcssCount\"",
")",
"static",
"String",
"expandEscapedChars",
"(",
"String",
"str",
")",
"{",
"StringBuilder",
"builder",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"str",
".",
"length",
"(",
")",
";",
"++",
"i",
")",
"{",
"char",
"c",
"=",
"str",
".",
"charAt",
"(",
"i",
")",
";",
"if",
"(",
"c",
"==",
"'",
"'",
")",
"{",
"++",
"i",
";",
"if",
"(",
"i",
">=",
"str",
".",
"length",
"(",
")",
")",
"{",
"throw",
"error",
"(",
"\"dangling escape\"",
",",
"str",
",",
"i",
")",
";",
"}",
"c",
"=",
"str",
".",
"charAt",
"(",
"i",
")",
";",
"switch",
"(",
"c",
")",
"{",
"case",
"'",
"'",
":",
"builder",
".",
"append",
"(",
"'",
"'",
")",
";",
"break",
";",
"case",
"'",
"'",
":",
"builder",
".",
"append",
"(",
"'",
"'",
")",
";",
"break",
";",
"case",
"'",
"'",
":",
"builder",
".",
"append",
"(",
"'",
"'",
")",
";",
"break",
";",
"case",
"'",
"'",
":",
"builder",
".",
"append",
"(",
"'",
"'",
")",
";",
"break",
";",
"case",
"'",
"'",
":",
"builder",
".",
"append",
"(",
"'",
"'",
")",
";",
"break",
";",
"case",
"'",
"'",
":",
"builder",
".",
"append",
"(",
"'",
"'",
")",
";",
"break",
";",
"case",
"'",
"'",
":",
"int",
"numDigits",
"=",
"0",
";",
"for",
"(",
"int",
"j",
"=",
"i",
"+",
"1",
";",
"j",
"<",
"Math",
".",
"min",
"(",
"i",
"+",
"4",
",",
"str",
".",
"length",
"(",
")",
")",
";",
"++",
"j",
")",
"{",
"c",
"=",
"str",
".",
"charAt",
"(",
"j",
")",
";",
"if",
"(",
"c",
">=",
"'",
"'",
"&&",
"c",
"<=",
"'",
"'",
")",
"{",
"++",
"numDigits",
";",
"}",
"else",
"{",
"break",
";",
"}",
"}",
"if",
"(",
"numDigits",
"<",
"1",
"||",
"numDigits",
">",
"3",
")",
"{",
"throw",
"error",
"(",
"\"invalid octal escape sequence\"",
",",
"str",
",",
"i",
")",
";",
"}",
"c",
"=",
"parse",
"(",
"str",
".",
"substring",
"(",
"i",
"+",
"1",
",",
"i",
"+",
"numDigits",
"+",
"1",
")",
",",
"8",
",",
"\"octal\"",
",",
"str",
",",
"i",
")",
";",
"builder",
".",
"append",
"(",
"c",
")",
";",
"i",
"+=",
"numDigits",
";",
"break",
";",
"case",
"'",
"'",
":",
"if",
"(",
"i",
"+",
"3",
">",
"str",
".",
"length",
"(",
")",
")",
"{",
"throw",
"error",
"(",
"\"invalid hexadecimal escape sequence\"",
",",
"str",
",",
"i",
")",
";",
"}",
"c",
"=",
"parse",
"(",
"str",
".",
"substring",
"(",
"i",
"+",
"1",
",",
"i",
"+",
"3",
")",
",",
"16",
",",
"\"hexadecimal\"",
",",
"str",
",",
"i",
")",
";",
"builder",
".",
"append",
"(",
"c",
")",
";",
"i",
"+=",
"2",
";",
"break",
";",
"case",
"'",
"'",
":",
"if",
"(",
"i",
"+",
"5",
">",
"str",
".",
"length",
"(",
")",
")",
"{",
"throw",
"error",
"(",
"\"invalid unicode escape sequence\"",
",",
"str",
",",
"i",
")",
";",
"}",
"c",
"=",
"parse",
"(",
"str",
".",
"substring",
"(",
"i",
"+",
"1",
",",
"i",
"+",
"5",
")",
",",
"16",
",",
"\"unicode\"",
",",
"str",
",",
"i",
")",
";",
"builder",
".",
"append",
"(",
"c",
")",
";",
"i",
"+=",
"4",
";",
"break",
";",
"default",
":",
"builder",
".",
"append",
"(",
"'",
"'",
")",
".",
"append",
"(",
"c",
")",
";",
"break",
";",
"}",
"}",
"else",
"{",
"builder",
".",
"append",
"(",
"c",
")",
";",
"}",
"}",
"return",
"builder",
".",
"toString",
"(",
")",
";",
"}"
] | Expand escaped characters. Escapes that are needed for structural elements of the
pattern will not be expanded. | [
"Expand",
"escaped",
"characters",
".",
"Escapes",
"that",
"are",
"needed",
"for",
"structural",
"elements",
"of",
"the",
"pattern",
"will",
"not",
"be",
"expanded",
"."
] | 259318252770de3bad581b85adff187d8f2c6537 | https://github.com/Netflix/spectator/blob/259318252770de3bad581b85adff187d8f2c6537/spectator-api/src/main/java/com/netflix/spectator/impl/matcher/PatternUtils.java#L90-L150 |
28,599 | Netflix/spectator | spectator-api/src/main/java/com/netflix/spectator/impl/matcher/PatternUtils.java | PatternUtils.escape | @SuppressWarnings("PMD.NcssCount")
static String escape(String str) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < str.length(); ++i) {
char c = str.charAt(i);
switch (c) {
case '\t': builder.append("\\t"); break;
case '\n': builder.append("\\n"); break;
case '\r': builder.append("\\r"); break;
case '\f': builder.append("\\f"); break;
case '\\': builder.append("\\\\"); break;
case '^': builder.append("\\^"); break;
case '$': builder.append("\\$"); break;
case '.': builder.append("\\."); break;
case '?': builder.append("\\?"); break;
case '*': builder.append("\\*"); break;
case '+': builder.append("\\+"); break;
case '[': builder.append("\\["); break;
case ']': builder.append("\\]"); break;
case '(': builder.append("\\("); break;
case ')': builder.append("\\)"); break;
case '{': builder.append("\\{"); break;
case '}': builder.append("\\}"); break;
default:
if (c <= ' ' || c > '~') {
builder.append(String.format("\\u%04x", (int) c));
} else {
builder.append(c);
}
break;
}
}
return builder.toString();
} | java | @SuppressWarnings("PMD.NcssCount")
static String escape(String str) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < str.length(); ++i) {
char c = str.charAt(i);
switch (c) {
case '\t': builder.append("\\t"); break;
case '\n': builder.append("\\n"); break;
case '\r': builder.append("\\r"); break;
case '\f': builder.append("\\f"); break;
case '\\': builder.append("\\\\"); break;
case '^': builder.append("\\^"); break;
case '$': builder.append("\\$"); break;
case '.': builder.append("\\."); break;
case '?': builder.append("\\?"); break;
case '*': builder.append("\\*"); break;
case '+': builder.append("\\+"); break;
case '[': builder.append("\\["); break;
case ']': builder.append("\\]"); break;
case '(': builder.append("\\("); break;
case ')': builder.append("\\)"); break;
case '{': builder.append("\\{"); break;
case '}': builder.append("\\}"); break;
default:
if (c <= ' ' || c > '~') {
builder.append(String.format("\\u%04x", (int) c));
} else {
builder.append(c);
}
break;
}
}
return builder.toString();
} | [
"@",
"SuppressWarnings",
"(",
"\"PMD.NcssCount\"",
")",
"static",
"String",
"escape",
"(",
"String",
"str",
")",
"{",
"StringBuilder",
"builder",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"str",
".",
"length",
"(",
")",
";",
"++",
"i",
")",
"{",
"char",
"c",
"=",
"str",
".",
"charAt",
"(",
"i",
")",
";",
"switch",
"(",
"c",
")",
"{",
"case",
"'",
"'",
":",
"builder",
".",
"append",
"(",
"\"\\\\t\"",
")",
";",
"break",
";",
"case",
"'",
"'",
":",
"builder",
".",
"append",
"(",
"\"\\\\n\"",
")",
";",
"break",
";",
"case",
"'",
"'",
":",
"builder",
".",
"append",
"(",
"\"\\\\r\"",
")",
";",
"break",
";",
"case",
"'",
"'",
":",
"builder",
".",
"append",
"(",
"\"\\\\f\"",
")",
";",
"break",
";",
"case",
"'",
"'",
":",
"builder",
".",
"append",
"(",
"\"\\\\\\\\\"",
")",
";",
"break",
";",
"case",
"'",
"'",
":",
"builder",
".",
"append",
"(",
"\"\\\\^\"",
")",
";",
"break",
";",
"case",
"'",
"'",
":",
"builder",
".",
"append",
"(",
"\"\\\\$\"",
")",
";",
"break",
";",
"case",
"'",
"'",
":",
"builder",
".",
"append",
"(",
"\"\\\\.\"",
")",
";",
"break",
";",
"case",
"'",
"'",
":",
"builder",
".",
"append",
"(",
"\"\\\\?\"",
")",
";",
"break",
";",
"case",
"'",
"'",
":",
"builder",
".",
"append",
"(",
"\"\\\\*\"",
")",
";",
"break",
";",
"case",
"'",
"'",
":",
"builder",
".",
"append",
"(",
"\"\\\\+\"",
")",
";",
"break",
";",
"case",
"'",
"'",
":",
"builder",
".",
"append",
"(",
"\"\\\\[\"",
")",
";",
"break",
";",
"case",
"'",
"'",
":",
"builder",
".",
"append",
"(",
"\"\\\\]\"",
")",
";",
"break",
";",
"case",
"'",
"'",
":",
"builder",
".",
"append",
"(",
"\"\\\\(\"",
")",
";",
"break",
";",
"case",
"'",
"'",
":",
"builder",
".",
"append",
"(",
"\"\\\\)\"",
")",
";",
"break",
";",
"case",
"'",
"'",
":",
"builder",
".",
"append",
"(",
"\"\\\\{\"",
")",
";",
"break",
";",
"case",
"'",
"'",
":",
"builder",
".",
"append",
"(",
"\"\\\\}\"",
")",
";",
"break",
";",
"default",
":",
"if",
"(",
"c",
"<=",
"'",
"'",
"||",
"c",
">",
"'",
"'",
")",
"{",
"builder",
".",
"append",
"(",
"String",
".",
"format",
"(",
"\"\\\\u%04x\"",
",",
"(",
"int",
")",
"c",
")",
")",
";",
"}",
"else",
"{",
"builder",
".",
"append",
"(",
"c",
")",
";",
"}",
"break",
";",
"}",
"}",
"return",
"builder",
".",
"toString",
"(",
")",
";",
"}"
] | Escape a string so it will be interpreted as a literal character sequence when processed
as a regular expression. | [
"Escape",
"a",
"string",
"so",
"it",
"will",
"be",
"interpreted",
"as",
"a",
"literal",
"character",
"sequence",
"when",
"processed",
"as",
"a",
"regular",
"expression",
"."
] | 259318252770de3bad581b85adff187d8f2c6537 | https://github.com/Netflix/spectator/blob/259318252770de3bad581b85adff187d8f2c6537/spectator-api/src/main/java/com/netflix/spectator/impl/matcher/PatternUtils.java#L156-L189 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.