code
stringlengths 25
201k
| docstring
stringlengths 19
96.2k
| func_name
stringlengths 0
235
| language
stringclasses 1
value | repo
stringlengths 8
51
| path
stringlengths 11
314
| url
stringlengths 62
377
| license
stringclasses 7
values |
|---|---|---|---|---|---|---|---|
public static int findAvailableTcpPort(int minPort, int maxPort) {
return findAvailablePort(minPort, maxPort);
}
|
Find an available TCP port randomly selected from the range [{@code minPort},
{@code maxPort}].
@param minPort the minimum port number
@param maxPort the maximum port number
@return an available TCP port number
@throws IllegalStateException if no available port could be found
|
findAvailableTcpPort
|
java
|
alibaba/arthas
|
common/src/main/java/com/taobao/arthas/common/SocketUtils.java
|
https://github.com/alibaba/arthas/blob/master/common/src/main/java/com/taobao/arthas/common/SocketUtils.java
|
Apache-2.0
|
private static int findAvailablePort(int minPort, int maxPort) {
int portRange = maxPort - minPort;
int candidatePort;
int searchCounter = 0;
do {
if (searchCounter > portRange) {
throw new IllegalStateException(
String.format("Could not find an available tcp port in the range [%d, %d] after %d attempts",
minPort, maxPort, searchCounter));
}
candidatePort = findRandomPort(minPort, maxPort);
searchCounter++;
} while (!isTcpPortAvailable(candidatePort));
return candidatePort;
}
|
Find an available port for this {@code SocketType}, randomly selected from
the range [{@code minPort}, {@code maxPort}].
@param minPort the minimum port number
@param maxPort the maximum port number
@return an available port number for this socket type
@throws IllegalStateException if no available port could be found
|
findAvailablePort
|
java
|
alibaba/arthas
|
common/src/main/java/com/taobao/arthas/common/SocketUtils.java
|
https://github.com/alibaba/arthas/blob/master/common/src/main/java/com/taobao/arthas/common/SocketUtils.java
|
Apache-2.0
|
private static int findRandomPort(int minPort, int maxPort) {
int portRange = maxPort - minPort;
return minPort + random.nextInt(portRange + 1);
}
|
Find a pseudo-random port number within the range [{@code minPort},
{@code maxPort}].
@param minPort the minimum port number
@param maxPort the maximum port number
@return a random port number within the specified range
|
findRandomPort
|
java
|
alibaba/arthas
|
common/src/main/java/com/taobao/arthas/common/SocketUtils.java
|
https://github.com/alibaba/arthas/blob/master/common/src/main/java/com/taobao/arthas/common/SocketUtils.java
|
Apache-2.0
|
void setTable(HashEntry<K, V>[] newTable) {
threshold = (int) (newTable.length * loadFactor);
table = newTable;
refQueue = new ReferenceQueue<Object>();
}
|
Sets table to new HashEntry array. Call only while holding lock or in
constructor.
|
setTable
|
java
|
alibaba/arthas
|
common/src/main/java/com/taobao/arthas/common/concurrent/ConcurrentWeakKeyHashMap.java
|
https://github.com/alibaba/arthas/blob/master/common/src/main/java/com/taobao/arthas/common/concurrent/ConcurrentWeakKeyHashMap.java
|
Apache-2.0
|
@Override
public int size() {
final Segment<K, V>[] segments = this.segments;
long sum = 0;
long check = 0;
int[] mc = new int[segments.length];
// Try a few times to get accurate count. On failure due to continuous
// async changes in table, resort to locking.
for (int k = 0; k < RETRIES_BEFORE_LOCK; ++ k) {
check = 0;
sum = 0;
int mcsum = 0;
for (int i = 0; i < segments.length; ++ i) {
sum += segments[i].count;
mcsum += mc[i] = segments[i].modCount;
}
if (mcsum != 0) {
for (int i = 0; i < segments.length; ++ i) {
check += segments[i].count;
if (mc[i] != segments[i].modCount) {
check = -1; // force retry
break;
}
}
}
if (check == sum) {
break;
}
}
if (check != sum) { // Resort to locking all segments
sum = 0;
for (Segment<K, V> segment: segments) {
segment.lock();
}
for (Segment<K, V> segment: segments) {
sum += segment.count;
}
for (Segment<K, V> segment: segments) {
segment.unlock();
}
}
if (sum > Integer.MAX_VALUE) {
return Integer.MAX_VALUE;
} else {
return (int) sum;
}
}
|
Returns the number of key-value mappings in this map. If the map contains
more than <tt>Integer.MAX_VALUE</tt> elements, returns
<tt>Integer.MAX_VALUE</tt>.
@return the number of key-value mappings in this map
|
size
|
java
|
alibaba/arthas
|
common/src/main/java/com/taobao/arthas/common/concurrent/ConcurrentWeakKeyHashMap.java
|
https://github.com/alibaba/arthas/blob/master/common/src/main/java/com/taobao/arthas/common/concurrent/ConcurrentWeakKeyHashMap.java
|
Apache-2.0
|
@Override
public V get(Object key) {
int hash = hashOf(key);
return segmentFor(hash).get(key, hash);
}
|
Returns the value to which the specified key is mapped, or {@code null}
if this map contains no mapping for the key.
<p>More formally, if this map contains a mapping from a key {@code k} to
a value {@code v} such that {@code key.equals(k)}, then this method
returns {@code v}; otherwise it returns {@code null}. (There can be at
most one such mapping.)
@throws NullPointerException if the specified key is null
|
get
|
java
|
alibaba/arthas
|
common/src/main/java/com/taobao/arthas/common/concurrent/ConcurrentWeakKeyHashMap.java
|
https://github.com/alibaba/arthas/blob/master/common/src/main/java/com/taobao/arthas/common/concurrent/ConcurrentWeakKeyHashMap.java
|
Apache-2.0
|
@Override
public boolean containsKey(Object key) {
int hash = hashOf(key);
return segmentFor(hash).containsKey(key, hash);
}
|
Tests if the specified object is a key in this table.
@param key possible key
@return <tt>true</tt> if and only if the specified object is a key in
this table, as determined by the <tt>equals</tt> method;
<tt>false</tt> otherwise.
@throws NullPointerException if the specified key is null
|
containsKey
|
java
|
alibaba/arthas
|
common/src/main/java/com/taobao/arthas/common/concurrent/ConcurrentWeakKeyHashMap.java
|
https://github.com/alibaba/arthas/blob/master/common/src/main/java/com/taobao/arthas/common/concurrent/ConcurrentWeakKeyHashMap.java
|
Apache-2.0
|
@Override
public boolean containsValue(Object value) {
if (value == null) {
throw new NullPointerException();
}
// See explanation of modCount use above
final Segment<K, V>[] segments = this.segments;
int[] mc = new int[segments.length];
// Try a few times without locking
for (int k = 0; k < RETRIES_BEFORE_LOCK; ++ k) {
int mcsum = 0;
for (int i = 0; i < segments.length; ++ i) {
mcsum += mc[i] = segments[i].modCount;
if (segments[i].containsValue(value)) {
return true;
}
}
boolean cleanSweep = true;
if (mcsum != 0) {
for (int i = 0; i < segments.length; ++ i) {
if (mc[i] != segments[i].modCount) {
cleanSweep = false;
break;
}
}
}
if (cleanSweep) {
return false;
}
}
// Resort to locking all segments
for (Segment<K, V> segment: segments) {
segment.lock();
}
boolean found = false;
try {
for (Segment<K, V> segment: segments) {
if (segment.containsValue(value)) {
found = true;
break;
}
}
} finally {
for (Segment<K, V> segment: segments) {
segment.unlock();
}
}
return found;
}
|
Returns <tt>true</tt> if this map maps one or more keys to the specified
value. Note: This method requires a full internal traversal of the hash
table, and so is much slower than method <tt>containsKey</tt>.
@param value value whose presence in this map is to be tested
@return <tt>true</tt> if this map maps one or more keys to the specified
value
@throws NullPointerException if the specified value is null
|
containsValue
|
java
|
alibaba/arthas
|
common/src/main/java/com/taobao/arthas/common/concurrent/ConcurrentWeakKeyHashMap.java
|
https://github.com/alibaba/arthas/blob/master/common/src/main/java/com/taobao/arthas/common/concurrent/ConcurrentWeakKeyHashMap.java
|
Apache-2.0
|
@Override
public V put(K key, V value) {
if (value == null) {
throw new NullPointerException();
}
int hash = hashOf(key);
return segmentFor(hash).put(key, hash, value, false);
}
|
Maps the specified key to the specified value in this table. Neither the
key nor the value can be null.
<p>The value can be retrieved by calling the <tt>get</tt> method with a
key that is equal to the original key.
@param key key with which the specified value is to be associated
@param value value to be associated with the specified key
@return the previous value associated with <tt>key</tt>, or <tt>null</tt>
if there was no mapping for <tt>key</tt>
@throws NullPointerException if the specified key or value is null
|
put
|
java
|
alibaba/arthas
|
common/src/main/java/com/taobao/arthas/common/concurrent/ConcurrentWeakKeyHashMap.java
|
https://github.com/alibaba/arthas/blob/master/common/src/main/java/com/taobao/arthas/common/concurrent/ConcurrentWeakKeyHashMap.java
|
Apache-2.0
|
@Override
public void putAll(Map<? extends K, ? extends V> m) {
for (Map.Entry<? extends K, ? extends V> e: m.entrySet()) {
put(e.getKey(), e.getValue());
}
}
|
Copies all of the mappings from the specified map to this one. These
mappings replace any mappings that this map had for any of the keys
currently in the specified map.
@param m mappings to be stored in this map
|
putAll
|
java
|
alibaba/arthas
|
common/src/main/java/com/taobao/arthas/common/concurrent/ConcurrentWeakKeyHashMap.java
|
https://github.com/alibaba/arthas/blob/master/common/src/main/java/com/taobao/arthas/common/concurrent/ConcurrentWeakKeyHashMap.java
|
Apache-2.0
|
@Override
public V remove(Object key) {
int hash = hashOf(key);
return segmentFor(hash).remove(key, hash, null, false);
}
|
Removes the key (and its corresponding value) from this map. This method
does nothing if the key is not in the map.
@param key the key that needs to be removed
@return the previous value associated with <tt>key</tt>, or <tt>null</tt>
if there was no mapping for <tt>key</tt>
@throws NullPointerException if the specified key is null
|
remove
|
java
|
alibaba/arthas
|
common/src/main/java/com/taobao/arthas/common/concurrent/ConcurrentWeakKeyHashMap.java
|
https://github.com/alibaba/arthas/blob/master/common/src/main/java/com/taobao/arthas/common/concurrent/ConcurrentWeakKeyHashMap.java
|
Apache-2.0
|
public void purgeStaleEntries() {
for (Segment<K, V> segment: segments) {
segment.removeStale();
}
}
|
Removes any stale entries whose keys have been finalized. Use of this
method is normally not necessary since stale entries are automatically
removed lazily, when blocking operations are required. However, there are
some cases where this operation should be performed eagerly, such as
cleaning up old references to a ClassLoader in a multi-classloader
environment.
Note: this method will acquire locks, one at a time, across all segments
of this table, so if it is to be used, it should be used sparingly.
|
purgeStaleEntries
|
java
|
alibaba/arthas
|
common/src/main/java/com/taobao/arthas/common/concurrent/ConcurrentWeakKeyHashMap.java
|
https://github.com/alibaba/arthas/blob/master/common/src/main/java/com/taobao/arthas/common/concurrent/ConcurrentWeakKeyHashMap.java
|
Apache-2.0
|
@Override
public Set<K> keySet() {
Set<K> ks = keySet;
return ks != null? ks : (keySet = new KeySet());
}
|
Returns a {@link Set} view of the keys contained in this map. The set is
backed by the map, so changes to the map are reflected in the set, and
vice-versa. The set supports element removal, which removes the
corresponding mapping from this map, via the <tt>Iterator.remove</tt>,
<tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt>, and
<tt>clear</tt> operations. It does not support the <tt>add</tt> or
<tt>addAll</tt> operations.
<p>The view's <tt>iterator</tt> is a "weakly consistent" iterator that
will never throw {@link ConcurrentModificationException}, and guarantees
to traverse elements as they existed upon construction of the iterator,
and may (but is not guaranteed to) reflect any modifications subsequent
to construction.
|
keySet
|
java
|
alibaba/arthas
|
common/src/main/java/com/taobao/arthas/common/concurrent/ConcurrentWeakKeyHashMap.java
|
https://github.com/alibaba/arthas/blob/master/common/src/main/java/com/taobao/arthas/common/concurrent/ConcurrentWeakKeyHashMap.java
|
Apache-2.0
|
@Override
public Collection<V> values() {
Collection<V> vs = values;
return vs != null? vs : (values = new Values());
}
|
Returns a {@link Collection} view of the values contained in this map.
The collection is backed by the map, so changes to the map are reflected
in the collection, and vice-versa. The collection supports element
removal, which removes the corresponding mapping from this map, via the
<tt>Iterator.remove</tt>, <tt>Collection.remove</tt>, <tt>removeAll</tt>,
<tt>retainAll</tt>, and <tt>clear</tt> operations. It does not support
the <tt>add</tt> or <tt>addAll</tt> operations.
<p>The view's <tt>iterator</tt> is a "weakly consistent" iterator that
will never throw {@link ConcurrentModificationException}, and guarantees
to traverse elements as they existed upon construction of the iterator,
and may (but is not guaranteed to) reflect any modifications subsequent
to construction.
|
values
|
java
|
alibaba/arthas
|
common/src/main/java/com/taobao/arthas/common/concurrent/ConcurrentWeakKeyHashMap.java
|
https://github.com/alibaba/arthas/blob/master/common/src/main/java/com/taobao/arthas/common/concurrent/ConcurrentWeakKeyHashMap.java
|
Apache-2.0
|
@Override
public Set<Map.Entry<K, V>> entrySet() {
Set<Map.Entry<K, V>> es = entrySet;
return es != null? es : (entrySet = new EntrySet());
}
|
Returns a {@link Set} view of the mappings contained in this map.
The set is backed by the map, so changes to the map are reflected in the
set, and vice-versa. The set supports element removal, which removes the
corresponding mapping from the map, via the <tt>Iterator.remove</tt>,
<tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt>, and
<tt>clear</tt> operations. It does not support the <tt>add</tt> or
<tt>addAll</tt> operations.
<p>The view's <tt>iterator</tt> is a "weakly consistent" iterator that
will never throw {@link ConcurrentModificationException}, and guarantees
to traverse elements as they existed upon construction of the iterator,
and may (but is not guaranteed to) reflect any modifications subsequent
to construction.
|
entrySet
|
java
|
alibaba/arthas
|
common/src/main/java/com/taobao/arthas/common/concurrent/ConcurrentWeakKeyHashMap.java
|
https://github.com/alibaba/arthas/blob/master/common/src/main/java/com/taobao/arthas/common/concurrent/ConcurrentWeakKeyHashMap.java
|
Apache-2.0
|
@Override
public void complete(Completion completion) {
CompletionUtils.complete(completion, System.getenv().keySet());
}
|
First, try to complete with the sysenv command scope. If completion is
failed, delegates to super class.
@param completion
the completion object
|
complete
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/command/basic1000/SystemEnvCommand.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/command/basic1000/SystemEnvCommand.java
|
Apache-2.0
|
@Override
public void complete(Completion completion) {
CompletionUtils.complete(completion, System.getProperties().stringPropertyNames());
}
|
First, try to complete with the sysprop command scope.
If completion is failed, delegates to super class.
@param completion the completion object
|
complete
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/command/basic1000/SystemPropertyCommand.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/command/basic1000/SystemPropertyCommand.java
|
Apache-2.0
|
@Override
public boolean isAccessible(Map context, Object target, Member member, String propertyName) {
int modifiers = member.getModifiers();
boolean result = Modifier.isPublic(modifiers);
if (!result) {
if (Modifier.isPrivate(modifiers)) {
result = getAllowPrivateAccess();
} else {
if (Modifier.isProtected(modifiers)) {
result = getAllowProtectedAccess();
} else {
result = getAllowPackageProtectedAccess();
}
}
}
return result;
}
|
Returns true if the given member is accessible or can be made accessible
by this object.
@param context the current execution context (not used).
@param target the Object to test accessibility for (not used).
@param member the Member to test accessibility for.
@param propertyName the property to test accessibility for (not used).
@return true if the member is accessible in the context, false otherwise.
|
isAccessible
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/command/express/DefaultMemberAccess.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/command/express/DefaultMemberAccess.java
|
Apache-2.0
|
@Override
public void draw(CommandProcess process, CatModel result) {
process.write(result.getContent()).write("\n");
}
|
Result view for CatCommand
@author gongdewei 2020/5/11
|
draw
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/command/view/CatView.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/command/view/CatView.java
|
Apache-2.0
|
@Override
public void draw(CommandProcess process, EnhancerModel result) {
// ignore enhance result status, judge by the following output
if (result.getEffect() != null) {
process.write(ViewRenderUtil.renderEnhancerAffect(result.getEffect()));
}
}
|
Term view for EnhancerModel
@author gongdewei 2020/7/21
|
draw
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/command/view/EnhancerView.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/command/view/EnhancerView.java
|
Apache-2.0
|
@Override
public void draw(CommandProcess process, OgnlModel model) {
if (model.getMatchedClassLoaders() != null) {
process.write("Matched classloaders: \n");
ClassLoaderView.drawClassLoaders(process, model.getMatchedClassLoaders(), false);
process.write("\n");
return;
}
ObjectVO objectVO = model.getValue();
String resultStr = StringUtils.objectToString(objectVO.needExpand() ? new ObjectView(objectVO).draw() : objectVO.getObject());
process.write(resultStr).write("\n");
}
|
Term view of OgnlCommand
@author gongdewei 2020/4/29
|
draw
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/command/view/OgnlView.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/command/view/OgnlView.java
|
Apache-2.0
|
@Override
public void draw(CommandProcess process, PerfCounterModel result) {
List<PerfCounterVO> perfCounters = result.getPerfCounters();
boolean details = result.isDetails();
TableElement table;
if (details) {
table = new TableElement(3, 1, 1, 10).leftCellPadding(1).rightCellPadding(1);
table.row(true, label("Name").style(Decoration.bold.bold()),
label("Variability").style(Decoration.bold.bold()),
label("Units").style(Decoration.bold.bold()), label("Value").style(Decoration.bold.bold()));
} else {
table = new TableElement(4, 6).leftCellPadding(1).rightCellPadding(1);
table.row(true, label("Name").style(Decoration.bold.bold()),
label("Value").style(Decoration.bold.bold()));
}
for (PerfCounterVO counter : perfCounters) {
if (details) {
table.row(counter.getName(), counter.getVariability(),
counter.getUnits(), String.valueOf(counter.getValue()));
} else {
table.row(counter.getName(), String.valueOf(counter.getValue()));
}
}
process.write(RenderUtil.render(table, process.width()));
}
|
View of 'perfcounter' command
@author gongdewei 2020/4/27
|
draw
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/command/view/PerfCounterView.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/command/view/PerfCounterView.java
|
Apache-2.0
|
@Override
public void draw(CommandProcess process, StackModel result) {
StringBuilder sb = new StringBuilder();
sb.append(ThreadUtil.getThreadTitle(result)).append("\n");
StackTraceElement[] stackTraceElements = result.getStackTrace();
StackTraceElement locationStackTraceElement = stackTraceElements[0];
String locationString = String.format(" @%s.%s()", locationStackTraceElement.getClassName(),
locationStackTraceElement.getMethodName());
sb.append(locationString).append("\n");
int skip = 1;
for (int index = skip; index < stackTraceElements.length; index++) {
StackTraceElement ste = stackTraceElements[index];
sb.append(" at ")
.append(ste.getClassName())
.append(".")
.append(ste.getMethodName())
.append("(")
.append(ste.getFileName())
.append(":")
.append(ste.getLineNumber())
.append(")\n");
}
process.write("ts=" + DateUtils.formatDateTime(result.getTs()) + ";" + sb.toString() + "\n");
}
|
Term view for StackModel
@author gongdewei 2020/4/13
|
draw
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/command/view/StackView.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/command/view/StackView.java
|
Apache-2.0
|
@Override
public void draw(CommandProcess process, ThreadModel result) {
if (result.getThreadInfo() != null) {
// no cpu usage info
String content = ThreadUtil.getFullStacktrace(result.getThreadInfo());
process.write(content);
} else if (result.getBusyThreads() != null) {
List<BusyThreadInfo> threadInfos = result.getBusyThreads();
for (BusyThreadInfo info : threadInfos) {
String stacktrace = ThreadUtil.getFullStacktrace(info, -1, -1);
process.write(stacktrace).write("\n");
}
} else if (result.getBlockingLockInfo() != null) {
String stacktrace = ThreadUtil.getFullStacktrace(result.getBlockingLockInfo());
process.write(stacktrace);
} else if (result.getThreadStateCount() != null) {
Map<Thread.State, Integer> threadStateCount = result.getThreadStateCount();
List<ThreadVO> threadStats = result.getThreadStats();
//sum total thread count
int total = 0;
for (Integer value : threadStateCount.values()) {
total += value;
}
int internalThreadCount = 0;
for (ThreadVO thread : threadStats) {
if (thread.getId() <= 0) {
internalThreadCount += 1;
}
}
total += internalThreadCount;
StringBuilder threadStat = new StringBuilder();
threadStat.append("Threads Total: ").append(total);
for (Thread.State s : Thread.State.values()) {
Integer count = threadStateCount.get(s);
threadStat.append(", ").append(s.name()).append(": ").append(count);
}
if (internalThreadCount > 0) {
threadStat.append(", Internal threads: ").append(internalThreadCount);
}
String stat = RenderUtil.render(new LabelElement(threadStat), process.width());
//thread stats
int height;
if (result.isAll()) {
height = threadStats.size() + 1;
} else {
height = Math.max(5, process.height() - 2);
//remove blank lines
height = Math.min(height, threadStats.size() + 2);
}
String content = ViewRenderUtil.drawThreadInfo(threadStats, process.width(), height);
process.write(stat + content);
}
}
|
View of 'thread' command
@author gongdewei 2020/4/26
|
draw
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/command/view/ThreadView.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/command/view/ThreadView.java
|
Apache-2.0
|
@Override
public void draw(CommandProcess process, TimeTunnelModel timeTunnelModel) {
Integer sizeLimit = timeTunnelModel.getSizeLimit();
if (timeTunnelModel.getTimeFragmentList() != null) {
//show list table: tt -l / tt -t
Element table = drawTimeTunnelTable(timeTunnelModel.getTimeFragmentList(), timeTunnelModel.getFirst());
process.write(RenderUtil.render(table, process.width()));
} else if (timeTunnelModel.getTimeFragment() != null) {
//show detail of single TimeFragment: tt -i 1000
TimeFragmentVO tf = timeTunnelModel.getTimeFragment();
TableElement table = TimeTunnelTable.createDefaultTable();
TimeTunnelTable.drawTimeTunnel(table, tf);
TimeTunnelTable.drawParameters(table, tf.getParams());
TimeTunnelTable.drawReturnObj(table, tf, sizeLimit);
TimeTunnelTable.drawThrowException(table, tf);
process.write(RenderUtil.render(table, process.width()));
} else if (timeTunnelModel.getWatchValue() != null) {
//watch single TimeFragment: tt -i 1000 -w 'params'
ObjectVO valueVO = timeTunnelModel.getWatchValue();
if (valueVO.needExpand()) {
process.write(new ObjectView(sizeLimit, valueVO).draw()).write("\n");
} else {
process.write(StringUtils.objectToString(valueVO.getObject())).write("\n");
}
} else if (timeTunnelModel.getWatchResults() != null) {
//search & watch: tt -s 'returnObj!=null' -w 'returnObj'
TableElement table = TimeTunnelTable.createDefaultTable();
TimeTunnelTable.drawWatchTableHeader(table);
TimeTunnelTable.drawWatchResults(table, timeTunnelModel.getWatchResults(), sizeLimit);
process.write(RenderUtil.render(table, process.width()));
} else if (timeTunnelModel.getReplayResult() != null) {
//replay: tt -i 1000 -p
TimeFragmentVO replayResult = timeTunnelModel.getReplayResult();
Integer replayNo = timeTunnelModel.getReplayNo();
TableElement table = TimeTunnelTable.createDefaultTable();
TimeTunnelTable.drawPlayHeader(replayResult.getClassName(), replayResult.getMethodName(), replayResult.getObject(), replayResult.getIndex(), table);
TimeTunnelTable.drawParameters(table, replayResult.getParams());
if (replayResult.isReturn()) {
TimeTunnelTable.drawPlayResult(table, replayResult.getReturnObj(), sizeLimit, replayResult.getCost());
} else {
TimeTunnelTable.drawPlayException(table, replayResult.getThrowExp());
}
process.write(RenderUtil.render(table, process.width()))
.write(format("Time fragment[%d] successfully replayed %d times.", replayResult.getIndex(), replayNo))
.write("\n\n");
}
}
|
Term view for TimeTunnelCommand
@author gongdewei 2020/4/27
|
draw
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/command/view/TimeTunnelView.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/command/view/TimeTunnelView.java
|
Apache-2.0
|
public static String renderKeyValueTable(Map<String, String> map, int width) {
TableElement table = new TableElement(1, 4).leftCellPadding(1).rightCellPadding(1);
table.row(true, label("KEY").style(Decoration.bold.bold()), label("VALUE").style(Decoration.bold.bold()));
for (Map.Entry<String, String> entry : map.entrySet()) {
table.row(entry.getKey(), entry.getValue());
}
return RenderUtil.render(table, width);
}
|
Render key-value table
@param map
@param width
@return
|
renderKeyValueTable
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/command/view/ViewRenderUtil.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/command/view/ViewRenderUtil.java
|
Apache-2.0
|
public static TableElement renderChangeResult(ChangeResultVO result) {
TableElement table = new TableElement().leftCellPadding(1).rightCellPadding(1);
table.row(true, label("NAME").style(Decoration.bold.bold()),
label("BEFORE-VALUE").style(Decoration.bold.bold()),
label("AFTER-VALUE").style(Decoration.bold.bold()));
table.row(result.getName(), StringUtils.objectToString(result.getBeforeValue()),
StringUtils.objectToString(result.getAfterValue()));
return table;
}
|
Render change result vo
@param result
@return
|
renderChangeResult
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/command/view/ViewRenderUtil.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/command/view/ViewRenderUtil.java
|
Apache-2.0
|
@Override
public void draw(CommandProcess process, WatchModel model) {
ObjectVO objectVO = model.getValue();
String result = StringUtils.objectToString(
objectVO.needExpand() ? new ObjectView(model.getSizeLimit(), objectVO).draw() : objectVO.getObject());
process.write("method=" + model.getClassName() + "." + model.getMethodName() + " location=" + model.getAccessPoint() + "\n");
process.write("ts=" + DateUtils.formatDateTime(model.getTs()) + "; [cost=" + model.getCost() + "ms] result=" + result + "\n");
}
|
Term view for WatchModel
@author gongdewei 2020/3/27
|
draw
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/command/view/WatchView.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/command/view/WatchView.java
|
Apache-2.0
|
@Override
public void setPlaceholderPrefix(String placeholderPrefix) {
this.placeholderPrefix = placeholderPrefix;
}
|
Set the prefix that placeholders replaced by this resolver must begin with.
<p>
The default is "${".
@see org.springframework.util.SystemPropertyUtils#PLACEHOLDER_PREFIX
|
setPlaceholderPrefix
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/env/AbstractPropertyResolver.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/env/AbstractPropertyResolver.java
|
Apache-2.0
|
@Override
public void setPlaceholderSuffix(String placeholderSuffix) {
this.placeholderSuffix = placeholderSuffix;
}
|
Set the suffix that placeholders replaced by this resolver must end with.
<p>
The default is "}".
@see org.springframework.util.SystemPropertyUtils#PLACEHOLDER_SUFFIX
|
setPlaceholderSuffix
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/env/AbstractPropertyResolver.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/env/AbstractPropertyResolver.java
|
Apache-2.0
|
@Override
public void setValueSeparator(String valueSeparator) {
this.valueSeparator = valueSeparator;
}
|
Specify the separating character between the placeholders replaced by this
resolver and their associated default value, or {@code null} if no such
special character should be processed as a value separator.
<p>
The default is ":".
@see org.springframework.util.SystemPropertyUtils#VALUE_SEPARATOR
|
setValueSeparator
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/env/AbstractPropertyResolver.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/env/AbstractPropertyResolver.java
|
Apache-2.0
|
@Override
public boolean containsProperty(String name) {
String[] propertyNames = getPropertyNames();
if (propertyNames == null) {
return false;
}
for (String temp : propertyNames) {
if (temp.equals(name)) {
return true;
}
}
return false;
}
|
Return whether this {@code PropertySource} contains a property with the given
name.
<p>
This implementation checks for the presence of the given name within the
{@link #getPropertyNames()} array.
@param name the name of the property to find
|
containsProperty
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/env/EnumerablePropertySource.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/env/EnumerablePropertySource.java
|
Apache-2.0
|
public Set<String> getMissingRequiredProperties() {
return this.missingRequiredProperties;
}
|
Return the set of properties marked as required but not present upon
validation.
@see ConfigurablePropertyResolver#setRequiredProperties(String...)
@see ConfigurablePropertyResolver#validateRequiredProperties()
|
getMissingRequiredProperties
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/env/MissingRequiredPropertiesException.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/env/MissingRequiredPropertiesException.java
|
Apache-2.0
|
public void addFirst(PropertySource<?> propertySource) {
// if (logger.isDebugEnabled()) {
// logger.debug(String.format("Adding [%s] PropertySource with highest search precedence",
// propertySource.getName()));
// }
removeIfPresent(propertySource);
this.propertySourceList.addFirst(propertySource);
}
|
Add the given property source object with highest precedence.
|
addFirst
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/env/MutablePropertySources.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/env/MutablePropertySources.java
|
Apache-2.0
|
public void addBefore(String relativePropertySourceName, PropertySource<?> propertySource) {
// if (logger.isDebugEnabled()) {
// logger.debug(String.format("Adding [%s] PropertySource with search precedence immediately higher than [%s]",
// propertySource.getName(), relativePropertySourceName));
// }
assertLegalRelativeAddition(relativePropertySourceName, propertySource);
removeIfPresent(propertySource);
int index = assertPresentAndGetIndex(relativePropertySourceName);
addAtIndex(index, propertySource);
}
|
Add the given property source object with precedence immediately higher than
the named relative property source.
|
addBefore
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/env/MutablePropertySources.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/env/MutablePropertySources.java
|
Apache-2.0
|
public void addAfter(String relativePropertySourceName, PropertySource<?> propertySource) {
// if (logger.isDebugEnabled()) {
// logger.debug(String.format("Adding [%s] PropertySource with search precedence immediately lower than [%s]",
// propertySource.getName(), relativePropertySourceName));
// }
assertLegalRelativeAddition(relativePropertySourceName, propertySource);
removeIfPresent(propertySource);
int index = assertPresentAndGetIndex(relativePropertySourceName);
addAtIndex(index + 1, propertySource);
}
|
Add the given property source object with precedence immediately lower than
the named relative property source.
|
addAfter
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/env/MutablePropertySources.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/env/MutablePropertySources.java
|
Apache-2.0
|
public PropertySource<?> remove(String name) {
// if (logger.isDebugEnabled()) {
// logger.debug(String.format("Removing [%s] PropertySource", name));
// }
int index = this.propertySourceList.indexOf(PropertySource.named(name));
return index == -1 ? null : this.propertySourceList.remove(index);
}
|
Remove and return the property source with the given name, {@code null} if
not found.
@param name the name of the property source to find and remove
|
remove
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/env/MutablePropertySources.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/env/MutablePropertySources.java
|
Apache-2.0
|
public void replace(String name, PropertySource<?> propertySource) {
// if (logger.isDebugEnabled()) {
// logger.debug(String.format("Replacing [%s] PropertySource with [%s]",
// name, propertySource.getName()));
// }
int index = assertPresentAndGetIndex(name);
this.propertySourceList.set(index, propertySource);
}
|
Replace the property source with the given name with the given property
source object.
@param name the name of the property source to find and replace
@param propertySource the replacement property source
@throws IllegalArgumentException if no property source with the given name is
present
@see #contains
|
replace
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/env/MutablePropertySources.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/env/MutablePropertySources.java
|
Apache-2.0
|
private int assertPresentAndGetIndex(String name) {
int index = this.propertySourceList.indexOf(PropertySource.named(name));
// Assert.isTrue(index >= 0, String.format(NON_EXISTENT_PROPERTY_SOURCE_MESSAGE, name));
return index;
}
|
Assert that the named property source is present and return its index.
@param name the {@linkplain PropertySource#getName() name of the property
source} to find
@throws IllegalArgumentException if the named property source is not present
|
assertPresentAndGetIndex
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/env/MutablePropertySources.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/env/MutablePropertySources.java
|
Apache-2.0
|
private static String nullSafeToString(Object obj) {
if (obj == null) {
return "null";
}
if (obj instanceof String) {
return (String) obj;
}
if (obj instanceof Object[]) {
return nullSafeToString((Object[]) obj);
}
if (obj instanceof boolean[]) {
return nullSafeToString((boolean[]) obj);
}
if (obj instanceof byte[]) {
return nullSafeToString((byte[]) obj);
}
if (obj instanceof char[]) {
return nullSafeToString((char[]) obj);
}
if (obj instanceof double[]) {
return nullSafeToString((double[]) obj);
}
if (obj instanceof float[]) {
return nullSafeToString((float[]) obj);
}
if (obj instanceof int[]) {
return nullSafeToString((int[]) obj);
}
if (obj instanceof long[]) {
return nullSafeToString((long[]) obj);
}
if (obj instanceof short[]) {
return nullSafeToString((short[]) obj);
}
String str = obj.toString();
return (str != null ? str : "");
}
|
Return a String representation of the specified Object.
<p>
Builds a String representation of the contents in case of an array. Returns
{@code "null"} if {@code obj} is {@code null}.
@param obj the object to build a String representation for
@return a String representation of {@code obj}
|
nullSafeToString
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/env/MutablePropertySources.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/env/MutablePropertySources.java
|
Apache-2.0
|
@Override
public String[] getPropertyNames() {
synchronized (this.source) {
return super.getPropertyNames();
}
}
|
{@link PropertySource} implementation that extracts properties from a
{@link java.util.Properties} object.
<p>
Note that because a {@code Properties} object is technically an
{@code <Object, Object>} {@link java.util.Hashtable Hashtable}, one may
contain non-{@code String} keys or values. This implementation, however is
restricted to accessing only {@code String}-based keys and values, in the
same fashion as {@link Properties#getProperty} and
{@link Properties#setProperty}.
@author Chris Beams
@author Juergen Hoeller
@since 3.1
|
getPropertyNames
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/env/PropertiesPropertySource.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/env/PropertiesPropertySource.java
|
Apache-2.0
|
public boolean containsProperty(String name) {
return (getProperty(name) != null);
}
|
Return whether this {@code PropertySource} contains the given name.
<p>
This implementation simply checks for a {@code null} return value from
{@link #getProperty(String)}. Subclasses may wish to implement a more
efficient algorithm if possible.
@param name the property name to find
|
containsProperty
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/env/PropertySource.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/env/PropertySource.java
|
Apache-2.0
|
@Override
public boolean equals(Object other) {
return (this == other
|| (other instanceof PropertySource && nullSafeEquals(this.name, ((PropertySource<?>) other).name)));
}
|
This {@code PropertySource} object is equal to the given object if:
<ul>
<li>they are the same instance
<li>the {@code name} properties for both objects are equal
</ul>
<p>
No properties other than {@code name} are evaluated.
|
equals
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/env/PropertySource.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/env/PropertySource.java
|
Apache-2.0
|
@Override
public String toString() {
return getClass().getSimpleName() + " {name='" + this.name + "'}";
}
|
Produce concise output (type and name) if the current log level does not
include debug. If debug is enabled, produce verbose output including the hash
code of the PropertySource instance and every name/value property pair.
<p>
This variable verbosity is useful as a property source such as system
properties or environment variables may contain an arbitrary number of
property pairs, potentially leading to difficult to read exception and log
messages.
@see Log#isDebugEnabled()
|
toString
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/env/PropertySource.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/env/PropertySource.java
|
Apache-2.0
|
public static PropertySource<?> named(String name) {
return new ComparisonPropertySource(name);
}
|
Return a {@code PropertySource} implementation intended for collection
comparison purposes only.
<p>
Primarily for internal use, but given a collection of {@code PropertySource}
objects, may be used as follows:
<pre class="code">
{
@code
List<PropertySource<?>> sources = new ArrayList<PropertySource<?>>();
sources.add(new MapPropertySource("sourceA", mapA));
sources.add(new MapPropertySource("sourceB", mapB));
assert sources.contains(PropertySource.named("sourceA"));
assert sources.contains(PropertySource.named("sourceB"));
assert !sources.contains(PropertySource.named("sourceC"));
}
</pre>
The returned {@code PropertySource} will throw
{@code UnsupportedOperationException} if any methods other than
{@code equals(Object)}, {@code hashCode()}, and {@code toString()} are
called.
@param name the name of the comparison {@code PropertySource} to be created
and returned.
|
named
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/env/PropertySource.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/env/PropertySource.java
|
Apache-2.0
|
protected void logKeyFound(String key, PropertySource<?> propertySource, Object value) {
// if (logger.isDebugEnabled()) {
// logger.debug("Found key '" + key + "' in PropertySource '" + propertySource.getName() +
// "' with value of type " + value.getClass().getSimpleName());
// }
}
|
Log the given key as found in the given {@link PropertySource}, resulting in
the given value.
<p>
The default implementation writes a debug log message with key and source. As
of 4.3.3, this does not log the value anymore in order to avoid accidental
logging of sensitive settings. Subclasses may override this method to change
the log level and/or log message, including the property's value if desired.
@param key the key found
@param propertySource the {@code PropertySource} that the key has been found
in
@param value the corresponding value
@since 4.3.1
|
logKeyFound
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/env/PropertySourcesPropertyResolver.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/env/PropertySourcesPropertyResolver.java
|
Apache-2.0
|
@Override
public boolean containsKey(Object key) {
return (get(key) != null);
}
|
Read-only {@code Map<String, String>} implementation that is backed by system
properties or environment variables.
<p>
Used by {@link AbstractApplicationContext} when a {@link SecurityManager}
prohibits access to {@link System#getProperties()} or
{@link System#getenv()}. It is for this reason that the implementations of
{@link #keySet()}, {@link #entrySet()}, and {@link #values()} always return
empty even though {@link #get(Object)} may in fact return non-null if the
current security manager allows access to individual keys.
@author Arjen Poutsma
@author Chris Beams
@since 3.0
|
containsKey
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/env/ReadOnlySystemAttributesMap.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/env/ReadOnlySystemAttributesMap.java
|
Apache-2.0
|
@Override
public boolean containsProperty(String name) {
return (getProperty(name) != null);
}
|
Return {@code true} if a property with the given name or any
underscore/uppercase variant thereof exists in this property source.
|
containsProperty
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/env/SystemEnvironmentPropertySource.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/env/SystemEnvironmentPropertySource.java
|
Apache-2.0
|
public static String resolvePlaceholders(String text) {
return resolvePlaceholders(text, false);
}
|
Resolve {@code ${...}} placeholders in the given text, replacing them with
corresponding system property values.
@param text the String to resolve
@return the resolved String
@throws IllegalArgumentException if there is an unresolvable placeholder
@see #PLACEHOLDER_PREFIX
@see #PLACEHOLDER_SUFFIX
|
resolvePlaceholders
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/env/SystemPropertyUtils.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/env/SystemPropertyUtils.java
|
Apache-2.0
|
public static <C> Class<C[]> arrayClass(Class<C> klass) {
return (Class<C[]>) Array.newInstance(klass, 0).getClass();
}
|
Get an array class of the given class.
@param klass to get an array class of
@param <C> the targeted class
@return an array class of the given class
|
arrayClass
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/env/convert/DefaultConversionService.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/env/convert/DefaultConversionService.java
|
Apache-2.0
|
public static Class<?> objectiveClass(Class<?> klass) {
Class<?> component = klass.getComponentType();
if (component != null) {
if (component.isPrimitive() || component.isArray())
return arrayClass(objectiveClass(component));
} else if (klass.isPrimitive()) {
if (klass == char.class)
return Character.class;
if (klass == int.class)
return Integer.class;
if (klass == boolean.class)
return Boolean.class;
if (klass == byte.class)
return Byte.class;
if (klass == double.class)
return Double.class;
if (klass == float.class)
return Float.class;
if (klass == long.class)
return Long.class;
if (klass == short.class)
return Short.class;
}
return klass;
}
|
Get the class that extends {@link Object} that represent the given class.
@param klass to get the object class of
@return the class that extends Object class and represent the given class
|
objectiveClass
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/env/convert/DefaultConversionService.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/env/convert/DefaultConversionService.java
|
Apache-2.0
|
public Boolean convert(String source, Class<Boolean> targetType) {
String value = source.trim();
if ("".equals(value)) {
return null;
}
value = value.toLowerCase();
if (trueValues.contains(value)) {
return Boolean.TRUE;
}
else if (falseValues.contains(value)) {
return Boolean.FALSE;
}
else {
throw new IllegalArgumentException("Invalid boolean value '" + source + "'");
}
}
|
Converts String to a Boolean.
@author Keith Donald
@author Juergen Hoeller
@since 3.0
|
convert
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/env/convert/StringToBooleanConverter.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/env/convert/StringToBooleanConverter.java
|
Apache-2.0
|
public Class<?> loadClass(String name) throws ClassNotFoundException {
if (name.startsWith("java.arthas.")) {
ClassLoader extClassLoader = ClassLoader.getSystemClassLoader().getParent();
if (extClassLoader != null) {
return extClassLoader.loadClass(name);
}
}
Class clazz = InstrumentApi.invokeOrigin();
return clazz;
}
|
@see java.lang.ClassLoader#loadClass(String)
@author hengyunabc 2020-11-30
|
loadClass
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/server/instrument/ClassLoader_Instrument.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/server/instrument/ClassLoader_Instrument.java
|
Apache-2.0
|
public static ShellServer create(ShellServerOptions options) {
return new ShellServerImpl(options);
}
|
Create a new shell server with default options.
@param options the options
@return the created shell server
|
create
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/shell/ShellServer.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/shell/ShellServer.java
|
Apache-2.0
|
public static ShellServer create() {
return new ShellServerImpl(new ShellServerOptions());
}
|
Create a new shell server with specific options.
@return the created shell server
|
create
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/shell/ShellServer.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/shell/ShellServer.java
|
Apache-2.0
|
public ShellServer listen() {
return listen(new NoOpHandler<Future<Void>>());
}
|
Start the shell service, this is an asynchronous start.
|
listen
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/shell/ShellServer.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/shell/ShellServer.java
|
Apache-2.0
|
public void close() {
close(new NoOpHandler<Future<Void>>());
}
|
Close the shell server, this is an asynchronous close.
|
close
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/shell/ShellServer.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/shell/ShellServer.java
|
Apache-2.0
|
public ShellServerOptions setWelcomeMessage(String welcomeMessage) {
this.welcomeMessage = welcomeMessage;
return this;
}
|
Set the shell welcome message, i.e the message displayed in the user console when he connects to the shell.
@param welcomeMessage the welcome message
@return a reference to this, so the API can be used fluently
|
setWelcomeMessage
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/shell/ShellServerOptions.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/shell/ShellServerOptions.java
|
Apache-2.0
|
public ShellServerOptions setSessionTimeout(long sessionTimeout) {
this.sessionTimeout = sessionTimeout;
return this;
}
|
Set the session timeout.
@param sessionTimeout the new session timeout
@return a reference to this, so the API can be used fluently
|
setSessionTimeout
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/shell/ShellServerOptions.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/shell/ShellServerOptions.java
|
Apache-2.0
|
public static CliToken createText(String text) {
return new CliTokenImpl(true, text, text);
}
|
Create a text token.
@param text the text
@return the token
|
createText
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/shell/cli/CliTokens.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/shell/cli/CliTokens.java
|
Apache-2.0
|
public static CliToken createBlank(String blank) {
return new CliTokenImpl(false, blank, blank);
}
|
Create a new blank token.
@param blank the blank value
@return the token
|
createBlank
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/shell/cli/CliTokens.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/shell/cli/CliTokens.java
|
Apache-2.0
|
public static List<CliToken> tokenize(String s) {
return CliTokenImpl.tokenize(s);
}
|
Tokenize the string argument and return a list of tokens.
@param s the tokenized string
@return the tokens
|
tokenize
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/shell/cli/CliTokens.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/shell/cli/CliTokens.java
|
Apache-2.0
|
public void complete(Completion completion) {
CompletionUtils.complete(completion, this.getClass());
}
|
Perform command completion, when the command is done completing it should call {@link Completion#complete(List)}
or {@link Completion#complete(String, boolean)} )} method to signal completion is done.
@param completion the completion object
|
complete
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/shell/command/AnnotatedCommand.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/shell/command/AnnotatedCommand.java
|
Apache-2.0
|
public static Command create(final Class<? extends AnnotatedCommand> clazz) {
return new AnnotatedCommandImpl(clazz);
}
|
Create a command from a Java class, annotated with CLI annotations.
@param clazz the class of the command
@return the command object
|
create
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/shell/command/Command.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/shell/command/Command.java
|
Apache-2.0
|
public static CommandBuilder command(String name) {
return new CommandBuilderImpl(name, null);
}
|
Create a new command builder, the command is responsible for managing the options and arguments via the
{@link CommandProcess#args() arguments}.
@param name the command name
@return the command
|
command
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/shell/command/CommandBuilder.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/shell/command/CommandBuilder.java
|
Apache-2.0
|
public static CommandBuilder command(CLI cli) {
return new CommandBuilderImpl(cli.getName(), cli);
}
|
Create a new command with its {@link CLI} descriptor. This command can then retrieve the parsed
{@link CommandProcess#commandLine()} when it executes to know get the command arguments and options.
@param cli the cli to use
@return the command
|
command
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/shell/command/CommandBuilder.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/shell/command/CommandBuilder.java
|
Apache-2.0
|
public static CommandRegistry create() {
return new CommandRegistry();
}
|
Create a new registry.
@return the created registry
|
create
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/shell/command/CommandRegistry.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/shell/command/CommandRegistry.java
|
Apache-2.0
|
public CommandRegistry registerCommand(Command command) {
return registerCommands(Collections.singletonList(command));
}
|
Register a command
@param command the command to register
@return a reference to this, so the API can be used fluently
|
registerCommand
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/shell/command/CommandRegistry.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/shell/command/CommandRegistry.java
|
Apache-2.0
|
public CommandRegistry registerCommands(List<Command> commands) {
for (Command command : commands) {
commandMap.put(command.name(), command);
}
return this;
}
|
Register a list of commands.
@param commands the commands to register
@return a reference to this, so the API can be used fluently
|
registerCommands
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/shell/command/CommandRegistry.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/shell/command/CommandRegistry.java
|
Apache-2.0
|
public static TermServer createTelnetTermServer(Configure configure, ShellServerOptions options) {
int port = configure.getTelnetPort() != null ? configure.getTelnetPort() : ArthasConstants.TELNET_PORT;
return new TelnetTermServer(configure.getIp(), port, options.getConnectionTimeout());
}
|
Create a term server for the Telnet protocol.
@param configure
@return the term server
|
createTelnetTermServer
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/shell/term/TermServer.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/shell/term/TermServer.java
|
Apache-2.0
|
public static TermServer createHttpTermServer() {
// TODO
return null;
}
|
Create a term server for the HTTP protocol, using an existing router.
@return the term server
|
createHttpTermServer
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/shell/term/TermServer.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/shell/term/TermServer.java
|
Apache-2.0
|
public TermServer listen() {
return listen(null);
}
|
Bind the term server, the {@link #termHandler(Handler)} must be set before.
@return this object
|
listen
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/shell/term/TermServer.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/shell/term/TermServer.java
|
Apache-2.0
|
protected static BasicPrincipal extractBasicAuthSubject(HttpRequest request) {
String auth = request.headers().get(HttpHeaderNames.AUTHORIZATION);
if (auth != null) {
String constraint = StringUtils.before(auth, " ");
if (constraint != null) {
if ("Basic".equalsIgnoreCase(constraint.trim())) {
String decoded = StringUtils.after(auth, " ");
if (decoded == null) {
logger.error("Extracted Basic Auth principal failed, bad auth String: {}", auth);
return null;
}
// the decoded part is base64 encoded, so we need to decode that
ByteBuf buf = Unpooled.wrappedBuffer(decoded.getBytes());
ByteBuf out = Base64.decode(buf);
String userAndPw = out.toString(Charset.defaultCharset());
String username = StringUtils.before(userAndPw, ":");
String password = StringUtils.after(userAndPw, ":");
BasicPrincipal principal = new BasicPrincipal(username, password);
logger.debug("Extracted Basic Auth principal from HTTP header: {}", principal);
return principal;
}
}
}
return null;
}
|
Extracts the username and password details from the HTTP basic header
Authorization.
<p/>
This requires that the <tt>Authorization</tt> HTTP header is provided, and
its using Basic. Currently Digest is <b>not</b> supported.
@return {@link HttpPrincipal} with username and password details, or
<tt>null</tt> if not possible to extract
|
extractBasicAuthSubject
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/shell/term/impl/http/BasicHttpAuthenticatorHandler.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/shell/term/impl/http/BasicHttpAuthenticatorHandler.java
|
Apache-2.0
|
private ApiResponse processExecRequest(ApiRequest apiRequest, Session session) {
boolean oneTimeAccess = false;
if (session.get(ONETIME_SESSION_KEY) != null) {
oneTimeAccess = true;
}
try {
String commandLine = apiRequest.getCommand();
Map<String, Object> body = new TreeMap<String, Object>();
body.put("command", commandLine);
ApiResponse response = new ApiResponse();
response.setSessionId(session.getSessionId())
.setBody(body);
if (!session.tryLock()) {
response.setState(ApiState.REFUSED)
.setMessage("Another command is executing.");
return response;
}
int lock = session.getLock();
PackingResultDistributor packingResultDistributor = null;
Job job = null;
try {
Job foregroundJob = session.getForegroundJob();
if (foregroundJob != null) {
response.setState(ApiState.REFUSED)
.setMessage("Another job is running.");
logger.info("Another job is running, jobId: {}", foregroundJob.id());
return response;
}
packingResultDistributor = new PackingResultDistributorImpl(session);
//distribute result message both to origin session channel and request channel by CompositeResultDistributor
//ResultDistributor resultDistributor = new CompositeResultDistributorImpl(packingResultDistributor, session.getResultDistributor());
job = this.createJob(commandLine, session, packingResultDistributor);
session.setForegroundJob(job);
updateSessionInputStatus(session, InputStatus.ALLOW_INTERRUPT);
job.run();
} catch (Throwable e) {
logger.error("Exec command failed:" + e.getMessage() + ", command:" + commandLine, e);
response.setState(ApiState.FAILED).setMessage("Exec command failed:" + e.getMessage());
return response;
} finally {
if (session.getLock() == lock) {
session.unLock();
}
}
//wait for job completed or timeout
Integer timeout = apiRequest.getExecTimeout();
if (timeout == null || timeout <= 0) {
timeout = DEFAULT_EXEC_TIMEOUT;
}
boolean timeExpired = !waitForJob(job, timeout);
if (timeExpired) {
logger.warn("Job is exceeded time limit, force interrupt it, jobId: {}", job.id());
job.interrupt();
response.setState(ApiState.INTERRUPTED).setMessage("The job is exceeded time limit, force interrupt");
} else {
response.setState(ApiState.SUCCEEDED);
}
//packing results
body.put("jobId", job.id());
body.put("jobStatus", job.status());
body.put("timeExpired", timeExpired);
if (timeExpired) {
body.put("timeout", timeout);
}
body.put("results", packingResultDistributor.getResults());
response.setSessionId(session.getSessionId())
//.setConsumerId(consumerId)
.setBody(body);
return response;
} finally {
if (oneTimeAccess) {
sessionManager.removeSession(session.getSessionId());
}
}
}
|
Execute command sync, wait for job finish or timeout, sending results immediately
@param apiRequest
@param session
@return
|
processExecRequest
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/shell/term/impl/http/api/HttpApiHandler.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/shell/term/impl/http/api/HttpApiHandler.java
|
Apache-2.0
|
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > LRUCache.this.cacheSize;
}
|
Creates a new LRU cache.
@param cacheSize the maximum number of entries that will be kept in this
cache.
|
removeEldestEntry
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/shell/term/impl/http/session/LRUCache.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/shell/term/impl/http/session/LRUCache.java
|
Apache-2.0
|
public synchronized V get(K key) {
return map.get(key);
}
|
Retrieves an entry from the cache.<br>
The retrieved entry becomes the MRU (most recently used) entry.
@param key the key whose associated value is to be returned.
@return the value associated to this key, or null if no value with this key
exists in the cache.
|
get
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/shell/term/impl/http/session/LRUCache.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/shell/term/impl/http/session/LRUCache.java
|
Apache-2.0
|
public synchronized void put(K key, V value) {
map.put(key, value);
}
|
Adds an entry to this cache. The new entry becomes the MRU (most recently
used) entry. If an entry with the specified key already exists in the cache,
it is replaced by the new entry. If the cache is full, the LRU (least
recently used) entry is removed from the cache.
@param key the key with which the specified value is to be associated.
@param value a value to be associated with the specified key.
|
put
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/shell/term/impl/http/session/LRUCache.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/shell/term/impl/http/session/LRUCache.java
|
Apache-2.0
|
public synchronized Collection<Map.Entry<K, V>> getAll() {
return new ArrayList<Map.Entry<K, V>>(map.entrySet());
}
|
Returns a <code>Collection</code> that contains a copy of all cache entries.
@return a <code>Collection</code> with a copy of the cache content.
|
getAll
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/shell/term/impl/http/session/LRUCache.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/shell/term/impl/http/session/LRUCache.java
|
Apache-2.0
|
public static <E> boolean isIn(E e, E... s) {
if (null != s) {
for (E es : s) {
if (isEquals(e, es)) {
return true;
}
}
}
return false;
}
|
check whether a component is in an Array<br/>
@param e component
@param s array
@param <E> component type
@return <br/>
(1,1,2,3) == true
(1,2,3,4) == false
(null,1,null,2) == true
(1,null) == false
|
isIn
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/util/ArthasCheckUtils.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/util/ArthasCheckUtils.java
|
Apache-2.0
|
public static <E> boolean isEquals(E src, E target) {
return null == src
&& null == target
|| null != src
&& null != target
&& src.equals(target);
}
|
check whether two components are equal<br/>
@param src source component
@param target target component
@param <E> component type
@return <br/>
(null, null) == true
(1L,2L) == false
(1L,1L) == true
("abc",null) == false
(null,"abc") == false
|
isEquals
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/util/ArthasCheckUtils.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/util/ArthasCheckUtils.java
|
Apache-2.0
|
public static void end(CommandProcess process, ExitStatus status) {
if (status != null) {
process.end(status.getStatusCode(), status.getMessage());
} else {
process.end(-1, "process error, exit status is null");
}
}
|
check exit status and end command processing
@param process CommandProcess instance
@param status ExitStatus of command
|
end
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/util/CommandUtils.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/util/CommandUtils.java
|
Apache-2.0
|
public static boolean isDirectoryOrNotExist(String path) {
File file = new File(path);
return !file.exists() || file.isDirectory();
}
|
Check if the given path is a directory or not exists.
@param path path of file.
@return {@code true} if the path is not exist or is an existing directory, otherwise returns {@code false}.
|
isDirectoryOrNotExist
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/util/FileUtils.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/util/FileUtils.java
|
Apache-2.0
|
public static String getCookieValue(Set<Cookie> cookies, String cookieName) {
for (Cookie cookie : cookies) {
if(cookie.name().equals(cookieName)){
return cookie.value();
}
}
return null;
}
|
Get cookie value by name
@param cookies request cookies
@param cookieName the cookie name
|
getCookieValue
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/util/HttpUtils.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/util/HttpUtils.java
|
Apache-2.0
|
public static void setCookie(DefaultFullHttpResponse response, String name, String value) {
response.headers().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode(name, value));
}
|
@param response
@param name
@param value
|
setCookie
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/util/HttpUtils.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/util/HttpUtils.java
|
Apache-2.0
|
public static boolean isWindowsOS() {
String osName = System.getProperty(OS_NAME);
return osName.toLowerCase().contains(WINDOWS);
}
|
check: whether current operating system is windows
@return true---is windows
|
isWindowsOS
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/util/IPUtils.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/util/IPUtils.java
|
Apache-2.0
|
public static String simpleRequest(String url) {
BufferedReader br = null;
try {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestProperty("Accept", "application/json");
int responseCode = con.getResponseCode();
br = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line);
sb.append("\n");
}
String result = sb.toString().trim();
if (responseCode == 500) {
JSONObject errorObj = JSON.parseObject(result);
if (errorObj.containsKey("errorMsg")) {
return errorObj.getString("errorMsg");
}
return result;
} else {
return result;
}
} catch (Exception e) {
return null;
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
// ignore
}
}
}
}
|
@deprecated
This implementation is based on HttpURLConnection,
which can not detail with status code other than 200.
@param url the requested url
@return the response string of given url
|
simpleRequest
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/util/NetUtils.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/util/NetUtils.java
|
Apache-2.0
|
public static boolean serverListening(String host, int port) {
Socket s = null;
try {
s = new Socket(host, port);
return true;
} catch (Exception e) {
return false;
} finally {
if (s != null) {
try {
s.close();
} catch (Exception e) {
// ignore
}
}
}
}
|
Test if a port is open on the give host
|
serverListening
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/util/NetUtils.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/util/NetUtils.java
|
Apache-2.0
|
public static String before(String text, String before) {
int pos = text.indexOf(before);
return pos == -1 ? null : text.substring(0, pos);
}
|
Returns the string before the given token
@param text the text
@param before the token
@return the text before the token, or <tt>null</tt> if text does not contain
the token
|
before
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/util/StringUtils.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/util/StringUtils.java
|
Apache-2.0
|
private static int findTheSpyAPIDepth(StackTraceElement[] stackTraceElementArray) {
if (MAGIC_STACK_DEPTH > 0) {
return MAGIC_STACK_DEPTH;
}
if (MAGIC_STACK_DEPTH > stackTraceElementArray.length) {
return 0;
}
for (int i = 0; i < stackTraceElementArray.length; ++i) {
if (SpyAPI.class.getName().equals(stackTraceElementArray[i].getClassName())) {
MAGIC_STACK_DEPTH = i + 1;
break;
}
}
return MAGIC_STACK_DEPTH;
}
|
</pre>
java.lang.Thread.getStackTrace(Thread.java:1559),
com.taobao.arthas.core.util.ThreadUtil.getThreadStack(ThreadUtil.java:349),
com.taobao.arthas.core.command.monitor200.StackAdviceListener.before(StackAdviceListener.java:33),
com.taobao.arthas.core.advisor.AdviceListenerAdapter.before(AdviceListenerAdapter.java:49),
com.taobao.arthas.core.advisor.SpyImpl.atEnter(SpyImpl.java:42),
java.arthas.SpyAPI.atEnter(SpyAPI.java:40),
demo.MathGame.print(MathGame.java), demo.MathGame.run(MathGame.java:25),
demo.MathGame.main(MathGame.java:16)
</pre>
|
findTheSpyAPIDepth
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/util/ThreadUtil.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/util/ThreadUtil.java
|
Apache-2.0
|
@Override
public boolean matching(T target) {
return false;
}
|
always return false
@param target
@return true/false
|
matching
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/util/matcher/FalseMatcher.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/util/matcher/FalseMatcher.java
|
Apache-2.0
|
@Override
public boolean matching(T target) {
return true;
}
|
always return true
@param target
@return
|
matching
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/util/matcher/TrueMatcher.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/util/matcher/TrueMatcher.java
|
Apache-2.0
|
private static long nextLong(long n) {
long bits, val;
do {
bits = ThreadLocalRandom.current().nextLong() & (~(1L << BITS_PER_LONG));
val = bits % n;
} while (bits - val + (n - 1) < 0L);
return val;
}
|
Get a pseudo-random long uniformly between 0 and n-1. Stolen from
{@link java.util.Random#nextInt()}.
@param n
the bound
@return a value select randomly from the range {@code [0..n)}.
|
nextLong
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/util/metrics/RateCounter.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/util/metrics/RateCounter.java
|
Apache-2.0
|
public static Object readDeclaredField(final Object target, final String fieldName, final boolean forceAccess) throws IllegalAccessException {
isTrue(target != null, "target object must not be null");
final Class<?> cls = target.getClass();
final Field field = getDeclaredField(cls, fieldName, forceAccess);
isTrue(field != null, "Cannot locate declared field %s.%s", cls, fieldName);
// already forced access above, don't repeat it here:
return readField(field, target, false);
}
|
Gets a {@link Field} value by name. Only the class of the specified object will be considered.
@param target
the object to reflect, must not be {@code null}
@param fieldName
the field name to obtain
@param forceAccess
whether to break scope restrictions using the
{@link java.lang.reflect.AccessibleObject#setAccessible(boolean)} method. {@code false} will only
match public fields.
@return the Field object
@throws IllegalArgumentException
if {@code target} is {@code null}, or the field name is blank or empty or could not be found
@throws IllegalAccessException
if the field is not made accessible
|
readDeclaredField
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/util/reflect/FieldUtils.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/util/reflect/FieldUtils.java
|
Apache-2.0
|
public static Field getDeclaredField(final Class<?> cls, final String fieldName, final boolean forceAccess) {
isTrue(cls != null, "The class must not be null");
isTrue(!StringUtils.isBlank(fieldName), "The field name must not be blank/empty");
try {
// only consider the specified class by using getDeclaredField()
final Field field = cls.getDeclaredField(fieldName);
if (!isAccessible(field)) {
if (forceAccess) {
field.setAccessible(true);
} else {
return null;
}
}
return field;
} catch (final NoSuchFieldException e) { // NOPMD
// ignore
}
return null;
}
|
Gets an accessible {@link Field} by name, breaking scope if requested. Only the specified class will be
considered.
@param cls
the {@link Class} to reflect, must not be {@code null}
@param fieldName
the field name to obtain
@param forceAccess
whether to break scope restrictions using the
{@link java.lang.reflect.AccessibleObject#setAccessible(boolean)} method. {@code false} will only
match {@code public} fields.
@return the Field object
@throws IllegalArgumentException
if the class is {@code null}, or the field name is blank or empty
|
getDeclaredField
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/util/reflect/FieldUtils.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/util/reflect/FieldUtils.java
|
Apache-2.0
|
public static Object readField(final Field field, final Object target, final boolean forceAccess) throws IllegalAccessException {
isTrue(field != null, "The field must not be null");
if (forceAccess && !field.isAccessible()) {
field.setAccessible(true);
} else {
setAccessibleWorkaround(field);
}
return field.get(target);
}
|
Reads a {@link Field}.
@param field
the field to use
@param target
the object to call on, may be {@code null} for {@code static} fields
@param forceAccess
whether to break scope restrictions using the
{@link java.lang.reflect.AccessibleObject#setAccessible(boolean)} method.
@return the field value
@throws IllegalArgumentException
if the field is {@code null}
@throws IllegalAccessException
if the field is not made accessible
|
readField
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/util/reflect/FieldUtils.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/util/reflect/FieldUtils.java
|
Apache-2.0
|
public static Object readStaticField(final Field field, final boolean forceAccess) throws IllegalAccessException {
isTrue(field != null, "The field must not be null");
isTrue(Modifier.isStatic(field.getModifiers()), "The field '%s' is not static", field.getName());
return readField(field, (Object) null, forceAccess);
}
|
Reads a static {@link Field}.
@param field
to read
@param forceAccess
whether to break scope restrictions using the
{@link java.lang.reflect.AccessibleObject#setAccessible(boolean)} method.
@return the field value
@throws IllegalArgumentException
if the field is {@code null} or not {@code static}
@throws IllegalAccessException
if the field is not made accessible
|
readStaticField
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/util/reflect/FieldUtils.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/util/reflect/FieldUtils.java
|
Apache-2.0
|
public static void writeStaticField(final Field field, final Object value, final boolean forceAccess) throws IllegalAccessException {
isTrue(field != null, "The field must not be null");
isTrue(Modifier.isStatic(field.getModifiers()), "The field %s.%s is not static", field.getDeclaringClass().getName(),
field.getName());
writeField(field, (Object) null, value, forceAccess);
}
|
Writes a static {@link Field}.
@param field
to write
@param value
to set
@param forceAccess
whether to break scope restrictions using the
{@link java.lang.reflect.AccessibleObject#setAccessible(boolean)} method. {@code false} will only
match {@code public} fields.
@throws IllegalArgumentException
if the field is {@code null} or not {@code static}, or {@code value} is not assignable
@throws IllegalAccessException
if the field is not made accessible or is {@code final}
|
writeStaticField
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/util/reflect/FieldUtils.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/util/reflect/FieldUtils.java
|
Apache-2.0
|
public static void writeField(final Field field, final Object target, final Object value, final boolean forceAccess)
throws IllegalAccessException {
isTrue(field != null, "The field must not be null");
if (forceAccess && !field.isAccessible()) {
field.setAccessible(true);
} else {
setAccessibleWorkaround(field);
}
field.set(target, value);
}
|
Writes a {@link Field}.
@param field
to write
@param target
the object to call on, may be {@code null} for {@code static} fields
@param value
to set
@param forceAccess
whether to break scope restrictions using the
{@link java.lang.reflect.AccessibleObject#setAccessible(boolean)} method. {@code false} will only
match {@code public} fields.
@throws IllegalArgumentException
if the field is {@code null} or {@code value} is not assignable
@throws IllegalAccessException
if the field is not made accessible or is {@code final}
|
writeField
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/util/reflect/FieldUtils.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/util/reflect/FieldUtils.java
|
Apache-2.0
|
public static Field getField(final Class<?> cls, final String fieldName) {
final Field field = getField(cls, fieldName, false);
setAccessibleWorkaround(field);
return field;
}
|
Gets an accessible {@link Field} by name respecting scope. Superclasses/interfaces will be considered.
@param cls
the {@link Class} to reflect, must not be {@code null}
@param fieldName
the field name to obtain
@return the Field object
@throws IllegalArgumentException
if the class is {@code null}, or the field name is blank or empty
|
getField
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/util/reflect/FieldUtils.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/util/reflect/FieldUtils.java
|
Apache-2.0
|
public static Field getField(final Class<?> cls, final String fieldName, final boolean forceAccess) {
isTrue(cls != null, "The class must not be null");
isTrue(!StringUtils.isBlank(fieldName), "The field name must not be blank/empty");
// FIXME is this workaround still needed? lang requires Java 6
// Sun Java 1.3 has a bugged implementation of getField hence we write the
// code ourselves
// getField() will return the Field object with the declaring class
// set correctly to the class that declares the field. Thus requesting the
// field on a subclass will return the field from the superclass.
//
// priority order for lookup:
// searchclass private/protected/package/public
// superclass protected/package/public
// private/different package blocks access to further superclasses
// implementedinterface public
// check up the superclass hierarchy
for (Class<?> acls = cls; acls != null; acls = acls.getSuperclass()) {
try {
final Field field = acls.getDeclaredField(fieldName);
// getDeclaredField checks for non-public scopes as well
// and it returns accurate results
if (!Modifier.isPublic(field.getModifiers())) {
if (forceAccess) {
field.setAccessible(true);
} else {
continue;
}
}
return field;
} catch (final NoSuchFieldException ex) { // NOPMD
// ignore
}
}
// check the public interface case. This must be manually searched for
// incase there is a public supersuperclass field hidden by a private/package
// superclass field.
Field match = null;
for (final Class<?> class1 : getAllInterfaces(cls)) {
try {
final Field test = class1.getField(fieldName);
isTrue(match == null, "Reference to field %s is ambiguous relative to %s"
+ "; a matching field exists on two or more implemented interfaces.", fieldName, cls);
match = test;
} catch (final NoSuchFieldException ex) { // NOPMD
// ignore
}
}
return match;
}
|
Gets an accessible {@link Field} by name, breaking scope if requested. Superclasses/interfaces will be
considered.
@param cls
the {@link Class} to reflect, must not be {@code null}
@param fieldName
the field name to obtain
@param forceAccess
whether to break scope restrictions using the
{@link java.lang.reflect.AccessibleObject#setAccessible(boolean)} method. {@code false} will only
match {@code public} fields.
@return the Field object
@throws IllegalArgumentException
if the class is {@code null}, or the field name is blank or empty or is matched at multiple places
in the inheritance hierarchy
|
getField
|
java
|
alibaba/arthas
|
core/src/main/java/com/taobao/arthas/core/util/reflect/FieldUtils.java
|
https://github.com/alibaba/arthas/blob/master/core/src/main/java/com/taobao/arthas/core/util/reflect/FieldUtils.java
|
Apache-2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.