code
stringlengths 11
173k
| docstring
stringlengths 2
593k
| func_name
stringlengths 2
189
| language
stringclasses 1
value | repo
stringclasses 833
values | path
stringlengths 11
294
| url
stringlengths 60
339
| license
stringclasses 4
values |
---|---|---|---|---|---|---|---|
public String newName(String suggestion, Object tag) {
checkNotNull(suggestion, "suggestion");
checkNotNull(tag, "tag");
suggestion = toJavaIdentifier(suggestion);
while (SourceVersion.isKeyword(suggestion) || !allocatedNames.add(suggestion)) {
suggestion = suggestion + "_";
}
String replaced = tagToName.put(tag, suggestion);
if (replaced != null) {
tagToName.put(tag, replaced); // Put things back as they were!
throw new IllegalArgumentException("tag " + tag + " cannot be used for both '" + replaced
+ "' and '" + suggestion + "'");
}
return suggestion;
} |
Return a new name using {@code suggestion} that will not be a Java identifier or clash with
other names. The returned value can be queried multiple times by passing {@code tag} to
{@link #get(Object)}.
| NameAllocator::newName | java | square/javapoet | src/main/java/com/squareup/javapoet/NameAllocator.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/NameAllocator.java | Apache-2.0 |
public String get(Object tag) {
String result = tagToName.get(tag);
if (result == null) {
throw new IllegalArgumentException("unknown tag: " + tag);
}
return result;
} |
Return a new name using {@code suggestion} that will not be a Java identifier or clash with
other names. The returned value can be queried multiple times by passing {@code tag} to
{@link #get(Object)}.
public String newName(String suggestion, Object tag) {
checkNotNull(suggestion, "suggestion");
checkNotNull(tag, "tag");
suggestion = toJavaIdentifier(suggestion);
while (SourceVersion.isKeyword(suggestion) || !allocatedNames.add(suggestion)) {
suggestion = suggestion + "_";
}
String replaced = tagToName.put(tag, suggestion);
if (replaced != null) {
tagToName.put(tag, replaced); // Put things back as they were!
throw new IllegalArgumentException("tag " + tag + " cannot be used for both '" + replaced
+ "' and '" + suggestion + "'");
}
return suggestion;
}
public static String toJavaIdentifier(String suggestion) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < suggestion.length(); ) {
int codePoint = suggestion.codePointAt(i);
if (i == 0
&& !Character.isJavaIdentifierStart(codePoint)
&& Character.isJavaIdentifierPart(codePoint)) {
result.append("_");
}
int validCodePoint = Character.isJavaIdentifierPart(codePoint) ? codePoint : '_';
result.appendCodePoint(validCodePoint);
i += Character.charCount(codePoint);
}
return result.toString();
}
/** Retrieve a name created with {@link #newName(String, Object)}. | NameAllocator::get | java | square/javapoet | src/main/java/com/squareup/javapoet/NameAllocator.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/NameAllocator.java | Apache-2.0 |
static String stringLiteralWithDoubleQuotes(String value, String indent) {
StringBuilder result = new StringBuilder(value.length() + 2);
result.append('"');
for (int i = 0; i < value.length(); i++) {
char c = value.charAt(i);
// trivial case: single quote must not be escaped
if (c == '\'') {
result.append("'");
continue;
}
// trivial case: double quotes must be escaped
if (c == '\"') {
result.append("\\\"");
continue;
}
// default case: just let character literal do its work
result.append(characterLiteralWithoutSingleQuotes(c));
// need to append indent after linefeed?
if (c == '\n' && i + 1 < value.length()) {
result.append("\"\n").append(indent).append(indent).append("+ \"");
}
}
result.append('"');
return result.toString();
} |
Like Guava, but worse and standalone. This makes it easier to mix JavaPoet with libraries that
bring their own version of Guava.
final class Util {
private Util() {
}
static <K, V> Map<K, List<V>> immutableMultimap(Map<K, List<V>> multimap) {
LinkedHashMap<K, List<V>> result = new LinkedHashMap<>();
for (Map.Entry<K, List<V>> entry : multimap.entrySet()) {
if (entry.getValue().isEmpty()) continue;
result.put(entry.getKey(), immutableList(entry.getValue()));
}
return Collections.unmodifiableMap(result);
}
static <K, V> Map<K, V> immutableMap(Map<K, V> map) {
return Collections.unmodifiableMap(new LinkedHashMap<>(map));
}
static void checkArgument(boolean condition, String format, Object... args) {
if (!condition) throw new IllegalArgumentException(String.format(format, args));
}
static <T> T checkNotNull(T reference, String format, Object... args) {
if (reference == null) throw new NullPointerException(String.format(format, args));
return reference;
}
static void checkState(boolean condition, String format, Object... args) {
if (!condition) throw new IllegalStateException(String.format(format, args));
}
static <T> List<T> immutableList(Collection<T> collection) {
return Collections.unmodifiableList(new ArrayList<>(collection));
}
static <T> Set<T> immutableSet(Collection<T> set) {
return Collections.unmodifiableSet(new LinkedHashSet<>(set));
}
static <T> Set<T> union(Set<T> a, Set<T> b) {
Set<T> result = new LinkedHashSet<>();
result.addAll(a);
result.addAll(b);
return result;
}
static void requireExactlyOneOf(Set<Modifier> modifiers, Modifier... mutuallyExclusive) {
int count = 0;
for (Modifier modifier : mutuallyExclusive) {
if (modifiers.contains(modifier)) count++;
}
checkArgument(count == 1, "modifiers %s must contain one of %s",
modifiers, Arrays.toString(mutuallyExclusive));
}
static String characterLiteralWithoutSingleQuotes(char c) {
// see https://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.10.6
switch (c) {
case '\b': return "\\b"; /* \u0008: backspace (BS)
case '\t': return "\\t"; /* \u0009: horizontal tab (HT)
case '\n': return "\\n"; /* \u000a: linefeed (LF)
case '\f': return "\\f"; /* \u000c: form feed (FF)
case '\r': return "\\r"; /* \u000d: carriage return (CR)
case '\"': return "\""; /* \u0022: double quote (")
case '\'': return "\\'"; /* \u0027: single quote (')
case '\\': return "\\\\"; /* \u005c: backslash (\)
default:
return isISOControl(c) ? String.format("\\u%04x", (int) c) : Character.toString(c);
}
}
/** Returns the string literal representing {@code value}, including wrapping double quotes. | Util::stringLiteralWithDoubleQuotes | java | square/javapoet | src/main/java/com/squareup/javapoet/Util.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/Util.java | Apache-2.0 |
public Builder beginControlFlow(String controlFlow, Object... args) {
code.beginControlFlow(controlFlow, args);
return this;
} |
@param controlFlow the control flow construct and its code, such as "if (foo == 5)".
Shouldn't contain braces or newline characters.
| Builder::beginControlFlow | java | square/javapoet | src/main/java/com/squareup/javapoet/MethodSpec.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/MethodSpec.java | Apache-2.0 |
public Builder beginControlFlow(CodeBlock codeBlock) {
return beginControlFlow("$L", codeBlock);
} |
@param codeBlock the control flow construct and its code, such as "if (foo == 5)".
Shouldn't contain braces or newline characters.
| Builder::beginControlFlow | java | square/javapoet | src/main/java/com/squareup/javapoet/MethodSpec.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/MethodSpec.java | Apache-2.0 |
public Builder nextControlFlow(String controlFlow, Object... args) {
code.nextControlFlow(controlFlow, args);
return this;
} |
@param controlFlow the control flow construct and its code, such as "else if (foo == 10)".
Shouldn't contain braces or newline characters.
| Builder::nextControlFlow | java | square/javapoet | src/main/java/com/squareup/javapoet/MethodSpec.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/MethodSpec.java | Apache-2.0 |
public Builder nextControlFlow(CodeBlock codeBlock) {
return nextControlFlow("$L", codeBlock);
} |
@param codeBlock the control flow construct and its code, such as "else if (foo == 10)".
Shouldn't contain braces or newline characters.
| Builder::nextControlFlow | java | square/javapoet | src/main/java/com/squareup/javapoet/MethodSpec.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/MethodSpec.java | Apache-2.0 |
public Builder endControlFlow(String controlFlow, Object... args) {
code.endControlFlow(controlFlow, args);
return this;
} |
@param controlFlow the optional control flow construct and its code, such as
"while(foo == 20)". Only used for "do/while" control flows.
| Builder::endControlFlow | java | square/javapoet | src/main/java/com/squareup/javapoet/MethodSpec.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/MethodSpec.java | Apache-2.0 |
public Builder endControlFlow(CodeBlock codeBlock) {
return endControlFlow("$L", codeBlock);
} |
@param codeBlock the optional control flow construct and its code, such as
"while(foo == 20)". Only used for "do/while" control flows.
| Builder::endControlFlow | java | square/javapoet | src/main/java/com/squareup/javapoet/MethodSpec.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/MethodSpec.java | Apache-2.0 |
public static CodeBlock join(Iterable<CodeBlock> codeBlocks, String separator) {
return StreamSupport.stream(codeBlocks.spliterator(), false).collect(joining(separator));
} |
Joins {@code codeBlocks} into a single {@link CodeBlock}, each separated by {@code separator}.
For example, joining {@code String s}, {@code Object o} and {@code int i} using {@code ", "}
would produce {@code String s, Object o, int i}.
| CodeBlock::join | java | square/javapoet | src/main/java/com/squareup/javapoet/CodeBlock.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/CodeBlock.java | Apache-2.0 |
public static Collector<CodeBlock, ?, CodeBlock> joining(String separator) {
return Collector.of(
() -> new CodeBlockJoiner(separator, builder()),
CodeBlockJoiner::add,
CodeBlockJoiner::merge,
CodeBlockJoiner::join);
} |
A {@link Collector} implementation that joins {@link CodeBlock} instances together into one
separated by {@code separator}. For example, joining {@code String s}, {@code Object o} and
{@code int i} using {@code ", "} would produce {@code String s, Object o, int i}.
| CodeBlock::joining | java | square/javapoet | src/main/java/com/squareup/javapoet/CodeBlock.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/CodeBlock.java | Apache-2.0 |
public Builder addNamed(String format, Map<String, ?> arguments) {
int p = 0;
for (String argument : arguments.keySet()) {
checkArgument(LOWERCASE.matcher(argument).matches(),
"argument '%s' must start with a lowercase character", argument);
}
while (p < format.length()) {
int nextP = format.indexOf("$", p);
if (nextP == -1) {
formatParts.add(format.substring(p));
break;
}
if (p != nextP) {
formatParts.add(format.substring(p, nextP));
p = nextP;
}
Matcher matcher = null;
int colon = format.indexOf(':', p);
if (colon != -1) {
int endIndex = Math.min(colon + 2, format.length());
matcher = NAMED_ARGUMENT.matcher(format.substring(p, endIndex));
}
if (matcher != null && matcher.lookingAt()) {
String argumentName = matcher.group("argumentName");
checkArgument(arguments.containsKey(argumentName), "Missing named argument for $%s",
argumentName);
char formatChar = matcher.group("typeChar").charAt(0);
addArgument(format, formatChar, arguments.get(argumentName));
formatParts.add("$" + formatChar);
p += matcher.regionEnd();
} else {
checkArgument(p < format.length() - 1, "dangling $ at end");
checkArgument(isNoArgPlaceholder(format.charAt(p + 1)),
"unknown format $%s at %s in '%s'", format.charAt(p + 1), p + 1, format);
formatParts.add(format.substring(p, p + 2));
p += 2;
}
}
return this;
} |
Adds code using named arguments.
<p>Named arguments specify their name after the '$' followed by : and the corresponding type
character. Argument names consist of characters in {@code a-z, A-Z, 0-9, and _} and must
start with a lowercase character.
<p>For example, to refer to the type {@link java.lang.Integer} with the argument name {@code
clazz} use a format string containing {@code $clazz:T} and include the key {@code clazz} with
value {@code java.lang.Integer.class} in the argument map.
| Builder::addNamed | java | square/javapoet | src/main/java/com/squareup/javapoet/CodeBlock.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/CodeBlock.java | Apache-2.0 |
public Builder add(String format, Object... args) {
boolean hasRelative = false;
boolean hasIndexed = false;
int relativeParameterCount = 0;
int[] indexedParameterCount = new int[args.length];
for (int p = 0; p < format.length(); ) {
if (format.charAt(p) != '$') {
int nextP = format.indexOf('$', p + 1);
if (nextP == -1) nextP = format.length();
formatParts.add(format.substring(p, nextP));
p = nextP;
continue;
}
p++; // '$'.
// Consume zero or more digits, leaving 'c' as the first non-digit char after the '$'.
int indexStart = p;
char c;
do {
checkArgument(p < format.length(), "dangling format characters in '%s'", format);
c = format.charAt(p++);
} while (c >= '0' && c <= '9');
int indexEnd = p - 1;
// If 'c' doesn't take an argument, we're done.
if (isNoArgPlaceholder(c)) {
checkArgument(
indexStart == indexEnd, "$$, $>, $<, $[, $], $W, and $Z may not have an index");
formatParts.add("$" + c);
continue;
}
// Find either the indexed argument, or the relative argument. (0-based).
int index;
if (indexStart < indexEnd) {
index = Integer.parseInt(format.substring(indexStart, indexEnd)) - 1;
hasIndexed = true;
if (args.length > 0) {
indexedParameterCount[index % args.length]++; // modulo is needed, checked below anyway
}
} else {
index = relativeParameterCount;
hasRelative = true;
relativeParameterCount++;
}
checkArgument(index >= 0 && index < args.length,
"index %d for '%s' not in range (received %s arguments)",
index + 1, format.substring(indexStart - 1, indexEnd + 1), args.length);
checkArgument(!hasIndexed || !hasRelative, "cannot mix indexed and positional parameters");
addArgument(format, c, args[index]);
formatParts.add("$" + c);
}
if (hasRelative) {
checkArgument(relativeParameterCount >= args.length,
"unused arguments: expected %s, received %s", relativeParameterCount, args.length);
}
if (hasIndexed) {
List<String> unused = new ArrayList<>();
for (int i = 0; i < args.length; i++) {
if (indexedParameterCount[i] == 0) {
unused.add("$" + (i + 1));
}
}
String s = unused.size() == 1 ? "" : "s";
checkArgument(unused.isEmpty(), "unused argument%s: %s", s, String.join(", ", unused));
}
return this;
} |
Add code with positional or relative arguments.
<p>Relative arguments map 1:1 with the placeholders in the format string.
<p>Positional arguments use an index after the placeholder to identify which argument index
to use. For example, for a literal to reference the 3rd argument: "$3L" (1 based index)
<p>Mixing relative and positional arguments in a call to add is invalid and will result in an
error.
| Builder::add | java | square/javapoet | src/main/java/com/squareup/javapoet/CodeBlock.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/CodeBlock.java | Apache-2.0 |
char lastChar() {
return out.lastChar;
} |
Null if we have no buffering; otherwise the type to pass to the next call to {@link #flush}.
private FlushType nextFlush;
LineWrapper(Appendable out, String indent, int columnLimit) {
checkNotNull(out, "out == null");
this.out = new RecordingAppendable(out);
this.indent = indent;
this.columnLimit = columnLimit;
}
/** @return the last emitted char or {@link Character#MIN_VALUE} if nothing emitted yet. | LineWrapper::lastChar | java | square/javapoet | src/main/java/com/squareup/javapoet/LineWrapper.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/LineWrapper.java | Apache-2.0 |
void append(String s) throws IOException {
if (closed) throw new IllegalStateException("closed");
if (nextFlush != null) {
int nextNewline = s.indexOf('\n');
// If s doesn't cause the current line to cross the limit, buffer it and return. We'll decide
// whether or not we have to wrap it later.
if (nextNewline == -1 && column + s.length() <= columnLimit) {
buffer.append(s);
column += s.length();
return;
}
// Wrap if appending s would overflow the current line.
boolean wrap = nextNewline == -1 || column + nextNewline > columnLimit;
flush(wrap ? FlushType.WRAP : nextFlush);
}
out.append(s);
int lastNewline = s.lastIndexOf('\n');
column = lastNewline != -1
? s.length() - lastNewline - 1
: column + s.length();
} |
Null if we have no buffering; otherwise the type to pass to the next call to {@link #flush}.
private FlushType nextFlush;
LineWrapper(Appendable out, String indent, int columnLimit) {
checkNotNull(out, "out == null");
this.out = new RecordingAppendable(out);
this.indent = indent;
this.columnLimit = columnLimit;
}
/** @return the last emitted char or {@link Character#MIN_VALUE} if nothing emitted yet.
char lastChar() {
return out.lastChar;
}
/** Emit {@code s}. This may be buffered to permit line wraps to be inserted. | LineWrapper::append | java | square/javapoet | src/main/java/com/squareup/javapoet/LineWrapper.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/LineWrapper.java | Apache-2.0 |
void wrappingSpace(int indentLevel) throws IOException {
if (closed) throw new IllegalStateException("closed");
if (this.nextFlush != null) flush(nextFlush);
column++; // Increment the column even though the space is deferred to next call to flush().
this.nextFlush = FlushType.SPACE;
this.indentLevel = indentLevel;
} |
Null if we have no buffering; otherwise the type to pass to the next call to {@link #flush}.
private FlushType nextFlush;
LineWrapper(Appendable out, String indent, int columnLimit) {
checkNotNull(out, "out == null");
this.out = new RecordingAppendable(out);
this.indent = indent;
this.columnLimit = columnLimit;
}
/** @return the last emitted char or {@link Character#MIN_VALUE} if nothing emitted yet.
char lastChar() {
return out.lastChar;
}
/** Emit {@code s}. This may be buffered to permit line wraps to be inserted.
void append(String s) throws IOException {
if (closed) throw new IllegalStateException("closed");
if (nextFlush != null) {
int nextNewline = s.indexOf('\n');
// If s doesn't cause the current line to cross the limit, buffer it and return. We'll decide
// whether or not we have to wrap it later.
if (nextNewline == -1 && column + s.length() <= columnLimit) {
buffer.append(s);
column += s.length();
return;
}
// Wrap if appending s would overflow the current line.
boolean wrap = nextNewline == -1 || column + nextNewline > columnLimit;
flush(wrap ? FlushType.WRAP : nextFlush);
}
out.append(s);
int lastNewline = s.lastIndexOf('\n');
column = lastNewline != -1
? s.length() - lastNewline - 1
: column + s.length();
}
/** Emit either a space or a newline character. | LineWrapper::wrappingSpace | java | square/javapoet | src/main/java/com/squareup/javapoet/LineWrapper.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/LineWrapper.java | Apache-2.0 |
void zeroWidthSpace(int indentLevel) throws IOException {
if (closed) throw new IllegalStateException("closed");
if (column == 0) return;
if (this.nextFlush != null) flush(nextFlush);
this.nextFlush = FlushType.EMPTY;
this.indentLevel = indentLevel;
} |
Null if we have no buffering; otherwise the type to pass to the next call to {@link #flush}.
private FlushType nextFlush;
LineWrapper(Appendable out, String indent, int columnLimit) {
checkNotNull(out, "out == null");
this.out = new RecordingAppendable(out);
this.indent = indent;
this.columnLimit = columnLimit;
}
/** @return the last emitted char or {@link Character#MIN_VALUE} if nothing emitted yet.
char lastChar() {
return out.lastChar;
}
/** Emit {@code s}. This may be buffered to permit line wraps to be inserted.
void append(String s) throws IOException {
if (closed) throw new IllegalStateException("closed");
if (nextFlush != null) {
int nextNewline = s.indexOf('\n');
// If s doesn't cause the current line to cross the limit, buffer it and return. We'll decide
// whether or not we have to wrap it later.
if (nextNewline == -1 && column + s.length() <= columnLimit) {
buffer.append(s);
column += s.length();
return;
}
// Wrap if appending s would overflow the current line.
boolean wrap = nextNewline == -1 || column + nextNewline > columnLimit;
flush(wrap ? FlushType.WRAP : nextFlush);
}
out.append(s);
int lastNewline = s.lastIndexOf('\n');
column = lastNewline != -1
? s.length() - lastNewline - 1
: column + s.length();
}
/** Emit either a space or a newline character.
void wrappingSpace(int indentLevel) throws IOException {
if (closed) throw new IllegalStateException("closed");
if (this.nextFlush != null) flush(nextFlush);
column++; // Increment the column even though the space is deferred to next call to flush().
this.nextFlush = FlushType.SPACE;
this.indentLevel = indentLevel;
}
/** Emit a newline character if the line will exceed it's limit, otherwise do nothing. | LineWrapper::zeroWidthSpace | java | square/javapoet | src/main/java/com/squareup/javapoet/LineWrapper.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/LineWrapper.java | Apache-2.0 |
void close() throws IOException {
if (nextFlush != null) flush(nextFlush);
closed = true;
} |
Null if we have no buffering; otherwise the type to pass to the next call to {@link #flush}.
private FlushType nextFlush;
LineWrapper(Appendable out, String indent, int columnLimit) {
checkNotNull(out, "out == null");
this.out = new RecordingAppendable(out);
this.indent = indent;
this.columnLimit = columnLimit;
}
/** @return the last emitted char or {@link Character#MIN_VALUE} if nothing emitted yet.
char lastChar() {
return out.lastChar;
}
/** Emit {@code s}. This may be buffered to permit line wraps to be inserted.
void append(String s) throws IOException {
if (closed) throw new IllegalStateException("closed");
if (nextFlush != null) {
int nextNewline = s.indexOf('\n');
// If s doesn't cause the current line to cross the limit, buffer it and return. We'll decide
// whether or not we have to wrap it later.
if (nextNewline == -1 && column + s.length() <= columnLimit) {
buffer.append(s);
column += s.length();
return;
}
// Wrap if appending s would overflow the current line.
boolean wrap = nextNewline == -1 || column + nextNewline > columnLimit;
flush(wrap ? FlushType.WRAP : nextFlush);
}
out.append(s);
int lastNewline = s.lastIndexOf('\n');
column = lastNewline != -1
? s.length() - lastNewline - 1
: column + s.length();
}
/** Emit either a space or a newline character.
void wrappingSpace(int indentLevel) throws IOException {
if (closed) throw new IllegalStateException("closed");
if (this.nextFlush != null) flush(nextFlush);
column++; // Increment the column even though the space is deferred to next call to flush().
this.nextFlush = FlushType.SPACE;
this.indentLevel = indentLevel;
}
/** Emit a newline character if the line will exceed it's limit, otherwise do nothing.
void zeroWidthSpace(int indentLevel) throws IOException {
if (closed) throw new IllegalStateException("closed");
if (column == 0) return;
if (this.nextFlush != null) flush(nextFlush);
this.nextFlush = FlushType.EMPTY;
this.indentLevel = indentLevel;
}
/** Flush any outstanding text and forbid future writes to this line wrapper. | LineWrapper::close | java | square/javapoet | src/main/java/com/squareup/javapoet/LineWrapper.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/LineWrapper.java | Apache-2.0 |
private void flush(FlushType flushType) throws IOException {
switch (flushType) {
case WRAP:
out.append('\n');
for (int i = 0; i < indentLevel; i++) {
out.append(indent);
}
column = indentLevel * indent.length();
column += buffer.length();
break;
case SPACE:
out.append(' ');
break;
case EMPTY:
break;
default:
throw new IllegalArgumentException("Unknown FlushType: " + flushType);
}
out.append(buffer);
buffer.delete(0, buffer.length());
indentLevel = -1;
nextFlush = null;
} |
Null if we have no buffering; otherwise the type to pass to the next call to {@link #flush}.
private FlushType nextFlush;
LineWrapper(Appendable out, String indent, int columnLimit) {
checkNotNull(out, "out == null");
this.out = new RecordingAppendable(out);
this.indent = indent;
this.columnLimit = columnLimit;
}
/** @return the last emitted char or {@link Character#MIN_VALUE} if nothing emitted yet.
char lastChar() {
return out.lastChar;
}
/** Emit {@code s}. This may be buffered to permit line wraps to be inserted.
void append(String s) throws IOException {
if (closed) throw new IllegalStateException("closed");
if (nextFlush != null) {
int nextNewline = s.indexOf('\n');
// If s doesn't cause the current line to cross the limit, buffer it and return. We'll decide
// whether or not we have to wrap it later.
if (nextNewline == -1 && column + s.length() <= columnLimit) {
buffer.append(s);
column += s.length();
return;
}
// Wrap if appending s would overflow the current line.
boolean wrap = nextNewline == -1 || column + nextNewline > columnLimit;
flush(wrap ? FlushType.WRAP : nextFlush);
}
out.append(s);
int lastNewline = s.lastIndexOf('\n');
column = lastNewline != -1
? s.length() - lastNewline - 1
: column + s.length();
}
/** Emit either a space or a newline character.
void wrappingSpace(int indentLevel) throws IOException {
if (closed) throw new IllegalStateException("closed");
if (this.nextFlush != null) flush(nextFlush);
column++; // Increment the column even though the space is deferred to next call to flush().
this.nextFlush = FlushType.SPACE;
this.indentLevel = indentLevel;
}
/** Emit a newline character if the line will exceed it's limit, otherwise do nothing.
void zeroWidthSpace(int indentLevel) throws IOException {
if (closed) throw new IllegalStateException("closed");
if (column == 0) return;
if (this.nextFlush != null) flush(nextFlush);
this.nextFlush = FlushType.EMPTY;
this.indentLevel = indentLevel;
}
/** Flush any outstanding text and forbid future writes to this line wrapper.
void close() throws IOException {
if (nextFlush != null) flush(nextFlush);
closed = true;
}
/** Write the space followed by any buffered text that follows it. | LineWrapper::flush | java | square/javapoet | src/main/java/com/squareup/javapoet/LineWrapper.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/LineWrapper.java | Apache-2.0 |
public void writeTo(Path directory) throws IOException {
writeToPath(directory);
} | /*
Copyright (C) 2015 Square, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
package com.squareup.javapoet;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.URI;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import javax.annotation.processing.Filer;
import javax.lang.model.element.Element;
import javax.tools.JavaFileObject;
import javax.tools.JavaFileObject.Kind;
import javax.tools.SimpleJavaFileObject;
import static com.squareup.javapoet.Util.checkArgument;
import static com.squareup.javapoet.Util.checkNotNull;
import static java.nio.charset.StandardCharsets.UTF_8;
/** A Java file containing a single top level class.
public final class JavaFile {
private static final Appendable NULL_APPENDABLE = new Appendable() {
@Override public Appendable append(CharSequence charSequence) {
return this;
}
@Override public Appendable append(CharSequence charSequence, int start, int end) {
return this;
}
@Override public Appendable append(char c) {
return this;
}
};
public final CodeBlock fileComment;
public final String packageName;
public final TypeSpec typeSpec;
public final boolean skipJavaLangImports;
private final Set<String> staticImports;
private final Set<String> alwaysQualify;
private final String indent;
private JavaFile(Builder builder) {
this.fileComment = builder.fileComment.build();
this.packageName = builder.packageName;
this.typeSpec = builder.typeSpec;
this.skipJavaLangImports = builder.skipJavaLangImports;
this.staticImports = Util.immutableSet(builder.staticImports);
this.indent = builder.indent;
Set<String> alwaysQualifiedNames = new LinkedHashSet<>();
fillAlwaysQualifiedNames(builder.typeSpec, alwaysQualifiedNames);
this.alwaysQualify = Util.immutableSet(alwaysQualifiedNames);
}
private void fillAlwaysQualifiedNames(TypeSpec spec, Set<String> alwaysQualifiedNames) {
alwaysQualifiedNames.addAll(spec.alwaysQualifiedNames);
for (TypeSpec nested : spec.typeSpecs) {
fillAlwaysQualifiedNames(nested, alwaysQualifiedNames);
}
}
public void writeTo(Appendable out) throws IOException {
// First pass: emit the entire class, just to collect the types we'll need to import.
CodeWriter importsCollector = new CodeWriter(
NULL_APPENDABLE,
indent,
staticImports,
alwaysQualify
);
emit(importsCollector);
Map<String, ClassName> suggestedImports = importsCollector.suggestedImports();
// Second pass: write the code, taking advantage of the imports.
CodeWriter codeWriter
= new CodeWriter(out, indent, suggestedImports, staticImports, alwaysQualify);
emit(codeWriter);
}
/** Writes this to {@code directory} as UTF-8 using the standard directory structure. | JavaFile::writeTo | java | square/javapoet | src/main/java/com/squareup/javapoet/JavaFile.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/JavaFile.java | Apache-2.0 |
public void writeTo(Path directory, Charset charset) throws IOException {
writeToPath(directory, charset);
} |
Writes this to {@code directory} with the provided {@code charset} using the standard directory
structure.
| JavaFile::writeTo | java | square/javapoet | src/main/java/com/squareup/javapoet/JavaFile.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/JavaFile.java | Apache-2.0 |
public Path writeToPath(Path directory) throws IOException {
return writeToPath(directory, UTF_8);
} |
Writes this to {@code directory} as UTF-8 using the standard directory structure.
Returns the {@link Path} instance to which source is actually written.
| JavaFile::writeToPath | java | square/javapoet | src/main/java/com/squareup/javapoet/JavaFile.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/JavaFile.java | Apache-2.0 |
public Path writeToPath(Path directory, Charset charset) throws IOException {
checkArgument(Files.notExists(directory) || Files.isDirectory(directory),
"path %s exists but is not a directory.", directory);
Path outputDirectory = directory;
if (!packageName.isEmpty()) {
for (String packageComponent : packageName.split("\\.")) {
outputDirectory = outputDirectory.resolve(packageComponent);
}
Files.createDirectories(outputDirectory);
}
Path outputPath = outputDirectory.resolve(typeSpec.name + ".java");
try (Writer writer = new OutputStreamWriter(Files.newOutputStream(outputPath), charset)) {
writeTo(writer);
}
return outputPath;
} |
Writes this to {@code directory} with the provided {@code charset} using the standard directory
structure.
Returns the {@link Path} instance to which source is actually written.
| JavaFile::writeToPath | java | square/javapoet | src/main/java/com/squareup/javapoet/JavaFile.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/JavaFile.java | Apache-2.0 |
public void writeTo(File directory) throws IOException {
writeTo(directory.toPath());
} |
Writes this to {@code directory} with the provided {@code charset} using the standard directory
structure.
Returns the {@link Path} instance to which source is actually written.
public Path writeToPath(Path directory, Charset charset) throws IOException {
checkArgument(Files.notExists(directory) || Files.isDirectory(directory),
"path %s exists but is not a directory.", directory);
Path outputDirectory = directory;
if (!packageName.isEmpty()) {
for (String packageComponent : packageName.split("\\.")) {
outputDirectory = outputDirectory.resolve(packageComponent);
}
Files.createDirectories(outputDirectory);
}
Path outputPath = outputDirectory.resolve(typeSpec.name + ".java");
try (Writer writer = new OutputStreamWriter(Files.newOutputStream(outputPath), charset)) {
writeTo(writer);
}
return outputPath;
}
/** Writes this to {@code directory} as UTF-8 using the standard directory structure. | JavaFile::writeTo | java | square/javapoet | src/main/java/com/squareup/javapoet/JavaFile.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/JavaFile.java | Apache-2.0 |
public File writeToFile(File directory) throws IOException {
final Path outputPath = writeToPath(directory.toPath());
return outputPath.toFile();
} |
Writes this to {@code directory} as UTF-8 using the standard directory structure.
Returns the {@link File} instance to which source is actually written.
| JavaFile::writeToFile | java | square/javapoet | src/main/java/com/squareup/javapoet/JavaFile.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/JavaFile.java | Apache-2.0 |
public void writeTo(Filer filer) throws IOException {
String fileName = packageName.isEmpty()
? typeSpec.name
: packageName + "." + typeSpec.name;
List<Element> originatingElements = typeSpec.originatingElements;
JavaFileObject filerSourceFile = filer.createSourceFile(fileName,
originatingElements.toArray(new Element[originatingElements.size()]));
try (Writer writer = filerSourceFile.openWriter()) {
writeTo(writer);
} catch (Exception e) {
try {
filerSourceFile.delete();
} catch (Exception ignored) {
}
throw e;
}
} |
Writes this to {@code directory} as UTF-8 using the standard directory structure.
Returns the {@link File} instance to which source is actually written.
public File writeToFile(File directory) throws IOException {
final Path outputPath = writeToPath(directory.toPath());
return outputPath.toFile();
}
/** Writes this to {@code filer}. | JavaFile::writeTo | java | square/javapoet | src/main/java/com/squareup/javapoet/JavaFile.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/JavaFile.java | Apache-2.0 |
public Builder skipJavaLangImports(boolean skipJavaLangImports) {
this.skipJavaLangImports = skipJavaLangImports;
return this;
} |
Call this to omit imports for classes in {@code java.lang}, such as {@code java.lang.String}.
<p>By default, JavaPoet explicitly imports types in {@code java.lang} to defend against
naming conflicts. Suppose an (ill-advised) class is named {@code com.example.String}. When
{@code java.lang} imports are skipped, generated code in {@code com.example} that references
{@code java.lang.String} will get {@code com.example.String} instead.
| Builder::skipJavaLangImports | java | square/javapoet | src/main/java/com/squareup/javapoet/JavaFile.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/JavaFile.java | Apache-2.0 |
Builder addMemberForValue(String memberName, Object value) {
checkNotNull(memberName, "memberName == null");
checkNotNull(value, "value == null, constant non-null value expected for %s", memberName);
checkArgument(SourceVersion.isName(memberName), "not a valid name: %s", memberName);
if (value instanceof Class<?>) {
return addMember(memberName, "$T.class", value);
}
if (value instanceof Enum) {
return addMember(memberName, "$T.$L", value.getClass(), ((Enum<?>) value).name());
}
if (value instanceof String) {
return addMember(memberName, "$S", value);
}
if (value instanceof Float) {
return addMember(memberName, "$Lf", value);
}
if (value instanceof Long) {
return addMember(memberName, "$LL", value);
}
if (value instanceof Character) {
return addMember(memberName, "'$L'", characterLiteralWithoutSingleQuotes((char) value));
}
return addMember(memberName, "$L", value);
} |
Delegates to {@link #addMember(String, String, Object...)}, with parameter {@code format}
depending on the given {@code value} object. Falls back to {@code "$L"} literal format if
the class of the given {@code value} object is not supported.
| Builder::addMemberForValue | java | square/javapoet | src/main/java/com/squareup/javapoet/AnnotationSpec.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/AnnotationSpec.java | Apache-2.0 |
public static TypeVariableName get(String name) {
return TypeVariableName.of(name, Collections.emptyList());
} | /*
Copyright (C) 2015 Square, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
package com.squareup.javapoet;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.lang.model.element.TypeParameterElement;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.type.TypeVariable;
import static com.squareup.javapoet.Util.checkArgument;
import static com.squareup.javapoet.Util.checkNotNull;
public final class TypeVariableName extends TypeName {
public final String name;
public final List<TypeName> bounds;
private TypeVariableName(String name, List<TypeName> bounds) {
this(name, bounds, new ArrayList<>());
}
private TypeVariableName(String name, List<TypeName> bounds, List<AnnotationSpec> annotations) {
super(annotations);
this.name = checkNotNull(name, "name == null");
this.bounds = bounds;
for (TypeName bound : this.bounds) {
checkArgument(!bound.isPrimitive() && bound != VOID, "invalid bound: %s", bound);
}
}
@Override public TypeVariableName annotated(List<AnnotationSpec> annotations) {
return new TypeVariableName(name, bounds, annotations);
}
@Override public TypeName withoutAnnotations() {
return new TypeVariableName(name, bounds);
}
public TypeVariableName withBounds(Type... bounds) {
return withBounds(TypeName.list(bounds));
}
public TypeVariableName withBounds(TypeName... bounds) {
return withBounds(Arrays.asList(bounds));
}
public TypeVariableName withBounds(List<? extends TypeName> bounds) {
ArrayList<TypeName> newBounds = new ArrayList<>();
newBounds.addAll(this.bounds);
newBounds.addAll(bounds);
return new TypeVariableName(name, newBounds, annotations);
}
private static TypeVariableName of(String name, List<TypeName> bounds) {
// Strip java.lang.Object from bounds if it is present.
List<TypeName> boundsNoObject = new ArrayList<>(bounds);
boundsNoObject.remove(OBJECT);
return new TypeVariableName(name, Collections.unmodifiableList(boundsNoObject));
}
@Override CodeWriter emit(CodeWriter out) throws IOException {
emitAnnotations(out);
return out.emitAndIndent(name);
}
/** Returns type variable named {@code name} without bounds. | TypeVariableName::get | java | square/javapoet | src/main/java/com/squareup/javapoet/TypeVariableName.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/TypeVariableName.java | Apache-2.0 |
public static TypeVariableName get(String name, TypeName... bounds) {
return TypeVariableName.of(name, Arrays.asList(bounds));
} | /*
Copyright (C) 2015 Square, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
package com.squareup.javapoet;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.lang.model.element.TypeParameterElement;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.type.TypeVariable;
import static com.squareup.javapoet.Util.checkArgument;
import static com.squareup.javapoet.Util.checkNotNull;
public final class TypeVariableName extends TypeName {
public final String name;
public final List<TypeName> bounds;
private TypeVariableName(String name, List<TypeName> bounds) {
this(name, bounds, new ArrayList<>());
}
private TypeVariableName(String name, List<TypeName> bounds, List<AnnotationSpec> annotations) {
super(annotations);
this.name = checkNotNull(name, "name == null");
this.bounds = bounds;
for (TypeName bound : this.bounds) {
checkArgument(!bound.isPrimitive() && bound != VOID, "invalid bound: %s", bound);
}
}
@Override public TypeVariableName annotated(List<AnnotationSpec> annotations) {
return new TypeVariableName(name, bounds, annotations);
}
@Override public TypeName withoutAnnotations() {
return new TypeVariableName(name, bounds);
}
public TypeVariableName withBounds(Type... bounds) {
return withBounds(TypeName.list(bounds));
}
public TypeVariableName withBounds(TypeName... bounds) {
return withBounds(Arrays.asList(bounds));
}
public TypeVariableName withBounds(List<? extends TypeName> bounds) {
ArrayList<TypeName> newBounds = new ArrayList<>();
newBounds.addAll(this.bounds);
newBounds.addAll(bounds);
return new TypeVariableName(name, newBounds, annotations);
}
private static TypeVariableName of(String name, List<TypeName> bounds) {
// Strip java.lang.Object from bounds if it is present.
List<TypeName> boundsNoObject = new ArrayList<>(bounds);
boundsNoObject.remove(OBJECT);
return new TypeVariableName(name, Collections.unmodifiableList(boundsNoObject));
}
@Override CodeWriter emit(CodeWriter out) throws IOException {
emitAnnotations(out);
return out.emitAndIndent(name);
}
/** Returns type variable named {@code name} without bounds.
public static TypeVariableName get(String name) {
return TypeVariableName.of(name, Collections.emptyList());
}
/** Returns type variable named {@code name} with {@code bounds}. | TypeVariableName::get | java | square/javapoet | src/main/java/com/squareup/javapoet/TypeVariableName.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/TypeVariableName.java | Apache-2.0 |
public static TypeVariableName get(String name, Type... bounds) {
return TypeVariableName.of(name, TypeName.list(bounds));
} | /*
Copyright (C) 2015 Square, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
package com.squareup.javapoet;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.lang.model.element.TypeParameterElement;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.type.TypeVariable;
import static com.squareup.javapoet.Util.checkArgument;
import static com.squareup.javapoet.Util.checkNotNull;
public final class TypeVariableName extends TypeName {
public final String name;
public final List<TypeName> bounds;
private TypeVariableName(String name, List<TypeName> bounds) {
this(name, bounds, new ArrayList<>());
}
private TypeVariableName(String name, List<TypeName> bounds, List<AnnotationSpec> annotations) {
super(annotations);
this.name = checkNotNull(name, "name == null");
this.bounds = bounds;
for (TypeName bound : this.bounds) {
checkArgument(!bound.isPrimitive() && bound != VOID, "invalid bound: %s", bound);
}
}
@Override public TypeVariableName annotated(List<AnnotationSpec> annotations) {
return new TypeVariableName(name, bounds, annotations);
}
@Override public TypeName withoutAnnotations() {
return new TypeVariableName(name, bounds);
}
public TypeVariableName withBounds(Type... bounds) {
return withBounds(TypeName.list(bounds));
}
public TypeVariableName withBounds(TypeName... bounds) {
return withBounds(Arrays.asList(bounds));
}
public TypeVariableName withBounds(List<? extends TypeName> bounds) {
ArrayList<TypeName> newBounds = new ArrayList<>();
newBounds.addAll(this.bounds);
newBounds.addAll(bounds);
return new TypeVariableName(name, newBounds, annotations);
}
private static TypeVariableName of(String name, List<TypeName> bounds) {
// Strip java.lang.Object from bounds if it is present.
List<TypeName> boundsNoObject = new ArrayList<>(bounds);
boundsNoObject.remove(OBJECT);
return new TypeVariableName(name, Collections.unmodifiableList(boundsNoObject));
}
@Override CodeWriter emit(CodeWriter out) throws IOException {
emitAnnotations(out);
return out.emitAndIndent(name);
}
/** Returns type variable named {@code name} without bounds.
public static TypeVariableName get(String name) {
return TypeVariableName.of(name, Collections.emptyList());
}
/** Returns type variable named {@code name} with {@code bounds}.
public static TypeVariableName get(String name, TypeName... bounds) {
return TypeVariableName.of(name, Arrays.asList(bounds));
}
/** Returns type variable named {@code name} with {@code bounds}. | TypeVariableName::get | java | square/javapoet | src/main/java/com/squareup/javapoet/TypeVariableName.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/TypeVariableName.java | Apache-2.0 |
public static TypeVariableName get(TypeVariable mirror) {
return get((TypeParameterElement) mirror.asElement());
} | /*
Copyright (C) 2015 Square, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
package com.squareup.javapoet;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.lang.model.element.TypeParameterElement;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.type.TypeVariable;
import static com.squareup.javapoet.Util.checkArgument;
import static com.squareup.javapoet.Util.checkNotNull;
public final class TypeVariableName extends TypeName {
public final String name;
public final List<TypeName> bounds;
private TypeVariableName(String name, List<TypeName> bounds) {
this(name, bounds, new ArrayList<>());
}
private TypeVariableName(String name, List<TypeName> bounds, List<AnnotationSpec> annotations) {
super(annotations);
this.name = checkNotNull(name, "name == null");
this.bounds = bounds;
for (TypeName bound : this.bounds) {
checkArgument(!bound.isPrimitive() && bound != VOID, "invalid bound: %s", bound);
}
}
@Override public TypeVariableName annotated(List<AnnotationSpec> annotations) {
return new TypeVariableName(name, bounds, annotations);
}
@Override public TypeName withoutAnnotations() {
return new TypeVariableName(name, bounds);
}
public TypeVariableName withBounds(Type... bounds) {
return withBounds(TypeName.list(bounds));
}
public TypeVariableName withBounds(TypeName... bounds) {
return withBounds(Arrays.asList(bounds));
}
public TypeVariableName withBounds(List<? extends TypeName> bounds) {
ArrayList<TypeName> newBounds = new ArrayList<>();
newBounds.addAll(this.bounds);
newBounds.addAll(bounds);
return new TypeVariableName(name, newBounds, annotations);
}
private static TypeVariableName of(String name, List<TypeName> bounds) {
// Strip java.lang.Object from bounds if it is present.
List<TypeName> boundsNoObject = new ArrayList<>(bounds);
boundsNoObject.remove(OBJECT);
return new TypeVariableName(name, Collections.unmodifiableList(boundsNoObject));
}
@Override CodeWriter emit(CodeWriter out) throws IOException {
emitAnnotations(out);
return out.emitAndIndent(name);
}
/** Returns type variable named {@code name} without bounds.
public static TypeVariableName get(String name) {
return TypeVariableName.of(name, Collections.emptyList());
}
/** Returns type variable named {@code name} with {@code bounds}.
public static TypeVariableName get(String name, TypeName... bounds) {
return TypeVariableName.of(name, Arrays.asList(bounds));
}
/** Returns type variable named {@code name} with {@code bounds}.
public static TypeVariableName get(String name, Type... bounds) {
return TypeVariableName.of(name, TypeName.list(bounds));
}
/** Returns type variable equivalent to {@code mirror}. | TypeVariableName::get | java | square/javapoet | src/main/java/com/squareup/javapoet/TypeVariableName.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/TypeVariableName.java | Apache-2.0 |
static TypeVariableName get(
TypeVariable mirror, Map<TypeParameterElement, TypeVariableName> typeVariables) {
TypeParameterElement element = (TypeParameterElement) mirror.asElement();
TypeVariableName typeVariableName = typeVariables.get(element);
if (typeVariableName == null) {
// Since the bounds field is public, we need to make it an unmodifiableList. But we control
// the List that that wraps, which means we can change it before returning.
List<TypeName> bounds = new ArrayList<>();
List<TypeName> visibleBounds = Collections.unmodifiableList(bounds);
typeVariableName = new TypeVariableName(element.getSimpleName().toString(), visibleBounds);
typeVariables.put(element, typeVariableName);
for (TypeMirror typeMirror : element.getBounds()) {
bounds.add(TypeName.get(typeMirror, typeVariables));
}
bounds.remove(OBJECT);
}
return typeVariableName;
} |
Make a TypeVariableName for the given TypeMirror. This form is used internally to avoid
infinite recursion in cases like {@code Enum<E extends Enum<E>>}. When we encounter such a
thing, we will make a TypeVariableName without bounds and add that to the {@code typeVariables}
map before looking up the bounds. Then if we encounter this TypeVariable again while
constructing the bounds, we can just return it from the map. And, the code that put the entry
in {@code variables} will make sure that the bounds are filled in before returning.
| TypeVariableName::get | java | square/javapoet | src/main/java/com/squareup/javapoet/TypeVariableName.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/TypeVariableName.java | Apache-2.0 |
public static TypeVariableName get(TypeParameterElement element) {
String name = element.getSimpleName().toString();
List<? extends TypeMirror> boundsMirrors = element.getBounds();
List<TypeName> boundsTypeNames = new ArrayList<>();
for (TypeMirror typeMirror : boundsMirrors) {
boundsTypeNames.add(TypeName.get(typeMirror));
}
return TypeVariableName.of(name, boundsTypeNames);
} |
Make a TypeVariableName for the given TypeMirror. This form is used internally to avoid
infinite recursion in cases like {@code Enum<E extends Enum<E>>}. When we encounter such a
thing, we will make a TypeVariableName without bounds and add that to the {@code typeVariables}
map before looking up the bounds. Then if we encounter this TypeVariable again while
constructing the bounds, we can just return it from the map. And, the code that put the entry
in {@code variables} will make sure that the bounds are filled in before returning.
static TypeVariableName get(
TypeVariable mirror, Map<TypeParameterElement, TypeVariableName> typeVariables) {
TypeParameterElement element = (TypeParameterElement) mirror.asElement();
TypeVariableName typeVariableName = typeVariables.get(element);
if (typeVariableName == null) {
// Since the bounds field is public, we need to make it an unmodifiableList. But we control
// the List that that wraps, which means we can change it before returning.
List<TypeName> bounds = new ArrayList<>();
List<TypeName> visibleBounds = Collections.unmodifiableList(bounds);
typeVariableName = new TypeVariableName(element.getSimpleName().toString(), visibleBounds);
typeVariables.put(element, typeVariableName);
for (TypeMirror typeMirror : element.getBounds()) {
bounds.add(TypeName.get(typeMirror, typeVariables));
}
bounds.remove(OBJECT);
}
return typeVariableName;
}
/** Returns type variable equivalent to {@code element}. | TypeVariableName::get | java | square/javapoet | src/main/java/com/squareup/javapoet/TypeVariableName.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/TypeVariableName.java | Apache-2.0 |
public static TypeVariableName get(java.lang.reflect.TypeVariable<?> type) {
return get(type, new LinkedHashMap<>());
} |
Make a TypeVariableName for the given TypeMirror. This form is used internally to avoid
infinite recursion in cases like {@code Enum<E extends Enum<E>>}. When we encounter such a
thing, we will make a TypeVariableName without bounds and add that to the {@code typeVariables}
map before looking up the bounds. Then if we encounter this TypeVariable again while
constructing the bounds, we can just return it from the map. And, the code that put the entry
in {@code variables} will make sure that the bounds are filled in before returning.
static TypeVariableName get(
TypeVariable mirror, Map<TypeParameterElement, TypeVariableName> typeVariables) {
TypeParameterElement element = (TypeParameterElement) mirror.asElement();
TypeVariableName typeVariableName = typeVariables.get(element);
if (typeVariableName == null) {
// Since the bounds field is public, we need to make it an unmodifiableList. But we control
// the List that that wraps, which means we can change it before returning.
List<TypeName> bounds = new ArrayList<>();
List<TypeName> visibleBounds = Collections.unmodifiableList(bounds);
typeVariableName = new TypeVariableName(element.getSimpleName().toString(), visibleBounds);
typeVariables.put(element, typeVariableName);
for (TypeMirror typeMirror : element.getBounds()) {
bounds.add(TypeName.get(typeMirror, typeVariables));
}
bounds.remove(OBJECT);
}
return typeVariableName;
}
/** Returns type variable equivalent to {@code element}.
public static TypeVariableName get(TypeParameterElement element) {
String name = element.getSimpleName().toString();
List<? extends TypeMirror> boundsMirrors = element.getBounds();
List<TypeName> boundsTypeNames = new ArrayList<>();
for (TypeMirror typeMirror : boundsMirrors) {
boundsTypeNames.add(TypeName.get(typeMirror));
}
return TypeVariableName.of(name, boundsTypeNames);
}
/** Returns type variable equivalent to {@code type}. | TypeVariableName::get | java | square/javapoet | src/main/java/com/squareup/javapoet/TypeVariableName.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/TypeVariableName.java | Apache-2.0 |
static TypeVariableName get(java.lang.reflect.TypeVariable<?> type,
Map<Type, TypeVariableName> map) {
TypeVariableName result = map.get(type);
if (result == null) {
List<TypeName> bounds = new ArrayList<>();
List<TypeName> visibleBounds = Collections.unmodifiableList(bounds);
result = new TypeVariableName(type.getName(), visibleBounds);
map.put(type, result);
for (Type bound : type.getBounds()) {
bounds.add(TypeName.get(bound, map));
}
bounds.remove(OBJECT);
}
return result;
} |
Make a TypeVariableName for the given TypeMirror. This form is used internally to avoid
infinite recursion in cases like {@code Enum<E extends Enum<E>>}. When we encounter such a
thing, we will make a TypeVariableName without bounds and add that to the {@code typeVariables}
map before looking up the bounds. Then if we encounter this TypeVariable again while
constructing the bounds, we can just return it from the map. And, the code that put the entry
in {@code variables} will make sure that the bounds are filled in before returning.
static TypeVariableName get(
TypeVariable mirror, Map<TypeParameterElement, TypeVariableName> typeVariables) {
TypeParameterElement element = (TypeParameterElement) mirror.asElement();
TypeVariableName typeVariableName = typeVariables.get(element);
if (typeVariableName == null) {
// Since the bounds field is public, we need to make it an unmodifiableList. But we control
// the List that that wraps, which means we can change it before returning.
List<TypeName> bounds = new ArrayList<>();
List<TypeName> visibleBounds = Collections.unmodifiableList(bounds);
typeVariableName = new TypeVariableName(element.getSimpleName().toString(), visibleBounds);
typeVariables.put(element, typeVariableName);
for (TypeMirror typeMirror : element.getBounds()) {
bounds.add(TypeName.get(typeMirror, typeVariables));
}
bounds.remove(OBJECT);
}
return typeVariableName;
}
/** Returns type variable equivalent to {@code element}.
public static TypeVariableName get(TypeParameterElement element) {
String name = element.getSimpleName().toString();
List<? extends TypeMirror> boundsMirrors = element.getBounds();
List<TypeName> boundsTypeNames = new ArrayList<>();
for (TypeMirror typeMirror : boundsMirrors) {
boundsTypeNames.add(TypeName.get(typeMirror));
}
return TypeVariableName.of(name, boundsTypeNames);
}
/** Returns type variable equivalent to {@code type}.
public static TypeVariableName get(java.lang.reflect.TypeVariable<?> type) {
return get(type, new LinkedHashMap<>());
}
/** @see #get(java.lang.reflect.TypeVariable, Map) | TypeVariableName::get | java | square/javapoet | src/main/java/com/squareup/javapoet/TypeVariableName.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/TypeVariableName.java | Apache-2.0 |
public static ArrayTypeName of(TypeName componentType) {
return new ArrayTypeName(componentType);
} | /*
Copyright (C) 2015 Square, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
package com.squareup.javapoet;
import java.io.IOException;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.lang.model.element.TypeParameterElement;
import javax.lang.model.type.ArrayType;
import static com.squareup.javapoet.Util.checkNotNull;
public final class ArrayTypeName extends TypeName {
public final TypeName componentType;
private ArrayTypeName(TypeName componentType) {
this(componentType, new ArrayList<>());
}
private ArrayTypeName(TypeName componentType, List<AnnotationSpec> annotations) {
super(annotations);
this.componentType = checkNotNull(componentType, "rawType == null");
}
@Override public ArrayTypeName annotated(List<AnnotationSpec> annotations) {
return new ArrayTypeName(componentType, concatAnnotations(annotations));
}
@Override public TypeName withoutAnnotations() {
return new ArrayTypeName(componentType);
}
@Override CodeWriter emit(CodeWriter out) throws IOException {
return emit(out, false);
}
CodeWriter emit(CodeWriter out, boolean varargs) throws IOException {
emitLeafType(out);
return emitBrackets(out, varargs);
}
private CodeWriter emitLeafType(CodeWriter out) throws IOException {
if (TypeName.asArray(componentType) != null) {
return TypeName.asArray(componentType).emitLeafType(out);
}
return componentType.emit(out);
}
private CodeWriter emitBrackets(CodeWriter out, boolean varargs) throws IOException {
if (isAnnotated()) {
out.emit(" ");
emitAnnotations(out);
}
if (TypeName.asArray(componentType) == null) {
// Last bracket.
return out.emit(varargs ? "..." : "[]");
}
out.emit("[]");
return TypeName.asArray(componentType) .emitBrackets(out, varargs);
}
/** Returns an array type whose elements are all instances of {@code componentType}. | ArrayTypeName::of | java | square/javapoet | src/main/java/com/squareup/javapoet/ArrayTypeName.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/ArrayTypeName.java | Apache-2.0 |
public static ArrayTypeName of(Type componentType) {
return of(TypeName.get(componentType));
} | /*
Copyright (C) 2015 Square, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
package com.squareup.javapoet;
import java.io.IOException;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.lang.model.element.TypeParameterElement;
import javax.lang.model.type.ArrayType;
import static com.squareup.javapoet.Util.checkNotNull;
public final class ArrayTypeName extends TypeName {
public final TypeName componentType;
private ArrayTypeName(TypeName componentType) {
this(componentType, new ArrayList<>());
}
private ArrayTypeName(TypeName componentType, List<AnnotationSpec> annotations) {
super(annotations);
this.componentType = checkNotNull(componentType, "rawType == null");
}
@Override public ArrayTypeName annotated(List<AnnotationSpec> annotations) {
return new ArrayTypeName(componentType, concatAnnotations(annotations));
}
@Override public TypeName withoutAnnotations() {
return new ArrayTypeName(componentType);
}
@Override CodeWriter emit(CodeWriter out) throws IOException {
return emit(out, false);
}
CodeWriter emit(CodeWriter out, boolean varargs) throws IOException {
emitLeafType(out);
return emitBrackets(out, varargs);
}
private CodeWriter emitLeafType(CodeWriter out) throws IOException {
if (TypeName.asArray(componentType) != null) {
return TypeName.asArray(componentType).emitLeafType(out);
}
return componentType.emit(out);
}
private CodeWriter emitBrackets(CodeWriter out, boolean varargs) throws IOException {
if (isAnnotated()) {
out.emit(" ");
emitAnnotations(out);
}
if (TypeName.asArray(componentType) == null) {
// Last bracket.
return out.emit(varargs ? "..." : "[]");
}
out.emit("[]");
return TypeName.asArray(componentType) .emitBrackets(out, varargs);
}
/** Returns an array type whose elements are all instances of {@code componentType}.
public static ArrayTypeName of(TypeName componentType) {
return new ArrayTypeName(componentType);
}
/** Returns an array type whose elements are all instances of {@code componentType}. | ArrayTypeName::of | java | square/javapoet | src/main/java/com/squareup/javapoet/ArrayTypeName.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/ArrayTypeName.java | Apache-2.0 |
public static ArrayTypeName get(ArrayType mirror) {
return get(mirror, new LinkedHashMap<>());
} | /*
Copyright (C) 2015 Square, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
package com.squareup.javapoet;
import java.io.IOException;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.lang.model.element.TypeParameterElement;
import javax.lang.model.type.ArrayType;
import static com.squareup.javapoet.Util.checkNotNull;
public final class ArrayTypeName extends TypeName {
public final TypeName componentType;
private ArrayTypeName(TypeName componentType) {
this(componentType, new ArrayList<>());
}
private ArrayTypeName(TypeName componentType, List<AnnotationSpec> annotations) {
super(annotations);
this.componentType = checkNotNull(componentType, "rawType == null");
}
@Override public ArrayTypeName annotated(List<AnnotationSpec> annotations) {
return new ArrayTypeName(componentType, concatAnnotations(annotations));
}
@Override public TypeName withoutAnnotations() {
return new ArrayTypeName(componentType);
}
@Override CodeWriter emit(CodeWriter out) throws IOException {
return emit(out, false);
}
CodeWriter emit(CodeWriter out, boolean varargs) throws IOException {
emitLeafType(out);
return emitBrackets(out, varargs);
}
private CodeWriter emitLeafType(CodeWriter out) throws IOException {
if (TypeName.asArray(componentType) != null) {
return TypeName.asArray(componentType).emitLeafType(out);
}
return componentType.emit(out);
}
private CodeWriter emitBrackets(CodeWriter out, boolean varargs) throws IOException {
if (isAnnotated()) {
out.emit(" ");
emitAnnotations(out);
}
if (TypeName.asArray(componentType) == null) {
// Last bracket.
return out.emit(varargs ? "..." : "[]");
}
out.emit("[]");
return TypeName.asArray(componentType) .emitBrackets(out, varargs);
}
/** Returns an array type whose elements are all instances of {@code componentType}.
public static ArrayTypeName of(TypeName componentType) {
return new ArrayTypeName(componentType);
}
/** Returns an array type whose elements are all instances of {@code componentType}.
public static ArrayTypeName of(Type componentType) {
return of(TypeName.get(componentType));
}
/** Returns an array type equivalent to {@code mirror}. | ArrayTypeName::get | java | square/javapoet | src/main/java/com/squareup/javapoet/ArrayTypeName.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/ArrayTypeName.java | Apache-2.0 |
public static ArrayTypeName get(GenericArrayType type) {
return get(type, new LinkedHashMap<>());
} | /*
Copyright (C) 2015 Square, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
package com.squareup.javapoet;
import java.io.IOException;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.lang.model.element.TypeParameterElement;
import javax.lang.model.type.ArrayType;
import static com.squareup.javapoet.Util.checkNotNull;
public final class ArrayTypeName extends TypeName {
public final TypeName componentType;
private ArrayTypeName(TypeName componentType) {
this(componentType, new ArrayList<>());
}
private ArrayTypeName(TypeName componentType, List<AnnotationSpec> annotations) {
super(annotations);
this.componentType = checkNotNull(componentType, "rawType == null");
}
@Override public ArrayTypeName annotated(List<AnnotationSpec> annotations) {
return new ArrayTypeName(componentType, concatAnnotations(annotations));
}
@Override public TypeName withoutAnnotations() {
return new ArrayTypeName(componentType);
}
@Override CodeWriter emit(CodeWriter out) throws IOException {
return emit(out, false);
}
CodeWriter emit(CodeWriter out, boolean varargs) throws IOException {
emitLeafType(out);
return emitBrackets(out, varargs);
}
private CodeWriter emitLeafType(CodeWriter out) throws IOException {
if (TypeName.asArray(componentType) != null) {
return TypeName.asArray(componentType).emitLeafType(out);
}
return componentType.emit(out);
}
private CodeWriter emitBrackets(CodeWriter out, boolean varargs) throws IOException {
if (isAnnotated()) {
out.emit(" ");
emitAnnotations(out);
}
if (TypeName.asArray(componentType) == null) {
// Last bracket.
return out.emit(varargs ? "..." : "[]");
}
out.emit("[]");
return TypeName.asArray(componentType) .emitBrackets(out, varargs);
}
/** Returns an array type whose elements are all instances of {@code componentType}.
public static ArrayTypeName of(TypeName componentType) {
return new ArrayTypeName(componentType);
}
/** Returns an array type whose elements are all instances of {@code componentType}.
public static ArrayTypeName of(Type componentType) {
return of(TypeName.get(componentType));
}
/** Returns an array type equivalent to {@code mirror}.
public static ArrayTypeName get(ArrayType mirror) {
return get(mirror, new LinkedHashMap<>());
}
static ArrayTypeName get(
ArrayType mirror, Map<TypeParameterElement, TypeVariableName> typeVariables) {
return new ArrayTypeName(get(mirror.getComponentType(), typeVariables));
}
/** Returns an array type equivalent to {@code type}. | ArrayTypeName::get | java | square/javapoet | src/main/java/com/squareup/javapoet/ArrayTypeName.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/ArrayTypeName.java | Apache-2.0 |
public static WildcardTypeName subtypeOf(TypeName upperBound) {
return new WildcardTypeName(Collections.singletonList(upperBound), Collections.emptyList());
} |
Returns a type that represents an unknown type that extends {@code bound}. For example, if
{@code bound} is {@code CharSequence.class}, this returns {@code ? extends CharSequence}. If
{@code bound} is {@code Object.class}, this returns {@code ?}, which is shorthand for {@code
? extends Object}.
| WildcardTypeName::subtypeOf | java | square/javapoet | src/main/java/com/squareup/javapoet/WildcardTypeName.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/WildcardTypeName.java | Apache-2.0 |
public ParameterizedTypeName nestedClass(String name) {
checkNotNull(name, "name == null");
return new ParameterizedTypeName(this, rawType.nestedClass(name), new ArrayList<>(),
new ArrayList<>());
} |
Returns a new {@link ParameterizedTypeName} instance for the specified {@code name} as nested
inside this class.
| ParameterizedTypeName::nestedClass | java | square/javapoet | src/main/java/com/squareup/javapoet/ParameterizedTypeName.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/ParameterizedTypeName.java | Apache-2.0 |
public ParameterizedTypeName nestedClass(String name, List<TypeName> typeArguments) {
checkNotNull(name, "name == null");
return new ParameterizedTypeName(this, rawType.nestedClass(name), typeArguments,
new ArrayList<>());
} |
Returns a new {@link ParameterizedTypeName} instance for the specified {@code name} as nested
inside this class, with the specified {@code typeArguments}.
| ParameterizedTypeName::nestedClass | java | square/javapoet | src/main/java/com/squareup/javapoet/ParameterizedTypeName.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/ParameterizedTypeName.java | Apache-2.0 |
public static ParameterizedTypeName get(ClassName rawType, TypeName... typeArguments) {
return new ParameterizedTypeName(null, rawType, Arrays.asList(typeArguments));
} |
Returns a new {@link ParameterizedTypeName} instance for the specified {@code name} as nested
inside this class, with the specified {@code typeArguments}.
public ParameterizedTypeName nestedClass(String name, List<TypeName> typeArguments) {
checkNotNull(name, "name == null");
return new ParameterizedTypeName(this, rawType.nestedClass(name), typeArguments,
new ArrayList<>());
}
/** Returns a parameterized type, applying {@code typeArguments} to {@code rawType}. | ParameterizedTypeName::get | java | square/javapoet | src/main/java/com/squareup/javapoet/ParameterizedTypeName.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/ParameterizedTypeName.java | Apache-2.0 |
public static ParameterizedTypeName get(Class<?> rawType, Type... typeArguments) {
return new ParameterizedTypeName(null, ClassName.get(rawType), list(typeArguments));
} |
Returns a new {@link ParameterizedTypeName} instance for the specified {@code name} as nested
inside this class, with the specified {@code typeArguments}.
public ParameterizedTypeName nestedClass(String name, List<TypeName> typeArguments) {
checkNotNull(name, "name == null");
return new ParameterizedTypeName(this, rawType.nestedClass(name), typeArguments,
new ArrayList<>());
}
/** Returns a parameterized type, applying {@code typeArguments} to {@code rawType}.
public static ParameterizedTypeName get(ClassName rawType, TypeName... typeArguments) {
return new ParameterizedTypeName(null, rawType, Arrays.asList(typeArguments));
}
/** Returns a parameterized type, applying {@code typeArguments} to {@code rawType}. | ParameterizedTypeName::get | java | square/javapoet | src/main/java/com/squareup/javapoet/ParameterizedTypeName.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/ParameterizedTypeName.java | Apache-2.0 |
public static ParameterizedTypeName get(ParameterizedType type) {
return get(type, new LinkedHashMap<>());
} |
Returns a new {@link ParameterizedTypeName} instance for the specified {@code name} as nested
inside this class, with the specified {@code typeArguments}.
public ParameterizedTypeName nestedClass(String name, List<TypeName> typeArguments) {
checkNotNull(name, "name == null");
return new ParameterizedTypeName(this, rawType.nestedClass(name), typeArguments,
new ArrayList<>());
}
/** Returns a parameterized type, applying {@code typeArguments} to {@code rawType}.
public static ParameterizedTypeName get(ClassName rawType, TypeName... typeArguments) {
return new ParameterizedTypeName(null, rawType, Arrays.asList(typeArguments));
}
/** Returns a parameterized type, applying {@code typeArguments} to {@code rawType}.
public static ParameterizedTypeName get(Class<?> rawType, Type... typeArguments) {
return new ParameterizedTypeName(null, ClassName.get(rawType), list(typeArguments));
}
/** Returns a parameterized type equivalent to {@code type}. | ParameterizedTypeName::get | java | square/javapoet | src/main/java/com/squareup/javapoet/ParameterizedTypeName.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/ParameterizedTypeName.java | Apache-2.0 |
static ParameterizedTypeName get(ParameterizedType type, Map<Type, TypeVariableName> map) {
ClassName rawType = ClassName.get((Class<?>) type.getRawType());
ParameterizedType ownerType = (type.getOwnerType() instanceof ParameterizedType)
&& !Modifier.isStatic(((Class<?>) type.getRawType()).getModifiers())
? (ParameterizedType) type.getOwnerType() : null;
List<TypeName> typeArguments = TypeName.list(type.getActualTypeArguments(), map);
return (ownerType != null)
? get(ownerType, map).nestedClass(rawType.simpleName(), typeArguments)
: new ParameterizedTypeName(null, rawType, typeArguments);
} |
Returns a new {@link ParameterizedTypeName} instance for the specified {@code name} as nested
inside this class, with the specified {@code typeArguments}.
public ParameterizedTypeName nestedClass(String name, List<TypeName> typeArguments) {
checkNotNull(name, "name == null");
return new ParameterizedTypeName(this, rawType.nestedClass(name), typeArguments,
new ArrayList<>());
}
/** Returns a parameterized type, applying {@code typeArguments} to {@code rawType}.
public static ParameterizedTypeName get(ClassName rawType, TypeName... typeArguments) {
return new ParameterizedTypeName(null, rawType, Arrays.asList(typeArguments));
}
/** Returns a parameterized type, applying {@code typeArguments} to {@code rawType}.
public static ParameterizedTypeName get(Class<?> rawType, Type... typeArguments) {
return new ParameterizedTypeName(null, ClassName.get(rawType), list(typeArguments));
}
/** Returns a parameterized type equivalent to {@code type}.
public static ParameterizedTypeName get(ParameterizedType type) {
return get(type, new LinkedHashMap<>());
}
/** Returns a parameterized type equivalent to {@code type}. | ParameterizedTypeName::get | java | square/javapoet | src/main/java/com/squareup/javapoet/ParameterizedTypeName.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/ParameterizedTypeName.java | Apache-2.0 |
public Elements getElements() {
checkState(elements != null, "Not running within the rule");
return elements;
} |
Returns the {@link Elements} instance associated with the current execution of the rule.
@throws IllegalStateException if this method is invoked outside the execution of the rule.
| CompilationRule::getElements | java | square/javapoet | src/test/java/com/squareup/javapoet/TypesEclipseTest.java | https://github.com/square/javapoet/blob/master/src/test/java/com/squareup/javapoet/TypesEclipseTest.java | Apache-2.0 |
public Types getTypes() {
checkState(elements != null, "Not running within the rule");
return types;
} |
Returns the {@link Types} instance associated with the current execution of the rule.
@throws IllegalStateException if this method is invoked outside the execution of the rule.
| CompilationRule::getTypes | java | square/javapoet | src/test/java/com/squareup/javapoet/TypesEclipseTest.java | https://github.com/square/javapoet/blob/master/src/test/java/com/squareup/javapoet/TypesEclipseTest.java | Apache-2.0 |
public String getMigration() {
return migration;
} |
@TableName migrations
@TableName(value = "migrations")
public class Migration implements Serializable {
/**
@TableId(type = IdType.AUTO)
private Integer id;
/**
private String migration;
@TableField(exist = false)
private static final long serialVersionUID = 1L;
/**
public Integer getId() {
return id;
}
/**
public void setId(Integer id) {
this.id = id;
}
/** | Migration::getMigration | java | PlayEdu/PlayEdu | playedu-api/playedu-system/src/main/java/xyz/playedu/system/domain/Migration.java | https://github.com/PlayEdu/PlayEdu/blob/master/playedu-api/playedu-system/src/main/java/xyz/playedu/system/domain/Migration.java | Apache-2.0 |
public void setMigration(String migration) {
this.migration = migration;
} |
@TableName migrations
@TableName(value = "migrations")
public class Migration implements Serializable {
/**
@TableId(type = IdType.AUTO)
private Integer id;
/**
private String migration;
@TableField(exist = false)
private static final long serialVersionUID = 1L;
/**
public Integer getId() {
return id;
}
/**
public void setId(Integer id) {
this.id = id;
}
/**
public String getMigration() {
return migration;
}
/** | Migration::setMigration | java | PlayEdu/PlayEdu | playedu-api/playedu-system/src/main/java/xyz/playedu/system/domain/Migration.java | https://github.com/PlayEdu/PlayEdu/blob/master/playedu-api/playedu-system/src/main/java/xyz/playedu/system/domain/Migration.java | Apache-2.0 |
private Log getAnnotationLog(JoinPoint joinPoint) throws Exception {
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
Method method = methodSignature.getMethod();
if (method != null) {
return method.getAnnotation(Log.class);
}
return null;
} |
拦截异常操作
@param joinPoint 切点
@param e 异常
@AfterThrowing(value = "logPointCut()", throwing = "e")
public void doAfterThrowing(JoinPoint joinPoint, Exception e) {
handleLog(joinPoint, e, null);
}
protected void handleLog(final JoinPoint joinPoint, final Exception e, Object jsonResult) {
try {
// 获取注解信息
Log controllerLog = getAnnotationLog(joinPoint);
if (null == controllerLog) {
return;
}
AdminUser adminUser = adminUserService.findById(authService.userId());
if (null == adminUser) {
return;
}
// 日志
AdminLog adminLog = new AdminLog();
adminLog.setAdminId(adminUser.getId());
adminLog.setAdminName(adminUser.getName());
adminLog.setModule("BACKEND");
adminLog.setTitle(controllerLog.title());
adminLog.setOpt(controllerLog.businessType().ordinal());
// 设置方法名称
String className = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();
adminLog.setMethod(className + "." + methodName + "()");
HttpServletRequest request = RequestUtil.handler();
if (null == request) {
return;
}
adminLog.setRequestMethod(request.getMethod());
adminLog.setUrl(request.getRequestURL().toString());
String params = "";
Map<String, String[]> parameterMap = request.getParameterMap();
if (StringUtil.isNotEmpty(parameterMap)) {
params = JSONUtil.toJsonStr(parameterMap);
} else {
Object[] args = joinPoint.getArgs();
if (StringUtil.isNotNull(args)) {
params = StringUtil.arrayToString(args);
}
}
if (StringUtil.isNotEmpty(params)) {
JSONObject paramObj = excludeProperties(params);
adminLog.setParam(JSONUtil.toJsonStr(paramObj));
}
if (null != jsonResult) {
jsonResult = excludeProperties(JSONUtil.toJsonStr(jsonResult));
adminLog.setResult(JSONUtil.toJsonStr(jsonResult));
}
adminLog.setIp(IpUtil.getIpAddress());
adminLog.setIpArea(IpUtil.getRealAddressByIP(IpUtil.getIpAddress()));
if (null != e) {
adminLog.setErrorMsg(e.getMessage());
}
adminLog.setCreatedAt(new Date());
// 保存数据库
adminLogService.save(adminLog);
} catch (Exception exp) {
// 记录本地异常日志
log.error("异常信息:" + exp.getMessage(), e);
}
}
/** 是否存在注解,如果存在就获取 | AdminLogAspect::getAnnotationLog | java | PlayEdu/PlayEdu | playedu-api/playedu-system/src/main/java/xyz/playedu/system/aspectj/AdminLogAspect.java | https://github.com/PlayEdu/PlayEdu/blob/master/playedu-api/playedu-system/src/main/java/xyz/playedu/system/aspectj/AdminLogAspect.java | Apache-2.0 |
public static String desValue(
String origin, int prefixNoMaskLen, int suffixNoMaskLen, String maskStr) {
if (origin == null) {
return null;
}
StringBuilder sb = new StringBuilder();
for (int i = 0, n = origin.length(); i < n; i++) {
if (i < prefixNoMaskLen) {
sb.append(origin.charAt(i));
continue;
}
if (i > (n - suffixNoMaskLen - 1)) {
sb.append(origin.charAt(i));
continue;
}
sb.append(maskStr);
}
return sb.toString();
} |
对字符串进行脱敏操作
@param origin 原始字符串
@param prefixNoMaskLen 左侧需要保留几位明文字段
@param suffixNoMaskLen 右侧需要保留几位明文字段
@param maskStr 用于遮罩的字符串, 如'*'
@return 脱敏后结果
| PrivacyUtil::desValue | java | PlayEdu/PlayEdu | playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/PrivacyUtil.java | https://github.com/PlayEdu/PlayEdu/blob/master/playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/PrivacyUtil.java | Apache-2.0 |
public static boolean isEmpty(String str) {
return isNull(str) || NULL_STR.equals(str.trim());
} |
判断一个字符串是否为空串
@param str String
@return true=为空, false=非空
| StringUtil::isEmpty | java | PlayEdu/PlayEdu | playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/StringUtil.java | https://github.com/PlayEdu/PlayEdu/blob/master/playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/StringUtil.java | Apache-2.0 |
public static String toUnderScoreCase(String str) {
if (str == null) {
return null;
}
StringBuilder sb = new StringBuilder();
// 前置字符是否大写
boolean preCharIsUpperCase = true;
// 当前字符是否大写
boolean cureCharIsUpperCase = true;
// 下一字符是否大写
boolean nextCharIsUpperCase = true;
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (i > 0) {
preCharIsUpperCase = Character.isUpperCase(str.charAt(i - 1));
} else {
preCharIsUpperCase = false;
}
cureCharIsUpperCase = Character.isUpperCase(c);
if (i < (str.length() - 1)) {
nextCharIsUpperCase = Character.isUpperCase(str.charAt(i + 1));
}
if (preCharIsUpperCase && cureCharIsUpperCase && !nextCharIsUpperCase) {
sb.append(SEPARATOR);
} else if ((i != 0 && !preCharIsUpperCase) && cureCharIsUpperCase) {
sb.append(SEPARATOR);
}
sb.append(Character.toLowerCase(c));
}
return sb.toString();
} |
查找指定字符串是否包含指定字符串列表中的任意一个字符串同时串忽略大小写
@param cs 指定字符串
@param searchCharSequences 需要检查的字符串数组
@return 是否包含任意一个字符串
public static boolean containsAnyIgnoreCase(
CharSequence cs, CharSequence... searchCharSequences) {
if (isEmpty(cs) || isEmpty(searchCharSequences)) {
return false;
}
for (CharSequence testStr : searchCharSequences) {
if (containsIgnoreCase(cs, testStr)) {
return true;
}
}
return false;
}
/** 驼峰转下划线命名 | StringUtil::toUnderScoreCase | java | PlayEdu/PlayEdu | playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/StringUtil.java | https://github.com/PlayEdu/PlayEdu/blob/master/playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/StringUtil.java | Apache-2.0 |
public static boolean inStringIgnoreCase(String str, String... strArr) {
if (str != null && strArr != null) {
for (String s : strArr) {
if (str.equalsIgnoreCase(trim(s))) {
return true;
}
}
}
return false;
} |
是否包含字符串
@param str 验证字符串
@param strArr 字符串组
@return 包含返回true
| StringUtil::inStringIgnoreCase | java | PlayEdu/PlayEdu | playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/StringUtil.java | https://github.com/PlayEdu/PlayEdu/blob/master/playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/StringUtil.java | Apache-2.0 |
public static boolean matches(String str, List<String> strArr) {
if (isEmpty(str) || isEmpty(strArr)) {
return false;
}
for (String pattern : strArr) {
if (isMatch(pattern, str)) {
return true;
}
}
return false;
} |
查找指定字符串是否匹配指定字符串列表中的任意一个字符串
@param str 指定字符串
@param strArr 需要检查的字符串数组
@return 是否匹配
| StringUtil::matches | java | PlayEdu/PlayEdu | playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/StringUtil.java | https://github.com/PlayEdu/PlayEdu/blob/master/playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/StringUtil.java | Apache-2.0 |
public static String padL(final Number num, final int size) {
return padL(num.toString(), size, '0');
} |
数字左边补齐0,使之达到指定长度。 注意,如果数字转换为字符串后,长度大于size,则只保留 最后size个字符。
@param num 数字对象
@param size 字符串指定长度
@return 返回数字的字符串格式,该字符串为指定长度。
| StringUtil::padL | java | PlayEdu/PlayEdu | playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/StringUtil.java | https://github.com/PlayEdu/PlayEdu/blob/master/playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/StringUtil.java | Apache-2.0 |
public static String padL(final String s, final int size, final char c) {
final StringBuilder sb = new StringBuilder(size);
if (s != null) {
final int len = s.length();
if (s.length() <= size) {
for (int i = size - len; i > 0; i--) {
sb.append(c);
}
sb.append(s);
} else {
return s.substring(len - size, len);
}
} else {
for (int i = size; i > 0; i--) {
sb.append(c);
}
}
return sb.toString();
} |
字符串左补齐 如果原始字符串s长度大于size,则只保留最后size个字符。
@param s 原始字符串
@param size 字符串指定长度
@param c 用于补齐的字符
@return 返回指定长度的字符串,由原字符串左补齐或截取得到。
| StringUtil::padL | java | PlayEdu/PlayEdu | playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/StringUtil.java | https://github.com/PlayEdu/PlayEdu/blob/master/playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/StringUtil.java | Apache-2.0 |
public static String format(String strPattern, Object... argArray) {
String EMPTY_JSON = "{}";
char C_BACKSLASH = '\\';
char C_DELIM_START = '{';
if (isEmpty(argArray) || isEmpty(strPattern)) {
return strPattern;
}
final int strPatternLength = strPattern.length();
StringBuilder sbuf = new StringBuilder(strPatternLength + 50);
int handledPosition = 0;
int delimIndex;
for (int argIndex = 0; argIndex < argArray.length; argIndex++) {
delimIndex = strPattern.indexOf(EMPTY_JSON, handledPosition);
if (delimIndex == -1) {
if (handledPosition == 0) {
return strPattern;
} else {
sbuf.append(strPattern, handledPosition, strPatternLength);
return sbuf.toString();
}
} else {
if (delimIndex > 0 && strPattern.charAt(delimIndex - 1) == C_BACKSLASH) {
if (delimIndex > 1 && strPattern.charAt(delimIndex - 2) == C_BACKSLASH) {
sbuf.append(strPattern, handledPosition, delimIndex - 1);
sbuf.append(argArray[argIndex]);
handledPosition = delimIndex + 2;
} else {
// 占位符被转义
argIndex--;
sbuf.append(strPattern, handledPosition, delimIndex - 1);
sbuf.append(C_DELIM_START);
handledPosition = delimIndex + 1;
}
} else {
// 正常占位符
sbuf.append(strPattern, handledPosition, delimIndex);
sbuf.append(argArray[argIndex]);
handledPosition = delimIndex + 2;
}
}
}
sbuf.append(strPattern, handledPosition, strPattern.length());
return sbuf.toString();
} |
格式化文本, {} 表示占位符<br>
此方法只是简单将占位符 {} 按照顺序替换为参数<br>
如果想输出 {} 使用 \\转义 { 即可,如果想输出 {} 之前的 \ 使用双转义符 \\\\ 即可<br>
例:<br>
通常使用:format("this is {} for {}", "a", "b") -> this is a for b<br>
转义{}: format("this is \\{} for {}", "a", "b") -> this is \{} for a<br>
转义\: format("this is \\\\{} for {}", "a", "b") -> this is \a for b<br>
@param strPattern 文本模板,被替换的部分用 {} 表示
@param argArray 参数值
@return 格式化后的文本
| StringUtil::format | java | PlayEdu/PlayEdu | playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/StringUtil.java | https://github.com/PlayEdu/PlayEdu/blob/master/playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/StringUtil.java | Apache-2.0 |
public static String getIpAddress() {
HttpServletRequest request = RequestUtil.handler();
if (request == null) {
return "unknown";
}
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("X-Forwarded-For");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("X-Real-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : getMultistageReverseProxyIp(ip);
} |
获取客户端IP
@return IP地址 (113.67.10.194)
@author fzr
| IpUtil::getIpAddress | java | PlayEdu/PlayEdu | playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/IpUtil.java | https://github.com/PlayEdu/PlayEdu/blob/master/playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/IpUtil.java | Apache-2.0 |
public static String getRealAddressByIP(String ip) {
String IP_URL = "https://whois.pconline.com.cn/ipJson.jsp";
String UNKNOWN = "未知";
if (IpUtil.internalIp(ip)) {
return "内网";
}
try {
String rspStr =
HttpUtil.get(
IP_URL,
new HashMap<>() {
{
put("ip", ip);
put("json", true);
}
});
if (StringUtil.isEmpty(rspStr)) {
log.error("获取地理位置异常1 {}", ip);
return UNKNOWN;
}
JSONObject json = JSONUtil.parseObj(rspStr);
return String.format("%s-%s", json.getStr("pro"), json.getStr("city"));
} catch (Exception e) {
log.error("获取地理位置异常2 {} msg {}", ip, e.getMessage());
}
return UNKNOWN;
} |
根据IP获取所在地址
@param ip Ip地址
@return String (广州省-广州市)
@author fzr
| IpUtil::getRealAddressByIP | java | PlayEdu/PlayEdu | playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/IpUtil.java | https://github.com/PlayEdu/PlayEdu/blob/master/playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/IpUtil.java | Apache-2.0 |
private static boolean internalIp(byte[] address) {
if (address == null || address.length < 2) {
return true;
}
final byte b0 = address[0];
final byte b1 = address[1];
// 10.x.x.x/8
final byte SECTION_1 = 0x0A;
// 172.16.x.x/12
final byte SECTION_2 = (byte) 0xAC;
final byte SECTION_3 = (byte) 0x10;
final byte SECTION_4 = (byte) 0x1F;
// 192.168.x.x/16
final byte SECTION_5 = (byte) 0xC0;
final byte SECTION_6 = (byte) 0xA8;
switch (b0) {
case SECTION_1:
return true;
case SECTION_2:
if (b1 >= SECTION_3 && b1 <= SECTION_4) {
return true;
}
case SECTION_5:
if (b1 == SECTION_6) {
return true;
}
default:
return false;
}
} |
检查是否为内部IP地址
@param address byte地址
@return 结果
@author fzr
| IpUtil::internalIp | java | PlayEdu/PlayEdu | playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/IpUtil.java | https://github.com/PlayEdu/PlayEdu/blob/master/playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/IpUtil.java | Apache-2.0 |
public static byte[] textToNumericFormatV4(String text) {
if (text.length() == 0) {
return null;
}
byte[] bytes = new byte[4];
String[] elements = text.split("\\.", -1);
try {
long l;
int i;
switch (elements.length) {
case 1:
l = Long.parseLong(elements[0]);
if ((l < 0L) || (l > 4294967295L)) {
return null;
}
bytes[0] = (byte) (int) (l >> 24 & 0xFF);
bytes[1] = (byte) (int) ((l & 0xFFFFFF) >> 16 & 0xFF);
bytes[2] = (byte) (int) ((l & 0xFFFF) >> 8 & 0xFF);
bytes[3] = (byte) (int) (l & 0xFF);
break;
case 2:
l = Integer.parseInt(elements[0]);
if ((l < 0L) || (l > 255L)) {
return null;
}
bytes[0] = (byte) (int) (l & 0xFF);
l = Integer.parseInt(elements[1]);
if ((l < 0L) || (l > 16777215L)) {
return null;
}
bytes[1] = (byte) (int) (l >> 16 & 0xFF);
bytes[2] = (byte) (int) ((l & 0xFFFF) >> 8 & 0xFF);
bytes[3] = (byte) (int) (l & 0xFF);
break;
case 3:
for (i = 0; i < 2; ++i) {
l = Integer.parseInt(elements[i]);
if ((l < 0L) || (l > 255L)) {
return null;
}
bytes[i] = (byte) (int) (l & 0xFF);
}
l = Integer.parseInt(elements[2]);
if ((l < 0L) || (l > 65535L)) {
return null;
}
bytes[2] = (byte) (int) (l >> 8 & 0xFF);
bytes[3] = (byte) (int) (l & 0xFF);
break;
case 4:
for (i = 0; i < 4; ++i) {
l = Integer.parseInt(elements[i]);
if ((l < 0L) || (l > 255L)) {
return null;
}
bytes[i] = (byte) (int) (l & 0xFF);
}
break;
default:
return null;
}
} catch (NumberFormatException e) {
return null;
}
return bytes;
} |
将IPv4地址转换成字节
@param text IPv4地址
@return byte 字节
@author fzr
| IpUtil::textToNumericFormatV4 | java | PlayEdu/PlayEdu | playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/IpUtil.java | https://github.com/PlayEdu/PlayEdu/blob/master/playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/IpUtil.java | Apache-2.0 |
public static String getHostIp() {
try {
return InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException ignored) {
}
return "127.0.0.1";
} |
获取IP地址
@return 本地IP地址
@author fzr
| IpUtil::getHostIp | java | PlayEdu/PlayEdu | playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/IpUtil.java | https://github.com/PlayEdu/PlayEdu/blob/master/playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/IpUtil.java | Apache-2.0 |
public static String getMultistageReverseProxyIp(String ip) {
if (ip != null && ip.indexOf(",") > 0) {
final String[] ips = ip.trim().split(",");
for (String subIp : ips) {
if (!isUnknown(subIp)) {
ip = subIp;
break;
}
}
}
return ip;
} |
从多级反向代理中获得第一个非unknown IP地址
@param ip 获得的IP地址
@return 第一个非unknown IP地址
@author fzr
| IpUtil::getMultistageReverseProxyIp | java | PlayEdu/PlayEdu | playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/IpUtil.java | https://github.com/PlayEdu/PlayEdu/blob/master/playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/IpUtil.java | Apache-2.0 |
public static boolean isUnknown(String checkString) {
return StringUtil.isBlank(checkString) || "unknown".equalsIgnoreCase(checkString);
} |
检测给定字符串是否为未知,多用于检测HTTP请求相关
@param checkString 被检测的字符串
@return 是否未知
@author fzr
| IpUtil::isUnknown | java | PlayEdu/PlayEdu | playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/IpUtil.java | https://github.com/PlayEdu/PlayEdu/blob/master/playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/IpUtil.java | Apache-2.0 |
public static String uuid() {
return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
} |
制作UUID
@return String
@author fzr
| HelperUtil::uuid | java | PlayEdu/PlayEdu | playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/HelperUtil.java | https://github.com/PlayEdu/PlayEdu/blob/master/playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/HelperUtil.java | Apache-2.0 |
public static String randomString(int length) {
Random random = new Random();
StringBuilder stringBuffer = new StringBuilder();
String str = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
int strLength = str.length();
for (int i = 0; i < length; i++) {
int index = random.nextInt(strLength);
stringBuffer.append(str.charAt(index));
}
return stringBuffer.toString();
} |
返回随机字符串
@param length 要生成的长度
@return String
@author fzr
| HelperUtil::randomString | java | PlayEdu/PlayEdu | playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/HelperUtil.java | https://github.com/PlayEdu/PlayEdu/blob/master/playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/HelperUtil.java | Apache-2.0 |
public static String randomInt(int length) {
Random random = new Random();
StringBuilder stringBuffer = new StringBuilder();
String str = "0123456789";
for (int i = 0; i < length; i++) {
int index = random.nextInt(10);
stringBuffer.append(str.charAt(index));
}
return stringBuffer.toString();
} |
返回随机数字字符串
@param length 要生成的长度
@return String
@author fzr
| HelperUtil::randomInt | java | PlayEdu/PlayEdu | playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/HelperUtil.java | https://github.com/PlayEdu/PlayEdu/blob/master/playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/HelperUtil.java | Apache-2.0 |
public static String storageUnit(Long size) {
if (size == null) {
return "0B";
}
if (size < 1024) {
return size + "B";
} else {
size = size / 1024;
}
if (size < 1024) {
return size + "KB";
} else {
size = size / 1024;
}
if (size < 1024) {
size = size * 100;
return (size / 100) + "." + (size % 100) + "MB";
} else {
size = size * 100 / 1024;
return (size / 100) + "." + (size % 100) + "GB";
}
} |
转换存储单位: KB MB GB TB
@return String
@author fzr
| HelperUtil::storageUnit | java | PlayEdu/PlayEdu | playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/HelperUtil.java | https://github.com/PlayEdu/PlayEdu/blob/master/playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/HelperUtil.java | Apache-2.0 |
public static void download(String urlString, String savePath, String filename)
throws IOException {
URL url = new URL(urlString);
URLConnection con = url.openConnection();
con.setConnectTimeout(20 * 1000);
File sf = new File(savePath);
if (!sf.exists()) {
if (sf.mkdirs()) {
throw new IOException("创建目录失败");
}
}
try (InputStream in = con.getInputStream();
OutputStream out = new FileOutputStream(sf.getPath() + "\\" + filename)) {
byte[] buff = new byte[1024];
int n;
while ((n = in.read(buff)) >= 0) {
out.write(buff, 0, n);
}
} catch (Exception e) {
e.printStackTrace();
}
} |
下载文件
@param urlString (文件网址)
@param savePath (保存路径,如: /www/uploads)
@param filename (保存名称,如: aa.png)
@throws IOException 异常
@author fzr
| HelperUtil::download | java | PlayEdu/PlayEdu | playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/HelperUtil.java | https://github.com/PlayEdu/PlayEdu/blob/master/playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/HelperUtil.java | Apache-2.0 |
public static Map<String, Object> mergeMapByObj(
Map<String, Object> map, Map<String, Object> map1) {
HashMap<String, Object> map2 = new HashMap<>();
map2.putAll(map);
map2.putAll(map1);
return map2;
} |
对象类型Map合并
@param map 对象
@return Object
@author fzr
| HelperUtil::mergeMapByObj | java | PlayEdu/PlayEdu | playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/HelperUtil.java | https://github.com/PlayEdu/PlayEdu/blob/master/playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/HelperUtil.java | Apache-2.0 |
public static Map<String, String> mergeMapByStr(
Map<String, String> map, Map<String, String> map1) {
HashMap<String, String> map2 = new HashMap<>();
map2.putAll(map);
map2.putAll(map1);
return map2;
} |
字符串类型Map合并
@param map 对象
@return Object
@author fzr
| HelperUtil::mergeMapByStr | java | PlayEdu/PlayEdu | playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/HelperUtil.java | https://github.com/PlayEdu/PlayEdu/blob/master/playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/HelperUtil.java | Apache-2.0 |
public static RedisTemplate<String, Object> handler() {
return redisTemplate;
} |
对象句柄
@return RedisTemplate
@author fzr
| RedisUtil::handler | java | PlayEdu/PlayEdu | playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/RedisUtil.java | https://github.com/PlayEdu/PlayEdu/blob/master/playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/RedisUtil.java | Apache-2.0 |
public static void expire(String key, Long second) {
key = redisPrefix + key;
redisTemplate.expire(key, second, TimeUnit.SECONDS);
} |
指定缓存失效时间
@param key 键
@param second 时间(秒)
@author fzr
| RedisUtil::expire | java | PlayEdu/PlayEdu | playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/RedisUtil.java | https://github.com/PlayEdu/PlayEdu/blob/master/playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/RedisUtil.java | Apache-2.0 |
public static void pExpire(String key, Long millisecond) {
key = redisPrefix + key;
redisTemplate.expire(key, millisecond, TimeUnit.MILLISECONDS);
} |
指定缓存失效时间
@param key 键
@param millisecond 时间(毫秒)
@author fzr
| RedisUtil::pExpire | java | PlayEdu/PlayEdu | playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/RedisUtil.java | https://github.com/PlayEdu/PlayEdu/blob/master/playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/RedisUtil.java | Apache-2.0 |
public static void persist(String key) {
key = redisPrefix + key;
redisTemplate.persist(key);
} |
指定缓存永久有效
@param key 键
@author fzr
| RedisUtil::persist | java | PlayEdu/PlayEdu | playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/RedisUtil.java | https://github.com/PlayEdu/PlayEdu/blob/master/playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/RedisUtil.java | Apache-2.0 |
public static Long ttl(String key) {
key = redisPrefix + key;
return redisTemplate.getExpire(key, TimeUnit.SECONDS);
} |
根据key获取过期时间
@param key 键不能为null
@return 返回0代表为永久有效(秒)
@author fzr
| RedisUtil::ttl | java | PlayEdu/PlayEdu | playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/RedisUtil.java | https://github.com/PlayEdu/PlayEdu/blob/master/playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/RedisUtil.java | Apache-2.0 |
public static Long pTtl(String key) {
key = redisPrefix + key;
return redisTemplate.getExpire(key, TimeUnit.MILLISECONDS);
} |
根据key获取过期时间
@param key 键不能为null
@return 返回0代表为永久有效(毫秒)
@author fzr
| RedisUtil::pTtl | java | PlayEdu/PlayEdu | playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/RedisUtil.java | https://github.com/PlayEdu/PlayEdu/blob/master/playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/RedisUtil.java | Apache-2.0 |
public static Boolean exists(String key) {
key = redisPrefix + key;
return redisTemplate.hasKey(key);
} |
判断key是否存在
@param key 键
@return true=存在,false=不存在
@author fzr
| RedisUtil::exists | java | PlayEdu/PlayEdu | playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/RedisUtil.java | https://github.com/PlayEdu/PlayEdu/blob/master/playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/RedisUtil.java | Apache-2.0 |
public static void rename(String oldKey, String newKey) {
oldKey = redisPrefix + oldKey;
newKey = redisPrefix + newKey;
redisTemplate.rename(oldKey, newKey);
} |
给key赋值一个新的key名
@param oldKey 旧的key
@param newKey 新的key
@author fzr
| RedisUtil::rename | java | PlayEdu/PlayEdu | playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/RedisUtil.java | https://github.com/PlayEdu/PlayEdu/blob/master/playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/RedisUtil.java | Apache-2.0 |
public static Boolean move(String key, int db) {
key = redisPrefix + key;
return redisTemplate.move(key, db);
} |
将当前数据库的key移动到给定的数据库db当中
@param key 键
@param db 库
@return Boolean
@author fzr
| RedisUtil::move | java | PlayEdu/PlayEdu | playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/RedisUtil.java | https://github.com/PlayEdu/PlayEdu/blob/master/playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/RedisUtil.java | Apache-2.0 |
public static Set<String> keys(String pattern) {
return redisTemplate.keys(pattern);
} |
获取匹配的key值
@param pattern 通配符(*, ?, [])
@return Set
@author fzr
@author fzr
| RedisUtil::keys | java | PlayEdu/PlayEdu | playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/RedisUtil.java | https://github.com/PlayEdu/PlayEdu/blob/master/playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/RedisUtil.java | Apache-2.0 |
public static String randomKey() {
return redisTemplate.randomKey();
} |
随机返回一个key
@return String
@author fzr
@author fzr
| RedisUtil::randomKey | java | PlayEdu/PlayEdu | playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/RedisUtil.java | https://github.com/PlayEdu/PlayEdu/blob/master/playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/RedisUtil.java | Apache-2.0 |
public static Set<String> matchSet(String pattern) {
Set<String> keys = new LinkedHashSet<>();
RedisUtil.handler()
.execute(
(RedisConnection connection) -> {
try (Cursor<byte[]> cursor =
connection.scan(
ScanOptions.scanOptions()
.count(Long.MAX_VALUE)
.match(pattern)
.build())) {
cursor.forEachRemaining(
item -> {
keys.add(RedisSerializer.string().deserialize(item));
});
return null;
} catch (Exception e) {
throw new RuntimeException(e);
}
});
return keys;
} |
按匹配获取或有KEY
@param pattern 规则
@return Set<String>
@author fzr
| RedisUtil::matchSet | java | PlayEdu/PlayEdu | playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/RedisUtil.java | https://github.com/PlayEdu/PlayEdu/blob/master/playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/RedisUtil.java | Apache-2.0 |
public static Object get(String key) {
key = redisPrefix + key;
return redisTemplate.opsForValue().get(key);
} |
获取key的值
@param key 键
@return Object
@author fzr
| RedisUtil::get | java | PlayEdu/PlayEdu | playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/RedisUtil.java | https://github.com/PlayEdu/PlayEdu/blob/master/playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/RedisUtil.java | Apache-2.0 |
public static Object getSet(String key, Object newVal) {
key = redisPrefix + key;
return redisTemplate.opsForValue().getAndSet(key, newVal);
} |
获取旧值并设置新值
@param key 键
@param newVal 新值
@return Object
@author fzr
| RedisUtil::getSet | java | PlayEdu/PlayEdu | playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/RedisUtil.java | https://github.com/PlayEdu/PlayEdu/blob/master/playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/RedisUtil.java | Apache-2.0 |
public static void set(String key, Object value) {
key = redisPrefix + key;
redisTemplate.opsForValue().set(key, value);
} |
设置键值对
@param key 键
@param value 值
@author fzr
| RedisUtil::set | java | PlayEdu/PlayEdu | playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/RedisUtil.java | https://github.com/PlayEdu/PlayEdu/blob/master/playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/RedisUtil.java | Apache-2.0 |
public static void set(String key, Object value, long time) {
key = redisPrefix + key;
if (time > 0) {
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
} else {
set(key, value);
}
} |
设置键值对并设置时间
@param key 键
@param value 值
@param time time要大于0 如果time小于等于0 将设置无限期
@author fzr
| RedisUtil::set | java | PlayEdu/PlayEdu | playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/RedisUtil.java | https://github.com/PlayEdu/PlayEdu/blob/master/playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/RedisUtil.java | Apache-2.0 |
public static Long incr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("递增因子必须大于0");
}
key = redisPrefix + key;
return redisTemplate.opsForValue().increment(key, delta);
} |
递增
@param key 键
@param delta 要增加几(大于0)
@return Long
@author fzr
| RedisUtil::incr | java | PlayEdu/PlayEdu | playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/RedisUtil.java | https://github.com/PlayEdu/PlayEdu/blob/master/playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/RedisUtil.java | Apache-2.0 |
public static Long decr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("递减因子必须大于0");
}
key = redisPrefix + key;
return redisTemplate.opsForValue().increment(key, -delta);
} |
递减
@param key 键
@param delta 要减少几(小于0)
@return Long
@author fzr
| RedisUtil::decr | java | PlayEdu/PlayEdu | playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/RedisUtil.java | https://github.com/PlayEdu/PlayEdu/blob/master/playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/RedisUtil.java | Apache-2.0 |
public static Object hGet(String key, String field) {
key = redisPrefix + key;
return redisTemplate.opsForHash().get(key, field);
} |
获取key中field域的值
@param key 键 不能为null
@param field 项 不能为null
@return 值
@author fzr
| RedisUtil::hGet | java | PlayEdu/PlayEdu | playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/RedisUtil.java | https://github.com/PlayEdu/PlayEdu/blob/master/playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/RedisUtil.java | Apache-2.0 |
public static Boolean hExists(String key, Object field) {
key = redisPrefix + key;
return redisTemplate.opsForHash().hasKey(key, field);
} |
判断key中有没有field域名
@param key 键
@param field 字段
@return Boolean
@author fzr
| RedisUtil::hExists | java | PlayEdu/PlayEdu | playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/RedisUtil.java | https://github.com/PlayEdu/PlayEdu/blob/master/playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/RedisUtil.java | Apache-2.0 |
public Map<Object, Object> hmGet(String key) {
key = redisPrefix + key;
return redisTemplate.opsForHash().entries(key);
} |
获取hashKey对应的所有键值
@param key 键
@return 对应的多个键值
@author fzr
| RedisUtil::hmGet | java | PlayEdu/PlayEdu | playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/RedisUtil.java | https://github.com/PlayEdu/PlayEdu/blob/master/playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/RedisUtil.java | Apache-2.0 |
public static void hmSet(String key, Map<String, Object> map) {
key = redisPrefix + key;
redisTemplate.opsForHash().putAll(key, map);
} |
设置field1->N个域,对应的值是value1->N
@param key 键
@param map 对应多个键值
@author fzr
| RedisUtil::hmSet | java | PlayEdu/PlayEdu | playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/RedisUtil.java | https://github.com/PlayEdu/PlayEdu/blob/master/playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/RedisUtil.java | Apache-2.0 |
public static void hmSet(String key, Map<String, Object> map, long time) {
key = redisPrefix + key;
redisTemplate.opsForHash().putAll(key, map);
if (time > 0) {
expire(key, time);
}
} |
HashSet 并设置时间
@param key 键
@param map 对应多个键值
@param time 时间(秒)
@author fzr
| RedisUtil::hmSet | java | PlayEdu/PlayEdu | playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/RedisUtil.java | https://github.com/PlayEdu/PlayEdu/blob/master/playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/RedisUtil.java | Apache-2.0 |
public static void hSet(String key, String item, Object value) {
key = redisPrefix + key;
redisTemplate.opsForHash().put(key, item, value);
} |
向一张hash表中放入数据,如果不存在将创建
@param key 键
@param item 项
@param value 值
@author fzr
| RedisUtil::hSet | java | PlayEdu/PlayEdu | playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/RedisUtil.java | https://github.com/PlayEdu/PlayEdu/blob/master/playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/RedisUtil.java | Apache-2.0 |
public static boolean hSet(String key, String item, Object value, long time) {
key = redisPrefix + key;
redisTemplate.opsForHash().put(key, item, value);
if (time > 0) {
expire(key, time);
}
return true;
} |
向一张hash表中放入数据,如果不存在将创建
@param key 键
@param item 项
@param value 值
@param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
@return true 成功 false失败
@author fzr
| RedisUtil::hSet | java | PlayEdu/PlayEdu | playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/RedisUtil.java | https://github.com/PlayEdu/PlayEdu/blob/master/playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/RedisUtil.java | Apache-2.0 |
public static void hDel(String key, Object... item) {
key = redisPrefix + key;
redisTemplate.opsForHash().delete(key, item);
} |
删除hash表中的值
@param key 键 不能为null
@param item 项 可以使多个 不能为null
@author fzr
| RedisUtil::hDel | java | PlayEdu/PlayEdu | playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/RedisUtil.java | https://github.com/PlayEdu/PlayEdu/blob/master/playedu-api/playedu-common/src/main/java/xyz/playedu/common/util/RedisUtil.java | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.