file_id
int64
1
180k
content
stringlengths
13
357k
repo
stringlengths
6
109
path
stringlengths
6
1.15k
1
/* * Copyright (C) 2010 The Guava Authors * * 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.google.common.base; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static java.util.logging.Level.WARNING; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.VisibleForTesting; import com.google.errorprone.annotations.InlineMe; import com.google.errorprone.annotations.InlineMeValidationDisabled; import java.util.logging.Logger; import javax.annotation.CheckForNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * Static utility methods pertaining to {@code String} or {@code CharSequence} instances. * * @author Kevin Bourrillion * @since 3.0 */ @GwtCompatible @ElementTypesAreNonnullByDefault public final class Strings { private Strings() {} /** * Returns the given string if it is non-null; the empty string otherwise. * * @param string the string to test and possibly return * @return {@code string} itself if it is non-null; {@code ""} if it is null */ public static String nullToEmpty(@CheckForNull String string) { return Platform.nullToEmpty(string); } /** * Returns the given string if it is nonempty; {@code null} otherwise. * * @param string the string to test and possibly return * @return {@code string} itself if it is nonempty; {@code null} if it is empty or null */ @CheckForNull public static String emptyToNull(@CheckForNull String string) { return Platform.emptyToNull(string); } /** * Returns {@code true} if the given string is null or is the empty string. * * <p>Consider normalizing your string references with {@link #nullToEmpty}. If you do, you can * use {@link String#isEmpty()} instead of this method, and you won't need special null-safe forms * of methods like {@link String#toUpperCase} either. Or, if you'd like to normalize "in the other * direction," converting empty strings to {@code null}, you can use {@link #emptyToNull}. * * @param string a string reference to check * @return {@code true} if the string is null or is the empty string */ public static boolean isNullOrEmpty(@CheckForNull String string) { return Platform.stringIsNullOrEmpty(string); } /** * Returns a string, of length at least {@code minLength}, consisting of {@code string} prepended * with as many copies of {@code padChar} as are necessary to reach that length. For example, * * <ul> * <li>{@code padStart("7", 3, '0')} returns {@code "007"} * <li>{@code padStart("2010", 3, '0')} returns {@code "2010"} * </ul> * * <p>See {@link java.util.Formatter} for a richer set of formatting capabilities. * * @param string the string which should appear at the end of the result * @param minLength the minimum length the resulting string must have. Can be zero or negative, in * which case the input string is always returned. * @param padChar the character to insert at the beginning of the result until the minimum length * is reached * @return the padded string */ public static String padStart(String string, int minLength, char padChar) { checkNotNull(string); // eager for GWT. if (string.length() >= minLength) { return string; } StringBuilder sb = new StringBuilder(minLength); for (int i = string.length(); i < minLength; i++) { sb.append(padChar); } sb.append(string); return sb.toString(); } /** * Returns a string, of length at least {@code minLength}, consisting of {@code string} appended * with as many copies of {@code padChar} as are necessary to reach that length. For example, * * <ul> * <li>{@code padEnd("4.", 5, '0')} returns {@code "4.000"} * <li>{@code padEnd("2010", 3, '!')} returns {@code "2010"} * </ul> * * <p>See {@link java.util.Formatter} for a richer set of formatting capabilities. * * @param string the string which should appear at the beginning of the result * @param minLength the minimum length the resulting string must have. Can be zero or negative, in * which case the input string is always returned. * @param padChar the character to append to the end of the result until the minimum length is * reached * @return the padded string */ public static String padEnd(String string, int minLength, char padChar) { checkNotNull(string); // eager for GWT. if (string.length() >= minLength) { return string; } StringBuilder sb = new StringBuilder(minLength); sb.append(string); for (int i = string.length(); i < minLength; i++) { sb.append(padChar); } return sb.toString(); } /** * Returns a string consisting of a specific number of concatenated copies of an input string. For * example, {@code repeat("hey", 3)} returns the string {@code "heyheyhey"}. * * <p><b>Java 11+ users:</b> use {@code string.repeat(count)} instead. * * @param string any non-null string * @param count the number of times to repeat it; a nonnegative integer * @return a string containing {@code string} repeated {@code count} times (the empty string if * {@code count} is zero) * @throws IllegalArgumentException if {@code count} is negative */ @InlineMe(replacement = "string.repeat(count)") @InlineMeValidationDisabled("Java 11+ API only") public static String repeat(String string, int count) { checkNotNull(string); // eager for GWT. if (count <= 1) { checkArgument(count >= 0, "invalid count: %s", count); return (count == 0) ? "" : string; } // IF YOU MODIFY THE CODE HERE, you must update StringsRepeatBenchmark final int len = string.length(); final long longSize = (long) len * (long) count; final int size = (int) longSize; if (size != longSize) { throw new ArrayIndexOutOfBoundsException("Required array size too large: " + longSize); } final char[] array = new char[size]; string.getChars(0, len, array, 0); int n; for (n = len; n < size - n; n <<= 1) { System.arraycopy(array, 0, array, n, n); } System.arraycopy(array, 0, array, n, size - n); return new String(array); } /** * Returns the longest string {@code prefix} such that {@code a.toString().startsWith(prefix) && * b.toString().startsWith(prefix)}, taking care not to split surrogate pairs. If {@code a} and * {@code b} have no common prefix, returns the empty string. * * @since 11.0 */ public static String commonPrefix(CharSequence a, CharSequence b) { checkNotNull(a); checkNotNull(b); int maxPrefixLength = Math.min(a.length(), b.length()); int p = 0; while (p < maxPrefixLength && a.charAt(p) == b.charAt(p)) { p++; } if (validSurrogatePairAt(a, p - 1) || validSurrogatePairAt(b, p - 1)) { p--; } return a.subSequence(0, p).toString(); } /** * Returns the longest string {@code suffix} such that {@code a.toString().endsWith(suffix) && * b.toString().endsWith(suffix)}, taking care not to split surrogate pairs. If {@code a} and * {@code b} have no common suffix, returns the empty string. * * @since 11.0 */ public static String commonSuffix(CharSequence a, CharSequence b) { checkNotNull(a); checkNotNull(b); int maxSuffixLength = Math.min(a.length(), b.length()); int s = 0; while (s < maxSuffixLength && a.charAt(a.length() - s - 1) == b.charAt(b.length() - s - 1)) { s++; } if (validSurrogatePairAt(a, a.length() - s - 1) || validSurrogatePairAt(b, b.length() - s - 1)) { s--; } return a.subSequence(a.length() - s, a.length()).toString(); } /** * True when a valid surrogate pair starts at the given {@code index} in the given {@code string}. * Out-of-range indexes return false. */ @VisibleForTesting static boolean validSurrogatePairAt(CharSequence string, int index) { return index >= 0 && index <= (string.length() - 2) && Character.isHighSurrogate(string.charAt(index)) && Character.isLowSurrogate(string.charAt(index + 1)); } /** * Returns the given {@code template} string with each occurrence of {@code "%s"} replaced with * the corresponding argument value from {@code args}; or, if the placeholder and argument counts * do not match, returns a best-effort form of that string. Will not throw an exception under * normal conditions. * * <p><b>Note:</b> For most string-formatting needs, use {@link String#format String.format}, * {@link java.io.PrintWriter#format PrintWriter.format}, and related methods. These support the * full range of <a * href="https://docs.oracle.com/javase/9/docs/api/java/util/Formatter.html#syntax">format * specifiers</a>, and alert you to usage errors by throwing {@link * java.util.IllegalFormatException}. * * <p>In certain cases, such as outputting debugging information or constructing a message to be * used for another unchecked exception, an exception during string formatting would serve little * purpose except to supplant the real information you were trying to provide. These are the cases * this method is made for; it instead generates a best-effort string with all supplied argument * values present. This method is also useful in environments such as GWT where {@code * String.format} is not available. As an example, method implementations of the {@link * Preconditions} class use this formatter, for both of the reasons just discussed. * * <p><b>Warning:</b> Only the exact two-character placeholder sequence {@code "%s"} is * recognized. * * @param template a string containing zero or more {@code "%s"} placeholder sequences. {@code * null} is treated as the four-character string {@code "null"}. * @param args the arguments to be substituted into the message template. The first argument * specified is substituted for the first occurrence of {@code "%s"} in the template, and so * forth. A {@code null} argument is converted to the four-character string {@code "null"}; * non-null values are converted to strings using {@link Object#toString()}. * @since 25.1 */ // TODO(diamondm) consider using Arrays.toString() for array parameters public static String lenientFormat( @CheckForNull String template, @CheckForNull @Nullable Object... args) { template = String.valueOf(template); // null -> "null" if (args == null) { args = new Object[] {"(Object[])null"}; } else { for (int i = 0; i < args.length; i++) { args[i] = lenientToString(args[i]); } } // start substituting the arguments into the '%s' placeholders StringBuilder builder = new StringBuilder(template.length() + 16 * args.length); int templateStart = 0; int i = 0; while (i < args.length) { int placeholderStart = template.indexOf("%s", templateStart); if (placeholderStart == -1) { break; } builder.append(template, templateStart, placeholderStart); builder.append(args[i++]); templateStart = placeholderStart + 2; } builder.append(template, templateStart, template.length()); // if we run out of placeholders, append the extra args in square braces if (i < args.length) { builder.append(" ["); builder.append(args[i++]); while (i < args.length) { builder.append(", "); builder.append(args[i++]); } builder.append(']'); } return builder.toString(); } private static String lenientToString(@CheckForNull Object o) { if (o == null) { return "null"; } try { return o.toString(); } catch (Exception e) { // Default toString() behavior - see Object.toString() String objectToString = o.getClass().getName() + '@' + Integer.toHexString(System.identityHashCode(o)); // Logger is created inline with fixed name to avoid forcing Proguard to create another class. Logger.getLogger("com.google.common.base.Strings") .log(WARNING, "Exception during lenientFormat for " + objectToString, e); return "<" + objectToString + " threw " + e.getClass().getName() + ">"; } } }
google/guava
guava/src/com/google/common/base/Strings.java
2
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.core; public final class Booleans { private Booleans() { throw new AssertionError("No instances intended"); } /** * Parses a char[] representation of a boolean value to <code>boolean</code>. * * @return <code>true</code> iff the sequence of chars is "true", <code>false</code> iff the sequence of chars is "false" or the * provided default value iff either text is <code>null</code> or length == 0. * @throws IllegalArgumentException if the string cannot be parsed to boolean. */ public static boolean parseBoolean(char[] text, int offset, int length, boolean defaultValue) { if (text == null || length == 0) { return defaultValue; } else { return parseBoolean(new String(text, offset, length)); } } /** * returns true iff the sequence of chars is one of "true","false". * * @param text sequence to check * @param offset offset to start * @param length length to check */ public static boolean isBoolean(char[] text, int offset, int length) { if (text == null || length == 0) { return false; } return isBoolean(new String(text, offset, length)); } public static boolean isBoolean(String value) { return isFalse(value) || isTrue(value); } /** * Parses a string representation of a boolean value to <code>boolean</code>. * * @return <code>true</code> iff the provided value is "true". <code>false</code> iff the provided value is "false". * @throws IllegalArgumentException if the string cannot be parsed to boolean. */ public static boolean parseBoolean(String value) { if (isFalse(value)) { return false; } if (isTrue(value)) { return true; } throw new IllegalArgumentException("Failed to parse value [" + value + "] as only [true] or [false] are allowed."); } private static boolean hasText(CharSequence str) { if (str == null || str.length() == 0) { return false; } int strLen = str.length(); for (int i = 0; i < strLen; i++) { if (Character.isWhitespace(str.charAt(i)) == false) { return true; } } return false; } /** * * @param value text to parse. * @param defaultValue The default value to return if the provided value is <code>null</code>. * @return see {@link #parseBoolean(String)} */ public static boolean parseBoolean(String value, boolean defaultValue) { if (hasText(value)) { return parseBoolean(value); } return defaultValue; } public static Boolean parseBoolean(String value, Boolean defaultValue) { if (hasText(value)) { return parseBoolean(value); } return defaultValue; } /** * Returns {@code false} if text is in "false", "0", "off", "no"; else, {@code true}. * * @deprecated Only kept to provide automatic upgrades for pre 6.0 indices. Use {@link #parseBoolean(String, Boolean)} instead. */ @Deprecated public static Boolean parseBooleanLenient(String value, Boolean defaultValue) { if (value == null) { // only for the null case we do that here! return defaultValue; } return parseBooleanLenient(value, false); } /** * Returns {@code false} if text is in "false", "0", "off", "no"; else, {@code true}. * * @deprecated Only kept to provide automatic upgrades for pre 6.0 indices. Use {@link #parseBoolean(String, boolean)} instead. */ @Deprecated public static boolean parseBooleanLenient(String value, boolean defaultValue) { if (value == null) { return defaultValue; } return switch (value) { case "false", "0", "off", "no" -> false; default -> true; }; } /** * @return {@code true} iff the value is "false", otherwise {@code false}. */ public static boolean isFalse(String value) { return "false".equals(value); } /** * @return {@code true} iff the value is "true", otherwise {@code false}. */ public static boolean isTrue(String value) { return "true".equals(value); } /** * Returns {@code false} if text is in "false", "0", "off", "no"; else, {@code true}. * * @deprecated Only kept to provide automatic upgrades for pre 6.0 indices. Use {@link #parseBoolean(char[], int, int, boolean)} instead */ @Deprecated public static boolean parseBooleanLenient(char[] text, int offset, int length, boolean defaultValue) { if (text == null || length == 0) { return defaultValue; } if (length == 1) { return text[offset] != '0'; } if (length == 2) { return (text[offset] == 'n' && text[offset + 1] == 'o') == false; } if (length == 3) { return (text[offset] == 'o' && text[offset + 1] == 'f' && text[offset + 2] == 'f') == false; } if (length == 5) { return (text[offset] == 'f' && text[offset + 1] == 'a' && text[offset + 2] == 'l' && text[offset + 3] == 's' && text[offset + 4] == 'e') == false; } return true; } /** * returns true if the a sequence of chars is one of "true","false","on","off","yes","no","0","1" * * @param text sequence to check * @param offset offset to start * @param length length to check * * @deprecated Only kept to provide automatic upgrades for pre 6.0 indices. Use {@link #isBoolean(char[], int, int)} instead. */ @Deprecated public static boolean isBooleanLenient(char[] text, int offset, int length) { if (text == null || length == 0) { return false; } if (length == 1) { return text[offset] == '0' || text[offset] == '1'; } if (length == 2) { return (text[offset] == 'n' && text[offset + 1] == 'o') || (text[offset] == 'o' && text[offset + 1] == 'n'); } if (length == 3) { return (text[offset] == 'o' && text[offset + 1] == 'f' && text[offset + 2] == 'f') || (text[offset] == 'y' && text[offset + 1] == 'e' && text[offset + 2] == 's'); } if (length == 4) { return (text[offset] == 't' && text[offset + 1] == 'r' && text[offset + 2] == 'u' && text[offset + 3] == 'e'); } if (length == 5) { return (text[offset] == 'f' && text[offset + 1] == 'a' && text[offset + 2] == 'l' && text[offset + 3] == 's' && text[offset + 4] == 'e'); } return false; } }
elastic/elasticsearch
libs/core/src/main/java/org/elasticsearch/core/Booleans.java
3
// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you 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 org.openqa.selenium.remote.tracing; import org.openqa.selenium.internal.Require; public class Status { private final Kind kind; private final String description; public static final Status OK = new Status(Kind.OK, ""); public static final Status ABORTED = new Status(Kind.ABORTED, ""); public static final Status CANCELLED = new Status(Kind.CANCELLED, ""); public static final Status NOT_FOUND = new Status(Kind.NOT_FOUND, ""); public static final Status RESOURCE_EXHAUSTED = new Status(Kind.RESOURCE_EXHAUSTED, ""); public static final Status UNKNOWN = new Status(Kind.UNKNOWN, ""); public static final Status INVALID_ARGUMENT = new Status(Kind.INVALID_ARGUMENT, ""); public static final Status DEADLINE_EXCEEDED = new Status(Kind.DEADLINE_EXCEEDED, ""); public static final Status ALREADY_EXISTS = new Status(Kind.ALREADY_EXISTS, ""); public static final Status PERMISSION_DENIED = new Status(Kind.PERMISSION_DENIED, ""); public static final Status OUT_OF_RANGE = new Status(Kind.OUT_OF_RANGE, ""); public static final Status UNIMPLEMENTED = new Status(Kind.UNIMPLEMENTED, ""); public static final Status INTERNAL = new Status(Kind.INTERNAL, ""); public static final Status UNAVAILABLE = new Status(Kind.UNAVAILABLE, ""); public static final Status UNAUTHENTICATED = new Status(Kind.UNAUTHENTICATED, ""); private Status(Kind kind, String description) { this.kind = Require.nonNull("Kind", kind); this.description = Require.nonNull("Description", description); } public Status withDescription(String description) { return new Status(getKind(), Require.nonNull("Description", description)); } public Kind getKind() { return kind; } public String getDescription() { return description; } public enum Kind { OK, ABORTED, CANCELLED, NOT_FOUND, RESOURCE_EXHAUSTED, UNKNOWN, INVALID_ARGUMENT, DEADLINE_EXCEEDED, ALREADY_EXISTS, PERMISSION_DENIED, OUT_OF_RANGE, UNIMPLEMENTED, INTERNAL, UNAVAILABLE, UNAUTHENTICATED } }
SeleniumHQ/selenium
java/src/org/openqa/selenium/remote/tracing/Status.java
4
/* * Copyright 2002-2023 the original author or authors. * * 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 * * https://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 org.springframework.format.datetime; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Collections; import java.util.Date; import java.util.EnumMap; import java.util.Locale; import java.util.Map; import java.util.TimeZone; import org.springframework.format.Formatter; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.format.annotation.DateTimeFormat.ISO; import org.springframework.lang.Nullable; import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; /** * A formatter for {@link java.util.Date} types. * <p>Supports the configuration of an explicit date time pattern, timezone, * locale, and fallback date time patterns for lenient parsing. * * @author Keith Donald * @author Juergen Hoeller * @author Phillip Webb * @author Sam Brannen * @since 3.0 * @see SimpleDateFormat */ public class DateFormatter implements Formatter<Date> { private static final TimeZone UTC = TimeZone.getTimeZone("UTC"); // We use an EnumMap instead of Map.of(...) since the former provides better performance. private static final Map<ISO, String> ISO_PATTERNS; static { Map<ISO, String> formats = new EnumMap<>(ISO.class); formats.put(ISO.DATE, "yyyy-MM-dd"); formats.put(ISO.TIME, "HH:mm:ss.SSSXXX"); formats.put(ISO.DATE_TIME, "yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); ISO_PATTERNS = Collections.unmodifiableMap(formats); } @Nullable private Object source; @Nullable private String pattern; @Nullable private String[] fallbackPatterns; private int style = DateFormat.DEFAULT; @Nullable private String stylePattern; @Nullable private ISO iso; @Nullable private TimeZone timeZone; private boolean lenient = false; /** * Create a new default {@code DateFormatter}. */ public DateFormatter() { } /** * Create a new {@code DateFormatter} for the given date time pattern. */ public DateFormatter(String pattern) { this.pattern = pattern; } /** * Set the source of the configuration for this {@code DateFormatter} &mdash; * for example, an instance of the {@link DateTimeFormat @DateTimeFormat} * annotation if such an annotation was used to configure this {@code DateFormatter}. * <p>The supplied source object will only be used for descriptive purposes * by invoking its {@code toString()} method &mdash; for example, when * generating an exception message to provide further context. * @param source the source of the configuration * @since 5.3.5 */ public void setSource(Object source) { this.source = source; } /** * Set the pattern to use to format date values. * <p>If not specified, DateFormat's default style will be used. */ public void setPattern(String pattern) { this.pattern = pattern; } /** * Set additional patterns to use as a fallback in case parsing fails for the * configured {@linkplain #setPattern pattern}, {@linkplain #setIso ISO format}, * {@linkplain #setStyle style}, or {@linkplain #setStylePattern style pattern}. * @param fallbackPatterns the fallback parsing patterns * @since 5.3.5 * @see DateTimeFormat#fallbackPatterns() */ public void setFallbackPatterns(String... fallbackPatterns) { this.fallbackPatterns = fallbackPatterns; } /** * Set the ISO format to use to format date values. * @param iso the {@link ISO} format * @since 3.2 */ public void setIso(ISO iso) { this.iso = iso; } /** * Set the {@link DateFormat} style to use to format date values. * <p>If not specified, DateFormat's default style will be used. * @see DateFormat#DEFAULT * @see DateFormat#SHORT * @see DateFormat#MEDIUM * @see DateFormat#LONG * @see DateFormat#FULL */ public void setStyle(int style) { this.style = style; } /** * Set the two characters to use to format date values. * <p>The first character is used for the date style; the second is used for * the time style. * <p>Supported characters: * <ul> * <li>'S' = Small</li> * <li>'M' = Medium</li> * <li>'L' = Long</li> * <li>'F' = Full</li> * <li>'-' = Omitted</li> * </ul> * This method mimics the styles supported by Joda-Time. * @param stylePattern two characters from the set {"S", "M", "L", "F", "-"} * @since 3.2 */ public void setStylePattern(String stylePattern) { this.stylePattern = stylePattern; } /** * Set the {@link TimeZone} to normalize the date values into, if any. */ public void setTimeZone(TimeZone timeZone) { this.timeZone = timeZone; } /** * Specify whether parsing is to be lenient. Default is {@code false}. * <p>With lenient parsing, the parser may allow inputs that do not precisely match the format. * With strict parsing, inputs must match the format exactly. */ public void setLenient(boolean lenient) { this.lenient = lenient; } @Override public String print(Date date, Locale locale) { return getDateFormat(locale).format(date); } @Override public Date parse(String text, Locale locale) throws ParseException { try { return getDateFormat(locale).parse(text); } catch (ParseException ex) { if (!ObjectUtils.isEmpty(this.fallbackPatterns)) { for (String pattern : this.fallbackPatterns) { try { DateFormat dateFormat = configureDateFormat(new SimpleDateFormat(pattern, locale)); // Align timezone for parsing format with printing format if ISO is set. if (this.iso != null && this.iso != ISO.NONE) { dateFormat.setTimeZone(UTC); } return dateFormat.parse(text); } catch (ParseException ignoredException) { // Ignore fallback parsing exceptions since the exception thrown below // will include information from the "source" if available -- for example, // the toString() of a @DateTimeFormat annotation. } } } if (this.source != null) { ParseException parseException = new ParseException( String.format("Unable to parse date time value \"%s\" using configuration from %s", text, this.source), ex.getErrorOffset()); parseException.initCause(ex); throw parseException; } // else rethrow original exception throw ex; } } protected DateFormat getDateFormat(Locale locale) { return configureDateFormat(createDateFormat(locale)); } private DateFormat configureDateFormat(DateFormat dateFormat) { if (this.timeZone != null) { dateFormat.setTimeZone(this.timeZone); } dateFormat.setLenient(this.lenient); return dateFormat; } private DateFormat createDateFormat(Locale locale) { if (StringUtils.hasLength(this.pattern)) { return new SimpleDateFormat(this.pattern, locale); } if (this.iso != null && this.iso != ISO.NONE) { String pattern = ISO_PATTERNS.get(this.iso); if (pattern == null) { throw new IllegalStateException("Unsupported ISO format " + this.iso); } SimpleDateFormat format = new SimpleDateFormat(pattern); format.setTimeZone(UTC); return format; } if (StringUtils.hasLength(this.stylePattern)) { int dateStyle = getStylePatternForChar(0); int timeStyle = getStylePatternForChar(1); if (dateStyle != -1 && timeStyle != -1) { return DateFormat.getDateTimeInstance(dateStyle, timeStyle, locale); } if (dateStyle != -1) { return DateFormat.getDateInstance(dateStyle, locale); } if (timeStyle != -1) { return DateFormat.getTimeInstance(timeStyle, locale); } throw unsupportedStylePatternException(); } return DateFormat.getDateInstance(this.style, locale); } private int getStylePatternForChar(int index) { if (this.stylePattern != null && this.stylePattern.length() > index) { char ch = this.stylePattern.charAt(index); return switch (ch) { case 'S' -> DateFormat.SHORT; case 'M' -> DateFormat.MEDIUM; case 'L' -> DateFormat.LONG; case 'F' -> DateFormat.FULL; case '-' -> -1; default -> throw unsupportedStylePatternException(); }; } throw unsupportedStylePatternException(); } private IllegalStateException unsupportedStylePatternException() { return new IllegalStateException("Unsupported style pattern '" + this.stylePattern + "'"); } }
spring-projects/spring-framework
spring-context/src/main/java/org/springframework/format/datetime/DateFormatter.java
5
package com.blankj.subutil.util; import androidx.collection.SimpleArrayMap; /** * <pre> * author: Blankj * blog : http://blankj.com * time : 16/11/16 * desc : 拼音相关工具类 * </pre> */ public final class PinyinUtils { private PinyinUtils() { throw new UnsupportedOperationException("u can't instantiate me..."); } /** * 汉字转拼音 * * @param ccs 汉字字符串(Chinese characters) * @return 拼音 */ public static String ccs2Pinyin(final CharSequence ccs) { return ccs2Pinyin(ccs, ""); } /** * 汉字转拼音 * * @param ccs 汉字字符串(Chinese characters) * @param split 汉字拼音之间的分隔符 * @return 拼音 */ public static String ccs2Pinyin(final CharSequence ccs, final CharSequence split) { if (ccs == null || ccs.length() == 0) return null; StringBuilder sb = new StringBuilder(); for (int i = 0, len = ccs.length(); i < len; i++) { char ch = ccs.charAt(i); if (ch >= 0x4E00 && ch <= 0x9FA5) { int sp = (ch - 0x4E00) * 6; sb.append(pinyinTable.substring(sp, sp + 6).trim()); } else { sb.append(ch); } sb.append(split); } return sb.toString(); } /** * 获取第一个汉字首字母 * * @param ccs 汉字字符串(Chinese characters) * @return 拼音 */ public static String getPinyinFirstLetter(final CharSequence ccs) { if (ccs == null || ccs.length() == 0) return null; return ccs2Pinyin(String.valueOf(ccs.charAt(0))).substring(0, 1); } /** * 获取所有汉字的首字母 * * @param ccs 汉字字符串(Chinese characters) * @return 所有汉字的首字母 */ public static String getPinyinFirstLetters(final CharSequence ccs) { return getPinyinFirstLetters(ccs, ""); } /** * 获取所有汉字的首字母 * * @param ccs 汉字字符串(Chinese characters) * @param split 首字母之间的分隔符 * @return 所有汉字的首字母 */ public static String getPinyinFirstLetters(final CharSequence ccs, final CharSequence split) { if (ccs == null || ccs.length() == 0) return null; int len = ccs.length(); StringBuilder sb = new StringBuilder(len); for (int i = 0; i < len; i++) { sb.append(ccs2Pinyin(String.valueOf(ccs.charAt(i))).substring(0, 1)).append(split); } return sb.toString(); } /** * 根据名字获取姓氏的拼音 * * @param name 名字 * @return 姓氏的拼音 */ public static String getSurnamePinyin(final CharSequence name) { if (name == null || name.length() == 0) return null; if (name.length() >= 2) { CharSequence str = name.subSequence(0, 2); if (str.equals("澹台")) return "tantai"; else if (str.equals("尉迟")) return "yuchi"; else if (str.equals("万俟")) return "moqi"; else if (str.equals("单于")) return "chanyu"; } char ch = name.charAt(0); if (SURNAMES.containsKey(ch)) { return SURNAMES.get(ch); } if (ch >= 0x4E00 && ch <= 0x9FA5) { int sp = (ch - 0x4E00) * 6; return pinyinTable.substring(sp, sp + 6).trim(); } else { return String.valueOf(ch); } } /** * 根据名字获取姓氏的首字母 * * @param name 名字 * @return 姓氏的首字母 */ public static String getSurnameFirstLetter(final CharSequence name) { String surname = getSurnamePinyin(name); if (surname == null || surname.length() == 0) return null; return String.valueOf(surname.charAt(0)); } // 多音字姓氏映射表 private static final SimpleArrayMap<Character, String> SURNAMES; /** * 获取拼音对照表,对比过pinyin4j和其他方式,这样查表设计的好处就是读取快 * <p>当该类加载后会一直占有123KB的内存</p> * <p>如果你想存进文件,然后读取操作的话也是可以,但速度肯定没有这样空间换时间快,毕竟现在设备内存都很大</p> * <p>如需更多用法可以用pinyin4j开源库</p> */ private static final String pinyinTable; static { SURNAMES = new SimpleArrayMap<>(35); SURNAMES.put('乐', "yue"); SURNAMES.put('乘', "sheng"); SURNAMES.put('乜', "nie"); SURNAMES.put('仇', "qiu"); SURNAMES.put('会', "gui"); SURNAMES.put('便', "pian"); SURNAMES.put('区', "ou"); SURNAMES.put('单', "shan"); SURNAMES.put('参', "shen"); SURNAMES.put('句', "gou"); SURNAMES.put('召', "shao"); SURNAMES.put('员', "yun"); SURNAMES.put('宓', "fu"); SURNAMES.put('弗', "fei"); SURNAMES.put('折', "she"); SURNAMES.put('曾', "zeng"); SURNAMES.put('朴', "piao"); SURNAMES.put('查', "zha"); SURNAMES.put('洗', "xian"); SURNAMES.put('盖', "ge"); SURNAMES.put('祭', "zhai"); SURNAMES.put('种', "chong"); SURNAMES.put('秘', "bi"); SURNAMES.put('繁', "po"); SURNAMES.put('缪', "miao"); SURNAMES.put('能', "nai"); SURNAMES.put('蕃', "pi"); SURNAMES.put('覃', "qin"); SURNAMES.put('解', "xie"); SURNAMES.put('谌', "shan"); SURNAMES.put('适', "kuo"); SURNAMES.put('都', "du"); SURNAMES.put('阿', "e"); SURNAMES.put('难', "ning"); SURNAMES.put('黑', "he"); //noinspection StringBufferReplaceableByString pinyinTable = new StringBuilder(125412) .append("yi ding kao qi shang xia none wan zhang san shang xia ji bu yu mian gai chou chou zhuan qie pi shi shi qiu bing ye cong dong si cheng diu qiu liang diu you liang yan bing sang shu jiu ge ya qiang zhong ji jie feng guan chuan chan lin zhuo zhu none wan dan wei zhu jing li ju pie fu yi yi nai none jiu jiu tuo me yi none zhi wu zha hu fa le zhong ping pang qiao hu guai cheng cheng yi yin none mie jiu qi ye xi xiang gai diu none none shu none shi ji nang jia none shi none none mai luan none ru xi yan fu sha na gan none none none none qian zhi gui gan luan lin yi jue le none yu zheng shi shi er chu yu kui yu yun hu qi wu jing si sui gen gen ya xie ya qi ya ji tou wang kang ta jiao hai yi chan heng mu none xiang jing ting liang heng jing ye qin bo you xie dan lian duo wei ren ren ji none wang yi shen ren le ding ze jin pu chou ba zhang jin jie bing reng cong fo san lun none cang zi shi ta zhang fu xian xian cha hong tong ren qian gan ge di dai ling yi chao chang sa shang yi mu men ren jia chao yang qian zhong pi wan wu jian jia yao feng cang ren wang fen di fang zhong qi pei yu diao dun wen yi xin kang yi ji ai wu ji fu fa xiu jin bei chen fu tang zhong you huo hui yu cui yun san wei chuan che ya xian shang chang lun cang xun xin wei zhu chi xuan nao bo gu ni ni xie ban xu ling zhou shen qu si beng si jia pi yi si ai zheng dian han mai dan zhu bu qu bi shao ci wei di zhu zuo you yang ti zhan he bi tuo she yu yi fo zuo gou ning tong ni xuan ju yong wa qian none ka none pei huai he lao xiang ge yang bai fa ming jia nai bing ji heng huo gui quan tiao jiao ci yi shi xing shen tuo kan zhi gai lai yi chi kua guang li yin shi mi zhu xu you an lu mou er lun dong cha chi xun gong zhou yi ru jian xia jia zai lu: none jiao zhen ce qiao kuai chai ning nong jin wu hou jiong cheng zhen cuo chou qin lu: ju shu ting shen tuo bo nan hao bian tui yu xi cu e qiu xu kuang ku wu jun yi fu lang zu qiao li yong hun jing xian san pai su fu xi li mian ping bao yu si xia xin xiu yu ti che chou none yan liang li lai si jian xiu fu he ju xiao pai jian biao ti fei feng ya an bei yu xin bi chi chang zhi bing zan yao cui lia wan lai cang zong ge guan bei tian shu shu men dao tan jue chui xing peng tang hou yi qi ti gan jing jie xu chang jie fang zhi kong juan zong ju qian ni lun zhuo wo luo song leng hun dong zi ben wu ju nai cai jian zhai ye zhi sha qing none ying cheng qian yan nuan zhong chun jia jie wei yu bing ruo ti wei pian yan feng tang wo e xie che sheng kan di zuo cha ting bei ye huang yao zhan qiu yan you jian xu zha chai fu bi zhi zong mian ji yi xie xun si duan ce zhen ou tou tou bei za lou jie wei fen chang kui sou chi su xia fu yuan rong li ru yun gou ma bang dian tang hao jie xi shan qian jue cang chu san bei xiao yong yao ta suo wang fa bing jia dai zai tang none bin chu nuo zan lei cui yong zao zong peng song ao chuan yu zhai zu shang qian") .append("g qiang chi sha han zhang qing yan di xi lou bei piao jin lian lu man qian xian qiu ying dong zhuan xiang shan qiao jiong tui zun pu xi lao chang guang liao qi deng chan wei zhang fan hui chuan tie dan jiao jiu seng fen xian jue e jiao jian tong lin bo gu xian su xian jiang min ye jin jia qiao pi feng zhou ai sai yi jun nong shan yi dang jing xuan kuai jian chu dan jiao sha zai none bin an ru tai chou chai lan ni jin qian meng wu neng qiong ni chang lie lei lu: kuang bao du biao zan zhi si you hao qin chen li teng wei long chu chan rang shu hui li luo zan nuo tang yan lei nang er wu yun zan yuan xiong chong zhao xiong xian guang dui ke dui mian tu chang er dui er jin tu si yan yan shi shi dang qian dou fen mao xin dou bai jing li kuang ru wang nei quan liang yu ba gong liu xi none lan gong tian guan xing bing qi ju dian zi none yang jian shou ji yi ji chan jiong mao ran nei yuan mao gang ran ce jiong ce zai gua jiong mao zhou mao gou xu mian mi rong yin xie kan jun nong yi mi shi guan meng zhong zui yuan ming kou none fu xie mi bing dong tai gang feng bing hu chong jue hu kuang ye leng pan fu min dong xian lie xia jian jing shu mei shang qi gu zhun song jing liang qing diao ling dong gan jian yin cou ai li cang ming zhun cui si duo jin lin lin ning xi du ji fan fan fan feng ju chu none feng none none fu feng ping feng kai huang kai gan deng ping qu xiong kuai tu ao chu ji dang han han zao dao diao dao ren ren chuangfen qie yi ji kan qian cun chu wen ji dan xing hua wan jue li yue lie liu ze gang chuangfu chu qu ju shan min ling zhong pan bie jie jie bao li shan bie chan jing gua gen dao chuangkui ku duo er zhi shua quan cha ci ke jie gui ci gui kai duo ji ti jing lou luo ze yuan cuo xue ke la qian cha chuan gua jian cuo li ti fei pou chan qi chuangzi gang wan bo ji duo qing yan zhuo jian ji bo yan ju huo sheng jian duo duan wu gua fu sheng jian ge zha kai chuangjuan chan tuan lu li fou shan piao kou jiao gua qiao jue hua zha zhuo lian ju pi liu gui jiao gui jian jian tang huo ji jian yi jian zhi chan cuan mo li zhu li ya quan ban gong jia wu mai lie jing keng xie zhi dong zhu nu jie qu shao yi zhu mo li jing lao lao juan kou yang wa xiao mou kuang jie lie he shi ke jing hao bo min chi lang yong yong mian ke xun juan qing lu bu meng lai le kai mian dong xu xu kan wu yi xun weng sheng lao mu lu piao shi ji qin qiang jiao quan xiang yi qiao fan juan tong ju dan xie mai xun xun lu: li che rang quan bao shao yun jiu bao gou wu yun none none gai gai bao cong none xiong peng ju tao ge pu an pao fu gong da jiu qiong bi hua bei nao chi fang jiu yi za jiang kang jiang kuang hu xia qu fan gui qie cang kuang fei hu yu gui kui hui dan kui lian lian suan du jiu qu xi pi qu yi an yan bian ni qu shi xin qian nian sa zu sheng wu hui ban shi xi wan hua xie wan bei zu zhuo xie dan mai nan dan ji bo shuai bu kuang bian bu zhan ka lu you lu xi gua wo xie jie jie wei ang qiong zhi mao yin we") .append("i shao ji que luan shi juan xie xu jin que wu ji e qing xi none chang han e ting li zhe an li ya ya yan she zhi zha pang none ke ya zhi ce pang ti li she hou ting zui cuo fei yuan ce yuan xiang yan li jue sha dian chu jiu qin ao gui yan si li chang lan li yan yan yuan si si lin qiu qu qu none lei du xian zhuan san can can san can ai dai you cha ji you shuangfan shou guai ba fa ruo shi shu zhui qu shou bian xu jia pan sou ji yu sou die rui cong kou gu ju ling gua tao kou zhi jiao zhao ba ding ke tai chi shi you qiu po ye hao si tan chi le diao ji none hong mie yu mang chi ge xuan yao zi he ji diao cun tong ming hou li tu xiang zha he ye lu: a ma ou xue yi jun chou lin tun yin fei bi qin qin jie pou fou ba dun fen e han ting hang shun qi hu zhi yin wu wu chao na chuo xi chui dou wen hou ou wu gao ya jun lu: e ge mei dai qi cheng wu gao fu jiao hong chi sheng na tun m yi dai ou li bei yuan guo none qiang wu e shi quan pen wen ni mou ling ran you di zhou shi zhou zhan ling yi qi ping zi gua ci wei xu he nao xia pei yi xiao shen hu ming da qu ju gan za tuo duo pou pao bie fu bi he za he hai jiu yong fu da zhou wa ka gu ka zuo bu long dong ning zha si xian huo qi er e guang zha xi yi lie zi mie mi zhi yao ji zhou ge shuai zan xiao ke hui kua huai tao xian e xuan xiu guo yan lao yi ai pin shen tong hong xiong duo wa ha zai you di pai xiang ai gen kuang ya da xiao bi hui none hua none kuai duo none ji nong mou yo hao yuan long pou mang ge e chi shao li na zu he ku xiao xian lao bei zhe zha liang ba mi le sui fou bu han heng geng shuo ge you yan gu gu bai han suo chun yi ai jia tu xian guan li xi tang zuo miu che wu zao ya dou qi di qin ma none gong dou none lao liang suo zao huan none gou ji zuo wo feng yin hu qi shou wei shua chang er li qiang an jie yo nian yu tian lai sha xi tuo hu ai zhou nou ken zhuo zhuo shang di heng lin a xiao xiang tun wu wen cui jie hu qi qi tao dan dan wan zi bi cui chuo he ya qi zhe fei liang xian pi sha la ze qing gua pa zhe se zhuan nie guo luo yan di quan tan bo ding lang xiao none tang chi ti an jiu dan ka yong wei nan shan yu zhe la jie hou han die zhou chai kuai re yu yin zan yao wo mian hu yun chuan hui huan huan xi he ji kui zhong wei sha xu huang du nie xuan liang yu sang chi qiao yan dan pen shi li yo zha wei miao ying pen none kui xi yu jie lou ku cao huo ti yao he a xiu qiang se yong su hong xie ai suo ma cha hai ke da sang chen ru sou gong ji pang wu qian shi ge zi jie luo weng wa si chi hao suo jia hai suo qin nie he none sai ng ge na dia ai none tong bi ao ao lian cui zhe mo sou sou tan di qi jiao chong jiao kai tan san cao jia none xiao piao lou ga gu xiao hu hui guo ou xian ze chang xu po de ma ma hu lei du ga tang ye beng ying none jiao mi xiao hua ") .append("mai ran zuo peng lao xiao ji zhu chao kui zui xiao si hao fu liao qiao xi xu chan dan hei xun wu zun pan chi kui can zan cu dan yu tun cheng jiao ye xi qi hao lian xu deng hui yin pu jue qin xun nie lu si yan ying da zhan o zhou jin nong hui hui qi e zao yi shi jiao yuan ai yong xue kuai yu pen dao ga xin dun dang none sai pi pi yin zui ning di han ta huo ru hao xia yan duo pi chou ji jin hao ti chang none none ca ti lu hui bao you nie yin hu mo huang zhe li liu none nang xiao mo yan li lu long mo dan chen pin pi xiang huo mo xi duo ku yan chan ying rang dian la ta xiao jiao chuo huan huo zhuan nie xiao ca li chan chai li yi luo nang zan su xi none jian za zhu lan nie nang none none wei hui yin qiu si nin jian hui xin yin nan tuan tuan dun kang yuan jiong pian yun cong hu hui yuan e guo kun cong wei tu wei lun guo jun ri ling gu guo tai guo tu you guo yin hun pu yu han yuan lun quan yu qing guo chui wei yuan quan ku pu yuan yuan e tu tu tu tuan lu:e hui yi yuan luan luan tu ya tu ting sheng yan lu none ya zai wei ge yu wu gui pi yi di qian qian zhen zhuo dang qia none none kuang chang qi nie mo ji jia zhi zhi ban xun tou qin fen jun keng dun fang fen ben tan kan huai zuo keng bi xing di jing ji kuai di jing jian tan li ba wu fen zhui po pan tang kun qu tan zhi tuo gan ping dian wa ni tai pi jiong yang fo ao liu qiu mu ke gou xue ba chi che ling zhu fu hu zhi chui la long long lu ao none pao none xing tong ji ke lu ci chi lei gai yin hou dui zhao fu guang yao duo duo gui cha yang yin fa gou yuan die xie ken shang shou e none dian hong ya kua da none dang kai none nao an xing xian huan bang pei ba yi yin han xu chui cen geng ai peng fang que yong jun jia di mai lang xuan cheng shan jin zhe lie lie pu cheng none bu shi xun guo jiong ye nian di yu bu wu juan sui pi cheng wan ju lun zheng kong zhong dong dai tan an cai shu beng kan zhi duo yi zhi yi pei ji zhun qi sao ju ni ku ke tang kun ni jian dui jin gang yu e peng gu tu leng none ya qian none an chen duo nao tu cheng yin hun bi lian guo die zhuan hou bao bao yu di mao jie ruan e geng kan zong yu huang e yao yan bao ji mei chang du tuo an feng zhong jie zhen heng gang chuan jian none lei gang huang leng duan wan xuan ji ji kuai ying ta cheng yong kai su su shi mi ta weng cheng tu tang qiao zhong li peng bang sai zang dui tian wu cheng xun ge zhen ai gong yan kan tian yuan wen xie liu none lang chang peng beng chen lu lu ou qian mei mo zhuan shuangshu lou chi man biao jing ce shu di zhang kan yong dian chen zhi ji guo qiang jin di shang mu cui yan ta zeng qi qiang liang none zhui qiao zeng xu shan shan ba pu kuai dong fan que mo dun dun zun zui sheng duo duo tan deng mu fen huang tan da ye chu none ao qiang ji qiao ken yi pi bi dian jiang ye yong xue tan lan ju huai dang rang qian xuan lan mi he kai ya dao hao ruan none lei kuang lu yan tan wei huai long long rui li ") .append(" lin rang chan xun yan lei ba none shi ren none zhuangzhuangsheng yi mai qiao zhu zhuanghu hu kun yi hu xu kun shou mang zun shou yi zhi gu chu xiang feng bei none bian sui qun ling fu zuo xia xiong none nao xia kui xi wai yuan mao su duo duo ye qing none gou gou qi meng meng yin huo chen da ze tian tai fu guai yao yang hang gao shi ben tai tou yan bi yi kua jia duo none kuang yun jia ba en lian huan di yan pao juan qi nai feng xie fen dian none kui zou huan qi kai she ben yi jiang tao zhuangben xi huang fei diao sui beng dian ao she weng pan ao wu ao jiang lian duo yun jiang shi fen huo bei lian che nu: nu ding nai qian jian ta jiu nan cha hao xian fan ji shuo ru fei wang hong zhuangfu ma dan ren fu jing yan xie wen zhong pa du ji keng zhong yao jin yun miao pei chi yue zhuangniu yan na xin fen bi yu tuo feng yuan fang wu yu gui du ba ni zhou zhou zhao da nai yuan tou xuan zhi e mei mo qi bi shen qie e he xu fa zheng ni ban mu fu ling zi zi shi ran shan yang qian jie gu si xing wei zi ju shan pin ren yao tong jiang shu ji gai shang kuo juan jiao gou lao jian jian yi nian zhi ji ji xian heng guang jun kua yan ming lie pei yan you yan cha xian yin chi gui quan zi song wei hong wa lou ya rao jiao luan ping xian shao li cheng xie mang none suo mu wei ke lai chuo ding niang keng nan yu na pei sui juan shen zhi han di zhuange pin tui xian mian wu yan wu xi yan yu si yu wa li xian ju qu chui qi xian zhui dong chang lu ai e e lou mian cong pou ju po cai ling wan biao xiao shu qi hui fu wo rui tan fei none jie tian ni quan jing hun jing qian dian xing hu wan lai bi yin chou chuo fu jing lun yan lan kun yin ya none li dian xian none hua ying chan shen ting yang yao wu nan chuo jia tou xu yu wei ti rou mei dan ruan qin none wu qian chun mao fu jie duan xi zhong mei huang mian an ying xuan none wei mei yuan zhen qiu ti xie tuo lian mao ran si pian wei wa jiu hu ao none bao xu tou gui zou yao pi xi yuan ying rong ru chi liu mei pan ao ma gou kui qin jia sao zhen yuan cha yong ming ying ji su niao xian tao pang lang niao bao ai pi pin yi piao yu lei xuan man yi zhang kang yong ni li di gui yan jin zhuan chang ce han nen lao mo zhe hu hu ao nen qiang none bi gu wu qiao tuo zhan mao xian xian mo liao lian hua gui deng zhi xu none hua xi hui rao xi yan chan jiao mei fan fan xian yi wei chan fan shi bi shan sui qiang lian huan none niao dong yi can ai niang ning ma tiao chou jin ci yu pin none xu nai yan tai ying can niao none ying mian none ma shen xing ni du liu yuan lan yan shuangling jiao niang lan xian ying shuangshuai quan mi li luan yan zhu lan zi jie jue jue kong yun zi zi cun sun fu bei zi xiao xin meng si tai bao ji gu nu xue none chan hai luan sun nao mie cong jian shu chan ya zi ni fu zi li xue bo ru nai nie nie ying luan mian ning rong ta gui zhai qiong yu shou an tu song wan rou yao hong yi jing zhun mi guai dang hong zong guan zhou ding wa") .append("n yi bao shi shi chong shen ke xuan shi you huan yi tiao shi xian gong cheng qun gong xiao zai zha bao hai yan xiao jia shen chen rong huang mi kou kuan bin su cai zan ji yuan ji yin mi kou qing he zhen jian fu ning bing huan mei qin han yu shi ning jin ning zhi yu bao kuan ning qin mo cha ju gua qin hu wu liao shi ning zhai shen wei xie kuan hui liao jun huan yi yi bao qin chong bao feng cun dui si xun dao lu: dui shou po feng zhuan fu she ke jiang jiang zhuan wei zun xun shu dui dao xiao ji shao er er er ga jian shu chen shang shang yuan ga chang liao xian xian none wang wang you liao liao yao mang wang wang wang ga yao duo kui zhong jiu gan gu gan gan gan gan shi yin chi kao ni jin wei niao ju pi ceng xi bi ju jie tian qu ti jie wu diao shi shi ping ji xie chen xi ni zhan xi none man e lou ping ti fei shu xie tu lu: lu: xi ceng lu: ju xie ju jue liao jue shu xi che tun ni shan wa xian li e none none long yi qi ren wu han shen yu chu sui qi none yue ban yao ang ya wu jie e ji qian fen wan qi cen qian qi cha jie qu gang xian ao lan dao ba zhai zuo yang ju gang ke gou xue bo li tiao qu yan fu xiu jia ling tuo pei you dai kuang yue qu hu po min an tiao ling chi none dong none kui xiu mao tong xue yi none he ke luo e fu xun die lu lang er gai quan tong yi mu shi an wei hu zhi mi li ji tong kui you none xia li yao jiao zheng luan jiao e e yu ye bu qiao qun feng feng nao li you xian hong dao shen cheng tu geng jun hao xia yin wu lang kan lao lai xian que kong chong chong ta none hua ju lai qi min kun kun zu gu cui ya ya gang lun lun leng jue duo cheng guo yin dong han zheng wei yao pi yan song jie beng zu jue dong zhan gu yin zi ze huang yu wei yang feng qiu dun ti yi zhi shi zai yao e zhu kan lu: yan mei gan ji ji huan ting sheng mei qian wu yu zong lan jie yan yan wei zong cha sui rong ke qin yu qi lou tu dui xi weng cang dang rong jie ai liu wu song qiao zi wei beng dian cuo qian yong nie cuo ji none none song zong jiang liao none chan di cen ding tu lou zhang zhan zhan ao cao qu qiang zui zui dao dao xi yu bo long xiang ceng bo qin jiao yan lao zhan lin liao liao jin deng duo zun jiao gui yao qiao yao jue zhan yi xue nao ye ye yi e xian ji xie ke sui di ao zui none yi rong dao ling za yu yue yin none jie li sui long long dian ying xi ju chan ying kui yan wei nao quan chao cuan luan dian dian nie yan yan yan nao yan chuan gui chuan zhou huang jing xun chao chao lie gong zuo qiao ju gong none wu none none cha qiu qiu ji yi si ba zhi zhao xiang yi jin xun juan none xun jin fu za bi shi bu ding shuai fan nie shi fen pa zhi xi hu dan wei zhang tang dai ma pei pa tie fu lian zhi zhou bo zhi di mo yi yi ping qia juan ru shuai dai zhen shui qiao zhen shi qun xi bang dai gui chou ping zhang sha wan dai wei chang sha qi ze guo mao du hou zhen xu mi wei wo fu yi bang ping none gong pan huang dao mi jia teng hui zhong sen ") .append("man mu biao guo ze mu bang zhang jiong chan fu zhi hu fan chuangbi bi none mi qiao dan fen meng bang chou mie chu jie xian lan gan ping nian jian bing bing xing gan yao huan you you ji guang pi ting ze guang zhuangmo qing bi qin dun chuanggui ya bai jie xu lu wu none ku ying di pao dian ya miao geng ci fu tong pang fei xiang yi zhi tiao zhi xiu du zuo xiao tu gui ku pang ting you bu bing cheng lai bi ji an shu kang yong tuo song shu qing yu yu miao sou ce xiang fei jiu he hui liu sha lian lang sou jian pou qing jiu jiu qin ao kuo lou yin liao dai lu yi chu chan tu si xin miao chang wu fei guang none guai bi qiang xie lin lin liao lu none ying xian ting yong li ting yin xun yan ting di po jian hui nai hui gong nian kai bian yi qi nong fen ju yan yi zang bi yi yi er san shi er shi shi gong diao yin hu fu hong wu tui chi qiang ba shen di zhang jue tao fu di mi xian hu chao nu jing zhen yi mi quan wan shao ruo xuan jing diao zhang jiang qiang beng dan qiang bi bi she dan jian gou none fa bi kou none bie xiao dan kuang qiang hong mi kuo wan jue ji ji gui dang lu lu tuan hui zhi hui hui yi yi yi yi huo huo shan xing zhang tong yan yan yu chi cai biao diao bin peng yong piao zhang ying chi chi zhuo tuo ji pang zhong yi wang che bi di ling fu wang zheng cu wang jing dai xi xun hen yang huai lu: hou wang cheng zhi xu jing tu cong none lai cong de pai xi none qi chang zhi cong zhou lai yu xie jie jian chi jia bian huang fu xun wei pang yao wei xi zheng piao chi de zheng zhi bie de chong che jiao wei jiao hui mei long xiang bao qu xin xin bi yi le ren dao ding gai ji ren ren chan tan te te gan qi dai cun zhi wang mang xi fan ying tian min min zhong chong wu ji wu xi ye you wan zong zhong kuai yu bian zhi chi cui chen tai tun qian nian hun xiong niu wang xian xin kang hu kai fen huai tai song wu ou chang chuangju yi bao chao min pi zuo zen yang kou ban nu nao zheng pa bu tie hu hu ju da lian si zhou di dai yi tu you fu ji peng xing yuan ni guai fu xi bi you qie xuan zong bing huang xu chu pi xi xi tan none zong dui none none yi chi nen xun shi xi lao heng kuang mou zhi xie lian tiao huang die hao kong gui heng xi xiao shu sai hu qiu yang hui hui chi jia yi xiong guai lin hui zi xu chi xiang nu: hen en ke dong tian gong quan xi qia yue peng ken de hui e none tong yan kai ce nao yun mang yong yong juan mang kun qiao yue yu yu jie xi zhe lin ti han hao qie ti bu yi qian hui xi bei man yi heng song quan cheng kui wu wu you li liang huan cong yi yue li nin nao e que xuan qian wu min cong fei bei de cui chang men li ji guan guan xing dao qi kong tian lun xi kan kun ni qing chou dun guo chan jing wan yuan jin ji lin yu huo he quan yan ti ti nie wang chuo hu hun xi chang xin wei hui e rui zong jian yong dian ju can cheng de bei qie can dan guan duo nao yun xiang zhui die huang chun qiong re xing ce bian hun zong ti qiao chou bei xuan wei ge qian wei yu yu bi xuan huan") .append(" min bi yi mian yong kai dang yin e chen mou qia ke yu ai qie yan nuo gan yun zong sai leng fen none kui kui que gong yun su su qi yao song huang none gu ju chuangta xie kai zheng yong cao sun shen bo kai yuan xie hun yong yang li sao tao yin ci xu qian tai huang yun shen ming none she cong piao mo mu guo chi can can can cui min ni zhang tong ao shuangman guan que zao jiu hui kai lian ou song jin yin lu: shang wei tuan man qian zhe yong qing kang di zhi lu: juan qi qi yu ping liao zong you chuangzhi tong cheng qi qu peng bei bie chun jiao zeng chi lian ping kui hui qiao cheng yin yin xi xi dan tan duo dui dui su jue ce xiao fan fen lao lao chong han qi xian min jing liao wu can jue chou xian tan sheng pi yi chu xian nao dan tan jing song han jiao wei huan dong qin qin qu cao ken xie ying ao mao yi lin se jun huai men lan ai lin yan gua xia chi yu yin dai meng ai meng dui qi mo lan men chou zhi nuo nuo yan yang bo zhi xing kuang you fu liu mie cheng none chan meng lan huai xuan rang chan ji ju huan she yi lian nan mi tang jue gang gang zhuangge yue wu jian xu shu rong xi cheng wo jie ge jian qiang huo qiang zhan dong qi jia die cai jia ji shi kan ji kui gai deng zhan chuangge jian jie yu jian yan lu xi zhan xi xi chuo dai qu hu hu hu e shi li mao hu li fang suo bian dian jiong shang yi yi shan hu fei yan shou shou cai zha qiu le pu ba da reng fu none zai tuo zhang diao kang yu ku han shen cha chi gu kou wu tuo qian zhi cha kuo men sao yang niu ban che rao xi qian ban jia yu fu ao xi pi zhi zi e dun zhao cheng ji yan kuang bian chao ju wen hu yue jue ba qin zhen zheng yun wan na yi shu zhua pou tou dou kang zhe pou fu pao ba ao ze tuan kou lun qiang none hu bao bing zhi peng tan pu pi tai yao zhen zha yang bao he ni yi di chi pi za mo mo chen ya chou qu min chu jia fu zha zhu dan chai mu nian la fu pao ban pai lin na guai qian ju tuo ba tuo tuo ao ju zhuo pan zhao bai bai di ni ju kuo long jian qia yong lan ning bo ze qian hen kuo shi jie zheng nin gong gong quan shuan tun zan kao chi xie ce hui pin zhuai shi na bo chi gua zhi kuo duo duo zhi qie an nong zhen ge jiao kua dong ru tiao lie zha lu: die wa jue none ju zhi luan ya wo ta xie nao dang jiao zheng ji hui xian none ai tuo nuo cuo bo geng ti zhen cheng suo suo keng mei long ju peng jian yi ting shan nuo wan xie cha feng jiao wu jun jiu tong kun huo tu zhuo pou lu: ba han shao nie juan she shu ye jue bu huan bu jun yi zhai lu: sou tuo lao sun bang jian huan dao none wan qin peng she lie min men fu bai ju dao wo ai juan yue zong chen chui jie tu ben na nian nuo zu wo xi xian cheng dian sao lun qing gang duo shou diao pou di zhang gun ji tao qia qi pai shu qian ling ye ya jue zheng liang gua yi huo shan ding lu:e cai tan che bing jie ti kong tui yan cuo zou ju tian qian ken bai shou jie lu guai none none zhi dan none chan sao guan peng yuan nuo jian zheng jiu jian yu ya") .append("n kui nan hong rou pi wei sai zou xuan miao ti nie cha shi zong zhen yi shun heng bian yang huan yan zan an xu ya wo ke chuai ji ti la la cheng kai jiu jiu tu jie hui geng chong shuo she xie yuan qian ye cha zha bei yao none none lan wen qin chan ge lou zong geng jiao gou qin yong que chou chuai zhan sun sun bo chu rong bang cuo sao ke yao dao zhi nu xie jian sou qiu gao xian shuo sang jin mie e chui nuo shan ta jie tang pan ban da li tao hu zhi wa xia qian wen qiang chen zhen e xie nuo quan cha zha ge wu en she gong she shu bai yao bin sou tan sha chan suo liao chong chuangguo bing feng shuai di qi none zhai lian cheng chi guan lu luo lou zong gai hu zha chuangtang hua cui nai mo jiang gui ying zhi ao zhi chi man shan kou shu suo tuan zhao mo mo zhe chan keng biao jiang yin gou qian liao ji ying jue pie pie lao dun xian ruan kui zan yi xian cheng cheng sa nao heng si han huang da zun nian lin zheng hui zhuangjiao ji cao dan dan che bo che jue xiao liao ben fu qiao bo cuo zhuo zhuan tuo pu qin dun nian none xie lu jiao cuan ta han qiao zhua jian gan yong lei kuo lu shan zhuo ze pu chuo ji dang se cao qing jing huan jie qin kuai dan xie ge pi bo ao ju ye none none sou mi ji tai zhuo dao xing lan ca ju ye ru ye ye ni huo ji bin ning ge zhi jie kuo mo jian xie lie tan bai sou lu lu:e rao zhi pan yang lei sa shu zan nian xian jun huo lu:e la han ying lu long qian qian zan qian lan san ying mei rang chan none cuan xie she luo jun mi li zan luan tan zuan li dian wa dang jiao jue lan li nang zhi gui gui qi xin po po shou kao you gai gai gong gan ban fang zheng bo dian kou min wu gu ge ce xiao mi chu ge di xu jiao min chen jiu shen duo yu chi ao bai xu jiao duo lian nie bi chang dian duo yi gan san ke yan dun qi dou xiao duo jiao jing yang xia hun shu ai qiao ai zheng di zhen fu shu liao qu xiong xi jiao none qiao zhuo yi lian bi li xue xiao wen xue qi qi zhai bin jue zhai lang fei ban ban lan yu lan wei dou sheng liao jia hu xie jia yu zhen jiao wo tiao dou jin chi yin fu qiang zhan qu zhuo zhan duan zhuo si xin zhuo zhuo qin lin zhuo chu duan zhu fang xie hang wu shi pei you none pang qi zhan mao lu: pei pi liu fu fang xuan jing jing ni zu zhao yi liu shao jian none yi qi zhi fan piao fan zhan guai sui yu wu ji ji ji huo ri dan jiu zhi zao xie tiao xun xu ga la gan han tai di xu chan shi kuang yang shi wang min min tun chun wu yun bei ang ze ban jie kun sheng hu fang hao gui chang xuan ming hun fen qin hu yi xi xin yan ze fang tan shen ju yang zan bing xing ying xuan pei zhen ling chun hao mei zuo mo bian xu hun zhao zong shi shi yu fei die mao ni chang wen dong ai bing ang zhou long xian kuang tiao chao shi huang huang xuan kui xu jiao jin zhi jin shang tong hong yan gai xiang shai xiao ye yun hui han han jun wan xian kun zhou xi sheng sheng bu zhe zhe wu han hui hao chen wan tian zhuo zui zhou pu jing xi shan yi xi qing qi jing gui zhen yi zhi an wan lin ") .append("liang chang wang xiao zan none xuan geng yi xia yun hui fu min kui he ying du wei shu qing mao nan jian nuan an yang chun yao suo pu ming jiao kai gao weng chang qi hao yan li ai ji gui men zan xie hao mu mo cong ni zhang hui bao han xuan chuan liao xian dan jing pie lin tun xi yi ji kuang dai ye ye li tan tong xiao fei qin zhao hao yi xiang xing sen jiao bao jing none ai ye ru shu meng xun yao pu li chen kuang die none yan huo lu xi rong long nang luo luan shai tang yan chu yue yue qu ye geng zhuai hu he shu cao cao sheng man ceng ceng ti zui can xu hui yin qie fen pi yue you ruan peng ban fu ling fei qu none nu: tiao shuo zhen lang lang juan ming huang wang tun chao ji qi ying zong wang tong lang none meng long mu deng wei mo ben zha zhu shu none zhu ren ba po duo duo dao li qiu ji jiu bi xiu ting ci sha none za quan qian yu gan wu cha shan xun fan wu zi li xing cai cun ren shao zhe di zhang mang chi yi gu gong du yi qi shu gang tiao none none none lai shan mang yang ma miao si yuan hang fei bei jie dong gao yao xian chu chun pa shu hua xin chou zhu chou song ban song ji yue yun gou ji mao pi bi wang ang fang fen yi fu nan xi hu ya dou xun zhen yao lin rui e mei zhao guo zhi zong yun none dou shu zao none li lu jian cheng song qiang feng nan xiao xian ku ping tai xi zhi guai xiao jia jia gou bao mo yi ye sang shi nie bi tuo yi ling bing ni la he ban fan zhong dai ci yang fu bo mou gan qi ran rou mao zhao song zhe xia you shen ju tuo zuo nan ning yong di zhi zha cha dan gu none jiu ao fu jian bo duo ke nai zhu bi liu chai zha si zhu pei shi guai cha yao cheng jiu shi zhi liu mei none rong zha none biao zhan zhi long dong lu none li lan yong shu xun shuan qi zhen qi li chi xiang zhen li su gua kan bing ren xiao bo ren bing zi chou yi ci xu zhu jian zui er er yu fa gong kao lao zhan li none yang he gen zhi chi ge zai luan fa jie heng gui tao guang wei kuang ru an an juan yi zhuo ku zhi qiong tong sang sang huan jie jiu xue duo zhui yu zan none ying none none zhan ya rao zhen dang qi qiao hua gui jiang zhuangxun suo suo zhen bei ting kuo jing bo ben fu rui tong jue xi lang liu feng qi wen jun gan cu liang qiu ting you mei bang long peng zhuangdi xuan tu zao ao gu bi di han zi zhi ren bei geng jian huan wan nuo jia tiao ji xiao lu: kuan shao cen fen song meng wu li li dou cen ying suo ju ti xie kun zhuo shu chan fan wei jing li bing none none tao zhi lai lian jian zhuo ling li qi bing lun cong qian mian qi qi cai gun chan de fei pai bang pou hun zong cheng zao ji li peng yu yu gu hun dong tang gang wang di xi fan cheng zhan qi yuan yan yu quan yi sen ren chui leng qi zhuo fu ke lai zou zou zhao guan fen fen chen qiong nie wan guo lu hao jie yi chou ju ju cheng zuo liang qiang zhi zhui ya ju bei jiao zhuo zi bin peng ding chu shan none none jian gui xi du qian none kui none luo zhi none none none none peng shan none tuo sen duo ye fu wei wei duan jia zong") .append(" jian yi shen xi yan yan chuan zhan chun yu he zha wo bian bi yao huo xu ruo yang la yan ben hun kui jie kui si feng xie tuo ji jian mu mao chu hu hu lian leng ting nan yu you mei song xuan xuan ying zhen pian die ji jie ye chu shun yu cou wei mei di ji jie kai qiu ying rou heng lou le none gui pin none gai tan lan yun yu chen lu: ju none none none xie jia yi zhan fu nuo mi lang rong gu jian ju ta yao zhen bang sha yuan zi ming su jia yao jie huang gan fei zha qian ma sun yuan xie rong shi zhi cui yun ting liu rong tang que zhai si sheng ta ke xi gu qi kao gao sun pan tao ge xun dian nou ji shuo gou chui qiang cha qian huai mei xu gang gao zhuo tuo qiao yang dian jia jian zui none long bin zhu none xi qi lian hui yong qian guo gai gai tuan hua qi sen cui beng you hu jiang hu huan kui yi yi gao kang gui gui cao man jin di zhuangle lang chen cong li xiu qing shuangfan tong guan ji suo lei lu liang mi lou chao su ke chu tang biao lu jiu shu zha shu zhang men mo niao yang tiao peng zhu sha xi quan heng jian cong none none qiang none ying er xin zhi qiao zui cong pu shu hua kui zhen zun yue zhan xi xun dian fa gan mo wu qiao rao lin liu qiao xian run fan zhan tuo lao yun shun tui cheng tang meng ju cheng su jue jue tan hui ji nuo xiang tuo ning rui zhu tong zeng fen qiong ran heng cen gu liu lao gao chu none none none none ji dou none lu none none yuan ta shu jiang tan lin nong yin xi sui shan zui xuan cheng gan ju zui yi qin pu yan lei feng hui dang ji sui bo bi ding chu zhua gui ji jia jia qing zhe jian qiang dao yi biao song she lin li cha meng yin tao tai mian qi none bin huo ji qian mi ning yi gao jian yin er qing yan qi mi zhao gui chun ji kui po deng chu none mian you zhi guang qian lei lei sa lu none cuan lu: mie hui ou lu: zhi gao du yuan li fei zhu sou lian none chu none zhu lu yan li zhu chen jie e su huai nie yu long lai none xian none ju xiao ling ying jian yin you ying xiang nong bo chan lan ju shuangshe wei cong quan qu none none yu luo li zan luan dang jue none lan lan zhu lei li ba nang yu ling none qian ci huan xin yu yu qian ou xu chao chu qi kai yi jue xi xu xia yu kuai lang kuan shuo xi e yi qi hu chi qin kuan kan kuan kan chuan sha none yin xin xie yu qian xiao yi ge wu tan jin ou hu ti huan xu pen xi xiao hu she none lian chu yi kan yu chuo huan zhi zheng ci bu wu qi bu bu wai ju qian chi se chi se zhong sui sui li cuo yu li gui dai dai si jian zhe mo mo yao mo cu yang tian sheng dai shang xu xun shu can jue piao qia qiu su qing yun lian yi fou zhi ye can hun dan ji ye none yun wen chou bin ti jin shang yin diao cu hui cuan yi dan du jiang lian bin du jian jian shu ou duan zhu yin qing yi sha ke ke yao xun dian hui hui gu que ji yi ou hui duan yi xiao wu guan mu mei mei ai zuo du yu bi bi bi pi pi bi chan mao none none pi none jia zhan sai mu tuo xun er rong xian ju mu hao qiu dou none ta") .append("n pei ju duo cui bi san none mao sui shu yu tuo he jian ta san lu: mu li tong rong chang pu lu zhan sao zhan meng lu qu die shi di min jue mang qi pie nai qi dao xian chuan fen ri nei none fu shen dong qing qi yin xi hai yang an ya ke qing ya dong dan lu: qing yang yun yun shui shui zheng bing yong dang shui le ni tun fan gui ting zhi qiu bin ze mian cuan hui diao han cha zhuo chuan wan fan dai xi tuo mang qiu qi shan pai han qian wu wu xun si ru gong jiang chi wu none none tang zhi chi qian mi gu wang qing jing rui jun hong tai quan ji bian bian gan wen zhong fang xiong jue hu none qi fen xu xu qin yi wo yun yuan hang yan shen chen dan you dun hu huo qi mu rou mei ta mian wu chong tian bi sha zhi pei pan zhui za gou liu mei ze feng ou li lun cang feng wei hu mo mei shu ju zan tuo tuo duo he li mi yi fu fei you tian zhi zhao gu zhan yan si kuang jiong ju xie qiu yi jia zhong quan bo hui mi ben zhuo chu le you gu hong gan fa mao si hu ping ci fan zhi su ning cheng ling pao bo qi si ni ju yue zhu sheng lei xuan xue fu pan min tai yang ji yong guan beng xue long lu dan luo xie po ze jing yin zhou jie yi hui hui zui cheng yin wei hou jian yang lie si ji er xing fu sa zi zhi yin wu xi kao zhu jiang luo none an dong yi mou lei yi mi quan jin po wei xiao xie hong xu su kuang tao qie ju er zhou ru ping xun xiong zhi guang huan ming huo wa qia pai wu qu liu yi jia jing qian jiang jiao zhen shi zhuo ce none hui ji liu chan hun hu nong xun jin lie qiu wei zhe jun han bang mang zhuo you xi bo dou huan hong yi pu ying lan hao lang han li geng fu wu li chun feng yi yu tong lao hai jin jia chong weng mei sui cheng pei xian shen tu kun pin nie han jing xiao she nian tu yong xiao xian ting e su tun juan cen ti li shui si lei shui tao du lao lai lian wei wo yun huan di none run jian zhang se fu guan xing shou shuan ya chuo zhang ye kong wan han tuo dong he wo ju gan liang hun ta zhuo dian qie de juan zi xi xiao qi gu guo han lin tang zhou peng hao chang shu qi fang chi lu nao ju tao cong lei zhi peng fei song tian pi dan yu ni yu lu gan mi jing ling lun yin cui qu huai yu nian shen piao chun hu yuan lai hun qing yan qian tian miao zhi yin mi ben yuan wen re fei qing yuan ke ji she yuan se lu zi du none jian mian pi xi yu yuan shen shen rou huan zhu jian nuan yu qiu ting qu du feng zha bo wo wo di wei wen ru xie ce wei ge gang yan hong xuan mi ke mao ying yan you hong miao xing mei zai hun nai kui shi e pai mei lian qi qi mei tian cou wei can tuan mian xu mo xu ji pen jian jian hu feng xiang yi yin zhan shi jie zhen huang tan yu bi min shi tu sheng yong ju zhong none qiu jiao none yin tang long huo yuan nan ban you quan chui liang chan yan chun nie zi wan shi man ying la kui none jian xu lou gui gai none none po jin gui tang yuan suo yuan lian yao meng zhun sheng ke tai ta wa liu gou sao ming zha shi yi lun ma pu wei li ") .append("cai wu xi wen qiang ce shi su yi zhen sou yun xiu yin rong hun su su ni ta shi ru wei pan chu chu pang weng cang mie he dian hao huang xi zi di zhi ying fu jie hua ge zi tao teng sui bi jiao hui gun yin gao long zhi yan she man ying chun lu: lan luan xiao bin tan yu xiu hu bi biao zhi jiang kou shen shang di mi ao lu hu hu you chan fan yong gun man qing yu piao ji ya jiao qi xi ji lu lu: long jin guo cong lou zhi gai qiang li yan cao jiao cong chun tuan ou teng ye xi mi tang mo shang han lian lan wa li qian feng xuan yi man zi mang kang luo peng shu zhang zhang chong xu huan kuo jian yan chuangliao cui ti yang jiang cong ying hong xiu shu guan ying xiao none none xu lian zhi wei pi yu jiao po xiang hui jie wu pa ji pan wei xiao qian qian xi lu xi sun dun huang min run su liao zhen zhong yi di wan dan tan chao xun kui none shao tu zhu sa hei bi shan chan chan shu tong pu lin wei se se cheng jiong cheng hua jiao lao che gan cun heng si shu peng han yun liu hong fu hao he xian jian shan xi ao lu lan none yu lin min zao dang huan ze xie yu li shi xue ling man zi yong kuai can lian dian ye ao huan lian chan man dan dan yi sui pi ju ta qin ji zhuo lian nong guo jin fen se ji sui hui chu ta song ding se zhu lai bin lian mi shi shu mi ning ying ying meng jin qi bi ji hao ru zui wo tao yin yin dui ci huo jing lan jun ai pu zhuo wei bin gu qian xing bin kuo fei none bin jian dui luo luo lu: li you yang lu si jie ying du wang hui xie pan shen biao chan mie liu jian pu se cheng gu bin huo xian lu qin han ying rong li jing xiao ying sui wei xie huai hao zhu long lai dui fan hu lai none none ying mi ji lian jian ying fen lin yi jian yue chan dai rang jian lan fan shuangyuan zhuo feng she lei lan cong qu yong qian fa guan que yan hao none sa zan luan yan li mi dan tan dang jiao chan none hao ba zhu lan lan nang wan luan quan xian yan gan yan yu huo biao mie guang deng hui xiao xiao none hong ling zao zhuan jiu zha xie chi zhuo zai zai can yang qi zhong fen niu gui wen po yi lu chui pi kai pan yan kai pang mu chao liao gui kang dun guang xin zhi guang xin wei qiang bian da xia zheng zhu ke zhao fu ba duo duo ling zhuo xuan ju tan pao jiong pao tai tai bing yang tong han zhu zha dian wei shi lian chi ping none hu shuo lan ting jiao xu xing quan lie huan yang xiao xiu xian yin wu zhou yao shi wei tong tong zai kai hong luo xia zhu xuan zheng po yan hui guang zhe hui kao none fan shao ye hui none tang jin re none xi fu jiong che pu jing zhuo ting wan hai peng lang shan hu feng chi rong hu none shu lang xun xun jue xiao xi yan han zhuangqu di xie qi wu none none han yan huan men ju dao bei fen lin kun hun chun xi cui wu hong ju fu yue jiao cong feng ping qiong cui xi qiong xin zhuo yan yan yi jue yu gang ran pi yan none sheng chang shao none none none none chen he kui zhong duan ya hui feng lian xuan xing huang jiao jian bi ying zhu wei tuan tian xi nuan nuan chan yan jiong jiong yu mei sha wu ye ") .append(" xin qiong rou mei huan xu zhao wei fan qiu sui yang lie zhu none gao gua bao hu yun xia none none bian wei tui tang chao shan yun bo huang xie xi wu xi yun he he xi yun xiong nai kao none yao xun ming lian ying wen rong none none qiang liu xi bi biao cong lu jian shu yi lou feng sui yi teng jue zong yun hu yi zhi ao wei liao han ou re jiong man none shang cuan zeng jian xi xi xi yi xiao chi huang chan ye qian ran yan xian qiao zun deng dun shen jiao fen si liao yu lin tong shao fen fan yan xun lan mei tang yi jing men none none ying yu yi xue lan tai zao can sui xi que cong lian hui zhu xie ling wei yi xie zhao hui none none lan ru xian kao xun jin chou dao yao he lan biao rong li mo bao ruo di lu: ao xun kuang shuo none li lu jue liao yan xi xie long yan none rang yue lan cong jue tong guan none che mi tang lan zhu lan ling cuan yu zhua lan pa zheng pao zhao yuan ai wei none jue jue fu ye ba die ye yao zu shuanger pan chuan ke zang zang qiang die qiang pian ban pan shao jian pai du yong tou tou bian die bang bo bang you none du ya cheng niu cheng pin jiu mou ta mu lao ren mang fang mao mu ren wu yan fa bei si jian gu you gu sheng mu di qian quan quan zi te xi mang keng qian wu gu xi li li pou ji gang zhi ben quan run du ju jia jian feng pian ke ju kao chu xi bei luo jie ma san wei li dun tong se jiang xi li du lie pi piao bao xi chou wei kui chou quan quan ba fan qiu bo chai chuo an jie zhuangguang ma you kang bo hou ya han huan zhuangyun kuang niu di qing zhong yun bei pi ju ni sheng pao xia tuo hu ling fei pi ni sheng you gou yue ju dan bo gu xian ning huan hen jiao he zhao ji huan shan ta rong shou tong lao du xia shi kuai zheng yu sun yu bi mang xi juan li xia yin suan lang bei zhi yan sha li zhi xian jing han fei yao ba qi ni biao yin li lie jian qiang kun yan guo zong mi chang yi zhi zheng ya meng cai cu she lie none luo hu zong hu wei feng wo yuan xing zhu mao wei yuan xian tuan ya nao xie jia hou bian you you mei cha yao sun bo ming hua yuan sou ma yuan dai yu shi hao none yi zhen chuanghao man jing jiang mo zhang chan ao ao hao cui ben jue bi bi huang bu lin yu tong yao liao shuo xiao shou none xi ge juan du hui kuai xian xie ta xian xun ning bian huo nou meng lie nao guang shou lu ta xian mi rang huan nao luo xian qi qu xuan miao zi lu: lu yu su wang qiu ga ding le ba ji hong di chuan gan jiu yu qi yu yang ma hong wu fu min jie ya bin bian beng yue jue yun jue wan jian mei dan pi wei huan xian qiang ling dai yi an ping dian fu xuan xi bo ci gou jia shao po ci ke ran sheng shen yi zu jia min shan liu bi zhen zhen jue fa long jin jiao jian li guang xian zhou gong yan xiu yang xu luo su zhu qin ken xun bao er xiang yao xia heng gui chong xu ban pei none dang ying hun wen e cheng ti wu wu cheng jun mei bei ting xian chuo han xuan yan qiu quan lang li xiu fu liu ya xi ling li jin lian suo suo none wan dian bing zhan cui min yu") .append(" ju chen lai wen sheng wei dian chu zhuo pei cheng hu qi e kun chang qi beng wan lu cong guan yan diao bei lin qin pi pa qiang zhuo qin fa none qiong du jie hun yu mao mei chun xuan ti xing dai rou min zhen wei ruan huan xie chuan jian zhuan yang lian quan xia duan yuan ye nao hu ying yu huang rui se liu none rong suo yao wen wu jin jin ying ma tao liu tang li lang gui tian qiang cuo jue zhao yao ai bin tu chang kun zhuan cong jin yi cui cong qi li ying suo qiu xuan ao lian man zhang yin none ying wei lu wu deng none zeng xun qu dang lin liao qiong su huang gui pu jing fan jin liu ji none jing ai bi can qu zao dang jiao gun tan hui huan se sui tian none yu jin fu bin shu wen zui lan xi ji xuan ruan huo gai lei du li zhi rou li zan qiong zhe gui sui la long lu li zan lan ying mi xiang xi guan dao zan huan gua bao die pao hu zhi piao ban rang li wa none jiang qian ban pen fang dan weng ou none none none hu ling yi ping ci none juan chang chi none dang meng bu chui ping bian zhou zhen none ci ying qi xian lou di ou meng zhuan beng lin zeng wu pi dan weng ying yan gan dai shen tian tian han chang sheng qing shen chan chan rui sheng su shen yong shuai lu fu yong beng none ning tian you jia shen zha dian fu nan dian ping ding hua ting quan zai meng bi qi liu xun liu chang mu yun fan fu geng tian jie jie quan wei fu tian mu none pan jiang wa da nan liu ben zhen chu mu mu ce none gai bi da zhi lu:e qi lu:e pan none fan hua yu yu mu jun yi liu she die chou hua dang chuo ji wan jiang cheng chang tun lei ji cha liu die tuan lin jiang jiang chou bo die die pi nie dan shu shu zhi yi chuangnai ding bi jie liao gong ge jiu zhou xia shan xu nu:e li yang chen you ba jie jue xi xia cui bi yi li zong chuangfeng zhu pao pi gan ke ci xie qi dan zhen fa zhi teng ju ji fei ju dian jia xuan zha bing nie zheng yong jing quan chong tong yi jie wei hui duo yang chi zhi hen ya mei dou jing xiao tong tu mang pi xiao suan pu li zhi cuo duo wu sha lao shou huan xian yi peng zhang guan tan fei ma lin chi ji tian an chi bi bi min gu dui e wei yu cui ya zhu xi dan shen zhong ji yu hou feng la yang shen tu yu gua wen huan ku jia yin yi lou sao jue chi xi guan yi wen ji chuangban lei liu chai shou nu:e dian da bie tan zhang biao shen cu luo yi zong chou zhang zhai sou suo que diao lou lou mo jin yin ying huang fu liao long qiao liu lao xian fei dan yin he ai ban xian guan guai nong yu wei yi yong pi lei li shu dan lin dian lin lai bie ji chi yang xuan jie zheng none li huo lai ji dian xian ying yin qu yong tan dian luo luan luan bo none gui po fa deng fa bai bai qie bi zao zao mao de pa jie huang gui ci ling gao mo ji jiao peng gao ai e hao han bi wan chou qian xi ai jiong hao huang hao ze cui hao xiao ye po hao jiao ai xing huang li piao he jiao pi gan pao zhou jun qiu cun que zha gu jun jun zhou zha gu zhan du min qi ying yu bei zhao zhong pen he ying he yi bo wan he ang zhan yan jian ") .append("he yu kui fan gai dao pan fu qiu sheng dao lu zhan meng lu jin xu jian pan guan an lu xu zhou dang an gu li mu ding gan xu mang mang zhi qi wan tian xiang dun xin xi pan feng dun min ming sheng shi yun mian pan fang miao dan mei mao kan xian kou shi yang zheng yao shen huo da zhen kuang ju shen yi sheng mei mo zhu zhen zhen mian di yuan die yi zi zi chao zha xuan bing mi long sui tong mi die yi er ming xuan chi kuang juan mou zhen tiao yang yan mo zhong mai zhe zheng mei suo shao han huan di cheng cuo juan e wan xian xi kun lai jian shan tian hun wan ling shi qiong lie ya jing zheng li lai sui juan shui sui du pi pi mu hun ni lu gao jie cai zhou yu hun ma xia xing hui gun none chun jian mei du hou xuan ti kui gao rui mao xu fa wen miao chou kui mi weng kou dang chen ke sou xia qiong mao ming man shui ze zhang yi diao kou mo shun cong lou chi man piao cheng ji meng huan run pie xi qiao pu zhu deng shen shun liao che xian kan ye xu tong wu lin kui jian ye ai hui zhan jian gu zhao ju wei chou ji ning xun yao huo meng mian bin mian li guang jue xuan mian huo lu meng long guan man xi chu tang kan zhu mao jin lin yu shuo ce jue shi yi shen zhi hou shen ying ju zhou jiao cuo duan ai jiao zeng huo bai shi ding qi ji zi gan wu tuo ku qiang xi fan kuang dang ma sha dan jue li fu min nuo hua kang zhi qi kan jie fen e ya pi zhe yan sui zhuan che dun pan yan none feng fa mo zha qu yu ke tuo tuo di zhai zhen e fu mu zhu la bian nu ping peng ling pao le po bo po shen za ai li long tong none li kuang chu keng quan zhu kuang gui e nao jia lu wei ai luo ken xing yan dong peng xi none hong shuo xia qiao none wei qiao none keng xiao que chan lang hong yu xiao xia mang long none che che wo liu ying mang que yan cuo kun yu none none lu chen jian none song zhuo keng peng yan zhui kong ceng qi zong qing lin jun bo ding min diao jian he liu ai sui que ling bei yin dui wu qi lun wan dian gang bei qi chen ruan yan die ding zhou tuo jie ying bian ke bi wei shuo zhen duan xia dang ti nao peng jian di tan cha none qi none feng xuan que que ma gong nian su e ci liu si tang bang hua pi wei sang lei cuo tian xia xi lian pan wei yun dui zhe ke la none qing gun zhuan chan qi ao peng lu lu kan qiang chen yin lei biao qi mo qi cui zong qing chuo none ji shan lao qu zeng deng jian xi lin ding dian huang pan za qiao di li jian jiao xi zhang qiao dun jian yu zhui he huo zhai lei ke chu ji que dang wo jiang pi pi yu pin qi ai ke jian yu ruan meng pao zi bo none mie ca xian kuang lei lei zhi li li fan que pao ying li long long mo bo shuangguan lan zan yan shi shi li reng she yue si qi ta ma xie yao xian zhi qi zhi beng shu chong none yi shi you zhi tiao fu fu mi zu zhi suan mei zuo qu hu zhu shen sui ci chai mi lu: yu xiang wu tiao piao zhu gui xia zhi ji gao zhen gao shui jin zhen gai kun di dao huo tao qi gu guan zui ling lu bing jin dao zhi lu shan bei zhe hui you xi ") .append(" yin zi huo zhen fu yuan wu xian yang ti yi mei si di none zhuo zhen yong ji gao tang chi ma ta none xuan qi yu xi ji si chan xuan hui sui li nong ni dao li rang yue ti zan lei rou yu yu li xie qin he tu xiu si ren tu zi cha gan yi xian bing nian qiu qiu zhong fen hao yun ke miao zhi jing bi zhi yu mi ku ban pi ni li you zu pi ba ling mo cheng nian qin yang zuo zhi zhi shu ju zi tai ji cheng tong zhi huo he yin zi zhi jie ren du yi zhu hui nong fu xi kao lang fu ze shui lu: kun gan jing ti cheng tu shao shui ya lun lu gu zuo ren zhun bang bai ji zhi zhi kun leng peng ke bing chou zui yu su none none yi xi bian ji fu bi nuo jie zhong zong xu cheng dao wen lian zi yu ji xu zhen zhi dao jia ji gao gao gu rong sui none ji kang mu shan men zhi ji lu su ji ying wen qiu se none yi huang qie ji sui xiao pu jiao zhuo tong none lu: sui nong se hui rang nuo yu none ji tui wen cheng huo gong lu: biao none rang jue li zan xue wa jiu qiong xi qiong kong yu sen jing yao chuan zhun tu lao qie zhai yao bian bao yao bing yu zhu jiao qiao diao wu gui yao zhi chuan yao tiao jiao chuangjiong xiao cheng kou cuan wo dan ku ke zhui xu su none kui dou none yin wo wa ya yu ju qiong yao yao tiao liao yu tian diao ju liao xi wu kui chuangju none kuan long cheng cui piao zao cuan qiao qiong dou zao zao qie li chu shi fu qian chu hong qi qian gong shi shu miao ju zhan zhu ling long bing jing jing zhang yi si jun hong tong song jing diao yi shu jing qu jie ping duan shao zhuan ceng deng cun huai jing kan jing zhu zhu le peng yu chi gan mang zhu none du ji xiao ba suan ji zhen zhao sun ya zhui yuan hu gang xiao cen pi bi jian yi dong shan sheng xia di zhu na chi gu li qie min bao tiao si fu ce ben fa da zi di ling ze nu fu gou fan jia ge fan shi mao po none jian qiong long none bian luo gui qu chi yin yao xian bi qiong gua deng jiao jin quan sun ru fa kuang zhu tong ji da hang ce zhong kou lai bi shai dang zheng ce fu yun tu pa li lang ju guan jian han tong xia zhi cheng suan shi zhu zuo xiao shao ting jia yan gao kuai gan chou kuang gang yun none qian xiao jian pu lai zou bi bi bi ge chi guai yu jian zhao gu chi zheng qing sha zhou lu bo ji lin suan jun fu zha gu kong qian qian jun chui guan yuan ce ju bo ze qie tuo luo dan xiao ruo jian none bian sun xiang xian ping zhen sheng hu shi zhu yue chun fu wu dong shuo ji jie huang xing mei fan chuan zhuan pian feng zhu hong qie hou qiu miao qian none kui none lou yun he tang yue chou gao fei ruo zheng gou nie qian xiao cuan gong pang du li bi zhuo chu shai chi zhu qiang long lan jian bu li hui bi di cong yan peng sen cuan pai piao dou yu mie zhuan ze xi guo yi hu chan kou cu ping zao ji gui su lou zha lu nian suo cuan none suo le duan liang xiao bo mi shai dang liao dan dian fu jian min kui dai qiao deng huang sun lao zan xiao lu shi zan none pai qi pai gan ju du lu yan bo dang sai ke gou qian lian bu zhou lai none la") .append("n kui yu yue hao zhen tai ti mi chou ji none qi teng zhuan zhou fan sou zhou qian kuo teng lu lu jian tuo ying yu lai long none lian lan qian yue zhong qu lian bian duan zuan li shai luo ying yue zhuo xu mi di fan shen zhe shen nu: xie lei xian zi ni cun zhang qian none bi ban wu sha kang rou fen bi cui yin li chi tai none ba li gan ju po mo cu zhan zhou li su tiao li xi su hong tong zi ce yue zhou lin zhuangbai none fen mian qu none liang xian fu liang can jing li yue lu ju qi cui bai chang lin zong jing guo none san san tang bian rou mian hou xu zong hu jian zan ci li xie fu nuo bei gu xiu gao tang qiu none cao zhuangtang mi san fen zao kang jiang mo san san nuo chi liang jiang kuai bo huan shu zong jian nuo tuan nie li zuo di nie tiao lan mi mi jiu xi gong zheng jiu you ji cha zhou xun yue hong yu he wan ren wen wen qiu na zi tou niu fou jie shu chun pi yin sha hong zhi ji fen yun ren dan jin su fang suo cui jiu zha ba jin fu zhi qi zi chou hong zha lei xi fu xie shen bei zhu qu ling zhu shao gan yang fu tuo zhen dai chu shi zhong xian zu jiong ban ju pa shu zui kuang jing ren heng xie jie zhu chou gua bai jue kuang hu ci geng geng tao xie ku jiao quan gai luo xuan beng xian fu gei tong rong tiao yin lei xie quan xu hai die tong si jiang xiang hui jue zhi jian juan chi mian zhen lu: cheng qiu shu bang tong xiao wan qin geng xiu ti xiu xie hong xi fu ting sui dui kun fu jing hu zhi yan jiong feng ji xu none zong lin duo li lu: liang chou quan shao qi qi zhun qi wan qian xian shou wei qi tao wan gang wang beng zhui cai guo cui lun liu qi zhan bei chuo ling mian qi jie tan zong gun zou yi zi xing liang jin fei rui min yu zong fan lu: xu none shang none xu xiang jian ke xian ruan mian ji duan zhong di min miao yuan xie bao si qiu bian huan geng zong mian wei fu wei yu gou miao jie lian zong bian yun yin ti gua zhi yun cheng chan dai jia yuan zong xu sheng none geng none ying jin yi zhui ni bang gu pan zhou jian cuo quan shuangyun xia shuai xi rong tao fu yun zhen gao ru hu zai teng xian su zhen zong tao huang cai bi feng cu li suo yin xi zong lei zhuan qian man zhi lu: mo piao lian mi xuan zong ji shan sui fan shuai beng yi sao mou zhou qiang hun xian xi none xiu ran xuan hui qiao zeng zuo zhi shan san lin yu fan liao chuo zun jian rao chan rui xiu hui hua zuan xi qiang none da sheng hui xi se jian jiang huan qiao cong jie jiao bo chan yi nao sui yi shai xu ji bin qian jian pu xun zuan qi peng li mo lei xie zuan kuang you xu lei xian chan none lu chan ying cai xiang xian zui zuan luo xi dao lan lei lian mi jiu yu hong zhou xian he yue ji wan kuang ji ren wei yun hong chun pi sha gang na ren zong lun fen zhi wen fang zhu zhen niu shu xian gan xie fu lian zu shen xi zhi zhong zhou ban fu chu shao yi jing dai bang rong jie ku rao die hang hui ji xuan jiang luo jue jiao tong geng xiao juan xiu xi sui tao ji ti ji xu ling yin xu qi fei chuo shang gun sheng wei mian shou beng chou tao liu quan ") .append("zong zhan wan lu: zhui zi ke xiang jian mian lan ti miao ji yun hui si duo duan bian xian gou zhui huan di lu: bian min yuan jin fu ru zhen feng cui gao chan li yi jian bin piao man lei ying suo mou sao xie liao shan zeng jiang qian qiao huan jiao zuan fou xie gang fou que fou que bo ping hou none gang ying ying qing xia guan zun tan none qing weng ying lei tan lu guan wang gang wang wang han none luo fu mi fa gu zhu ju mao gu min gang ba gua ti juan fu lin yan zhao zui gua zhuo yu zhi an fa lan shu si pi ma liu ba fa li chao wei bi ji zeng tong liu ji juan mi zhao luo pi ji ji luan yang mie qiang ta mei yang you you fen ba gao yang gu qiang zang gao ling yi zhu di xiu qiang yi xian rong qun qun qian huan suo xian yi yang qiang xian yu geng jie tang yuan xi fan shan fen shan lian lei geng nou qiang chan yu gong yi chong weng fen hong chi chi cui fu xia pen yi la yi pi ling liu zhi qu xi xie xiang xi xi qi qiao hui hui shu se hong jiang zhai cui fei tao sha chi zhu jian xuan shi pian zong wan hui hou he he han ao piao yi lian qu none lin pen qiao ao fan yi hui xuan dao yao lao none kao mao zhe qi gou gou gou die die er shua ruan er nai zhuan lei ting zi geng chao hao yun pa pi chi si qu jia ju huo chu lao lun ji tang ou lou nou jiang pang ze lou ji lao huo you mo huai er zhe ding ye da song qin yun chi dan dan hong geng zhi none nie dan zhen che ling zheng you wa liao long zhi ning tiao er ya die guo none lian hao sheng lie pin jing ju bi di guo wen xu ping cong none none ting yu cong kui lian kui cong lian weng kui lian lian cong ao sheng song ting kui nie zhi dan ning none ji ting ting long yu yu zhao si su yi su si zhao zhao rou yi lei ji qiu ken cao ge di huan huang yi ren xiao ru zhou yuan du gang rong gan cha wo chang gu zhi qin fu fei ban pei pang jian fang zhun you na ang ken ran gong yu wen yao jin pi qian xi xi fei ken jing tai shen zhong zhang xie shen wei zhou die dan fei ba bo qu tian bei gua tai zi ku zhi ni ping zi fu pang zhen xian zuo pei jia sheng zhi bao mu qu hu ke yi yin xu yang long dong ka lu jing nu yan pang kua yi guang hai ge dong zhi jiao xiong xiong er an xing pian neng zi none cheng tiao zhi cui mei xie cui xie mo mai ji xie none kuai sa zang qi nao mi nong luan wan bo wen wan qiu jiao jing you heng cuo lie shan ting mei chun shen xie none juan cu xiu xin tuo pao cheng nei fu dou tuo niao nao pi gu luo li lian zhang cui jie liang shui pi biao lun pian guo juan chui dan tian nei jing jie la ye a ren shen chuo fu fu ju fei qiang wan dong pi guo zong ding wu mei ruan zhuan zhi cou gua ou di an xing nao shu shuan nan yun zhong rou e sai tu yao jian wei jiao yu jia duan bi chang fu xian ni mian wa teng tui bang qian lu: wa shou tang su zhui ge yi bo liao ji pi xie gao lu: bin none chang lu guo pang chuai biao jiang fu tang mo xi zhuan lu: jiao ying lu: zhi xue chun lin tong peng ni chuai liao cui gui xiao teng fan zhi jiao shan hu ") .append(" cui run xin sui fen ying shan gua dan kuai nong tun lian bei yong jue chu yi juan la lian sao tun gu qi cui bin xun nao huo zang xian biao xing kuan la yan lu hu za luo qu zang luan ni za chen qian wo guang zang lin guang zi jiao nie chou ji gao chou mian nie zhi zhi ge jian die zhi xiu tai zhen jiu xian yu cha yao yu chong xi xi jiu yu yu xing ju jiu xin she she she jiu shi tan shu shi tian dan pu pu guan hua tian chuan shun xia wu zhou dao chuan shan yi none pa tai fan ban chuan hang fang ban bi lu zhong jian cang ling zhu ze duo bo xian ge chuan jia lu hong pang xi none fu zao feng li shao yu lang ting none wei bo meng nian ju huang shou zong bian mao die none bang cha yi sou cang cao lou dai none yao chong none dang qiang lu yi jie jian huo meng qi lu lu chan shuanggen liang jian jian se yan fu ping yan yan cao cao yi le ting jiao ai nai tiao jiao jie peng wan yi chai mian mi gan qian yu yu shao xiong du xia qi mang zi hui sui zhi xiang bi fu tun wei wu zhi qi shan wen qian ren fou kou jie lu zhu ji qin qi yan fen ba rui xin ji hua hua fang wu jue gou zhi yun qin ao chu mao ya fei reng hang cong yin you bian yi none wei li pi e xian chang cang zhu su yi yuan ran ling tai tiao di miao qing li rao ke mu pei bao gou min yi yi ju pie ruo ku zhu ni bo bing shan qiu yao xian ben hong ying zha dong ju die nie gan hu ping mei fu sheng gu bi wei fu zhuo mao fan qie mao mao ba zi mo zi di chi gou jing long none niao none xue ying qiong ge ming li rong yin gen qian chai chen yu xiu zi lie wu duo kui ce jian ci gou guang mang cha jiao jiao fu yu zhu zi jiang hui yin cha fa rong ru chong mang tong zhong none zhu xun huan kua quan gai da jing xing chuan cao jing er an shou chi ren jian ti huang ping li jin lao rong zhuangda jia rao bi ce qiao hui ji dang none rong hun ying luo ying qian jin sun yin mai hong zhou yao du wei chu dou fu ren yin he bi bu yun di tu sui sui cheng chen wu bie xi geng li pu zhu mo li zhuangji duo qiu sha suo chen feng ju mei meng xing jing che xin jun yan ting you cuo guan han you cuo jia wang you niu shao xian lang fu e mo wen jie nan mu kan lai lian shi wo tu xian huo you ying ying none chun mang mang ci yu jing di qu dong jian zou gu la lu ju wei jun nie kun he pu zai gao guo fu lun chang chou song chui zhan men cai ba li tu bo han bao qin juan xi qin di jie pu dang jin zhao tai geng hua gu ling fei jin an wang beng zhou yan zu jian lin tan shu tian dao hu ji he cui tao chun bei chang huan fei lai qi meng ping wei dan sha huan yan yi tiao qi wan ce nai none tuo jiu tie luo none none meng none none ding ying ying ying xiao sa qiu ke xiang wan yu yu fu lian xuan xuan nan ze wo chun xiao yu pian mao an e luo ying huo gua jiang wan zuo zuo ju bao rou xi xie an qu jian fu lu: lu: pen feng hong hong hou yan tu zhu zi xiang shen ge qia jing mi huang shen pu ge dong zhou qian wei bo wei pa ji hu zang ji") .append("a duan yao jun cong quan wei xian kui ting hun xi shi qi lan zong yao yuan mei yun shu di zhuan guan none qiong chan kai kui none jiang lou wei pai none sou yin shi chun shi yun zhen lang nu meng he que suan yuan li ju xi bang chu xu tu liu huo zhen qian zu po cuo yuan chu yu kuai pan pu pu na shuo xi fen yun zheng jian ji ruo cang en mi hao sun zhen ming none xu liu xi gu lang rong weng gai cuo shi tang luo ru suo xian bei yao gui bi zong gun none xiu ce none lan none ji li can lang yu none ying mo diao xiu wu tong zhu peng an lian cong xi ping qiu jin chun jie wei tui cao yu yi ji liao bi lu xu bu zhang luo qiang man yan leng ji biao gun han di su lu she shang di mie xun man bo di cuo zhe sen xuan yu hu ao mi lou cu zhong cai po jiang mi cong niao hui jun yin jian nian shu yin kui chen hu sha kou qian ma cang ze qiang dou lian lin kou ai bi li wei ji qian sheng fan meng ou chan dian xun jiao rui rui lei yu qiao chu hua jian mai yun bao you qu lu rao hui e ti fei jue zui fa ru fen kui shun rui ya xu fu jue dang wu tong si xiao xi yong wen shao qi jian yun sun ling yu xia weng ji hong si deng lei xuan yun yu xi hao bo hao ai wei hui wei ji ci xiang luan mie yi leng jiang can shen qiang lian ke yuan da ti tang xue bi zhan sun lian fan ding xiao gu xie shu jian kao hong sa xin xun yao bai sou shu xun dui pin wei neng chou mai ru piao tai qi zao chen zhen er ni ying gao cong xiao qi fa jian xu kui jie bian di mi lan jin zang miao qiong qie xian none ou xian su lu: yi xu xie li yi la lei jiao di zhi pi teng yao mo huan biao fan sou tan tui qiong qiao wei liu hui shu gao yun none li zhu zhu ai lin zao xuan chen lai huo tuo wu rui rui qi heng lu su tui mang yun pin yu xun ji jiong xuan mo none su jiong none nie bo rang yi xian yu ju lian lian yin qiang ying long tou wei yue ling qu yao fan mi lan kui lan ji dang none lei lei tong feng zhi wei kui zhan huai li ji mi lei huai luo ji nao lu jian none none lei quan xiao yi luan men bie hu hu lu nu:e lu: zhi xiao qian chu hu xu cuo fu xu xu lu hu yu hao jiao ju guo bao yan zhan zhan kui ban xi shu chong qiu diao ji qiu ding shi none di zhe she yu gan zi hong hui meng ge sui xia chai shi yi ma xiang fang e pa chi qian wen wen rui bang pi yue yue jun qi ran yin qi can yuan jue hui qian qi zhong ya hao mu wang fen fen hang gong zao fu ran jie fu chi dou bao xian ni te qiu you zha ping chi you he han ju li fu ran zha gou pi bo xian zhu diao bie bing gu ran qu she tie ling gu dan gu ying li cheng qu mou ge ci hui hui mang fu yang wa lie zhu yi xian kuo jiao li yi ping ji ha she yi wang mo qiong qie gui gong zhi man none zhe jia nao si qi xing lie qiu shao yong jia tui che bai e han shu xuan feng shen zhen fu xian zhe wu fu li lang bi chu yuan you jie dan yan ting dian tui hui wo zhi song fei ju mi qi qi yu jun la meng qiang si xi ") .append("lun li die tiao tao kun gan han yu bang fei pi wei dun yi yuan su quan qian rui ni qing wei liang guo wan dong e ban zhuo wang can yang ying guo chan none la ke ji xie ting mai xu mian yu jie shi xuan huang yan bian rou wei fu yuan mei wei fu ruan xie you you mao xia ying shi chong tang zhu zong ti fu yuan kui meng la du hu qiu die li gua yun ju nan lou chun rong ying jiang tun lang pang si xi xi xi yuan weng lian sou ban rong rong ji wu xiu han qin yi bi hua tang yi du nai he hu xi ma ming yi wen ying teng yu cang none none man none shang shi cao chi di ao lu wei zhi tang chen piao qu pi yu jian luo lou qin zhong yin jiang shuai wen jiao wan zhe zhe ma ma guo liao mao xi cong li man xiao none zhang mang xiang mo zi si qiu te zhi peng peng jiao qu bie liao pan gui xi ji zhuan huang fei lao jue jue hui yin chan jiao shan rao xiao wu chong xun si none cheng dang li xie shan yi jing da chan qi zi xiang she luo qin ying chai li ze xuan lian zhu ze xie mang xie qi rong jian meng hao ru huo zhuo jie bin he mie fan lei jie la mi li chun li qiu nie lu du xiao zhu long li long feng ye pi rang gu juan ying none xi can qu quan du can man qu jie zhu zha xue huang nu: pei nu: xin zhong mo er mie mie shi xing yan kan yuan none ling xuan shu xian tong long jie xian ya hu wei dao chong wei dao zhun heng qu yi yi bu gan yu biao cha yi shan chen fu gun fen shuai jie na zhong dan ri zhong zhong xie qi xie ran zhi ren qin jin jun yuan mei chai ao niao hui ran jia tuo ling dai bao pao yao zuo bi shao tan ju he xue xiu zhen yi pa bo di wa fu gun zhi zhi ran pan yi mao none na kou xuan chan qu bei yu xi none bo none fu yi chi ku ren jiang jia cun mo jie er ge ru zhu gui yin cai lie none none zhuangdang none kun ken niao shu jia kun cheng li juan shen pou ge yi yu chen liu qiu qun ji yi bu zhuangshui sha qun li lian lian ku jian fou tan bi gun tao yuan ling chi chang chou duo biao liang shang pei pei fei yuan luo guo yan du ti zhi ju qi ji zhi gua ken none ti shi fu chong xie bian die kun duan xiu xiu he yuan bao bao fu yu tuan yan hui bei chu lu: none none yun ta gou da huai rong yuan ru nai jiong suo ban tun chi sang niao ying jie qian huai ku lian lan li zhe shi lu: yi die xie xian wei biao cao ji qiang sen bao xiang none pu jian zhuan jian zui ji dan za fan bo xiang xin bie rao man lan ao duo hui cao sui nong chan lian bi jin dang shu tan bi lan pu ru zhi none shu wa shi bai xie bo chen lai long xi xian lan zhe dai none zan shi jian pan yi none ya xi xi yao feng tan none none fu ba he ji ji jian guan bian yan gui jue pian mao mi mi mie shi si zhan luo jue mo tiao lian yao zhi jun xi shan wei xi tian yu lan e du qin pang ji ming ping gou qu zhan jin guan deng jian luo qu jian wei jue qu luo lan shen di guan jian guan yan gui mi shi chan lan jue ji xi di tian yu gou jin qu jiao jiu jin cu jue zhi chao ji gu dan zui di shan") .append("g hua quan ge zhi jie gui gong chu jie huan qiu xing su ni ji lu zhi zhu bi xing hu shang gong zhi xue chu xi yi li jue xi yan xi yan yan ding fu qiu qiu jiao hong ji fan xun diao hong cha tao xu jie yi ren xun yin shan qi tuo ji xun yin e fen ya yao song shen yin xin jue xiao ne chen you zhi xiong fang xin chao she xian sa zhun xu yi yi su chi he shen he xu zhen zhu zheng gou zi zi zhan gu fu jian die ling di yang li nao pan zhou gan shi ju ao zha tuo yi qu zhao ping bi xiong chu ba da zu tao zhu ci zhe yong xu xun yi huang he shi cha jiao shi hen cha gou gui quan hui jie hua gai xiang hui shen chou tong mi zhan ming e hui yan xiong gua er beng tiao chi lei zhu kuang kua wu yu teng ji zhi ren su lang e kuang e^ shi ting dan bei chan you heng qiao qin shua an yu xiao cheng jie xian wu wu gao song pu hui jing shuo zhen shuo du none chang shui jie ke qu cong xiao sui wang xuan fei chi ta yi na yin diao pi chuo chan chen zhun ji qi tan chui wei ju qing jian zheng ze zou qian zhuo liang jian zhu hao lun shen biao huai pian yu die xu pian shi xuan shi hun hua e zhong di xie fu pu ting jian qi yu zi chuan xi hui yin an xian nan chen feng zhu yang yan heng xuan ge nuo qi mou ye wei none teng zou shan jian bo none huang huo ge ying mi xiao mi xi qiang chen nu:e si su bang chi qian shi jiang yuan xie xue tao yao yao hu yu biao cong qing li mo mo shang zhe miu jian ze zha lian lou can ou guan xi zhuo ao ao jin zhe yi hu jiang man chao han hua chan xu zeng se xi she dui zheng nao lan e ying jue ji zun jiao bo hui zhuan wu jian zha shi qiao tan zen pu sheng xuan zao zhan dang sui qian ji jiao jing lian nou yi ai zhan pi hui hua yi yi shan rang nou qian zhui ta hu zhou hao ni ying jian yu jian hui du zhe xuan zan lei shen wei chan li yi bian zhe yan e chou wei chou yao chan rang yin lan chen huo zhe huan zan yi dang zhan yan du yan ji ding fu ren ji jie hong tao rang shan qi tuo xun yi xun ji ren jiang hui ou ju ya ne xu e lun xiong song feng she fang jue zheng gu he ping zu shi xiong zha su zhen di zhou ci qu zhao bi yi yi kuang lei shi gua shi jie hui cheng zhu shen hua dan gou quan gui xun yi zheng gai xiang cha hun xu zhou jie wu yu qiao wu gao you hui kuang shuo song ei qing zhu zou nuo du zhuo fei ke wei yu shei shen diao chan liang zhun sui tan shen yi mou chen die huang jian xie xue ye wei e yu xuan chan zi an yan di mi pian xu mo dang su xie yao bang shi qian mi jin man zhe jian miu tan jian qiao lan pu jue yan qian zhan chen gu qian hong ya jue hong han hong qi xi huo liao han du long dou jiang qi chi feng deng wan bi shu xian feng zhi zhi yan yan shi chu hui tun yi tun yi jian ba hou e cu xiang huan jian ken gai qu fu xi bin hao yu zhu jia fen xi hu wen huan bin di zong fen yi zhi bao chai han pi na pi gou duo you diao mo si xiu huan kun he he mo an mao li ni bi yu jia tuan mao pi xi e ju") .append(" mo chu tan huan qu bei zhen yuan fu cai gong te yi hang wan pin huo fan tan guan ze zhi er zhu shi bi zi er gui pian bian mai dai sheng kuang fei tie yi chi mao he bi lu lin hui gai pian zi jia xu zei jiao gai zang jian ying xun zhen she bin bin qiu she chuan zang zhou lai zan si chen shang tian pei geng xian mai jian sui fu dan cong cong zhi ji zhang du jin xiong shun yun bao zai lai feng cang ji sheng ai zhuan fu gou sai ze liao wei bai chen zhuan zhi zhui biao yun zeng tan zan yan none shan wan ying jin gan xian zang bi du shu yan none xuan long gan zang bei zhen fu yuan gong cai ze xian bai zhang huo zhi fan tan pin bian gou zhu guan er jian bi shi tie gui kuang dai mao fei he yi zei zhi jia hui zi lin lu zang zi gai jin qiu zhen lai she fu du ji shu shang ci bi zhou geng pei dan lai feng zhui fu zhuan sai ze yan zan yun zeng shan ying gan chi xi she nan xiong xi cheng he cheng zhe xia tang zou zou li jiu fu zhao gan qi shan qiong qin xian ci jue qin chi ci chen chen die ju chao di se zhan zhu yue qu jie chi chu gua xue zi tiao duo lie gan suo cu xi zhao su yin ju jian que tang chuo cui lu qu dang qiu zi ti qu chi huang qiao qiao yao zao yue none zan zan zu pa bao ku he dun jue fu chen jian fang zhi ta yue pa qi yue qiang tuo tai yi nian ling mei ba die ku tuo jia ci pao qia zhu ju die zhi fu pan ju shan bo ni ju li gen yi ji dai xian jiao duo chu quan kua zhuai gui qiong kui xiang chi lu beng zhi jia tiao cai jian da qiao bi xian duo ji ju ji shu tu chu xing nie xiao bo xue qun mou shu liang yong jiao chou xiao none ta jian qi wo wei chuo jie ji nie ju ju lun lu leng huai ju chi wan quan ti bo zu qie qi cu zong cai zong pan zhi zheng dian zhi yu duo dun chun yong zhong di zha chen chuai jian gua tang ju fu zu die pian rou nuo ti cha tui jian dao cuo xi ta qiang zhan dian ti ji nie pan liu zhan bi chong lu liao cu tang dai su xi kui ji zhi qiang di man zong lian beng zao nian bie tui ju deng ceng xian fan chu zhong dun bo cu zu jue jue lin ta qiao qiao pu liao dun cuan kuang zao ta bi bi zhu ju chu qiao dun chou ji wu yue nian lin lie zhi li zhi chan chu duan wei long lin xian wei zuan lan xie rang xie nie ta qu jie cuan zuan xi kui jue lin shen gong dan none qu ti duo duo gong lang none luo ai ji ju tang none none yan none kang qu lou lao duo zhi none ti dao none yu che ya gui jun wei yue xin di xuan fan ren shan qiang shu tun chen dai e na qi mao ruan ren qian zhuan hong hu qu huang di ling dai ao zhen fan kuang ang peng bei gu gu pao zhu rong e ba zhou zhi yao ke yi qing shi ping er qiong ju jiao guang lu kai quan zhou zai zhi ju liang yu shao you huan yun zhe wan fu qing zhou ni ling zhe zhan liang zi hui wang chuo guo kan yi peng qian gun nian ping guan bei lun pai liang ruan rou ji yang xian chuan cou chun ge you hong shu fu zi fu wen ben zhan yu wen tao gu zhen xia yuan lu jiu chao zhuan wei hun none che jiao zhan ") .append("pu lao fen fan lin ge se kan huan yi ji dui er yu xian hong lei pei li li lu lin che ya gui xuan dai ren zhuan e lun ruan hong gu ke lu zhou zhi yi hu zhen li yao qing shi zai zhi jiao zhou quan lu jiao zhe fu liang nian bei hui gun wang liang chuo zi cou fu ji wen shu pei yuan xia zhan lu zhe lin xin gu ci ci pi zui bian la la ci xue ban bian bian bian none bian ban ci bian bian chen ru nong nong zhen chuo chuo none reng bian bian none none liao da chan gan qian yu yu qi xun yi guo mai qi za wang none zhun ying ti yun jin hang ya fan wu ta e hai zhei none jin yuan wei lian chi che ni tiao zhi yi jiong jia chen dai er di po wang die ze tao shu tuo none jing hui tong you mi beng ji nai yi jie zhui lie xun tui song shi tao pang hou ni dun jiong xuan xun bu you xiao qiu tou zhu qiu di di tu jing ti dou yi zhe tong guang wu shi cheng su zao qun feng lian suo hui li none zui ben cuo jue beng huan dai lu you zhou jin yu chuo kui wei ti yi da yuan luo bi nuo yu dang sui dun sui yan chuan chi ti yu shi zhen you yun e bian guo e xia huang qiu dao da wei none yi gou yao chu liu xun ta di chi yuan su ta qian none yao guan zhang ao shi ce su su zao zhe dun zhi lou chi cuo lin zun rao qian xuan yu yi wu liao ju shi bi yao mai xie sui huan zhan deng er miao bian bian la li yuan you luo li yi ting deng qi yong shan han yu mang ru qiong none kuang fu kang bin fang xing nei none shen bang yuan cun huo xie bang wu ju you han tai qiu bi pi bing shao bei wa di zou ye lin kuang gui zhu shi ku yu gai he qie zhi ji xun hou xing jiao xi gui nuo lang jia kuai zheng lang yun yan cheng dou xi lu: fu wu fu gao hao lang jia geng jun ying bo xi bei li yun bu xiao qi pi qing guo none tan zou ping lai ni chen you bu xiang dan ju yong qiao yi dou yan mei ruo bei e yu juan yu yun hou kui xiang xiang sou tang ming xi ru chu zi zou ju wu xiang yun hao yong bi mao chao fu liao yin zhuan hu qiao yan zhang fan wu xu deng bi xin bi ceng wei zheng mao shan lin po dan meng ye cao kuai feng meng zou kuang lian zan chan you qi yan chan cuo ling huan xi feng zan li you ding qiu zhuo pei zhou yi gan yu jiu yan zui mao dan xu tou zhen fen none none yun tai tian qia tuo zuo han gu su fa chou dai ming lao chuo chou you tong zhi xian jiang cheng yin tu jiao mei ku suan lei pu zui hai yan shi niang wei lu lan yan tao pei zhan chun tan zui chuo cu kun ti xian du hu xu xing tan qiu chun yun fa ke sou mi quan chou cuo yun yong ang zha hai tang jiang piao lao yu li zao lao yi jiang bu jiao xi tan fa nong yi li ju yan yi niang ru xun chou yan ling mi mi niang xin jiao shi mi yan bian cai shi you shi shi li zhong ye liang li jin jin ga yi liao dao zhao ding li qiu he fu zhen zhi ba luan fu nai diao shan qiao kou chuan zi fan yu hua han gong qi mang jian di si xi yi chai ta tu xi nu: qian none jian pi ye yin ba fang chen jian tou yue yan fu bu ") .append(" na xin e jue dun gou yin qian ban ji ren chao niu fen yun yi qin pi guo hong yin jun shi yi zhong nie gai ri huo tai kang none lu none none duo zi ni tu shi min gu ke ling bing yi gu ba pi yu si zuo bu you dian jia zhen shi shi tie ju zhan ta she xuan zhao bao he bi sheng chu shi bo zhu chi za po tong qian fu zhai liu qian fu li yue pi yang ban bo jie gou shu zheng mu ni xi di jia mu tan shen yi si kuang ka bei jian tong xing hong jiao chi er ge bing shi mou jia yin jun zhou chong shang tong mo lei ji yu xu ren cun zhi qiong shan chi xian xing quan pi yi zhu hou ming kua yao xian xian xiu jun cha lao ji yong ru mi yi yin guang an diu you se kao qian luan none ai diao han rui shi keng qiu xiao zhe xiu zang ti cuo gua gong zhong dou lu: mei lang wan xin yun bei wu su yu chan ting bo han jia hong cuan feng chan wan zhi si xuan wu wu tiao gong zhuo lu:e xing qin shen han none ye chu zeng ju xian e mang pu li shi rui cheng gao li te none zhu none tu liu zui ju chang yuan jian gang diao tao chang lun guo ling bei lu li qing pei juan min zui peng an pi xian ya zhui lei a kong ta kun du wei chui zi zheng ben nie cong chun tan ding qi qian zhuo qi yu jin guan mao chang dian xi lian tao gu cuo shu zhen lu meng lu hua biao ga lai ken zhui none nai wan zan none de xian none huo liang none men kai ying di lian guo xian du tu wei cong fu rou ji e rou chen ti zha hong yang duan xia yu keng xing huang wei fu zhao cha qie she hong kui nuo mou qiao qiao hou zhen huo huan ye min jian duan jian si kui hu xuan zang jie zhen bian zhong zi xiu ye mei pai ai jie none mei cha ta bang xia lian suo xi liu zu ye nou weng rong tang suo qiang ge shuo chui bo pan ta bi sang gang zi wu ying huang tiao liu kai sun sha sou wan hao zhen zhen luo yi yuan tang nie xi jia ge ma juan rong none suo none none none na lu suo kou zu tuan xiu guan xuan lian shou ao man mo luo bi wei liu di qiao huo yin lu ao keng qiang cui qi chang tang man yong chan feng jing biao shu lou xiu cong long zan jian cao li xia xi kang none beng none none zheng lu hua ji pu hui qiang po lin suo xiu san cheng kui san liu nao huang pie sui fan qiao chuan yang tang xiang jue jiao zun liao jie lao dui tan zan ji jian zhong deng lou ying dui jue nou ti pu tie none none ding shan kai jian fei sui lu juan hui yu lian zhuo qiao qian zhuo lei bi tie huan ye duo guo dang ju fen da bei yi ai dang xun diao zhu heng zhui ji nie ta huo qing bin ying kui ning xu jian jian qiang cha zhi mie li lei ji zuan kuang shang peng la du shuo chuo lu: biao bao lu none none long e lu xin jian lan bo jian yao chan xiang jian xi guan cang nie lei cuan qu pan luo zuan luan zao nie jue tang shu lan jin ga yi zhen ding zhao po liao tu qian chuan shan sa fan diao men nu: yang chai xing gai bu tai ju dun chao zhong na bei gang ban qian yao qin jun wu gou kang fang huo tou niu ba yu qian zheng qian gu bo ke po bu bo yue zuan mu tan jia dian you ti") .append("e bo ling shuo qian mao bao shi xuan tuo bi ni pi duo xing kao lao er mang ya you cheng jia ye nao zhi dang tong lu: diao yin kai zha zhu xian ting diu xian hua quan sha ha yao ge ming zheng se jiao yi chan chong tang an yin ru zhu lao pu wu lai te lian keng xiao suo li zeng chu guo gao e xiu cuo lu:e feng xin liu kai jian rui ti lang qin ju a qing zhe nuo cuo mao ben qi de ke kun chang xi gu luo chui zhui jin zhi xian juan huo pei tan ding jian ju meng zi qie ying kai qiang si e cha qiao zhong duan sou huang huan ai du mei lou zi fei mei mo zhen bo ge nie tang juan nie na liu hao bang yi jia bin rong biao tang man luo beng yong jing di zu xuan liu chan jue liao pu lu dun lan pu cuan qiang deng huo lei huan zhuo lian yi cha biao la chan xiang chang chang jiu ao die qu liao mi zhang men ma shuan shan huo men yan bi han bi none kai kang beng hong run san xian xian jian min xia min dou zha nao none peng ke ling bian bi run he guan ge he fa chu hong gui min none kun lang lu: ting sha yan yue yue chan qu lin chang shai kun yan min yan e hun yu wen xiang none xiang qu yao wen ban an wei yin kuo que lan du none none tian nie da kai he que chuangguan dou qi kui tang guan piao kan xi hui chan pi dang huan ta wen none men shuan shan yan han bi wen chuangrun wei xian hong jian min kang men zha nao gui wen ta min lu: kai fa ge he kun jiu yue lang du yu yan chang xi wen hun yan yan chan lan qu hui kuo que he tian da que kan huan fu fu le dui xin qian wu yi tuo yin yang dou e sheng ban pei keng yun ruan zhi pi jing fang yang yin zhen jie cheng e qu di zu zuo dian ling a tuo tuo po bing fu ji lu long chen xing duo lou mo jiang shu duo xian er gui wu gai shan jun qiao xing chun fu bi shan shan sheng zhi pu dou yuan zhen chu xian zhi nie yun xian pei pei zou yi dui lun yin ju chui chen pi ling tao xian lu none xian yin zhu yang reng shan chong yan yin yu ti yu long wei wei nie dui sui an huang jie sui yin gai yan hui ge yun wu wei ai xi tang ji zhang dao ao xi yin sa rao lin tui deng pi sui sui yu xian fen ni er ji dao xi yin zhi hui long xi li li li zhui he zhi sun juan nan yi que yan qin ya xiong ya ji gu huan zhi gou jun ci yong ju chu hu za luo yu chou diao sui han huo shuangguan chu za yong ji sui chou liu li nan xue za ji ji yu yu xue na fou se mu wen fen pang yun li li yang ling lei an bao meng dian dang hang wu zhao xu ji mu chen xiao zha ting zhen pei mei ling qi chou huo sha fei weng zhan ying ni chou tun lin none dong ying wu ling shuangling xia hong yin mai mo yun liu meng bin wu wei kuo yin xi yi ai dan deng xian yu lu long dai ji pang yang ba pi wei none xi ji mai meng meng lei li huo ai fei dai long ling ai feng li bao none he he bing qing qing jing qi zhen jing cheng qing jing jing dian jing tian fei fei kao mi mian mian pao ye tian hui ye ge ding ren jian ren di du wu ren qin jin xue niu ba yin sa ren ") .append("mo zu da ban yi yao tao bei jia hong pao yang mo yin jia tao ji xie an an hen gong gong da qiao ting man ying sui tiao qiao xuan kong beng ta zhang bing kuo ju la xie rou bang yi qiu qiu he xiao mu ju jian bian di jian none tao gou ta bei xie pan ge bi kuo tang lou gui qiao xue ji jian jiang chan da huo xian qian du wa jian lan wei ren fu mei juan ge wei qiao han chang none rou xun she wei ge bei tao gou yun gao bi wei hui shu wa du wei ren fu han wei yun tao jiu jiu xian xie xian ji yin za yun shao luo peng huang ying yun peng yin yin xiang hu ye ding qing pan xiang shun han xu yi xu gu song kui qi hang yu wan ban dun di dan pan po ling cheng jing lei he qiao e e wei jie gua shen yi yi ke dui pian ping lei fu jia tou hui kui jia le ting cheng ying jun hu han jing tui tui pin lai tui zi zi chui ding lai yan han qian ke cui jiong qin yi sai ti e e yan hun kan yong zhuan yan xian xin yi yuan sang dian dian jiang ku lei liao piao yi man qi yao hao qiao gu xun qian hui zhan ru hong bin xian pin lu lan nie quan ye ding qing han xiang shun xu xu wan gu dun qi ban song hang yu lu ling po jing jie jia ting he ying jiong ke yi pin hui tui han ying ying ke ti yong e zhuan yan e nie man dian sang hao lei zhan ru pin quan feng biao none fu xia zhan biao sa fa tai lie gua xuan shao ju biao si wei yang yao sou kai sao fan liu xi liao piao piao liu biao biao biao liao none se feng biao feng yang zhan biao sa ju si sou yao liu piao biao biao fei fan fei fei shi shi can ji ding si tuo jian sun xiang tun ren yu juan chi yin fan fan sun yin zhu yi zhai bi jie tao liu ci tie si bao shi duo hai ren tian jiao jia bing yao tong ci xiang yang yang er yan le yi can bo nei e bu jun dou su yu shi yao hun guo shi jian zhui bing xian bu ye tan fei zhang wei guan e nuan hun hu huang tie hui jian hou he xing fen wei gu cha song tang bo gao xi kui liu sou tao ye yun mo tang man bi yu xiu jin san kui zhuan shan chi dan yi ji rao cheng yong tao hui xiang zhan fen hai meng yan mo chan xiang luo zuan nang shi ding ji tuo xing tun xi ren yu chi fan yin jian shi bao si duo yi er rao xiang he le jiao xi bing bo dou e yu nei jun guo hun xian guan cha kui gu sou chan ye mo bo liu xiu jin man san zhuan nang shou kui guo xiang fen ba ni bi bo tu han fei jian yan ai fu xian wen xin fen bin xing ma yu feng han di tuo tuo chi xun zhu zhi pei xin ri sa yin wen zhi dan lu: you bo bao kuai tuo yi qu wen qu jiong bo zhao yuan peng zhou ju zhu nu ju pi zang jia ling zhen tai fu yang shi bi tuo tuo si liu ma pian tao zhi rong teng dong xun quan shen jiong er hai bo none yin luo none dan xie liu ju song qin mang liang han tu xuan tui jun e cheng xing ai lu zhui zhou she pian kun tao lai zong ke qi qi yan fei sao yan jie yao wu pian cong pian qian fei huang jian huo yu ti quan xia zong kui rou si gua tuo kui sou qian cheng zhi liu pang teng xi cao ") .append(" du yan yuan zou sao shan li zhi shuanglu xi luo zhang mo ao can piao cong qu bi zhi yu xu hua bo su xiao lin zhan dun liu tuo zeng tan jiao tie yan luo zhan jing yi ye tuo bin zou yan peng lu: teng xiang ji shuangju xi huan li biao ma yu tuo xun chi qu ri bo lu: zang shi si fu ju zou zhu tuo nu jia yi tai xiao ma yin jiao hua luo hai pian biao li cheng yan xing qin jun qi qi ke zhui zong su can pian zhi kui sao wu ao liu qian shan piao luo cong zhan zhou ji shuangxiang gu wei wei wei yu gan yi ang tou jie bo bi ci ti di ku hai qiao hou kua ge tui geng pian bi ke qia yu sui lou bo xiao bang bo cuo kuan bin mo liao lou nao du zang sui ti bin kuan lu gao gao qiao kao qiao lao zao biao kun kun ti fang xiu ran mao dan kun bin fa tiao pi zi fa ran ti pao pi mao fu er rong qu none xiu gua ji peng zhua shao sha ti li bin zong ti peng song zheng quan zong shun jian duo hu la jiu qi lian zhen bin peng mo san man man seng xu lie qian qian nong huan kuai ning bin lie rang dou dou nao hong xi dou kan dou dou jiu chang yu yu li juan fu qian gui zong liu gui shang yu gui mei ji qi jie kui hun ba po mei xu yan xiao liang yu tui qi wang liang wei jian chi piao bi mo ji xu chou yan zhan yu dao ren ji ba hong tuo diao ji yu e que sha hang tun mo gai shen fan yuan pi lu wen hu lu za fang fen na you none none he xia qu han pi ling tuo ba qiu ping fu bi ji wei ju diao ba you gun pi nian xing tai bao fu zha ju gu none none none ta jie shua hou xiang er an wei tiao zhu yin lie luo tong yi qi bing wei jiao pu gui xian ge hui none none kao none duo jun ti mian shao za suo qin yu nei zhe gun geng none wu qiu ting fu huan chou li sha sha gao meng none none none none yong ni zi qi qing xiang nei chun ji diao qie gu zhou dong lai fei ni yi kun lu jiu chang jing lun ling zou li meng zong zhi nian none none none shi sao hun ti hou xing ju la zong ji bian bian huan quan ji wei wei yu chun rou die huang lian yan qiu qiu jian bi e yang fu sai jian ha tuo hu none ruo none wen jian hao wu pang sao liu ma shi shi guan zi teng ta yao ge rong qian qi wen ruo none lian ao le hui min ji tiao qu jian sao man xi qiu biao ji ji zhu jiang qiu zhuan yong zhang kang xue bie jue qu xiang bo jiao xun su huang zun shan shan fan gui lin xun miao xi none xiang fen guan hou kuai zei sao zhan gan gui sheng li chang none none ai ru ji xu huo none li lie li mie zhen xiang e lu guan li xian yu dao ji you tun lu fang ba ke ba ping nian lu you zha fu ba bao hou pi tai gui jie kao wei er tong zei hou kuai ji jiao xian zha xiang xun geng li lian jian li shi tiao gun sha huan jun ji yong qing ling qi zou fei kun chang gu ni nian diao jing shen shi zi fen die bi chang ti wen wei sai e qiu fu huang quan jiang bian sao ao qi ta guan yao pang jian le biao xue bie man min yong wei xi gui shan lin zun hu gan li shan guan niao yi fu li jiu bu ya") .append("n fu diao ji feng none gan shi feng ming bao yuan zhi hu qian fu fen wen jian shi yu fou yiao ju jue pi huan zhen bao yan ya zheng fang feng wen ou te jia nu ling mie fu tuo wen li bian zhi ge yuan zi qu xiao chi dan ju you gu zhong yu yang rong ya zhi yu none ying zhui wu er gua ai zhi yan heng jiao ji lie zhu ren ti hong luo ru mou ge ren jiao xiu zhou chi luo none none none luan jia ji yu huan tuo bu wu juan yu bo xun xun bi xi jun ju tu jing ti e e kuang hu wu shen la none none lu bing shu fu an zhao peng qin qian bei diao lu que jian ju tu ya yuan qi li ye zhui kong duo kun sheng qi jing ni e jing zi lai dong qi chun geng ju qu none none ji shu none chi miao rou fu qiu ti hu ti e jie mao fu chun tu yan he yuan pian yun mei hu ying dun mu ju none cang fang ge ying yuan xuan weng shi he chu tang xia ruo liu ji gu jian zhun han zi ci yi yao yan ji li tian kou ti ti ni tu ma jiao liu zhen chen li zhuan zhe ao yao yi ou chi zhi liao rong lou bi shuangzhuo yu wu jue yin tan si jiao yi hua bi ying su huang fan jiao liao yan kao jiu xian xian tu mai zun yu ying lu tuan xian xue yi pi shu luo qi yi ji zhe yu zhan ye yang pi ning hu mi ying meng di yue yu lei bo lu he long shuangyue ying guan qu li luan niao jiu ji yuan ming shi ou ya cang bao zhen gu dong lu ya xiao yang ling chi qu yuan xue tuo si zhi er gua xiu heng zhou ge luan hong wu bo li juan hu e yu xian ti wu que miao an kun bei peng qian chun geng yuan su hu he e gu qiu ci mei wu yi yao weng liu ji yi jian he yi ying zhe liu liao jiao jiu yu lu huan zhan ying hu meng guan shuanglu jin ling jian xian cuo jian jian yan cuo lu you cu ji biao cu pao zhu jun zhu jian mi mi wu liu chen jun lin ni qi lu jiu jun jing li xiang yan jia mi li she zhang lin jing qi ling yan cu mai mai ge chao fu mian mian fu pao qu qu mou fu xian lai qu mian chi feng fu qu mian ma ma mo hui none zou nen fen huang huang jin guang tian tou hong xi kuang hong shu li nian chi hei hei yi qian zhen xi tuan mo mo qian dai chu you dian yi xia yan qu mei yan qing yu li dang du can yin an yan tan an zhen dai can yi mei dan yan du lu zhi fen fu fu min min yuan cu qu chao wa zhu zhi mang ao bie tuo bi yuan chao tuo ding mi nai ding zi gu gu dong fen tao yuan pi chang gao qi yuan tang teng shu shu fen fei wen ba diao tuo tong qu sheng shi you shi ting wu nian jing hun ju yan tu si xi xian yan lei bi yao yan han hui wu hou xi ge zha xiu weng zha nong nang qi zhai ji zi ji ji qi ji chi chen chen he ya ken xie bao ze shi zi chi nian ju tiao ling ling chu quan xie yin nie jiu nie chuo kun yu chu yi ni cuo chuo qu nian xian yu e wo yi chi zou dian chu jin ya chi chen he yin ju ling bao tiao zi yin yu chuo qu wo long pang gong pang yan long long gong kan ta ling ta long gong kan gui qiu bie gui yue chui he jue ") .append("xie yue ").toString(); } }
Blankj/AndroidUtilCode
lib/subutil/src/main/java/com/blankj/subutil/util/PinyinUtils.java
6
/* * Copyright 1999-2018 Alibaba Group Holding Ltd. * * 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.alibaba.druid.wall; import com.alibaba.druid.DbType; import com.alibaba.druid.sql.SQLUtils; import com.alibaba.druid.sql.ast.SQLName; import com.alibaba.druid.sql.ast.SQLStatement; import com.alibaba.druid.sql.ast.statement.SQLSelectStatement; import com.alibaba.druid.sql.ast.statement.SQLUpdateStatement; import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlHintStatement; import com.alibaba.druid.sql.parser.*; import com.alibaba.druid.sql.visitor.ExportParameterVisitor; import com.alibaba.druid.sql.visitor.ParameterizedOutputVisitorUtils; import com.alibaba.druid.util.ConcurrentLruCache; import com.alibaba.druid.util.Utils; import com.alibaba.druid.wall.spi.WallVisitorUtils; import com.alibaba.druid.wall.violation.ErrorCode; import com.alibaba.druid.wall.violation.IllegalSQLObjectViolation; import com.alibaba.druid.wall.violation.SyntaxErrorViolation; import java.security.PrivilegedAction; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicLong; import static com.alibaba.druid.util.JdbcSqlStatUtils.get; public abstract class WallProvider { private String name; private final Map<String, Object> attributes = new ConcurrentHashMap<String, Object>( 1, 0.75f, 1); private boolean whiteListEnable = true; /** * 8k */ private static final int MAX_SQL_LENGTH = 8192; private static final int WHITE_SQL_MAX_SIZE = 1024; // public for testing public static final int BLACK_SQL_MAX_SIZE = 256; private static final int MERGED_SQL_CACHE_SIZE = 256; private boolean blackListEnable = true; private final ConcurrentLruCache<String, WallSqlStat> whiteList = new ConcurrentLruCache<>(WHITE_SQL_MAX_SIZE); private final ConcurrentLruCache<String, WallSqlStat> blackList = new ConcurrentLruCache<>(BLACK_SQL_MAX_SIZE); private final ConcurrentLruCache<String, MergedSqlResult> mergedSqlCache = new ConcurrentLruCache<>(MERGED_SQL_CACHE_SIZE); protected final WallConfig config; private static final ThreadLocal<Boolean> privileged = new ThreadLocal<Boolean>(); private final ConcurrentMap<String, WallFunctionStat> functionStats = new ConcurrentHashMap<String, WallFunctionStat>( 16, 0.75f, 1); private final ConcurrentMap<String, WallTableStat> tableStats = new ConcurrentHashMap<String, WallTableStat>( 16, 0.75f, 1); public final WallDenyStat commentDeniedStat = new WallDenyStat(); protected DbType dbType; protected final AtomicLong checkCount = new AtomicLong(); protected final AtomicLong hardCheckCount = new AtomicLong(); protected final AtomicLong whiteListHitCount = new AtomicLong(); protected final AtomicLong blackListHitCount = new AtomicLong(); protected final AtomicLong syntaxErrorCount = new AtomicLong(); protected final AtomicLong violationCount = new AtomicLong(); protected final AtomicLong violationEffectRowCount = new AtomicLong(); public WallProvider(WallConfig config) { this.config = config; } public WallProvider(WallConfig config, String dbType) { this(config, DbType.of(dbType)); } public WallProvider(WallConfig config, DbType dbType) { this.config = config; this.dbType = dbType; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Map<String, Object> getAttributes() { return attributes; } public void reset() { this.checkCount.set(0); this.hardCheckCount.set(0); this.violationCount.set(0); this.whiteListHitCount.set(0); this.blackListHitCount.set(0); this.clearWhiteList(); this.clearBlackList(); this.functionStats.clear(); this.tableStats.clear(); } public ConcurrentMap<String, WallTableStat> getTableStats() { return this.tableStats; } public ConcurrentMap<String, WallFunctionStat> getFunctionStats() { return this.functionStats; } public WallSqlStat getSqlStat(String sql) { WallSqlStat sqlStat = this.getWhiteSql(sql); if (sqlStat == null) { sqlStat = this.getBlackSql(sql); } return sqlStat; } public WallTableStat getTableStat(String tableName) { String lowerCaseName = tableName.toLowerCase(); if (lowerCaseName.startsWith("`") && lowerCaseName.endsWith("`")) { lowerCaseName = lowerCaseName.substring(1, lowerCaseName.length() - 1); } return getTableStatWithLowerName(lowerCaseName); } public void addUpdateCount(WallSqlStat sqlStat, long updateCount) { sqlStat.addUpdateCount(updateCount); Map<String, WallSqlTableStat> sqlTableStats = sqlStat.getTableStats(); if (sqlTableStats == null) { return; } for (Map.Entry<String, WallSqlTableStat> entry : sqlTableStats.entrySet()) { String tableName = entry.getKey(); WallTableStat tableStat = this.getTableStat(tableName); if (tableStat == null) { continue; } WallSqlTableStat sqlTableStat = entry.getValue(); if (sqlTableStat.getDeleteCount() > 0) { tableStat.addDeleteDataCount(updateCount); } else if (sqlTableStat.getUpdateCount() > 0) { tableStat.addUpdateDataCount(updateCount); } else if (sqlTableStat.getInsertCount() > 0) { tableStat.addInsertDataCount(updateCount); } } } public void addFetchRowCount(WallSqlStat sqlStat, long fetchRowCount) { sqlStat.addAndFetchRowCount(fetchRowCount); Map<String, WallSqlTableStat> sqlTableStats = sqlStat.getTableStats(); if (sqlTableStats == null) { return; } for (Map.Entry<String, WallSqlTableStat> entry : sqlTableStats.entrySet()) { String tableName = entry.getKey(); WallTableStat tableStat = this.getTableStat(tableName); if (tableStat == null) { continue; } WallSqlTableStat sqlTableStat = entry.getValue(); if (sqlTableStat.getSelectCount() > 0) { tableStat.addFetchRowCount(fetchRowCount); } } } public WallTableStat getTableStatWithLowerName(String lowerCaseName) { WallTableStat stat = tableStats.get(lowerCaseName); if (stat == null) { if (tableStats.size() > 10000) { return null; } tableStats.putIfAbsent(lowerCaseName, new WallTableStat()); stat = tableStats.get(lowerCaseName); } return stat; } public WallFunctionStat getFunctionStat(String functionName) { String lowerCaseName = functionName.toLowerCase(); return getFunctionStatWithLowerName(lowerCaseName); } public WallFunctionStat getFunctionStatWithLowerName(String lowerCaseName) { WallFunctionStat stat = functionStats.get(lowerCaseName); if (stat == null) { if (functionStats.size() > 10000) { return null; } functionStats.putIfAbsent(lowerCaseName, new WallFunctionStat()); stat = functionStats.get(lowerCaseName); } return stat; } public WallConfig getConfig() { return config; } public WallSqlStat addWhiteSql(String sql, Map<String, WallSqlTableStat> tableStats, Map<String, WallSqlFunctionStat> functionStats, boolean syntaxError) { if (!whiteListEnable) { WallSqlStat stat = new WallSqlStat(tableStats, functionStats, syntaxError); return stat; } String mergedSql = getMergedSqlNullableIfParameterizeError(sql); if (mergedSql == null) { WallSqlStat stat = new WallSqlStat(tableStats, functionStats, syntaxError); stat.incrementAndGetExecuteCount(); return stat; } WallSqlStat wallSqlStat = whiteList.computeIfAbsent(mergedSql, key -> { WallSqlStat newStat = new WallSqlStat(tableStats, functionStats, syntaxError); newStat.setSample(sql); return newStat; }); wallSqlStat.incrementAndGetExecuteCount(); return wallSqlStat; } public WallSqlStat addBlackSql(String sql, Map<String, WallSqlTableStat> tableStats, Map<String, WallSqlFunctionStat> functionStats, List<Violation> violations, boolean syntaxError) { if (!blackListEnable) { return new WallSqlStat(tableStats, functionStats, violations, syntaxError); } String mergedSql = getMergedSqlNullableIfParameterizeError(sql); WallSqlStat wallSqlStat = blackList.computeIfAbsent(Utils.getIfNull(mergedSql, sql), key -> { WallSqlStat wallStat = new WallSqlStat(tableStats, functionStats, violations, syntaxError); wallStat.setSample(sql); return wallStat; }); wallSqlStat.incrementAndGetExecuteCount(); return wallSqlStat; } private String getMergedSqlNullableIfParameterizeError(String sql) { MergedSqlResult mergedSqlResult = mergedSqlCache.get(sql); if (mergedSqlResult != null) { return mergedSqlResult.mergedSql; } try { String mergedSql = ParameterizedOutputVisitorUtils.parameterize(sql, dbType); if (sql.length() < MAX_SQL_LENGTH) { mergedSqlCache.computeIfAbsent(sql, key -> MergedSqlResult.success(mergedSql)); } return mergedSql; } catch (Exception ex) { // skip mergedSqlCache.computeIfAbsent(sql, key -> MergedSqlResult.FAILED); return null; } } public Set<String> getWhiteList() { Set<String> hashSet = new HashSet<>(); Set<String> whiteListKeys = whiteList.keys(); if (!whiteListKeys.isEmpty()) { hashSet.addAll(whiteListKeys); } return Collections.unmodifiableSet(hashSet); } public Set<String> getSqlList() { Set<String> hashSet = new HashSet<>(); Set<String> whiteListKeys = whiteList.keys(); if (!whiteListKeys.isEmpty()) { hashSet.addAll(whiteListKeys); } Set<String> blackMergedListKeys = blackList.keys(); if (!blackMergedListKeys.isEmpty()) { hashSet.addAll(blackMergedListKeys); } return Collections.unmodifiableSet(hashSet); } public Set<String> getBlackList() { Set<String> hashSet = new HashSet<>(); Set<String> blackMergedListKeys = blackList.keys(); if (!blackMergedListKeys.isEmpty()) { hashSet.addAll(blackMergedListKeys); } return Collections.unmodifiableSet(hashSet); } public void clearCache() { whiteList.clear(); blackList.clear(); mergedSqlCache.clear(); } public void clearWhiteList() { whiteList.clear(); } public void clearBlackList() { blackList.clear(); } public WallSqlStat getWhiteSql(String sql) { String cacheKey = Utils.getIfNull(getMergedSqlNullableIfParameterizeError(sql), sql); return whiteList.get(cacheKey); } public WallSqlStat getBlackSql(String sql) { String cacheKey = Utils.getIfNull(getMergedSqlNullableIfParameterizeError(sql), sql); return blackList.get(cacheKey); } public boolean whiteContains(String sql) { return getWhiteSql(sql) != null; } public abstract SQLStatementParser createParser(String sql); public abstract WallVisitor createWallVisitor(); public abstract ExportParameterVisitor createExportParameterVisitor(); public boolean checkValid(String sql) { WallContext originalContext = WallContext.current(); try { WallContext.create(dbType); WallCheckResult result = checkInternal(sql); return result .getViolations() .isEmpty(); } finally { if (originalContext == null) { WallContext.clearContext(); } } } public void incrementCommentDeniedCount() { this.commentDeniedStat.incrementAndGetDenyCount(); } public boolean checkDenyFunction(String functionName) { if (functionName == null) { return true; } functionName = functionName.toLowerCase(); return !getConfig().getDenyFunctions().contains(functionName); } public boolean checkDenySchema(String schemaName) { if (schemaName == null) { return true; } if (!this.config.isSchemaCheck()) { return true; } schemaName = schemaName.toLowerCase(); return !getConfig().getDenySchemas().contains(schemaName); } public boolean checkDenyTable(String tableName) { if (tableName == null) { return true; } tableName = WallVisitorUtils.form(tableName); return !getConfig().getDenyTables().contains(tableName); } public boolean checkReadOnlyTable(String tableName) { if (tableName == null) { return true; } tableName = WallVisitorUtils.form(tableName); return !getConfig().isReadOnly(tableName); } public WallDenyStat getCommentDenyStat() { return this.commentDeniedStat; } public WallCheckResult check(String sql) { WallContext originalContext = WallContext.current(); try { WallContext.createIfNotExists(dbType); return checkInternal(sql); } finally { if (originalContext == null) { WallContext.clearContext(); } } } private WallCheckResult checkInternal(String sql) { checkCount.incrementAndGet(); WallContext context = WallContext.current(); if (config.isDoPrivilegedAllow() && ispPrivileged()) { WallCheckResult checkResult = new WallCheckResult(); checkResult.setSql(sql); return checkResult; } // first step, check whiteList boolean mulltiTenant = config.getTenantTablePattern() != null && config.getTenantTablePattern().length() > 0; if (!mulltiTenant) { WallCheckResult checkResult = checkWhiteAndBlackList(sql); if (checkResult != null) { checkResult.setSql(sql); return checkResult; } } hardCheckCount.incrementAndGet(); final List<Violation> violations = new ArrayList<Violation>(); List<SQLStatement> statementList = new ArrayList<SQLStatement>(); boolean syntaxError = false; boolean endOfComment = false; try { SQLStatementParser parser = createParser(sql); parser.getLexer().setCommentHandler(WallCommentHandler.instance); if (!config.isCommentAllow()) { parser.getLexer().setAllowComment(false); // deny comment } if (!config.isCompleteInsertValuesCheck()) { parser.setParseCompleteValues(false); parser.setParseValuesSize(config.getInsertValuesCheckSize()); } if (config.isHintAllow()) { parser.config(SQLParserFeature.StrictForWall, false); } parser.parseStatementList(statementList); final Token lastToken = parser.getLexer().token(); if (lastToken != Token.EOF && config.isStrictSyntaxCheck()) { violations.add(new IllegalSQLObjectViolation(ErrorCode.SYNTAX_ERROR, "not terminal sql, token " + lastToken, sql)); } endOfComment = parser.getLexer().isEOF(); } catch (NotAllowCommentException e) { violations.add(new IllegalSQLObjectViolation(ErrorCode.COMMENT_STATEMENT_NOT_ALLOW, "comment not allow", sql)); incrementCommentDeniedCount(); } catch (ParserException e) { syntaxErrorCount.incrementAndGet(); syntaxError = true; if (config.isStrictSyntaxCheck()) { violations.add(new SyntaxErrorViolation(e, sql)); } } catch (Exception e) { if (config.isStrictSyntaxCheck()) { violations.add(new SyntaxErrorViolation(e, sql)); } } if (statementList.size() > 1 && !config.isMultiStatementAllow()) { violations.add(new IllegalSQLObjectViolation(ErrorCode.MULTI_STATEMENT, "multi-statement not allow", sql)); } WallVisitor visitor = createWallVisitor(); visitor.setSqlEndOfComment(endOfComment); if (statementList.size() > 0) { boolean lastIsHint = false; for (int i = 0; i < statementList.size(); i++) { SQLStatement stmt = statementList.get(i); if ((i == 0 || lastIsHint) && stmt instanceof MySqlHintStatement) { lastIsHint = true; continue; } try { stmt.accept(visitor); } catch (ParserException e) { violations.add(new SyntaxErrorViolation(e, sql)); } } } if (visitor.getViolations().size() > 0) { violations.addAll(visitor.getViolations()); } Map<String, WallSqlTableStat> tableStat = context.getTableStats(); boolean updateCheckHandlerEnable = false; { WallUpdateCheckHandler updateCheckHandler = config.getUpdateCheckHandler(); if (updateCheckHandler != null) { for (SQLStatement stmt : statementList) { if (stmt instanceof SQLUpdateStatement) { SQLUpdateStatement updateStmt = (SQLUpdateStatement) stmt; SQLName table = updateStmt.getTableName(); if (table != null) { String tableName = table.getSimpleName(); Set<String> updateCheckColumns = config.getUpdateCheckTable(tableName); if (updateCheckColumns != null && updateCheckColumns.size() > 0) { updateCheckHandlerEnable = true; break; } } } } } } WallSqlStat sqlStat = null; if (violations.size() > 0) { violationCount.incrementAndGet(); if ((!updateCheckHandlerEnable) && sql.length() < MAX_SQL_LENGTH) { sqlStat = addBlackSql(sql, tableStat, context.getFunctionStats(), violations, syntaxError); } } else { if ((!updateCheckHandlerEnable) && sql.length() < MAX_SQL_LENGTH) { boolean selectLimit = false; if (config.getSelectLimit() > 0) { for (SQLStatement stmt : statementList) { if (stmt instanceof SQLSelectStatement) { selectLimit = true; break; } } } if (!selectLimit) { sqlStat = addWhiteSql(sql, tableStat, context.getFunctionStats(), syntaxError); } } } if (sqlStat == null && updateCheckHandlerEnable) { sqlStat = new WallSqlStat(tableStat, context.getFunctionStats(), violations, syntaxError); } Map<String, WallSqlTableStat> tableStats = null; Map<String, WallSqlFunctionStat> functionStats = null; if (context != null) { tableStats = context.getTableStats(); functionStats = context.getFunctionStats(); recordStats(tableStats, functionStats); } WallCheckResult result; if (sqlStat != null) { context.setSqlStat(sqlStat); result = new WallCheckResult(sqlStat, statementList); } else { result = new WallCheckResult(null, violations, tableStats, functionStats, statementList, syntaxError); } String resultSql; if (visitor.isSqlModified()) { resultSql = SQLUtils.toSQLString(statementList, dbType); } else { resultSql = sql; } result.setSql(resultSql); result.setUpdateCheckItems(visitor.getUpdateCheckItems()); return result; } private WallCheckResult checkWhiteAndBlackList(String sql) { if (config.getUpdateCheckHandler() != null) { return null; } // check white list first if (whiteListEnable) { WallSqlStat sqlStat = getWhiteSql(sql); if (sqlStat != null) { whiteListHitCount.incrementAndGet(); sqlStat.incrementAndGetExecuteCount(); if (sqlStat.isSyntaxError()) { syntaxErrorCount.incrementAndGet(); } recordStats(sqlStat.getTableStats(), sqlStat.getFunctionStats()); WallContext context = WallContext.current(); if (context != null) { context.setSqlStat(sqlStat); } return new WallCheckResult(sqlStat); } } // check black list if (blackListEnable) { WallSqlStat sqlStat = getBlackSql(sql); if (sqlStat != null) { blackListHitCount.incrementAndGet(); violationCount.incrementAndGet(); if (sqlStat.isSyntaxError()) { syntaxErrorCount.incrementAndGet(); } sqlStat.incrementAndGetExecuteCount(); recordStats(sqlStat.getTableStats(), sqlStat.getFunctionStats()); return new WallCheckResult(sqlStat); } } return null; } void recordStats(Map<String, WallSqlTableStat> tableStats, Map<String, WallSqlFunctionStat> functionStats) { if (tableStats != null) { for (Map.Entry<String, WallSqlTableStat> entry : tableStats.entrySet()) { String tableName = entry.getKey(); WallSqlTableStat sqlTableStat = entry.getValue(); WallTableStat tableStat = getTableStat(tableName); if (tableStat != null) { tableStat.addSqlTableStat(sqlTableStat); } } } if (functionStats != null) { for (Map.Entry<String, WallSqlFunctionStat> entry : functionStats.entrySet()) { String tableName = entry.getKey(); WallSqlFunctionStat sqlTableStat = entry.getValue(); WallFunctionStat functionStat = getFunctionStatWithLowerName(tableName); if (functionStat != null) { functionStat.addSqlFunctionStat(sqlTableStat); } } } } public static boolean ispPrivileged() { Boolean value = privileged.get(); if (value == null) { return false; } return value; } public static <T> T doPrivileged(PrivilegedAction<T> action) { final Boolean original = privileged.get(); privileged.set(Boolean.TRUE); try { return action.run(); } finally { privileged.set(original); } } private static final ThreadLocal<Object> tenantValueLocal = new ThreadLocal<Object>(); public static void setTenantValue(Object value) { tenantValueLocal.set(value); } public static Object getTenantValue() { return tenantValueLocal.get(); } public long getWhiteListHitCount() { return whiteListHitCount.get(); } public long getBlackListHitCount() { return blackListHitCount.get(); } public long getSyntaxErrorCount() { return syntaxErrorCount.get(); } public long getCheckCount() { return checkCount.get(); } public long getViolationCount() { return violationCount.get(); } public long getHardCheckCount() { return hardCheckCount.get(); } public long getViolationEffectRowCount() { return violationEffectRowCount.get(); } public void addViolationEffectRowCount(long rowCount) { violationEffectRowCount.addAndGet(rowCount); } public static class WallCommentHandler implements Lexer.CommentHandler { public static final WallCommentHandler instance = new WallCommentHandler(); @Override public boolean handle(Token lastToken, String comment) { if (lastToken == null) { return false; } switch (lastToken) { case SELECT: case INSERT: case DELETE: case UPDATE: case TRUNCATE: case SET: case CREATE: case ALTER: case DROP: case SHOW: case REPLACE: return true; default: break; } WallContext context = WallContext.current(); if (context != null) { context.incrementCommentCount(); } return false; } } public WallProviderStatValue getStatValue(boolean reset) { WallProviderStatValue statValue = new WallProviderStatValue(); statValue.setName(name); statValue.setCheckCount(get(checkCount, reset)); statValue.setHardCheckCount(get(hardCheckCount, reset)); statValue.setViolationCount(get(violationCount, reset)); statValue.setViolationEffectRowCount(get(violationEffectRowCount, reset)); statValue.setBlackListHitCount(get(blackListHitCount, reset)); statValue.setWhiteListHitCount(get(whiteListHitCount, reset)); statValue.setSyntaxErrorCount(get(syntaxErrorCount, reset)); for (Map.Entry<String, WallTableStat> entry : this.tableStats.entrySet()) { String tableName = entry.getKey(); WallTableStat tableStat = entry.getValue(); WallTableStatValue tableStatValue = tableStat.getStatValue(reset); if (tableStatValue.getTotalExecuteCount() == 0) { continue; } tableStatValue.setName(tableName); statValue.getTables().add(tableStatValue); } for (Map.Entry<String, WallFunctionStat> entry : this.functionStats.entrySet()) { String functionName = entry.getKey(); WallFunctionStat functionStat = entry.getValue(); WallFunctionStatValue functionStatValue = functionStat.getStatValue(reset); if (functionStatValue.getInvokeCount() == 0) { continue; } functionStatValue.setName(functionName); statValue.getFunctions().add(functionStatValue); } whiteList.forEach((sql, sqlStat) -> { WallSqlStatValue sqlStatValue = sqlStat.getStatValue(reset); if (sqlStatValue.getExecuteCount() == 0) { return; } sqlStatValue.setSql(sql); long sqlHash = sqlStat.getSqlHash(); if (sqlHash == 0) { sqlHash = Utils.fnv_64(sql); sqlStat.setSqlHash(sqlHash); } sqlStatValue.setSqlHash(sqlHash); statValue.getWhiteList().add(sqlStatValue); }); blackList.forEach((sql, sqlStat) -> { WallSqlStatValue sqlStatValue = sqlStat.getStatValue(reset); if (sqlStatValue.getExecuteCount() == 0) { return; } sqlStatValue.setSql(sql); statValue.getBlackList().add(sqlStatValue); }); return statValue; } public Map<String, Object> getStatsMap() { return getStatValue(false).toMap(); } public boolean isWhiteListEnable() { return whiteListEnable; } public void setWhiteListEnable(boolean whiteListEnable) { this.whiteListEnable = whiteListEnable; } public boolean isBlackListEnable() { return blackListEnable; } public void setBlackListEnable(boolean blackListEnable) { this.blackListEnable = blackListEnable; } private static class MergedSqlResult { public static final MergedSqlResult FAILED = new MergedSqlResult(null); final String mergedSql; MergedSqlResult(String mergedSql) { this.mergedSql = mergedSql; } public static MergedSqlResult success(String mergedSql) { return new MergedSqlResult(mergedSql); } } }
alibaba/druid
core/src/main/java/com/alibaba/druid/wall/WallProvider.java
7
/* * Copyright 2012 The Netty Project * * The Netty Project licenses this file to you 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: * * https://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 io.netty.handler.codec.http; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPipeline; import io.netty.handler.codec.ByteToMessageDecoder; import io.netty.handler.codec.DecoderResult; import io.netty.handler.codec.PrematureChannelClosureException; import io.netty.handler.codec.TooLongFrameException; import io.netty.util.AsciiString; import io.netty.util.ByteProcessor; import io.netty.util.internal.StringUtil; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import static io.netty.util.internal.ObjectUtil.checkNotNull; /** * Decodes {@link ByteBuf}s into {@link HttpMessage}s and * {@link HttpContent}s. * * <h3>Parameters that prevents excessive memory consumption</h3> * <table border="1"> * <tr> * <th>Name</th><th>Default value</th><th>Meaning</th> * </tr> * <tr> * <td>{@code maxInitialLineLength}</td> * <td>{@value #DEFAULT_MAX_INITIAL_LINE_LENGTH}</td> * <td>The maximum length of the initial line * (e.g. {@code "GET / HTTP/1.0"} or {@code "HTTP/1.0 200 OK"}) * If the length of the initial line exceeds this value, a * {@link TooLongHttpLineException} will be raised.</td> * </tr> * <tr> * <td>{@code maxHeaderSize}</td> * <td>{@value #DEFAULT_MAX_HEADER_SIZE}</td> * <td>The maximum length of all headers. If the sum of the length of each * header exceeds this value, a {@link TooLongHttpHeaderException} will be raised.</td> * </tr> * <tr> * <td>{@code maxChunkSize}</td> * <td>{@value #DEFAULT_MAX_CHUNK_SIZE}</td> * <td>The maximum length of the content or each chunk. If the content length * (or the length of each chunk) exceeds this value, the content or chunk * will be split into multiple {@link HttpContent}s whose length is * {@code maxChunkSize} at maximum.</td> * </tr> * </table> * * <h3>Parameters that control parsing behavior</h3> * <table border="1"> * <tr> * <th>Name</th><th>Default value</th><th>Meaning</th> * </tr> * <tr> * <td>{@code allowDuplicateContentLengths}</td> * <td>{@value #DEFAULT_ALLOW_DUPLICATE_CONTENT_LENGTHS}</td> * <td>When set to {@code false}, will reject any messages that contain multiple Content-Length header fields. * When set to {@code true}, will allow multiple Content-Length headers only if they are all the same decimal value. * The duplicated field-values will be replaced with a single valid Content-Length field. * See <a href="https://tools.ietf.org/html/rfc7230#section-3.3.2">RFC 7230, Section 3.3.2</a>.</td> * </tr> * <tr> * <td>{@code allowPartialChunks}</td> * <td>{@value #DEFAULT_ALLOW_PARTIAL_CHUNKS}</td> * <td>If the length of a chunk exceeds the {@link ByteBuf}s readable bytes and {@code allowPartialChunks} * is set to {@code true}, the chunk will be split into multiple {@link HttpContent}s. * Otherwise, if the chunk size does not exceed {@code maxChunkSize} and {@code allowPartialChunks} * is set to {@code false}, the {@link ByteBuf} is not decoded into an {@link HttpContent} until * the readable bytes are greater or equal to the chunk size.</td> * </tr> * </table> * * <h3>Chunked Content</h3> * * If the content of an HTTP message is greater than {@code maxChunkSize} or * the transfer encoding of the HTTP message is 'chunked', this decoder * generates one {@link HttpMessage} instance and its following * {@link HttpContent}s per single HTTP message to avoid excessive memory * consumption. For example, the following HTTP message: * <pre> * GET / HTTP/1.1 * Transfer-Encoding: chunked * * 1a * abcdefghijklmnopqrstuvwxyz * 10 * 1234567890abcdef * 0 * Content-MD5: ... * <i>[blank line]</i> * </pre> * triggers {@link HttpRequestDecoder} to generate 3 objects: * <ol> * <li>An {@link HttpRequest},</li> * <li>The first {@link HttpContent} whose content is {@code 'abcdefghijklmnopqrstuvwxyz'},</li> * <li>The second {@link LastHttpContent} whose content is {@code '1234567890abcdef'}, which marks * the end of the content.</li> * </ol> * * If you prefer not to handle {@link HttpContent}s by yourself for your * convenience, insert {@link HttpObjectAggregator} after this decoder in the * {@link ChannelPipeline}. However, please note that your server might not * be as memory efficient as without the aggregator. * * <h3>Extensibility</h3> * * Please note that this decoder is designed to be extended to implement * a protocol derived from HTTP, such as * <a href="https://en.wikipedia.org/wiki/Real_Time_Streaming_Protocol">RTSP</a> and * <a href="https://en.wikipedia.org/wiki/Internet_Content_Adaptation_Protocol">ICAP</a>. * To implement the decoder of such a derived protocol, extend this class and * implement all abstract methods properly. * * <h3>Header Validation</h3> * * It is recommended to always enable header validation. * <p> * Without header validation, your system can become vulnerable to * <a href="https://cwe.mitre.org/data/definitions/113.html"> * CWE-113: Improper Neutralization of CRLF Sequences in HTTP Headers ('HTTP Response Splitting') * </a>. * <p> * This recommendation stands even when both peers in the HTTP exchange are trusted, * as it helps with defence-in-depth. */ public abstract class HttpObjectDecoder extends ByteToMessageDecoder { public static final int DEFAULT_MAX_INITIAL_LINE_LENGTH = 4096; public static final int DEFAULT_MAX_HEADER_SIZE = 8192; public static final boolean DEFAULT_CHUNKED_SUPPORTED = true; public static final boolean DEFAULT_ALLOW_PARTIAL_CHUNKS = true; public static final int DEFAULT_MAX_CHUNK_SIZE = 8192; public static final boolean DEFAULT_VALIDATE_HEADERS = true; public static final int DEFAULT_INITIAL_BUFFER_SIZE = 128; public static final boolean DEFAULT_ALLOW_DUPLICATE_CONTENT_LENGTHS = false; private final int maxChunkSize; private final boolean chunkedSupported; private final boolean allowPartialChunks; /** * This field is no longer used. It is only kept around for backwards compatibility purpose. */ @Deprecated protected final boolean validateHeaders; protected final HttpHeadersFactory headersFactory; protected final HttpHeadersFactory trailersFactory; private final boolean allowDuplicateContentLengths; private final ByteBuf parserScratchBuffer; private final HeaderParser headerParser; private final LineParser lineParser; private HttpMessage message; private long chunkSize; private long contentLength = Long.MIN_VALUE; private boolean chunked; private boolean isSwitchingToNonHttp1Protocol; private final AtomicBoolean resetRequested = new AtomicBoolean(); // These will be updated by splitHeader(...) private AsciiString name; private String value; private LastHttpContent trailer; @Override protected void handlerRemoved0(ChannelHandlerContext ctx) throws Exception { try { parserScratchBuffer.release(); } finally { super.handlerRemoved0(ctx); } } /** * The internal state of {@link HttpObjectDecoder}. * <em>Internal use only</em>. */ private enum State { SKIP_CONTROL_CHARS, READ_INITIAL, READ_HEADER, READ_VARIABLE_LENGTH_CONTENT, READ_FIXED_LENGTH_CONTENT, READ_CHUNK_SIZE, READ_CHUNKED_CONTENT, READ_CHUNK_DELIMITER, READ_CHUNK_FOOTER, BAD_MESSAGE, UPGRADED } private State currentState = State.SKIP_CONTROL_CHARS; /** * Creates a new instance with the default * {@code maxInitialLineLength (4096)}, {@code maxHeaderSize (8192)}, and * {@code maxChunkSize (8192)}. */ protected HttpObjectDecoder() { this(new HttpDecoderConfig()); } /** * Creates a new instance with the specified parameters. * * @deprecated Use {@link #HttpObjectDecoder(HttpDecoderConfig)} instead. */ @Deprecated protected HttpObjectDecoder( int maxInitialLineLength, int maxHeaderSize, int maxChunkSize, boolean chunkedSupported) { this(new HttpDecoderConfig() .setMaxInitialLineLength(maxInitialLineLength) .setMaxHeaderSize(maxHeaderSize) .setMaxChunkSize(maxChunkSize) .setChunkedSupported(chunkedSupported)); } /** * Creates a new instance with the specified parameters. * * @deprecated Use {@link #HttpObjectDecoder(HttpDecoderConfig)} instead. */ @Deprecated protected HttpObjectDecoder( int maxInitialLineLength, int maxHeaderSize, int maxChunkSize, boolean chunkedSupported, boolean validateHeaders) { this(new HttpDecoderConfig() .setMaxInitialLineLength(maxInitialLineLength) .setMaxHeaderSize(maxHeaderSize) .setMaxChunkSize(maxChunkSize) .setChunkedSupported(chunkedSupported) .setValidateHeaders(validateHeaders)); } /** * Creates a new instance with the specified parameters. * * @deprecated Use {@link #HttpObjectDecoder(HttpDecoderConfig)} instead. */ @Deprecated protected HttpObjectDecoder( int maxInitialLineLength, int maxHeaderSize, int maxChunkSize, boolean chunkedSupported, boolean validateHeaders, int initialBufferSize) { this(new HttpDecoderConfig() .setMaxInitialLineLength(maxInitialLineLength) .setMaxHeaderSize(maxHeaderSize) .setMaxChunkSize(maxChunkSize) .setChunkedSupported(chunkedSupported) .setValidateHeaders(validateHeaders) .setInitialBufferSize(initialBufferSize)); } /** * Creates a new instance with the specified parameters. * * @deprecated Use {@link #HttpObjectDecoder(HttpDecoderConfig)} instead. */ @Deprecated protected HttpObjectDecoder( int maxInitialLineLength, int maxHeaderSize, int maxChunkSize, boolean chunkedSupported, boolean validateHeaders, int initialBufferSize, boolean allowDuplicateContentLengths) { this(new HttpDecoderConfig() .setMaxInitialLineLength(maxInitialLineLength) .setMaxHeaderSize(maxHeaderSize) .setMaxChunkSize(maxChunkSize) .setChunkedSupported(chunkedSupported) .setValidateHeaders(validateHeaders) .setInitialBufferSize(initialBufferSize) .setAllowDuplicateContentLengths(allowDuplicateContentLengths)); } /** * Creates a new instance with the specified parameters. * * @deprecated Use {@link #HttpObjectDecoder(HttpDecoderConfig)} instead. */ @Deprecated protected HttpObjectDecoder( int maxInitialLineLength, int maxHeaderSize, int maxChunkSize, boolean chunkedSupported, boolean validateHeaders, int initialBufferSize, boolean allowDuplicateContentLengths, boolean allowPartialChunks) { this(new HttpDecoderConfig() .setMaxInitialLineLength(maxInitialLineLength) .setMaxHeaderSize(maxHeaderSize) .setMaxChunkSize(maxChunkSize) .setChunkedSupported(chunkedSupported) .setValidateHeaders(validateHeaders) .setInitialBufferSize(initialBufferSize) .setAllowDuplicateContentLengths(allowDuplicateContentLengths) .setAllowPartialChunks(allowPartialChunks)); } /** * Creates a new instance with the specified configuration. */ protected HttpObjectDecoder(HttpDecoderConfig config) { checkNotNull(config, "config"); parserScratchBuffer = Unpooled.buffer(config.getInitialBufferSize()); lineParser = new LineParser(parserScratchBuffer, config.getMaxInitialLineLength()); headerParser = new HeaderParser(parserScratchBuffer, config.getMaxHeaderSize()); maxChunkSize = config.getMaxChunkSize(); chunkedSupported = config.isChunkedSupported(); headersFactory = config.getHeadersFactory(); trailersFactory = config.getTrailersFactory(); validateHeaders = isValidating(headersFactory); allowDuplicateContentLengths = config.isAllowDuplicateContentLengths(); allowPartialChunks = config.isAllowPartialChunks(); } protected boolean isValidating(HttpHeadersFactory headersFactory) { if (headersFactory instanceof DefaultHttpHeadersFactory) { DefaultHttpHeadersFactory builder = (DefaultHttpHeadersFactory) headersFactory; return builder.isValidatingHeaderNames() || builder.isValidatingHeaderValues(); } return true; // We can't actually tell in this case, but we assume some validation is taking place. } @Override protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) throws Exception { if (resetRequested.get()) { resetNow(); } switch (currentState) { case SKIP_CONTROL_CHARS: // Fall-through case READ_INITIAL: try { ByteBuf line = lineParser.parse(buffer); if (line == null) { return; } final String[] initialLine = splitInitialLine(line); assert initialLine.length == 3 : "initialLine::length must be 3"; message = createMessage(initialLine); currentState = State.READ_HEADER; // fall-through } catch (Exception e) { out.add(invalidMessage(message, buffer, e)); return; } case READ_HEADER: try { State nextState = readHeaders(buffer); if (nextState == null) { return; } currentState = nextState; switch (nextState) { case SKIP_CONTROL_CHARS: // fast-path // No content is expected. addCurrentMessage(out); out.add(LastHttpContent.EMPTY_LAST_CONTENT); resetNow(); return; case READ_CHUNK_SIZE: if (!chunkedSupported) { throw new IllegalArgumentException("Chunked messages not supported"); } // Chunked encoding - generate HttpMessage first. HttpChunks will follow. addCurrentMessage(out); return; default: /* * RFC 7230, 3.3.3 (https://tools.ietf.org/html/rfc7230#section-3.3.3) states that if a * request does not have either a transfer-encoding or a content-length header then the message body * length is 0. However, for a response the body length is the number of octets received prior to the * server closing the connection. So we treat this as variable length chunked encoding. */ if (contentLength == 0 || contentLength == -1 && isDecodingRequest()) { addCurrentMessage(out); out.add(LastHttpContent.EMPTY_LAST_CONTENT); resetNow(); return; } assert nextState == State.READ_FIXED_LENGTH_CONTENT || nextState == State.READ_VARIABLE_LENGTH_CONTENT; addCurrentMessage(out); if (nextState == State.READ_FIXED_LENGTH_CONTENT) { // chunkSize will be decreased as the READ_FIXED_LENGTH_CONTENT state reads data chunk by chunk. chunkSize = contentLength; } // We return here, this forces decode to be called again where we will decode the content return; } } catch (Exception e) { out.add(invalidMessage(message, buffer, e)); return; } case READ_VARIABLE_LENGTH_CONTENT: { // Keep reading data as a chunk until the end of connection is reached. int toRead = Math.min(buffer.readableBytes(), maxChunkSize); if (toRead > 0) { ByteBuf content = buffer.readRetainedSlice(toRead); out.add(new DefaultHttpContent(content)); } return; } case READ_FIXED_LENGTH_CONTENT: { int readLimit = buffer.readableBytes(); // Check if the buffer is readable first as we use the readable byte count // to create the HttpChunk. This is needed as otherwise we may end up with // create an HttpChunk instance that contains an empty buffer and so is // handled like it is the last HttpChunk. // // See https://github.com/netty/netty/issues/433 if (readLimit == 0) { return; } int toRead = Math.min(readLimit, maxChunkSize); if (toRead > chunkSize) { toRead = (int) chunkSize; } ByteBuf content = buffer.readRetainedSlice(toRead); chunkSize -= toRead; if (chunkSize == 0) { // Read all content. out.add(new DefaultLastHttpContent(content, trailersFactory)); resetNow(); } else { out.add(new DefaultHttpContent(content)); } return; } /* * everything else after this point takes care of reading chunked content. basically, read chunk size, * read chunk, read and ignore the CRLF and repeat until 0 */ case READ_CHUNK_SIZE: try { ByteBuf line = lineParser.parse(buffer); if (line == null) { return; } int chunkSize = getChunkSize(line.array(), line.arrayOffset() + line.readerIndex(), line.readableBytes()); this.chunkSize = chunkSize; if (chunkSize == 0) { currentState = State.READ_CHUNK_FOOTER; return; } currentState = State.READ_CHUNKED_CONTENT; // fall-through } catch (Exception e) { out.add(invalidChunk(buffer, e)); return; } case READ_CHUNKED_CONTENT: { assert chunkSize <= Integer.MAX_VALUE; int toRead = Math.min((int) chunkSize, maxChunkSize); if (!allowPartialChunks && buffer.readableBytes() < toRead) { return; } toRead = Math.min(toRead, buffer.readableBytes()); if (toRead == 0) { return; } HttpContent chunk = new DefaultHttpContent(buffer.readRetainedSlice(toRead)); chunkSize -= toRead; out.add(chunk); if (chunkSize != 0) { return; } currentState = State.READ_CHUNK_DELIMITER; // fall-through } case READ_CHUNK_DELIMITER: { final int wIdx = buffer.writerIndex(); int rIdx = buffer.readerIndex(); while (wIdx > rIdx) { byte next = buffer.getByte(rIdx++); if (next == HttpConstants.LF) { currentState = State.READ_CHUNK_SIZE; break; } } buffer.readerIndex(rIdx); return; } case READ_CHUNK_FOOTER: try { LastHttpContent trailer = readTrailingHeaders(buffer); if (trailer == null) { return; } out.add(trailer); resetNow(); return; } catch (Exception e) { out.add(invalidChunk(buffer, e)); return; } case BAD_MESSAGE: { // Keep discarding until disconnection. buffer.skipBytes(buffer.readableBytes()); break; } case UPGRADED: { int readableBytes = buffer.readableBytes(); if (readableBytes > 0) { // Keep on consuming as otherwise we may trigger an DecoderException, // other handler will replace this codec with the upgraded protocol codec to // take the traffic over at some point then. // See https://github.com/netty/netty/issues/2173 out.add(buffer.readBytes(readableBytes)); } break; } default: break; } } @Override protected void decodeLast(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { super.decodeLast(ctx, in, out); if (resetRequested.get()) { // If a reset was requested by decodeLast() we need to do it now otherwise we may produce a // LastHttpContent while there was already one. resetNow(); } // Handle the last unfinished message. switch (currentState) { case READ_VARIABLE_LENGTH_CONTENT: if (!chunked && !in.isReadable()) { // End of connection. out.add(LastHttpContent.EMPTY_LAST_CONTENT); resetNow(); } return; case READ_HEADER: // If we are still in the state of reading headers we need to create a new invalid message that // signals that the connection was closed before we received the headers. out.add(invalidMessage(message, Unpooled.EMPTY_BUFFER, new PrematureChannelClosureException("Connection closed before received headers"))); resetNow(); return; case READ_CHUNK_DELIMITER: // fall-trough case READ_CHUNK_FOOTER: // fall-trough case READ_CHUNKED_CONTENT: // fall-trough case READ_CHUNK_SIZE: // fall-trough case READ_FIXED_LENGTH_CONTENT: // Check if the closure of the connection signifies the end of the content. boolean prematureClosure; if (isDecodingRequest() || chunked) { // The last request did not wait for a response. prematureClosure = true; } else { // Compare the length of the received content and the 'Content-Length' header. // If the 'Content-Length' header is absent, the length of the content is determined by the end of // the connection, so it is perfectly fine. prematureClosure = contentLength > 0; } if (!prematureClosure) { out.add(LastHttpContent.EMPTY_LAST_CONTENT); } resetNow(); return; case SKIP_CONTROL_CHARS: // fall-trough case READ_INITIAL:// fall-trough case BAD_MESSAGE: // fall-trough case UPGRADED: // fall-trough // Do nothing break; default: throw new IllegalStateException("Unhandled state " + currentState); } } @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof HttpExpectationFailedEvent) { switch (currentState) { case READ_FIXED_LENGTH_CONTENT: case READ_VARIABLE_LENGTH_CONTENT: case READ_CHUNK_SIZE: reset(); break; default: break; } } super.userEventTriggered(ctx, evt); } private void addCurrentMessage(List<Object> out) { HttpMessage message = this.message; assert message != null; this.message = null; out.add(message); } protected boolean isContentAlwaysEmpty(HttpMessage msg) { if (msg instanceof HttpResponse) { HttpResponse res = (HttpResponse) msg; final HttpResponseStatus status = res.status(); final int code = status.code(); final HttpStatusClass statusClass = status.codeClass(); // Correctly handle return codes of 1xx. // // See: // - https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html Section 4.4 // - https://github.com/netty/netty/issues/222 if (statusClass == HttpStatusClass.INFORMATIONAL) { // One exception: Hixie 76 websocket handshake response return !(code == 101 && !res.headers().contains(HttpHeaderNames.SEC_WEBSOCKET_ACCEPT) && res.headers().contains(HttpHeaderNames.UPGRADE, HttpHeaderValues.WEBSOCKET, true)); } switch (code) { case 204: case 304: return true; default: return false; } } return false; } /** * Returns true if the server switched to a different protocol than HTTP/1.0 or HTTP/1.1, e.g. HTTP/2 or Websocket. * Returns false if the upgrade happened in a different layer, e.g. upgrade from HTTP/1.1 to HTTP/1.1 over TLS. */ protected boolean isSwitchingToNonHttp1Protocol(HttpResponse msg) { if (msg.status().code() != HttpResponseStatus.SWITCHING_PROTOCOLS.code()) { return false; } String newProtocol = msg.headers().get(HttpHeaderNames.UPGRADE); return newProtocol == null || !newProtocol.contains(HttpVersion.HTTP_1_0.text()) && !newProtocol.contains(HttpVersion.HTTP_1_1.text()); } /** * Resets the state of the decoder so that it is ready to decode a new message. * This method is useful for handling a rejected request with {@code Expect: 100-continue} header. */ public void reset() { resetRequested.lazySet(true); } private void resetNow() { message = null; name = null; value = null; contentLength = Long.MIN_VALUE; chunked = false; lineParser.reset(); headerParser.reset(); trailer = null; if (isSwitchingToNonHttp1Protocol) { isSwitchingToNonHttp1Protocol = false; currentState = State.UPGRADED; return; } resetRequested.lazySet(false); currentState = State.SKIP_CONTROL_CHARS; } private HttpMessage invalidMessage(HttpMessage current, ByteBuf in, Exception cause) { currentState = State.BAD_MESSAGE; message = null; trailer = null; // Advance the readerIndex so that ByteToMessageDecoder does not complain // when we produced an invalid message without consuming anything. in.skipBytes(in.readableBytes()); if (current == null) { current = createInvalidMessage(); } current.setDecoderResult(DecoderResult.failure(cause)); return current; } private HttpContent invalidChunk(ByteBuf in, Exception cause) { currentState = State.BAD_MESSAGE; message = null; trailer = null; // Advance the readerIndex so that ByteToMessageDecoder does not complain // when we produced an invalid message without consuming anything. in.skipBytes(in.readableBytes()); HttpContent chunk = new DefaultLastHttpContent(Unpooled.EMPTY_BUFFER); chunk.setDecoderResult(DecoderResult.failure(cause)); return chunk; } private State readHeaders(ByteBuf buffer) { final HttpMessage message = this.message; final HttpHeaders headers = message.headers(); final HeaderParser headerParser = this.headerParser; ByteBuf line = headerParser.parse(buffer); if (line == null) { return null; } int lineLength = line.readableBytes(); while (lineLength > 0) { final byte[] lineContent = line.array(); final int startLine = line.arrayOffset() + line.readerIndex(); final byte firstChar = lineContent[startLine]; if (name != null && (firstChar == ' ' || firstChar == '\t')) { //please do not make one line from below code //as it breaks +XX:OptimizeStringConcat optimization String trimmedLine = langAsciiString(lineContent, startLine, lineLength).trim(); String valueStr = value; value = valueStr + ' ' + trimmedLine; } else { if (name != null) { headers.add(name, value); } splitHeader(lineContent, startLine, lineLength); } line = headerParser.parse(buffer); if (line == null) { return null; } lineLength = line.readableBytes(); } // Add the last header. if (name != null) { headers.add(name, value); } // reset name and value fields name = null; value = null; // Done parsing initial line and headers. Set decoder result. HttpMessageDecoderResult decoderResult = new HttpMessageDecoderResult(lineParser.size, headerParser.size); message.setDecoderResult(decoderResult); List<String> contentLengthFields = headers.getAll(HttpHeaderNames.CONTENT_LENGTH); if (!contentLengthFields.isEmpty()) { HttpVersion version = message.protocolVersion(); boolean isHttp10OrEarlier = version.majorVersion() < 1 || (version.majorVersion() == 1 && version.minorVersion() == 0); // Guard against multiple Content-Length headers as stated in // https://tools.ietf.org/html/rfc7230#section-3.3.2: contentLength = HttpUtil.normalizeAndGetContentLength(contentLengthFields, isHttp10OrEarlier, allowDuplicateContentLengths); if (contentLength != -1) { String lengthValue = contentLengthFields.get(0).trim(); if (contentLengthFields.size() > 1 || // don't unnecessarily re-order headers !lengthValue.equals(Long.toString(contentLength))) { headers.set(HttpHeaderNames.CONTENT_LENGTH, contentLength); } } } else { // We know the content length if it's a Web Socket message even if // Content-Length header is missing. contentLength = HttpUtil.getWebSocketContentLength(message); } if (!isDecodingRequest() && message instanceof HttpResponse) { HttpResponse res = (HttpResponse) message; this.isSwitchingToNonHttp1Protocol = isSwitchingToNonHttp1Protocol(res); } if (isContentAlwaysEmpty(message)) { HttpUtil.setTransferEncodingChunked(message, false); return State.SKIP_CONTROL_CHARS; } if (HttpUtil.isTransferEncodingChunked(message)) { this.chunked = true; if (!contentLengthFields.isEmpty() && message.protocolVersion() == HttpVersion.HTTP_1_1) { handleTransferEncodingChunkedWithContentLength(message); } return State.READ_CHUNK_SIZE; } if (contentLength >= 0) { return State.READ_FIXED_LENGTH_CONTENT; } return State.READ_VARIABLE_LENGTH_CONTENT; } /** * Invoked when a message with both a "Transfer-Encoding: chunked" and a "Content-Length" header field is detected. * The default behavior is to <i>remove</i> the Content-Length field, but this method could be overridden * to change the behavior (to, e.g., throw an exception and produce an invalid message). * <p> * See: https://tools.ietf.org/html/rfc7230#section-3.3.3 * <pre> * If a message is received with both a Transfer-Encoding and a * Content-Length header field, the Transfer-Encoding overrides the * Content-Length. Such a message might indicate an attempt to * perform request smuggling (Section 9.5) or response splitting * (Section 9.4) and ought to be handled as an error. A sender MUST * remove the received Content-Length field prior to forwarding such * a message downstream. * </pre> * Also see: * https://github.com/apache/tomcat/blob/b693d7c1981fa7f51e58bc8c8e72e3fe80b7b773/ * java/org/apache/coyote/http11/Http11Processor.java#L747-L755 * https://github.com/nginx/nginx/blob/0ad4393e30c119d250415cb769e3d8bc8dce5186/ * src/http/ngx_http_request.c#L1946-L1953 */ protected void handleTransferEncodingChunkedWithContentLength(HttpMessage message) { message.headers().remove(HttpHeaderNames.CONTENT_LENGTH); contentLength = Long.MIN_VALUE; } private LastHttpContent readTrailingHeaders(ByteBuf buffer) { final HeaderParser headerParser = this.headerParser; ByteBuf line = headerParser.parse(buffer); if (line == null) { return null; } LastHttpContent trailer = this.trailer; int lineLength = line.readableBytes(); if (lineLength == 0 && trailer == null) { // We have received the empty line which signals the trailer is complete and did not parse any trailers // before. Just return an empty last content to reduce allocations. return LastHttpContent.EMPTY_LAST_CONTENT; } CharSequence lastHeader = null; if (trailer == null) { trailer = this.trailer = new DefaultLastHttpContent(Unpooled.EMPTY_BUFFER, trailersFactory); } while (lineLength > 0) { final byte[] lineContent = line.array(); final int startLine = line.arrayOffset() + line.readerIndex(); final byte firstChar = lineContent[startLine]; if (lastHeader != null && (firstChar == ' ' || firstChar == '\t')) { List<String> current = trailer.trailingHeaders().getAll(lastHeader); if (!current.isEmpty()) { int lastPos = current.size() - 1; //please do not make one line from below code //as it breaks +XX:OptimizeStringConcat optimization String lineTrimmed = langAsciiString(lineContent, startLine, line.readableBytes()).trim(); String currentLastPos = current.get(lastPos); current.set(lastPos, currentLastPos + lineTrimmed); } } else { splitHeader(lineContent, startLine, lineLength); AsciiString headerName = name; if (!HttpHeaderNames.CONTENT_LENGTH.contentEqualsIgnoreCase(headerName) && !HttpHeaderNames.TRANSFER_ENCODING.contentEqualsIgnoreCase(headerName) && !HttpHeaderNames.TRAILER.contentEqualsIgnoreCase(headerName)) { trailer.trailingHeaders().add(headerName, value); } lastHeader = name; // reset name and value fields name = null; value = null; } line = headerParser.parse(buffer); if (line == null) { return null; } lineLength = line.readableBytes(); } this.trailer = null; return trailer; } protected abstract boolean isDecodingRequest(); protected abstract HttpMessage createMessage(String[] initialLine) throws Exception; protected abstract HttpMessage createInvalidMessage(); /** * It skips any whitespace char and return the number of skipped bytes. */ private static int skipWhiteSpaces(byte[] hex, int start, int length) { for (int i = 0; i < length; i++) { if (!isWhitespace(hex[start + i])) { return i; } } return length; } private static int getChunkSize(byte[] hex, int start, int length) { // trim the leading bytes if white spaces, if any final int skipped = skipWhiteSpaces(hex, start, length); if (skipped == length) { // empty case throw new NumberFormatException(); } start += skipped; length -= skipped; int result = 0; for (int i = 0; i < length; i++) { final int digit = StringUtil.decodeHexNibble(hex[start + i]); if (digit == -1) { // uncommon path final byte b = hex[start + i]; if (b == ';' || isControlOrWhitespaceAsciiChar(b)) { if (i == 0) { // empty case throw new NumberFormatException("Empty chunk size"); } return result; } // non-hex char fail-fast path throw new NumberFormatException("Invalid character in chunk size"); } result *= 16; result += digit; if (result < 0) { throw new NumberFormatException("Chunk size overflow: " + result); } } return result; } private String[] splitInitialLine(ByteBuf asciiBuffer) { final byte[] asciiBytes = asciiBuffer.array(); final int arrayOffset = asciiBuffer.arrayOffset(); final int startContent = arrayOffset + asciiBuffer.readerIndex(); final int end = startContent + asciiBuffer.readableBytes(); final int aStart = findNonSPLenient(asciiBytes, startContent, end); final int aEnd = findSPLenient(asciiBytes, aStart, end); final int bStart = findNonSPLenient(asciiBytes, aEnd, end); final int bEnd = findSPLenient(asciiBytes, bStart, end); final int cStart = findNonSPLenient(asciiBytes, bEnd, end); final int cEnd = findEndOfString(asciiBytes, Math.max(cStart - 1, startContent), end); return new String[]{ splitFirstWordInitialLine(asciiBytes, aStart, aEnd - aStart), splitSecondWordInitialLine(asciiBytes, bStart, bEnd - bStart), cStart < cEnd ? splitThirdWordInitialLine(asciiBytes, cStart, cEnd - cStart) : StringUtil.EMPTY_STRING}; } protected String splitFirstWordInitialLine(final byte[] asciiContent, int start, int length) { return langAsciiString(asciiContent, start, length); } protected String splitSecondWordInitialLine(final byte[] asciiContent, int start, int length) { return langAsciiString(asciiContent, start, length); } protected String splitThirdWordInitialLine(final byte[] asciiContent, int start, int length) { return langAsciiString(asciiContent, start, length); } /** * This method shouldn't exist: look at https://bugs.openjdk.org/browse/JDK-8295496 for more context */ private static String langAsciiString(final byte[] asciiContent, int start, int length) { if (length == 0) { return StringUtil.EMPTY_STRING; } // DON'T REMOVE: it helps JIT to use a simpler intrinsic stub for System::arrayCopy based on the call-site if (start == 0) { if (length == asciiContent.length) { return new String(asciiContent, 0, 0, asciiContent.length); } return new String(asciiContent, 0, 0, length); } return new String(asciiContent, 0, start, length); } private void splitHeader(byte[] line, int start, int length) { final int end = start + length; int nameEnd; final int nameStart = findNonWhitespace(line, start, end); // hoist this load out of the loop, because it won't change! final boolean isDecodingRequest = isDecodingRequest(); for (nameEnd = nameStart; nameEnd < end; nameEnd ++) { byte ch = line[nameEnd]; // https://tools.ietf.org/html/rfc7230#section-3.2.4 // // No whitespace is allowed between the header field-name and colon. In // the past, differences in the handling of such whitespace have led to // security vulnerabilities in request routing and response handling. A // server MUST reject any received request message that contains // whitespace between a header field-name and colon with a response code // of 400 (Bad Request). A proxy MUST remove any such whitespace from a // response message before forwarding the message downstream. if (ch == ':' || // In case of decoding a request we will just continue processing and header validation // is done in the DefaultHttpHeaders implementation. // // In the case of decoding a response we will "skip" the whitespace. (!isDecodingRequest && isOWS(ch))) { break; } } if (nameEnd == end) { // There was no colon present at all. throw new IllegalArgumentException("No colon found"); } int colonEnd; for (colonEnd = nameEnd; colonEnd < end; colonEnd ++) { if (line[colonEnd] == ':') { colonEnd ++; break; } } name = splitHeaderName(line, nameStart, nameEnd - nameStart); final int valueStart = findNonWhitespace(line, colonEnd, end); if (valueStart == end) { value = StringUtil.EMPTY_STRING; } else { final int valueEnd = findEndOfString(line, start, end); // no need to make uses of the ByteBuf's toString ASCII method here, and risk to get JIT confused value = langAsciiString(line, valueStart, valueEnd - valueStart); } } protected AsciiString splitHeaderName(byte[] sb, int start, int length) { return new AsciiString(sb, start, length, true); } private static int findNonSPLenient(byte[] sb, int offset, int end) { for (int result = offset; result < end; ++result) { byte c = sb[result]; // See https://tools.ietf.org/html/rfc7230#section-3.5 if (isSPLenient(c)) { continue; } if (isWhitespace(c)) { // Any other whitespace delimiter is invalid throw new IllegalArgumentException("Invalid separator"); } return result; } return end; } private static int findSPLenient(byte[] sb, int offset, int end) { for (int result = offset; result < end; ++result) { if (isSPLenient(sb[result])) { return result; } } return end; } private static final boolean[] SP_LENIENT_BYTES; private static final boolean[] LATIN_WHITESPACE; static { // See https://tools.ietf.org/html/rfc7230#section-3.5 SP_LENIENT_BYTES = new boolean[256]; SP_LENIENT_BYTES[128 + ' '] = true; SP_LENIENT_BYTES[128 + 0x09] = true; SP_LENIENT_BYTES[128 + 0x0B] = true; SP_LENIENT_BYTES[128 + 0x0C] = true; SP_LENIENT_BYTES[128 + 0x0D] = true; // TO SAVE PERFORMING Character::isWhitespace ceremony LATIN_WHITESPACE = new boolean[256]; for (byte b = Byte.MIN_VALUE; b < Byte.MAX_VALUE; b++) { LATIN_WHITESPACE[128 + b] = Character.isWhitespace(b); } } private static boolean isSPLenient(byte c) { // See https://tools.ietf.org/html/rfc7230#section-3.5 return SP_LENIENT_BYTES[c + 128]; } private static boolean isWhitespace(byte b) { return LATIN_WHITESPACE[b + 128]; } private static int findNonWhitespace(byte[] sb, int offset, int end) { for (int result = offset; result < end; ++result) { byte c = sb[result]; if (!isWhitespace(c)) { return result; } else if (!isOWS(c)) { // Only OWS is supported for whitespace throw new IllegalArgumentException("Invalid separator, only a single space or horizontal tab allowed," + " but received a '" + c + "' (0x" + Integer.toHexString(c) + ")"); } } return end; } private static int findEndOfString(byte[] sb, int start, int end) { for (int result = end - 1; result > start; --result) { if (!isWhitespace(sb[result])) { return result + 1; } } return 0; } private static boolean isOWS(byte ch) { return ch == ' ' || ch == 0x09; } private static class HeaderParser { protected final ByteBuf seq; protected final int maxLength; int size; HeaderParser(ByteBuf seq, int maxLength) { this.seq = seq; this.maxLength = maxLength; } public ByteBuf parse(ByteBuf buffer) { final int readableBytes = buffer.readableBytes(); final int readerIndex = buffer.readerIndex(); final int maxBodySize = maxLength - size; assert maxBodySize >= 0; // adding 2 to account for both CR (if present) and LF // don't remove 2L: it's key to cover maxLength = Integer.MAX_VALUE final long maxBodySizeWithCRLF = maxBodySize + 2L; final int toProcess = (int) Math.min(maxBodySizeWithCRLF, readableBytes); final int toIndexExclusive = readerIndex + toProcess; assert toIndexExclusive >= readerIndex; final int indexOfLf = buffer.indexOf(readerIndex, toIndexExclusive, HttpConstants.LF); if (indexOfLf == -1) { if (readableBytes > maxBodySize) { // TODO: Respond with Bad Request and discard the traffic // or close the connection. // No need to notify the upstream handlers - just log. // If decoding a response, just throw an exception. throw newException(maxLength); } return null; } final int endOfSeqIncluded; if (indexOfLf > readerIndex && buffer.getByte(indexOfLf - 1) == HttpConstants.CR) { // Drop CR if we had a CRLF pair endOfSeqIncluded = indexOfLf - 1; } else { endOfSeqIncluded = indexOfLf; } final int newSize = endOfSeqIncluded - readerIndex; if (newSize == 0) { seq.clear(); buffer.readerIndex(indexOfLf + 1); return seq; } int size = this.size + newSize; if (size > maxLength) { throw newException(maxLength); } this.size = size; seq.clear(); seq.writeBytes(buffer, readerIndex, newSize); buffer.readerIndex(indexOfLf + 1); return seq; } public void reset() { size = 0; } protected TooLongFrameException newException(int maxLength) { return new TooLongHttpHeaderException("HTTP header is larger than " + maxLength + " bytes."); } } private final class LineParser extends HeaderParser { LineParser(ByteBuf seq, int maxLength) { super(seq, maxLength); } @Override public ByteBuf parse(ByteBuf buffer) { // Suppress a warning because HeaderParser.reset() is supposed to be called reset(); final int readableBytes = buffer.readableBytes(); if (readableBytes == 0) { return null; } final int readerIndex = buffer.readerIndex(); if (currentState == State.SKIP_CONTROL_CHARS && skipControlChars(buffer, readableBytes, readerIndex)) { return null; } return super.parse(buffer); } private boolean skipControlChars(ByteBuf buffer, int readableBytes, int readerIndex) { assert currentState == State.SKIP_CONTROL_CHARS; final int maxToSkip = Math.min(maxLength, readableBytes); final int firstNonControlIndex = buffer.forEachByte(readerIndex, maxToSkip, SKIP_CONTROL_CHARS_BYTES); if (firstNonControlIndex == -1) { buffer.skipBytes(maxToSkip); if (readableBytes > maxLength) { throw newException(maxLength); } return true; } // from now on we don't care about control chars buffer.readerIndex(firstNonControlIndex); currentState = State.READ_INITIAL; return false; } @Override protected TooLongFrameException newException(int maxLength) { return new TooLongHttpLineException("An HTTP line is larger than " + maxLength + " bytes."); } } private static final boolean[] ISO_CONTROL_OR_WHITESPACE; static { ISO_CONTROL_OR_WHITESPACE = new boolean[256]; for (byte b = Byte.MIN_VALUE; b < Byte.MAX_VALUE; b++) { ISO_CONTROL_OR_WHITESPACE[128 + b] = Character.isISOControl(b) || isWhitespace(b); } } private static final ByteProcessor SKIP_CONTROL_CHARS_BYTES = new ByteProcessor() { @Override public boolean process(byte value) { return ISO_CONTROL_OR_WHITESPACE[128 + value]; } }; private static boolean isControlOrWhitespaceAsciiChar(byte b) { return ISO_CONTROL_OR_WHITESPACE[128 + b]; } }
netty/netty
codec-http/src/main/java/io/netty/handler/codec/http/HttpObjectDecoder.java
8
package com.macro.mall.security.config; import com.macro.mall.security.component.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.access.intercept.FilterSecurityInterceptor; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; /** * SpringSecurity相关配置,仅用于配置SecurityFilterChain * Created by macro on 2019/11/5. */ @Configuration @EnableWebSecurity public class SecurityConfig { @Autowired private IgnoreUrlsConfig ignoreUrlsConfig; @Autowired private RestfulAccessDeniedHandler restfulAccessDeniedHandler; @Autowired private RestAuthenticationEntryPoint restAuthenticationEntryPoint; @Autowired private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter; @Autowired(required = false) private DynamicSecurityService dynamicSecurityService; @Autowired(required = false) private DynamicSecurityFilter dynamicSecurityFilter; @Bean SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception { ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = httpSecurity .authorizeRequests(); //不需要保护的资源路径允许访问 for (String url : ignoreUrlsConfig.getUrls()) { registry.antMatchers(url).permitAll(); } //允许跨域请求的OPTIONS请求 registry.antMatchers(HttpMethod.OPTIONS) .permitAll(); // 任何请求需要身份认证 registry.and() .authorizeRequests() .anyRequest() .authenticated() // 关闭跨站请求防护及不使用session .and() .csrf() .disable() .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS) // 自定义权限拒绝处理类 .and() .exceptionHandling() .accessDeniedHandler(restfulAccessDeniedHandler) .authenticationEntryPoint(restAuthenticationEntryPoint) // 自定义权限拦截器JWT过滤器 .and() .addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class); //有动态权限配置时添加动态权限校验过滤器 if(dynamicSecurityService!=null){ registry.and().addFilterBefore(dynamicSecurityFilter, FilterSecurityInterceptor.class); } return httpSecurity.build(); } }
macrozheng/mall
mall-security/src/main/java/com/macro/mall/security/config/SecurityConfig.java
9
/* Copyright (c) 2007-2015 Timothy Wall, All Rights Reserved * * The contents of this file is dual-licensed under 2 * alternative Open Source/Free licenses: LGPL 2.1 or later and * Apache License 2.0. (starting with JNA version 4.0.0). * * You can freely decide which license you want to apply to * the project. * * You may obtain a copy of the LGPL License at: * * http://www.gnu.org/licenses/licenses.html * * A copy is also included in the downloadable source code package * containing JNA, in file "LGPL2.1". * * You may obtain a copy of the Apache License at: * * http://www.apache.org/licenses/ * * A copy is also included in the downloadable source code package * containing JNA, in file "AL2.0". */ package com.sun.jna; import java.awt.Component; import java.awt.GraphicsEnvironment; import java.awt.HeadlessException; import java.awt.Window; import java.io.File; import java.io.FileOutputStream; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.lang.ref.Reference; import java.lang.ref.WeakReference; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.Proxy; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLClassLoader; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.nio.charset.IllegalCharsetNameException; import java.nio.charset.UnsupportedCharsetException; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import java.util.WeakHashMap; import com.sun.jna.Callback.UncaughtExceptionHandler; import com.sun.jna.Structure.FFIType; import java.util.logging.Level; import java.util.logging.Logger; /** Provides generation of invocation plumbing for a defined native * library interface. Also provides various utilities for native operations. * <p> * {@link #getTypeMapper} and {@link #getStructureAlignment} are provided * to avoid having to explicitly pass these parameters to {@link Structure}s, * which would require every {@link Structure} which requires custom mapping * or alignment to define a constructor and pass parameters to the superclass. * To avoid lots of boilerplate, the base {@link Structure} constructor * figures out these properties based on its enclosing interface.<p> * <a name=library_loading></a> * <h2>Library Loading</h2> * <p>When JNA classes are loaded, the native shared library (jnidispatch) is * loaded as well. An attempt is made to load it from the any paths defined * in <code>jna.boot.library.path</code> (if defined), then the system library * path using {@link System#loadLibrary}, unless <code>jna.nosys=true</code>. * If not found, the appropriate library will be extracted from the class path * (into a temporary directory if found within a jar file) and loaded from * there, unless <code>jna.noclasspath=true</code>. If your system has * additional security constraints regarding execution or load of files * (SELinux, for example), you should probably install the native library in * an accessible location and configure your system accordingly, rather than * relying on JNA to extract the library from its own jar file.</p> * <p>To avoid the automatic unpacking (in situations where you want to force a * failure if the JNA native library is not properly installed on the system), * set the system property <code>jna.nounpack=true</code>. * </p> * <p>While this class and its corresponding native library are loaded, the * system property <code>jna.loaded</code> will be set. The property will be * cleared when native support has been unloaded (i.e. the Native class and * its underlying native support has been GC'd).</p> * <p>NOTE: all native functions are provided within this class to ensure that * all other JNA-provided classes and objects are GC'd and/or * finalized/disposed before this class is disposed and/or removed from * memory (most notably Memory and any other class which by default frees its * resources in a finalizer).</p> * <a name=native_library_loading></a> * <h2>Native Library Loading</h2> * Native libraries loaded via {@link #load(Class)} may be found in * <a href="NativeLibrary.html#library_search_paths">several locations</a>. * @see Library * @author Todd Fast, todd.fast@sun.com * @author twall@users.sf.net */ public final class Native implements Version { private static final Logger LOG = Logger.getLogger(Native.class.getName()); public static final Charset DEFAULT_CHARSET; public static final String DEFAULT_ENCODING; static { // JNA used the defaultCharset to determine which encoding to use when // converting strings to native char*. The defaultCharset is set from // the system property file.encoding. Up to JDK 17 its value defaulted // to the system default encoding. From JDK 18 onwards its default value // changed to UTF-8. // JDK 18+ exposes the native encoding as the new system property // native.encoding, prior versions don't have that property and will // report NULL for it. // The algorithm is simple: If native.encoding is set, it will be used // else the original implementation of Charset#defaultCharset is used String nativeEncoding = System.getProperty("native.encoding"); Charset nativeCharset = null; if (nativeEncoding != null) { try { nativeCharset = Charset.forName(nativeEncoding); } catch (Exception ex) { LOG.log(Level.WARNING, "Failed to get charset for native.encoding value : '" + nativeEncoding + "'", ex); } } if (nativeCharset == null) { nativeCharset = Charset.defaultCharset(); } DEFAULT_CHARSET = nativeCharset; DEFAULT_ENCODING = nativeCharset.name(); } public static final boolean DEBUG_LOAD = Boolean.getBoolean("jna.debug_load"); public static final boolean DEBUG_JNA_LOAD = Boolean.getBoolean("jna.debug_load.jna"); private final static Level DEBUG_JNA_LOAD_LEVEL = DEBUG_JNA_LOAD ? Level.INFO : Level.FINE; // Used by tests, do not remove static String jnidispatchPath = null; private static final Map<Class<?>, Map<String, Object>> typeOptions = Collections.synchronizedMap(new WeakHashMap<Class<?>, Map<String, Object>>()); private static final Map<Class<?>, Reference<?>> libraries = Collections.synchronizedMap(new WeakHashMap<Class<?>, Reference<?>>()); private static final String _OPTION_ENCLOSING_LIBRARY = "enclosing-library"; private static final UncaughtExceptionHandler DEFAULT_HANDLER = new UncaughtExceptionHandler() { @Override public void uncaughtException(Callback c, Throwable e) { LOG.log(Level.WARNING, "JNA: Callback " + c + " threw the following exception", e); } }; private static UncaughtExceptionHandler callbackExceptionHandler = DEFAULT_HANDLER; /** The size of a native pointer (<code>void*</code>) on the current * platform, in bytes. */ public static final int POINTER_SIZE; /** Size of a native <code>long</code> type, in bytes. */ public static final int LONG_SIZE; /** Size of a native <code>wchar_t</code> type, in bytes. */ public static final int WCHAR_SIZE; /** Size of a native <code>size_t</code> type, in bytes. */ public static final int SIZE_T_SIZE; /** Size of a native <code>bool</code> type (C99 and later), in bytes. */ public static final int BOOL_SIZE; /** Size of a native <code>long double</code> type (C99 and later), in bytes. */ public static final int LONG_DOUBLE_SIZE; private static final int TYPE_VOIDP = 0; private static final int TYPE_LONG = 1; private static final int TYPE_WCHAR_T = 2; private static final int TYPE_SIZE_T = 3; private static final int TYPE_BOOL = 4; private static final int TYPE_LONG_DOUBLE = 5; static final int MAX_ALIGNMENT; static final int MAX_PADDING; /** * Version string must have the structure <major>.<minor>.<revision> * a bugfix change in the native code increments revision, the minor is * incremented for backwards compatible changes and the major version * is changed for backwards incompatbile changes. * * @param expectedVersion * @param nativeVersion * @return true if nativeVersion describes a version compatible to expectedVersion */ static boolean isCompatibleVersion(String expectedVersion, String nativeVersion) { String[] expectedVersionParts = expectedVersion.split("\\."); String[] nativeVersionParts = nativeVersion.split("\\."); if(expectedVersionParts.length < 3 || nativeVersionParts.length < 3) { return false; } int expectedMajor = Integer.parseInt(expectedVersionParts[0]); int nativeMajor = Integer.parseInt(nativeVersionParts[0]); int expectedMinor = Integer.parseInt(expectedVersionParts[1]); int nativeMinor = Integer.parseInt(nativeVersionParts[1]); if(expectedMajor != nativeMajor) { return false; } if(expectedMinor > nativeMinor) { return false; } return true; } static { loadNativeDispatchLibrary(); if (! isCompatibleVersion(VERSION_NATIVE, getNativeVersion())) { String LS = System.lineSeparator(); throw new Error(LS + LS + "There is an incompatible JNA native library installed on this system" + LS + "Expected: " + VERSION_NATIVE + LS + "Found: " + getNativeVersion() + LS + (jnidispatchPath != null ? "(at " + jnidispatchPath + ")" : System.getProperty("java.library.path")) + "." + LS + "To resolve this issue you may do one of the following:" + LS + " - remove or uninstall the offending library" + LS + " - set the system property jna.nosys=true" + LS + " - set jna.boot.library.path to include the path to the version of the " + LS + " jnidispatch library included with the JNA jar file you are using" + LS); } POINTER_SIZE = sizeof(TYPE_VOIDP); LONG_SIZE = sizeof(TYPE_LONG); WCHAR_SIZE = sizeof(TYPE_WCHAR_T); SIZE_T_SIZE = sizeof(TYPE_SIZE_T); BOOL_SIZE = sizeof(TYPE_BOOL); LONG_DOUBLE_SIZE = sizeof(TYPE_LONG_DOUBLE); // Perform initialization of other JNA classes until *after* // initializing the above final fields initIDs(); if (Boolean.getBoolean("jna.protected")) { setProtected(true); } MAX_ALIGNMENT = Platform.isSPARC() || Platform.isWindows() || (Platform.isLinux() && (Platform.isARM() || Platform.isPPC() || Platform.isMIPS() || Platform.isLoongArch())) || Platform.isAIX() || (Platform.isAndroid() && !Platform.isIntel()) ? 8 : LONG_SIZE; MAX_PADDING = (Platform.isMac() && Platform.isPPC()) ? 8 : MAX_ALIGNMENT; System.setProperty("jna.loaded", "true"); } /** Force a dispose when the Native class is GC'd. */ private static final Object finalizer = new Object() { @Override protected void finalize() throws Throwable { dispose(); super.finalize(); } }; /** Properly dispose of JNA functionality. Called when this class is finalized and also from JNI when JNA's native shared library is unloaded. */ private static void dispose() { CallbackReference.disposeAll(); Memory.disposeAll(); NativeLibrary.disposeAll(); unregisterAll(); jnidispatchPath = null; System.setProperty("jna.loaded", "false"); } /** Remove any automatically unpacked native library. This will fail on windows, which disallows removal of any file that is still in use, so an alternative is required in that case. Mark the file that could not be deleted, and attempt to delete any temporaries on next startup. Do NOT force the class loader to unload the native library, since that introduces issues with cleaning up any extant JNA bits (e.g. Memory) which may still need use of the library before shutdown. */ static boolean deleteLibrary(File lib) { if (lib.delete()) { return true; } // Couldn't delete it, mark for later deletion markTemporaryFile(lib); return false; } private Native() { } private static native void initIDs(); /** Set whether native memory accesses are protected from invalid * accesses. This should only be set true when testing or debugging, * and should not be considered reliable or robust for applications * where JNA native calls are occurring on multiple threads. * Protected mode will be automatically set if the * system property <code>jna.protected</code> has a value of "true" * when the JNA library is first loaded.<p> * If not supported by the underlying platform, this setting will * have no effect.<p> * NOTE: On platforms which support signals (non-Windows), JNA uses * signals to trap errors. This may interfere with the JVM's own use of * signals. When protected mode is enabled, you should make use of the * jsig library, if available (see <a href="http://download.oracle.com/javase/6/docs/technotes/guides/vm/signal-chaining.html">Signal Chaining</a>). * In short, set the environment variable <code>LD_PRELOAD</code> to the * path to <code>libjsig.so</code> in your JRE lib directory * (usually ${java.home}/lib/${os.arch}/libjsig.so) before launching your * Java application. */ public static synchronized native void setProtected(boolean enable); /** Returns whether protection is enabled. Check the result of this method * after calling {@link #setProtected setProtected(true)} to determine * if this platform supports protecting memory accesses. */ public static synchronized native boolean isProtected(); /** Utility method to get the native window ID for a Java {@link Window} * as a <code>long</code> value. * This method is primarily for X11-based systems, which use an opaque * <code>XID</code> (usually <code>long int</code>) to identify windows. * @throws HeadlessException if the current VM is running headless */ public static long getWindowID(Window w) throws HeadlessException { return AWT.getWindowID(w); } /** Utility method to get the native window ID for a heavyweight Java * {@link Component} as a <code>long</code> value. * This method is primarily for X11-based systems, which use an opaque * <code>XID</code> (usually <code>long int</code>) to identify windows. * @throws HeadlessException if the current VM is running headless */ public static long getComponentID(Component c) throws HeadlessException { return AWT.getComponentID(c); } /** Utility method to get the native window pointer for a Java * {@link Window} as a {@link Pointer} value. This method is primarily for * w32, which uses the <code>HANDLE</code> type (actually * <code>void *</code>) to identify windows. * @throws HeadlessException if the current VM is running headless */ public static Pointer getWindowPointer(Window w) throws HeadlessException { return new Pointer(AWT.getWindowID(w)); } /** Utility method to get the native window pointer for a heavyweight Java * {@link Component} as a {@link Pointer} value. This method is primarily * for w32, which uses the <code>HWND</code> type (actually * <code>void *</code>) to identify windows. * @throws HeadlessException if the current VM is running headless */ public static Pointer getComponentPointer(Component c) throws HeadlessException { return new Pointer(AWT.getComponentID(c)); } static native long getWindowHandle0(Component c); /** Convert a direct {@link Buffer} into a {@link Pointer}. * @throws IllegalArgumentException if the buffer is not direct. */ public static Pointer getDirectBufferPointer(Buffer b) { long peer = _getDirectBufferPointer(b); return peer == 0 ? null : new Pointer(peer); } private static native long _getDirectBufferPointer(Buffer b); /** * Gets the charset belonging to the given {@code encoding}. * @param encoding The encoding - if {@code null} then the default platform * encoding is used. * @return The charset belonging to the given {@code encoding} or the platform default. * Never {@code null}. */ private static Charset getCharset(String encoding) { Charset charset = null; if (encoding != null) { try { charset = Charset.forName(encoding); } catch(IllegalCharsetNameException | UnsupportedCharsetException e) { LOG.log(Level.WARNING, "JNA Warning: Encoding ''{0}'' is unsupported ({1})", new Object[]{encoding, e.getMessage()}); } } if (charset == null) { LOG.log(Level.WARNING, "JNA Warning: Using fallback encoding {0}", Native.DEFAULT_CHARSET); charset = Native.DEFAULT_CHARSET; } return charset; } /** * Obtain a Java String from the given native byte array. If there is * no NUL terminator, the String will comprise the entire array. The * encoding is obtained from {@link #getDefaultStringEncoding()}. * * @param buf The buffer containing the encoded bytes * @see #toString(byte[], String) */ public static String toString(byte[] buf) { return toString(buf, getDefaultStringEncoding()); } /** * Obtain a Java String from the given native byte array, using the given * encoding. If there is no NUL terminator, the String will comprise the * entire array. * * <p><strong>Usage note</strong>: This function assumes, that {@code buf} * holds a {@code char} array. This means only single-byte encodings are * supported.</p> * * @param buf The buffer containing the encoded bytes. Must not be {@code null}. * @param encoding The encoding name - if {@code null} then the platform * default encoding will be used */ public static String toString(byte[] buf, String encoding) { return Native.toString(buf, Native.getCharset(encoding)); } /** * Obtain a Java String from the given native byte array, using the given * encoding. If there is no NUL terminator, the String will comprise the * entire array. * * <p><strong>Usage note</strong>: This function assumes, that {@code buf} * holds a {@code char} array. This means only single-byte encodings are * supported.</p> * * @param buf The buffer containing the encoded bytes. Must not be {@code null}. * @param charset The charset to decode {@code buf}. Must not be {@code null}. */ public static String toString(byte[] buf, Charset charset) { int len = buf.length; // find out the effective length for (int index = 0; index < len; index++) { if (buf[index] == 0) { len = index; break; } } if (len == 0) { return ""; } return new String(buf, 0, len, charset); } /** * Obtain a Java String from the given native wchar_t array. If there is * no NUL terminator, the String will comprise the entire array. * * @param buf The buffer containing the characters */ public static String toString(char[] buf) { int len = buf.length; for (int index = 0; index < len; index++) { if (buf[index] == '\0') { len = index; break; } } if (len == 0) { return ""; } else { return new String(buf, 0, len); } } /** * Converts a &quot;list&quot; of strings each null terminated * into a {@link List} of {@link String} values. The end of the * list is signaled by an extra NULL value at the end or by the * end of the buffer. * @param buf The buffer containing the strings * @return A {@link List} of all the strings in the buffer * @see #toStringList(char[], int, int) */ public static List<String> toStringList(char[] buf) { return toStringList(buf, 0, buf.length); } /** * Converts a &quot;list&quot; of strings each null terminated * into a {@link List} of {@link String} values. The end of the * list is signaled by an extra NULL value at the end or by the * end of the data. * @param buf The buffer containing the strings * @param offset Offset to start parsing * @param len The total characters to parse * @return A {@link List} of all the strings in the buffer */ public static List<String> toStringList(char[] buf, int offset, int len) { List<String> list = new ArrayList<>(); int lastPos = offset; int maxPos = offset + len; for (int curPos = offset; curPos < maxPos; curPos++) { if (buf[curPos] != '\0') { continue; } // check if found the extra null terminator if (lastPos == curPos) { return list; } String value = new String(buf, lastPos, curPos - lastPos); list.add(value); lastPos = curPos + 1; // skip the '\0' } // This point is reached if there is no double null terminator if (lastPos < maxPos) { String value = new String(buf, lastPos, maxPos - lastPos); list.add(value); } return list; } /** Map a library interface to the current process, providing * the explicit interface class. * Native libraries loaded via this method may be found in * <a href="NativeLibrary.html#library_search_paths">several locations</a>. * @param <T> Type of expected wrapper * @param interfaceClass The implementation wrapper interface * @return an instance of the requested interface, mapped to the current * process. * @throws UnsatisfiedLinkError if the library cannot be found or * dependent libraries are missing. */ public static <T extends Library> T load(Class<T> interfaceClass) { return load(null, interfaceClass); } /** Map a library interface to the current process, providing * the explicit interface class. Any options provided for the library are * cached and associated with the library and any of its defined * structures and/or functions. * Native libraries loaded via this method may be found in * <a href="NativeLibrary.html#library_search_paths">several locations</a>. * @param <T> Type of expected wrapper * @param interfaceClass The implementation wrapper interface * @param options Map of library options * @return an instance of the requested interface, mapped to the current * process. * @throws UnsatisfiedLinkError if the library cannot be found or * dependent libraries are missing. * @see #load(String, Class, Map) */ public static <T extends Library> T load(Class<T> interfaceClass, Map<String, ?> options) { return load(null, interfaceClass, options); } /** Map a library interface to the given shared library, providing * the explicit interface class. * If <code>name</code> is null, attempts to map onto the current process. * Native libraries loaded via this method may be found in * <a href="NativeLibrary.html#library_search_paths">several locations</a>. * @param <T> Type of expected wrapper * @param name Library base name * @param interfaceClass The implementation wrapper interface * @return an instance of the requested interface, mapped to the indicated * native library. * @throws UnsatisfiedLinkError if the library cannot be found or * dependent libraries are missing. * @see #load(String, Class, Map) */ public static <T extends Library> T load(String name, Class<T> interfaceClass) { return load(name, interfaceClass, Collections.<String, Object>emptyMap()); } /** Load a library interface from the given shared library, providing * the explicit interface class and a map of options for the library. * If no library options are detected the map is interpreted as a map * of Java method names to native function names.<p> * If <code>name</code> is null, attempts to map onto the current process. * Native libraries loaded via this method may be found in * <a href="NativeLibrary.html#library_search_paths">several locations</a>. * @param <T> Type of expected wrapper * @param name Library base name * @param interfaceClass The implementation wrapper interface * @param options Map of library options * @return an instance of the requested interface, mapped to the indicated * native library. * @throws UnsatisfiedLinkError if the library cannot be found or * dependent libraries are missing. */ public static <T extends Library> T load(String name, Class<T> interfaceClass, Map<String, ?> options) { if (!Library.class.isAssignableFrom(interfaceClass)) { // Maybe still possible if the caller is not using generics? throw new IllegalArgumentException("Interface (" + interfaceClass.getSimpleName() + ")" + " of library=" + name + " does not extend " + Library.class.getSimpleName()); } Library.Handler handler = new Library.Handler(name, interfaceClass, options); ClassLoader loader = interfaceClass.getClassLoader(); Object proxy = Proxy.newProxyInstance(loader, new Class[] {interfaceClass}, handler); cacheOptions(interfaceClass, options, proxy); return interfaceClass.cast(proxy); } /** * Provided for improved compatibility between JNA 4.X and 5.X * * @see Native#load(java.lang.Class) */ @Deprecated public static <T> T loadLibrary(Class<T> interfaceClass) { return loadLibrary(null, interfaceClass); } /** * Provided for improved compatibility between JNA 4.X and 5.X * * @see Native#load(java.lang.Class, java.util.Map) */ @Deprecated public static <T> T loadLibrary(Class<T> interfaceClass, Map<String, ?> options) { return loadLibrary(null, interfaceClass, options); } /** * Provided for improved compatibility between JNA 4.X and 5.X * * @see Native#load(java.lang.String, java.lang.Class) */ @Deprecated public static <T> T loadLibrary(String name, Class<T> interfaceClass) { return loadLibrary(name, interfaceClass, Collections.<String, Object>emptyMap()); } /** * Provided for improved compatibility between JNA 4.X and 5.X * * @see Native#load(java.lang.String, java.lang.Class, java.util.Map) */ @Deprecated public static <T> T loadLibrary(String name, Class<T> interfaceClass, Map<String, ?> options) { if (!Library.class.isAssignableFrom(interfaceClass)) { // Maybe still possible if the caller is not using generics? throw new IllegalArgumentException("Interface (" + interfaceClass.getSimpleName() + ")" + " of library=" + name + " does not extend " + Library.class.getSimpleName()); } Library.Handler handler = new Library.Handler(name, interfaceClass, options); ClassLoader loader = interfaceClass.getClassLoader(); Object proxy = Proxy.newProxyInstance(loader, new Class[] {interfaceClass}, handler); cacheOptions(interfaceClass, options, proxy); return interfaceClass.cast(proxy); } /** Attempts to force initialization of an instance of the library interface * by loading a public static field of the requisite type. * Returns whether an instance variable was instantiated. * Expects that lock on libraries is already held */ private static void loadLibraryInstance(Class<?> cls) { if (cls != null && !libraries.containsKey(cls)) { try { Field[] fields = cls.getFields(); for (int i=0;i < fields.length;i++) { Field field = fields[i]; if (field.getType() == cls && Modifier.isStatic(field.getModifiers())) { // Ensure the field gets initialized by reading it field.setAccessible(true); // interface might be private libraries.put(cls, new WeakReference<>(field.get(null))); break; } } } catch (Exception e) { throw new IllegalArgumentException("Could not access instance of " + cls + " (" + e + ")"); } } } /** * Find the library interface corresponding to the given class. Checks * all ancestor classes and interfaces for a declaring class which * implements {@link Library}. * @param cls The given class * @return The enclosing class */ static Class<?> findEnclosingLibraryClass(Class<?> cls) { if (cls == null) { return null; } // Check for direct-mapped libraries, which won't necessarily // implement com.sun.jna.Library. Map<String, ?> libOptions = typeOptions.get(cls); if (libOptions != null) { Class<?> enclosingClass = (Class<?>)libOptions.get(_OPTION_ENCLOSING_LIBRARY); if (enclosingClass != null) { return enclosingClass; } return cls; } if (Library.class.isAssignableFrom(cls)) { return cls; } if (Callback.class.isAssignableFrom(cls)) { cls = CallbackReference.findCallbackClass(cls); } Class<?> declaring = cls.getDeclaringClass(); Class<?> fromDeclaring = findEnclosingLibraryClass(declaring); if (fromDeclaring != null) { return fromDeclaring; } return findEnclosingLibraryClass(cls.getSuperclass()); } /** Return the preferred native library configuration options for the given * class. First attempts to load any field of the interface type within * the interface mapping, then checks the cache for any specified library * options. If none found, a set of library options will be generated * from the fields (by order of precedence) <code>OPTIONS</code> (a {@link * Map}), <code>TYPE_MAPPER</code> (a {@link TypeMapper}), * <code>STRUCTURE_ALIGNMENT</code> (an {@link Integer}), and * <code>STRING_ENCODING</code> (a {@link String}). * * @param type The type class * @return The options map */ public static Map<String, Object> getLibraryOptions(Class<?> type) { Map<String, Object> libraryOptions; // cached already ? libraryOptions = typeOptions.get(type); if (libraryOptions != null) { return libraryOptions; } Class<?> mappingClass = findEnclosingLibraryClass(type); if (mappingClass != null) { loadLibraryInstance(mappingClass); } else { mappingClass = type; } libraryOptions = typeOptions.get(mappingClass); if (libraryOptions != null) { typeOptions.put(type, libraryOptions); // cache for next time return libraryOptions; } try { Field field = mappingClass.getField("OPTIONS"); field.setAccessible(true); libraryOptions = (Map<String, Object>) field.get(null); if (libraryOptions == null) { throw new IllegalStateException("Null options field"); } } catch (NoSuchFieldException e) { libraryOptions = Collections.<String, Object>emptyMap(); } catch (Exception e) { throw new IllegalArgumentException("OPTIONS must be a public field of type java.util.Map (" + e + "): " + mappingClass); } // Make a clone of the original options libraryOptions = new HashMap<>(libraryOptions); if (!libraryOptions.containsKey(Library.OPTION_TYPE_MAPPER)) { libraryOptions.put(Library.OPTION_TYPE_MAPPER, lookupField(mappingClass, "TYPE_MAPPER", TypeMapper.class)); } if (!libraryOptions.containsKey(Library.OPTION_STRUCTURE_ALIGNMENT)) { libraryOptions.put(Library.OPTION_STRUCTURE_ALIGNMENT, lookupField(mappingClass, "STRUCTURE_ALIGNMENT", Integer.class)); } if (!libraryOptions.containsKey(Library.OPTION_STRING_ENCODING)) { libraryOptions.put(Library.OPTION_STRING_ENCODING, lookupField(mappingClass, "STRING_ENCODING", String.class)); } libraryOptions = cacheOptions(mappingClass, libraryOptions, null); // Store the original lookup class, if different from the mapping class if (type != mappingClass) { typeOptions.put(type, libraryOptions); } return libraryOptions; } private static Object lookupField(Class<?> mappingClass, String fieldName, Class<?> resultClass) { try { Field field = mappingClass.getField(fieldName); field.setAccessible(true); return field.get(null); } catch (NoSuchFieldException e) { return null; } catch (Exception e) { throw new IllegalArgumentException(fieldName + " must be a public field of type " + resultClass.getName() + " (" + e + "): " + mappingClass); } } /** Return the preferred {@link TypeMapper} for the given native interface. * See {@link com.sun.jna.Library#OPTION_TYPE_MAPPER}. */ public static TypeMapper getTypeMapper(Class<?> cls) { Map<String, ?> options = getLibraryOptions(cls); return (TypeMapper) options.get(Library.OPTION_TYPE_MAPPER); } /** * @param cls The native interface type * @return The preferred string encoding for the given native interface. * If there is no setting, defaults to the {@link #getDefaultStringEncoding()}. * @see com.sun.jna.Library#OPTION_STRING_ENCODING */ public static String getStringEncoding(Class<?> cls) { Map<String, ?> options = getLibraryOptions(cls); String encoding = (String) options.get(Library.OPTION_STRING_ENCODING); return encoding != null ? encoding : getDefaultStringEncoding(); } /** * @return The default string encoding. Returns the value of the system * property <code>jna.encoding</code> or {@link Native#DEFAULT_ENCODING}. */ public static String getDefaultStringEncoding() { return System.getProperty("jna.encoding", DEFAULT_ENCODING); } /** * @param cls The native interface type * @return The preferred structure alignment for the given native interface. * @see com.sun.jna.Library#OPTION_STRUCTURE_ALIGNMENT */ public static int getStructureAlignment(Class<?> cls) { Integer alignment = (Integer)getLibraryOptions(cls).get(Library.OPTION_STRUCTURE_ALIGNMENT); return alignment == null ? Structure.ALIGN_DEFAULT : alignment; } /** * @param s The input string * @return A byte array corresponding to the given String. The encoding * used is obtained from {@link #getDefaultStringEncoding()}. */ static byte[] getBytes(String s) { return getBytes(s, getDefaultStringEncoding()); } /** * @param s The string. Must not be {@code null}. * @param encoding The encoding - if {@code null} then the default platform * encoding is used * @return A byte array corresponding to the given String, using the given * encoding. If the encoding is not found default to the platform native * encoding. */ static byte[] getBytes(String s, String encoding) { return Native.getBytes(s, Native.getCharset(encoding)); } /** * @param s The string. Must not be {@code null}. * @param charset The charset used to encode {@code s}. Must not be {@code null}. * @return A byte array corresponding to the given String, using the given * charset. */ static byte[] getBytes(String s, Charset charset) { return s.getBytes(charset); } /** * @param s The string * @return A NUL-terminated byte buffer equivalent to the given String, * using the encoding returned by {@link #getDefaultStringEncoding()}. * @see #toByteArray(String, String) */ public static byte[] toByteArray(String s) { return toByteArray(s, getDefaultStringEncoding()); } /** * @param s The string. Must not be {@code null}. * @param encoding The encoding - if {@code null} then the default platform * encoding is used * @return A NUL-terminated byte buffer equivalent to the given String, * using the given encoding. * @see #getBytes(String, String) */ public static byte[] toByteArray(String s, String encoding) { return Native.toByteArray(s, Native.getCharset(encoding)); } /** * @param s The string. Must not be {@code null}. * @param charset The charset used to encode {@code s}. Must not be {@code null}. * @return A NUL-terminated byte buffer equivalent to the given String, * using the given charset. * @see #getBytes(String, String) */ public static byte[] toByteArray(String s, Charset charset) { byte[] bytes = Native.getBytes(s, charset); byte[] buf = new byte[bytes.length+1]; System.arraycopy(bytes, 0, buf, 0, bytes.length); return buf; } /** * @param s The string * @return A NUL-terminated wide character buffer equivalent to the given string. */ public static char[] toCharArray(String s) { char[] chars = s.toCharArray(); char[] buf = new char[chars.length+1]; System.arraycopy(chars, 0, buf, 0, chars.length); return buf; } /** * Loads the JNA stub library. * First tries jna.boot.library.path, then the system path, then from the * jar file. */ private static void loadNativeDispatchLibrary() { if (!Boolean.getBoolean("jna.nounpack")) { try { removeTemporaryFiles(); } catch(IOException e) { LOG.log(Level.WARNING, "JNA Warning: IOException removing temporary files", e); } } String libName = System.getProperty("jna.boot.library.name", "jnidispatch"); String bootPath = System.getProperty("jna.boot.library.path"); if (bootPath != null) { // String.split not available in 1.4 StringTokenizer dirs = new StringTokenizer(bootPath, File.pathSeparator); while (dirs.hasMoreTokens()) { String dir = dirs.nextToken(); File file = new File(new File(dir), System.mapLibraryName(libName).replace(".dylib", ".jnilib")); String path = file.getAbsolutePath(); LOG.log(DEBUG_JNA_LOAD_LEVEL, "Looking in {0}", path); if (file.exists()) { try { LOG.log(DEBUG_JNA_LOAD_LEVEL, "Trying {0}", path); System.setProperty("jnidispatch.path", path); System.load(path); jnidispatchPath = path; LOG.log(DEBUG_JNA_LOAD_LEVEL, "Found jnidispatch at {0}", path); return; } catch (UnsatisfiedLinkError ex) { // Not a problem if already loaded in anoteher class loader // Unfortunately we can't distinguish the difference... //System.out.println("File found at " + file + " but not loadable: " + ex.getMessage()); } } if (Platform.isMac()) { String orig, ext; if (path.endsWith("dylib")) { orig = "dylib"; ext = "jnilib"; } else { orig = "jnilib"; ext = "dylib"; } path = path.substring(0, path.lastIndexOf(orig)) + ext; LOG.log(DEBUG_JNA_LOAD_LEVEL, "Looking in {0}", path); if (new File(path).exists()) { try { LOG.log(DEBUG_JNA_LOAD_LEVEL, "Trying {0}", path); System.setProperty("jnidispatch.path", path); System.load(path); jnidispatchPath = path; LOG.log(DEBUG_JNA_LOAD_LEVEL, "Found jnidispatch at {0}", path); return; } catch (UnsatisfiedLinkError ex) { LOG.log(Level.WARNING, "File found at " + path + " but not loadable: " + ex.getMessage(), ex); } } } } } String jnaNosys = System.getProperty("jna.nosys", "true"); if ((!Boolean.parseBoolean(jnaNosys)) || Platform.isAndroid()) { try { LOG.log(DEBUG_JNA_LOAD_LEVEL, "Trying (via loadLibrary) {0}", libName); System.loadLibrary(libName); LOG.log(DEBUG_JNA_LOAD_LEVEL, "Found jnidispatch on system path"); return; } catch(UnsatisfiedLinkError e) { } } if (!Boolean.getBoolean("jna.noclasspath")) { loadNativeDispatchLibraryFromClasspath(); } else { throw new UnsatisfiedLinkError("Unable to locate JNA native support library"); } } static final String JNA_TMPLIB_PREFIX = "jna"; /** * Attempts to load the native library resource from the filesystem, * extracting the JNA stub library from jna.jar if not already available. */ private static void loadNativeDispatchLibraryFromClasspath() { try { String mappedName = System.mapLibraryName("jnidispatch").replace(".dylib", ".jnilib"); if(Platform.isAIX()) { // OpenJDK is reported to map to .so -- this works around the // difference between J9 and OpenJDK mappedName = "libjnidispatch.a"; } String libName = "/com/sun/jna/" + Platform.RESOURCE_PREFIX + "/" + mappedName; File lib = extractFromResourcePath(libName, Native.class.getClassLoader()); if (lib == null) { if (lib == null) { throw new UnsatisfiedLinkError("Could not find JNA native support"); } } LOG.log(DEBUG_JNA_LOAD_LEVEL, "Trying {0}", lib.getAbsolutePath()); System.setProperty("jnidispatch.path", lib.getAbsolutePath()); System.load(lib.getAbsolutePath()); jnidispatchPath = lib.getAbsolutePath(); LOG.log(DEBUG_JNA_LOAD_LEVEL, "Found jnidispatch at {0}", jnidispatchPath); // Attempt to delete immediately once jnidispatch is successfully // loaded. This avoids the complexity of trying to do so on "exit", // which point can vary under different circumstances (native // compilation, dynamically loaded modules, normal application, etc). if (isUnpacked(lib) && !Boolean.getBoolean("jnidispatch.preserve")) { deleteLibrary(lib); } } catch(IOException e) { throw new UnsatisfiedLinkError(e.getMessage()); } } /** Identify temporary files unpacked from classpath jar files. */ static boolean isUnpacked(File file) { return file.getName().startsWith(JNA_TMPLIB_PREFIX); } /** Attempt to extract a native library from the current resource path, * using the current thread context class loader. * @param name Base name of native library to extract. May also be an * absolute resource path (i.e. starts with "/"), in which case the * no transformations of the library name are performed. If only the base * name is given, the resource path is attempted both with and without * {@link Platform#RESOURCE_PREFIX}, after mapping the library name via * {@link NativeLibrary#mapSharedLibraryName(String)}. * @return File indicating extracted resource on disk * @throws IOException if resource not found */ public static File extractFromResourcePath(String name) throws IOException { return extractFromResourcePath(name, null); } /** Attempt to extract a native library from the resource path using the * given class loader. * @param name Base name of native library to extract. May also be an * absolute resource path (i.e. starts with "/"), in which case the * no transformations of the library name are performed. If only the base * name is given, the resource path is attempted both with and without * {@link Platform#RESOURCE_PREFIX}, after mapping the library name via * {@link NativeLibrary#mapSharedLibraryName(String)}. * @param loader Class loader to use to load resources * @return File indicating extracted resource on disk * @throws IOException if resource not found */ public static File extractFromResourcePath(String name, ClassLoader loader) throws IOException { final Level DEBUG = (DEBUG_LOAD || (DEBUG_JNA_LOAD && name.contains("jnidispatch"))) ? Level.INFO : Level.FINE; if (loader == null) { loader = Thread.currentThread().getContextClassLoader(); // Context class loader is not guaranteed to be set if (loader == null) { loader = Native.class.getClassLoader(); } } LOG.log(DEBUG, "Looking in classpath from {0} for {1}", new Object[]{loader, name}); String libname = name.startsWith("/") ? name : NativeLibrary.mapSharedLibraryName(name); String resourcePath = name.startsWith("/") ? name : Platform.RESOURCE_PREFIX + "/" + libname; if (resourcePath.startsWith("/")) { resourcePath = resourcePath.substring(1); } URL url = loader.getResource(resourcePath); if (url == null) { if (resourcePath.startsWith(Platform.RESOURCE_PREFIX)) { // Fallback for legacy darwin behaviour: darwin was in the past // special cased in that all architectures were mapped to the same // prefix and it was expected, that a fat binary was present at that // point, that contained all architectures. if(Platform.RESOURCE_PREFIX.startsWith("darwin")) { url = loader.getResource("darwin/" + resourcePath.substring(Platform.RESOURCE_PREFIX.length() + 1)); } if (url == null) { // If not found with the standard resource prefix, try without it url = loader.getResource(libname); } } else if (resourcePath.startsWith("com/sun/jna/" + Platform.RESOURCE_PREFIX + "/")) { // Fallback for legacy darwin behaviour: darwin was in the past // special cased in that all architectures were mapped to the same // prefix and it was expected, that a fat binary was present at that // point, that contained all architectures. if(Platform.RESOURCE_PREFIX.startsWith("com/sun/jna/darwin")) { url = loader.getResource("com/sun/jna/darwin" + resourcePath.substring(("com/sun/jna/" + Platform.RESOURCE_PREFIX).length() + 1)); } if (url == null) { // If not found with the standard resource prefix, try without it url = loader.getResource(libname); } } } if (url == null) { String path = System.getProperty("java.class.path"); if (loader instanceof URLClassLoader) { path = Arrays.asList(((URLClassLoader)loader).getURLs()).toString(); } throw new IOException("Native library (" + resourcePath + ") not found in resource path (" + path + ")"); } LOG.log(DEBUG, "Found library resource at {0}", url); File lib = null; if (url.getProtocol().toLowerCase().equals("file")) { try { lib = new File(new URI(url.toString())); } catch(URISyntaxException e) { lib = new File(url.getPath()); } LOG.log(DEBUG, "Looking in {0}", lib.getAbsolutePath()); if (!lib.exists()) { throw new IOException("File URL " + url + " could not be properly decoded"); } } else if (!Boolean.getBoolean("jna.nounpack")) { InputStream is = url.openStream(); if (is == null) { throw new IOException("Can't obtain InputStream for " + resourcePath); } FileOutputStream fos = null; try { // Suffix is required on windows, or library fails to load // Let Java pick the suffix, except on windows, to avoid // problems with Web Start. File dir = getTempDir(); lib = File.createTempFile(JNA_TMPLIB_PREFIX, Platform.isWindows()?".dll":null, dir); if (!Boolean.getBoolean("jnidispatch.preserve")) { lib.deleteOnExit(); } LOG.log(DEBUG, "Extracting library to {0}", lib.getAbsolutePath()); fos = new FileOutputStream(lib); int count; byte[] buf = new byte[1024]; while ((count = is.read(buf, 0, buf.length)) > 0) { fos.write(buf, 0, count); } } catch(IOException e) { throw new IOException("Failed to create temporary file for " + name + " library: " + e.getMessage()); } finally { try { is.close(); } catch(IOException e) { } if (fos != null) { try { fos.close(); } catch(IOException e) { } } } } return lib; } /** * Initialize field and method IDs for native methods of this class. * Returns the size of a native pointer. **/ private static native int sizeof(int type); private static native String getNativeVersion(); private static native String getAPIChecksum(); /** Retrieve last error set by the OS. This corresponds to * <code>GetLastError()</code> on Windows, and <code>errno</code> on * most other platforms. The value is preserved per-thread, but whether * the original value is per-thread depends on the underlying OS. * <p> * An alternative method of obtaining the last error result is * to declare your mapped method to throw {@link LastErrorException} * instead. If a method's signature includes a throw of {@link * LastErrorException}, the last error will be set to zero before the * native call and a {@link LastErrorException} will be raised if the last * error value is non-zero after the call, regardless of the actual * returned value from the native function.</p> */ public static native int getLastError(); /** Set the OS last error code. The value will be saved on a per-thread * basis. */ public static native void setLastError(int code); /** * Returns a synchronized (thread-safe) library backed by the specified * library. This wrapping will prevent simultaneous invocations of any * functions mapped to a given {@link NativeLibrary}. Note that the * native library may still be sensitive to being called from different * threads. * <p> * @param library the library to be "wrapped" in a synchronized library. * @return a synchronized view of the specified library. */ public static Library synchronizedLibrary(final Library library) { Class<?> cls = library.getClass(); if (!Proxy.isProxyClass(cls)) { throw new IllegalArgumentException("Library must be a proxy class"); } InvocationHandler ih = Proxy.getInvocationHandler(library); if (!(ih instanceof Library.Handler)) { throw new IllegalArgumentException("Unrecognized proxy handler: " + ih); } final Library.Handler handler = (Library.Handler)ih; InvocationHandler newHandler = new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { synchronized(handler.getNativeLibrary()) { return handler.invoke(library, method, args); } } }; return (Library)Proxy.newProxyInstance(cls.getClassLoader(), cls.getInterfaces(), newHandler); } /** If running web start, determine the location of a given native * library. This value may be used to properly set * <code>jna.library.path</code> so that JNA can load libraries identified * by the &lt;nativelib&gt; tag in the JNLP configuration file. Returns * <code>null</code> if the Web Start native library cache location can not * be determined. Note that the path returned may be different for any * given library name. * <p> * Use <code>System.getProperty("javawebstart.version")</code> to detect * whether your code is running under Web Start. * @throws UnsatisfiedLinkError if the library can't be found by the * Web Start class loader, which usually means it wasn't included as * a <code>&lt;nativelib&gt;</code> resource in the JNLP file. * @return null if unable to query the web start loader. */ public static String getWebStartLibraryPath(final String libName) { if (System.getProperty("javawebstart.version") == null) return null; try { final ClassLoader cl = Native.class.getClassLoader(); Method m = AccessController.doPrivileged(new PrivilegedAction<Method>() { @Override public Method run() { try { Method m = ClassLoader.class.getDeclaredMethod("findLibrary", new Class[] { String.class }); m.setAccessible(true); return m; } catch(Exception e) { return null; } } }); String libpath = (String)m.invoke(cl, new Object[] { libName }); if (libpath != null) { return new File(libpath).getParent(); } return null; } catch (Exception e) { return null; } } /** Perform cleanup of automatically unpacked native shared library. */ static void markTemporaryFile(File file) { // If we can't force an unload/delete, flag the file for later // deletion try { File marker = new File(file.getParentFile(), file.getName() + ".x"); marker.createNewFile(); } catch(IOException e) { e.printStackTrace(); } } /** Obtain a directory suitable for writing JNA-specific temporary files. Override with <code>jna.tmpdir</code> */ static File getTempDir() throws IOException { File jnatmp; String prop = System.getProperty("jna.tmpdir"); if (prop != null) { jnatmp = new File(prop); jnatmp.mkdirs(); } else { File tmp = new File(System.getProperty("java.io.tmpdir")); if(Platform.isMac()) { // https://developer.apple.com/library/archive/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/MacOSXDirectories/MacOSXDirectories.html jnatmp = new File(System.getProperty("user.home"), "Library/Caches/JNA/temp"); } else if (Platform.isLinux() || Platform.isSolaris() || Platform.isAIX() || Platform.isDragonFlyBSD() || Platform.isFreeBSD() || Platform.isNetBSD() || Platform.isOpenBSD() || Platform.iskFreeBSD()) { // https://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html // The XDG_CACHE_DIR is expected to be per user String xdgCacheEnvironment = System.getenv("XDG_CACHE_HOME"); File xdgCacheFile; if(xdgCacheEnvironment == null || xdgCacheEnvironment.trim().isEmpty()) { xdgCacheFile = new File(System.getProperty("user.home"), ".cache"); } else { xdgCacheFile = new File(xdgCacheEnvironment); } jnatmp = new File(xdgCacheFile, "JNA/temp"); } else { // Loading DLLs via System.load() under a directory with a unicode // name will fail on windows, so use a hash code of the user's // name in case the user's name contains non-ASCII characters jnatmp = new File(tmp, "jna-" + System.getProperty("user.name").hashCode()); } jnatmp.mkdirs(); if (!jnatmp.exists() || !jnatmp.canWrite()) { jnatmp = tmp; } } if (!jnatmp.exists()) { throw new IOException("JNA temporary directory '" + jnatmp + "' does not exist"); } if (!jnatmp.canWrite()) { throw new IOException("JNA temporary directory '" + jnatmp + "' is not writable"); } return jnatmp; } /** Remove all marked temporary files in the given directory. */ static void removeTemporaryFiles() throws IOException { File dir = getTempDir(); FilenameFilter filter = new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith(".x") && name.startsWith(JNA_TMPLIB_PREFIX); } }; File[] files = dir.listFiles(filter); for (int i=0;files != null && i < files.length;i++) { File marker = files[i]; String name = marker.getName(); name = name.substring(0, name.length()-2); File target = new File(marker.getParentFile(), name); if (!target.exists() || target.delete()) { marker.delete(); } } } /** * @param type The Java class for which the native size is to be determined * @param value an instance of said class (if available) * @return the native size of the given class, in bytes. * For use with arrays. */ public static int getNativeSize(Class<?> type, Object value) { if (type.isArray()) { int len = Array.getLength(value); if (len > 0) { Object o = Array.get(value, 0); return len * getNativeSize(type.getComponentType(), o); } // Don't process zero-length arrays throw new IllegalArgumentException("Arrays of length zero not allowed: " + type); } if (Structure.class.isAssignableFrom(type) && !Structure.ByReference.class.isAssignableFrom(type)) { return Structure.size((Class<Structure>) type, (Structure)value); } try { return getNativeSize(type); } catch(IllegalArgumentException e) { throw new IllegalArgumentException("The type \"" + type.getName() + "\" is not supported: " + e.getMessage()); } } /** * Returns the native size for a given Java class. Structures are * assumed to be <code>struct</code> pointers unless they implement * {@link Structure.ByValue}. * * @param cls The Java class * @return The native size for the class */ public static int getNativeSize(Class<?> cls) { if (NativeMapped.class.isAssignableFrom(cls)) { cls = NativeMappedConverter.getInstance(cls).nativeType(); } // boolean defaults to 32 bit integer if not otherwise mapped if (cls == boolean.class || cls == Boolean.class) return 4; if (cls == byte.class || cls == Byte.class) return 1; if (cls == short.class || cls == Short.class) return 2; if (cls == char.class || cls == Character.class) return WCHAR_SIZE; if (cls == int.class || cls == Integer.class) return 4; if (cls == long.class || cls == Long.class) return 8; if (cls == float.class || cls == Float.class) return 4; if (cls == double.class || cls == Double.class) return 8; if (Structure.class.isAssignableFrom(cls)) { if (Structure.ByValue.class.isAssignableFrom(cls)) { return Structure.size((Class<? extends Structure>) cls); } return POINTER_SIZE; } if (Pointer.class.isAssignableFrom(cls) || (Platform.HAS_BUFFERS && Buffers.isBuffer(cls)) || Callback.class.isAssignableFrom(cls) || String.class == cls || WString.class == cls) { return POINTER_SIZE; } throw new IllegalArgumentException("Native size for type \"" + cls.getName() + "\" is unknown"); } /** * @param cls The Java class * @return {@code true} whether the given class is supported as a native argument type. */ public static boolean isSupportedNativeType(Class<?> cls) { if (Structure.class.isAssignableFrom(cls)) { return true; } try { return getNativeSize(cls) != 0; } catch(IllegalArgumentException e) { return false; } } /** * Set the default handler invoked when a callback throws an uncaught * exception. If the given handler is <code>null</code>, the default * handler will be reinstated. * * @param eh The default handler */ public static void setCallbackExceptionHandler(UncaughtExceptionHandler eh) { callbackExceptionHandler = eh == null ? DEFAULT_HANDLER : eh; } /** @return the current handler for callback uncaught exceptions. */ public static UncaughtExceptionHandler getCallbackExceptionHandler() { return callbackExceptionHandler; } /** * When called from a class static initializer, maps all native methods * found within that class to native libraries via the JNA raw calling * interface. * @param libName library name to which functions should be bound */ public static void register(String libName) { register(findDirectMappedClass(getCallingClass()), libName); } /** * When called from a class static initializer, maps all native methods * found within that class to native libraries via the JNA raw calling * interface. * @param lib native library to which functions should be bound */ public static void register(NativeLibrary lib) { register(findDirectMappedClass(getCallingClass()), lib); } /** Find the nearest enclosing class with native methods. */ static Class<?> findDirectMappedClass(Class<?> cls) { Method[] methods = cls.getDeclaredMethods(); for (Method m : methods) { if ((m.getModifiers() & Modifier.NATIVE) != 0) { return cls; } } int idx = cls.getName().lastIndexOf("$"); if (idx != -1) { String name = cls.getName().substring(0, idx); try { return findDirectMappedClass(Class.forName(name, true, cls.getClassLoader())); } catch(ClassNotFoundException e) { // ignored } } throw new IllegalArgumentException("Can't determine class with native methods from the current context (" + cls + ")"); } /** Try to determine the class context in which a {@link #register(String)} call was made. */ static Class<?> getCallingClass() { Class<?>[] context = new SecurityManager() { @Override public Class<?>[] getClassContext() { return super.getClassContext(); } }.getClassContext(); if (context == null) { throw new IllegalStateException("The SecurityManager implementation on this platform is broken; you must explicitly provide the class to register"); } if (context.length < 4) { throw new IllegalStateException("This method must be called from the static initializer of a class"); } return context[3]; } /** * Set a thread initializer for the given callback. * @param cb The callback to invoke * @param initializer The thread initializer indicates desired thread configuration when the * given Callback is invoked on a native thread not yet attached to the VM. */ public static void setCallbackThreadInitializer(Callback cb, CallbackThreadInitializer initializer) { CallbackReference.setCallbackThreadInitializer(cb, initializer); } private static final Map<Class<?>, long[]> registeredClasses = new WeakHashMap<>(); private static final Map<Class<?>, NativeLibrary> registeredLibraries = new WeakHashMap<>(); private static void unregisterAll() { synchronized(registeredClasses) { for (Map.Entry<Class<?>, long[]> e : registeredClasses.entrySet()) { unregister(e.getKey(), e.getValue()); } registeredClasses.clear(); } } /** Remove all native mappings for the calling class. Should only be called if the class is no longer referenced and about to be garbage collected. */ public static void unregister() { unregister(findDirectMappedClass(getCallingClass())); } /** Remove all native mappings for the given class. Should only be called if the class is no longer referenced and about to be garbage collected. */ public static void unregister(Class<?> cls) { synchronized(registeredClasses) { long[] handles = registeredClasses.get(cls); if (handles != null) { unregister(cls, handles); registeredClasses.remove(cls); registeredLibraries.remove(cls); } } } /** * @param cls The type {@link Class} * @return whether the given class's native components are registered. */ public static boolean registered(Class<?> cls) { synchronized(registeredClasses) { return registeredClasses.containsKey(cls); } } /* Unregister the native methods for the given class. */ private static native void unregister(Class<?> cls, long[] handles); static String getSignature(Class<?> cls) { if (cls.isArray()) { return "[" + getSignature(cls.getComponentType()); } if (cls.isPrimitive()) { if (cls == void.class) return "V"; if (cls == boolean.class) return "Z"; if (cls == byte.class) return "B"; if (cls == short.class) return "S"; if (cls == char.class) return "C"; if (cls == int.class) return "I"; if (cls == long.class) return "J"; if (cls == float.class) return "F"; if (cls == double.class) return "D"; } return "L" + replace(".", "/", cls.getName()) + ";"; } // No String.replace available in 1.4 static String replace(String s1, String s2, String str) { StringBuilder buf = new StringBuilder(); while (true) { int idx = str.indexOf(s1); if (idx == -1) { buf.append(str); break; } else { buf.append(str.substring(0, idx)); buf.append(s2); str = str.substring(idx + s1.length()); } } return buf.toString(); } /** Indicates whether the callback has an initializer. */ static final int CB_HAS_INITIALIZER = 1; private static final int CVT_UNSUPPORTED = -1; private static final int CVT_DEFAULT = 0; private static final int CVT_POINTER = 1; private static final int CVT_STRING = 2; private static final int CVT_STRUCTURE = 3; private static final int CVT_STRUCTURE_BYVAL = 4; private static final int CVT_BUFFER = 5; private static final int CVT_ARRAY_BYTE = 6; private static final int CVT_ARRAY_SHORT = 7; private static final int CVT_ARRAY_CHAR = 8; private static final int CVT_ARRAY_INT = 9; private static final int CVT_ARRAY_LONG = 10; private static final int CVT_ARRAY_FLOAT = 11; private static final int CVT_ARRAY_DOUBLE = 12; private static final int CVT_ARRAY_BOOLEAN = 13; private static final int CVT_BOOLEAN = 14; private static final int CVT_CALLBACK = 15; private static final int CVT_FLOAT = 16; private static final int CVT_NATIVE_MAPPED = 17; private static final int CVT_NATIVE_MAPPED_STRING = 18; private static final int CVT_NATIVE_MAPPED_WSTRING = 19; private static final int CVT_WSTRING = 20; private static final int CVT_INTEGER_TYPE = 21; private static final int CVT_POINTER_TYPE = 22; private static final int CVT_TYPE_MAPPER = 23; private static final int CVT_TYPE_MAPPER_STRING = 24; private static final int CVT_TYPE_MAPPER_WSTRING = 25; private static final int CVT_OBJECT = 26; private static final int CVT_JNIENV = 27; private static final int CVT_SHORT = 28; private static final int CVT_BYTE = 29; private static int getConversion(Class<?> type, TypeMapper mapper, boolean allowObjects) { if (type == Void.class) type = void.class; if (mapper != null) { FromNativeConverter fromNative = mapper.getFromNativeConverter(type); ToNativeConverter toNative = mapper.getToNativeConverter(type); if (fromNative != null) { Class<?> nativeType = fromNative.nativeType(); if (nativeType == String.class) { return CVT_TYPE_MAPPER_STRING; } if (nativeType == WString.class) { return CVT_TYPE_MAPPER_WSTRING; } return CVT_TYPE_MAPPER; } if (toNative != null) { Class<?> nativeType = toNative.nativeType(); if (nativeType == String.class) { return CVT_TYPE_MAPPER_STRING; } if (nativeType == WString.class) { return CVT_TYPE_MAPPER_WSTRING; } return CVT_TYPE_MAPPER; } } if (Pointer.class.isAssignableFrom(type)) { return CVT_POINTER; } if (String.class == type) { return CVT_STRING; } if (WString.class.isAssignableFrom(type)) { return CVT_WSTRING; } if (Platform.HAS_BUFFERS && Buffers.isBuffer(type)) { return CVT_BUFFER; } if (Structure.class.isAssignableFrom(type)) { if (Structure.ByValue.class.isAssignableFrom(type)) { return CVT_STRUCTURE_BYVAL; } return CVT_STRUCTURE; } if (type.isArray()) { switch(type.getName().charAt(1)) { case 'Z': return CVT_ARRAY_BOOLEAN; case 'B': return CVT_ARRAY_BYTE; case 'S': return CVT_ARRAY_SHORT; case 'C': return CVT_ARRAY_CHAR; case 'I': return CVT_ARRAY_INT; case 'J': return CVT_ARRAY_LONG; case 'F': return CVT_ARRAY_FLOAT; case 'D': return CVT_ARRAY_DOUBLE; default: break; } } if (type.isPrimitive()) { return type == boolean.class ? CVT_BOOLEAN : CVT_DEFAULT; } if (Callback.class.isAssignableFrom(type)) { return CVT_CALLBACK; } if (IntegerType.class.isAssignableFrom(type)) { return CVT_INTEGER_TYPE; } if (PointerType.class.isAssignableFrom(type)) { return CVT_POINTER_TYPE; } if (NativeMapped.class.isAssignableFrom(type)) { Class<?> nativeType = NativeMappedConverter.getInstance(type).nativeType(); if (nativeType == String.class) { return CVT_NATIVE_MAPPED_STRING; } if (nativeType == WString.class) { return CVT_NATIVE_MAPPED_WSTRING; } return CVT_NATIVE_MAPPED; } if (JNIEnv.class == type) { return CVT_JNIENV; } return allowObjects ? CVT_OBJECT : CVT_UNSUPPORTED; } /** * When called from a class static initializer, maps all native methods * found within that class to native libraries via the JNA raw calling * interface. Uses the class loader of the given class to search for the * native library in the resource path if it is not found in the system * library load path or <code>jna.library.path</code>. * @param cls Class with native methods to register * @param libName name of or path to native library to which functions * should be bound */ public static void register(Class<?> cls, String libName) { NativeLibrary library = NativeLibrary.getInstance(libName, Collections.singletonMap(Library.OPTION_CLASSLOADER, cls.getClassLoader())); register(cls, library); } /** When called from a class static initializer, maps all native methods * found within that class to native libraries via the JNA raw calling * interface. * @param cls Class with native methods to register * @param lib library to which functions should be bound */ // TODO: derive options from annotations (per-class or per-method) // options: read parameter type mapping (long/native long), // method name, library name, call conv public static void register(Class<?> cls, NativeLibrary lib) { Method[] methods = cls.getDeclaredMethods(); List<Method> mlist = new ArrayList<>(); Map<String, ?> options = lib.getOptions(); TypeMapper mapper = (TypeMapper) options.get(Library.OPTION_TYPE_MAPPER); boolean allowObjects = Boolean.TRUE.equals(options.get(Library.OPTION_ALLOW_OBJECTS)); options = cacheOptions(cls, options, null); for (Method m : methods) { if ((m.getModifiers() & Modifier.NATIVE) != 0) { mlist.add(m); } } long[] handles = new long[mlist.size()]; for (int i=0;i < handles.length;i++) { Method method = mlist.get(i); String sig = "("; Class<?> rclass = method.getReturnType(); long rtype, closure_rtype; Class<?>[] ptypes = method.getParameterTypes(); long[] atypes = new long[ptypes.length]; long[] closure_atypes = new long[ptypes.length]; int[] cvt = new int[ptypes.length]; ToNativeConverter[] toNative = new ToNativeConverter[ptypes.length]; FromNativeConverter fromNative = null; int rcvt = getConversion(rclass, mapper, allowObjects); boolean throwLastError = false; switch (rcvt) { case CVT_UNSUPPORTED: throw new IllegalArgumentException(rclass + " is not a supported return type (in method " + method.getName() + " in " + cls + ")"); case CVT_TYPE_MAPPER: case CVT_TYPE_MAPPER_STRING: case CVT_TYPE_MAPPER_WSTRING: fromNative = mapper.getFromNativeConverter(rclass); // FFIType.get() always looks up the native type for any given // class, so if we actually have conversion into a Java // object, make sure we use the proper type information closure_rtype = FFIType.get(rclass.isPrimitive() ? rclass : Pointer.class).getPointer().peer; rtype = FFIType.get(fromNative.nativeType()).getPointer().peer; break; case CVT_NATIVE_MAPPED: case CVT_NATIVE_MAPPED_STRING: case CVT_NATIVE_MAPPED_WSTRING: case CVT_INTEGER_TYPE: case CVT_POINTER_TYPE: closure_rtype = FFIType.get(Pointer.class).getPointer().peer; rtype = FFIType.get(NativeMappedConverter.getInstance(rclass).nativeType()).getPointer().peer; break; case CVT_STRUCTURE: case CVT_OBJECT: closure_rtype = rtype = FFIType.get(Pointer.class).getPointer().peer; break; case CVT_STRUCTURE_BYVAL: closure_rtype = FFIType.get(Pointer.class).getPointer().peer; rtype = FFIType.get(rclass).getPointer().peer; break; default: closure_rtype = rtype = FFIType.get(rclass).getPointer().peer; } for (int t=0;t < ptypes.length;t++) { Class<?> type = ptypes[t]; sig += getSignature(type); int conversionType = getConversion(type, mapper, allowObjects); cvt[t] = conversionType; if (conversionType == CVT_UNSUPPORTED) { throw new IllegalArgumentException(type + " is not a supported argument type (in method " + method.getName() + " in " + cls + ")"); } if ((conversionType == CVT_NATIVE_MAPPED) || (conversionType == CVT_NATIVE_MAPPED_STRING) || (conversionType == CVT_NATIVE_MAPPED_WSTRING) || (conversionType == CVT_INTEGER_TYPE)) { type = NativeMappedConverter.getInstance(type).nativeType(); } else if ((conversionType == CVT_TYPE_MAPPER) || (conversionType == CVT_TYPE_MAPPER_STRING) || (conversionType == CVT_TYPE_MAPPER_WSTRING)) { toNative[t] = mapper.getToNativeConverter(type); } // Determine the type that will be passed to the native // function, as well as the type to be passed // from Java initially switch(conversionType) { case CVT_STRUCTURE_BYVAL: case CVT_INTEGER_TYPE: case CVT_POINTER_TYPE: case CVT_NATIVE_MAPPED: case CVT_NATIVE_MAPPED_STRING: case CVT_NATIVE_MAPPED_WSTRING: atypes[t] = FFIType.get(type).getPointer().peer; closure_atypes[t] = FFIType.get(Pointer.class).getPointer().peer; break; case CVT_TYPE_MAPPER: case CVT_TYPE_MAPPER_STRING: case CVT_TYPE_MAPPER_WSTRING: closure_atypes[t] = FFIType.get(type.isPrimitive() ? type : Pointer.class).getPointer().peer; atypes[t] = FFIType.get(toNative[t].nativeType()).getPointer().peer; break; case CVT_DEFAULT: closure_atypes[t] = atypes[t] = FFIType.get(type).getPointer().peer; break; default: closure_atypes[t] = atypes[t] = FFIType.get(Pointer.class).getPointer().peer; } } sig += ")"; sig += getSignature(rclass); Class<?>[] etypes = method.getExceptionTypes(); for (int e=0;e < etypes.length;e++) { if (LastErrorException.class.isAssignableFrom(etypes[e])) { throwLastError = true; break; } } Function f = lib.getFunction(method.getName(), method); try { handles[i] = registerMethod(cls, method.getName(), sig, cvt, closure_atypes, atypes, rcvt, closure_rtype, rtype, method, f.peer, f.getCallingConvention(), throwLastError, toNative, fromNative, f.encoding); } catch(NoSuchMethodError e) { throw new UnsatisfiedLinkError("No method " + method.getName() + " with signature " + sig + " in " + cls); } } synchronized(registeredClasses) { registeredClasses.put(cls, handles); registeredLibraries.put(cls, lib); } } /* Take note of options used for a given library mapping, to facilitate * looking them up later. */ private static Map<String, Object> cacheOptions(Class<?> cls, Map<String, ?> options, Object proxy) { Map<String, Object> libOptions = new HashMap<>(options); libOptions.put(_OPTION_ENCLOSING_LIBRARY, cls); typeOptions.put(cls, libOptions); if (proxy != null) { libraries.put(cls, new WeakReference<>(proxy)); } // If it's a direct mapping, AND implements a Library interface, // cache the library interface as well, so that any nested // classes get the appropriate associated options if (!cls.isInterface() && Library.class.isAssignableFrom(cls)) { Class<?> ifaces[] = cls.getInterfaces(); for (Class<?> ifc : ifaces) { if (Library.class.isAssignableFrom(ifc)) { cacheOptions(ifc, libOptions, proxy); break; } } } return libOptions; } private static native long registerMethod(Class<?> cls, String name, String signature, int[] conversions, long[] closure_arg_types, long[] arg_types, int rconversion, long closure_rtype, long rtype, Method method, long fptr, int callingConvention, boolean throwLastError, ToNativeConverter[] toNative, FromNativeConverter fromNative, String encoding); // Called from native code private static NativeMapped fromNative(Class<?> cls, Object value) { // NOTE: technically should be CallbackParameterContext return (NativeMapped)NativeMappedConverter.getInstance(cls).fromNative(value, new FromNativeContext(cls)); } // Called from native code private static NativeMapped fromNative(Method m, Object value) { Class<?> cls = m.getReturnType(); return (NativeMapped)NativeMappedConverter.getInstance(cls).fromNative(value, new MethodResultContext(cls, null, null, m)); } // Called from native code private static Class<?> nativeType(Class<?> cls) { return NativeMappedConverter.getInstance(cls).nativeType(); } // Called from native code private static Object toNative(ToNativeConverter cvt, Object o) { // NOTE: technically should be either CallbackResultContext or // FunctionParameterContext return cvt.toNative(o, new ToNativeContext()); } // Called from native code private static Object fromNative(FromNativeConverter cvt, Object o, Method m) { return cvt.fromNative(o, new MethodResultContext(m.getReturnType(), null, null, m)); } /** Create a new cif structure. */ public static native long ffi_prep_cif(int abi, int nargs, long ffi_return_type, long ffi_types); /** Make an FFI function call. */ public static native void ffi_call(long cif, long fptr, long resp, long args); public static native long ffi_prep_closure(long cif, ffi_callback cb); public static native void ffi_free_closure(long closure); /** Returns the size (calculated by libffi) of the given type. */ static native int initialize_ffi_type(long type_info); public interface ffi_callback { void invoke(long cif, long resp, long argp); } /** Prints JNA library details to the console. */ public static void main(String[] args) { final String DEFAULT_TITLE = "Java Native Access (JNA)"; final String DEFAULT_VERSION = VERSION; final String DEFAULT_BUILD = VERSION + " (package information missing)"; Package pkg = Native.class.getPackage(); String title = pkg != null ? pkg.getSpecificationTitle() : DEFAULT_TITLE; if (title == null) title = DEFAULT_TITLE; String version = pkg != null ? pkg.getSpecificationVersion() : DEFAULT_VERSION; if (version == null) version = DEFAULT_VERSION; title += " API Version " + version; System.out.println(title); version = pkg != null ? pkg.getImplementationVersion() : DEFAULT_BUILD; if (version == null) version = DEFAULT_BUILD; System.out.println("Version: " + version); System.out.println(" Native: " + getNativeVersion() + " (" + getAPIChecksum() + ")"); System.out.println(" Prefix: " + Platform.RESOURCE_PREFIX); } /** Free the given callback trampoline. */ static synchronized native void freeNativeCallback(long ptr); /** Use direct mapping for callback. */ static final int CB_OPTION_DIRECT = 1; /** Return a DLL-resident fucntion pointer. */ static final int CB_OPTION_IN_DLL = 2; /** Create a native trampoline to delegate execution to the Java callback. */ static synchronized native long createNativeCallback(Callback callback, Method method, Class<?>[] parameterTypes, Class<?> returnType, int callingConvention, int flags, String encoding); /** * Call the native function. * * @param function Present to prevent the GC to collect the Function object * prematurely * @param fp function pointer * @param callFlags calling convention to be used * @param args Arguments to pass to the native function * * @return The value returned by the target native function */ static native int invokeInt(Function function, long fp, int callFlags, Object[] args); /** * Call the native function. * * @param function Present to prevent the GC to collect the Function object * prematurely * @param fp function pointer * @param callFlags calling convention to be used * @param args Arguments to pass to the native function * * @return The value returned by the target native function */ static native long invokeLong(Function function, long fp, int callFlags, Object[] args); /** * Call the native function. * * @param function Present to prevent the GC to collect the Function object * prematurely * @param fp function pointer * @param callFlags calling convention to be used * @param args Arguments to pass to the native function */ static native void invokeVoid(Function function, long fp, int callFlags, Object[] args); /** * Call the native function. * * @param function Present to prevent the GC to collect the Function object * prematurely * @param fp function pointer * @param callFlags calling convention to be used * @param args Arguments to pass to the native function * * @return The value returned by the target native function */ static native float invokeFloat(Function function, long fp, int callFlags, Object[] args); /** * Call the native function. * * @param function Present to prevent the GC to collect the Function object * prematurely * @param fp function pointer * @param callFlags calling convention to be used * @param args Arguments to pass to the native function * * @return The value returned by the target native function */ static native double invokeDouble(Function function, long fp, int callFlags, Object[] args); /** * Call the native function. * * @param function Present to prevent the GC to collect the Function object * prematurely * @param fp function pointer * @param callFlags calling convention to be used * @param args Arguments to pass to the native function * * @return The value returned by the target native function */ static native long invokePointer(Function function, long fp, int callFlags, Object[] args); /** * Call the native function, returning a struct by value. * * @param function Present to prevent the GC to collect the Function object * prematurely * @param fp function pointer * @param callFlags calling convention to be used * @param args Arguments to pass to the native function * @param memory Memory for pre-allocated structure to hold the result * @param typeInfo Native type information for the Structure */ private static native void invokeStructure(Function function, long fp, int callFlags, Object[] args, long memory, long type_info); /** * Call the native function, returning a struct by value. * * @param function Present to prevent the GC to collect the Function object * prematurely * @param fp function pointer * @param callFlags calling convention to be used * @param args Arguments to pass to the native function * * @return the passed-in Structure */ static Structure invokeStructure(Function function, long fp, int callFlags, Object[] args, Structure s) { invokeStructure(function, fp, callFlags, args, s.getPointer().peer, s.getTypeInfo().peer); return s; } /** * Call the native function, returning a Java <code>Object</code>. * * @param function Present to prevent the GC to collect the Function object * prematurely * @param fp function pointer * @param callFlags calling convention to be used * @param args Arguments to pass to the native function * * @return The returned Java <code>Object</code> */ static native Object invokeObject(Function function, long fp, int callFlags, Object[] args); /** Open the requested native library with default options. */ static long open(String name) { return open(name, -1); } /** Open the requested native library with the specified platform-specific * otions. */ static native long open(String name, int flags); /** Close the given native library. */ static native void close(long handle); static native long findSymbol(long handle, String name); /* ============================================================================ The first argument of the following read, write, get<Type> and set<Type> function is present to protect it from the GC. Although on the native side only the baseaddr and offset are used to access the memory, the Pointer argument must not be removed. This is the usecase: -------------------------------------- Memory pointer = <init>; <do something and work on Memory> String result = pointer.getWideString(0) <do nothing more with Memory> -------------------------------------- In getWideString the pointer address is resolved and is passed to native. If the Memory object itself is not passed to native, the GC can collect the object at that point as it is not used anymore and the finalizers could run. The would introduce a race between the native call and the GC running the finalizers. The finalizers free the allocated memory, which results in a SEGFAULT. Passing only the Pointer object and loading the peer value via JNI was not implemented, as in microbenchmarks it showed large impact. Passing the Pointer object instead of the peer and offset value to getInt resulted in a performance of 70% of the unmodified source. ============================================================================ */ static native long indexOf(Pointer pointer, long baseaddr, long offset, byte value); static native void read(Pointer pointer, long baseaddr, long offset, byte[] buf, int index, int length); static native void read(Pointer pointer, long baseaddr, long offset, short[] buf, int index, int length); static native void read(Pointer pointer, long baseaddr, long offset, char[] buf, int index, int length); static native void read(Pointer pointer, long baseaddr, long offset, int[] buf, int index, int length); static native void read(Pointer pointer, long baseaddr, long offset, long[] buf, int index, int length); static native void read(Pointer pointer, long baseaddr, long offset, float[] buf, int index, int length); static native void read(Pointer pointer, long baseaddr, long offset, double[] buf, int index, int length); static native void write(Pointer pointer, long baseaddr, long offset, byte[] buf, int index, int length); static native void write(Pointer pointer, long baseaddr, long offset, short[] buf, int index, int length); static native void write(Pointer pointer, long baseaddr, long offset, char[] buf, int index, int length); static native void write(Pointer pointer, long baseaddr, long offset, int[] buf, int index, int length); static native void write(Pointer pointer, long baseaddr, long offset, long[] buf, int index, int length); static native void write(Pointer pointer, long baseaddr, long offset, float[] buf, int index, int length); static native void write(Pointer pointer, long baseaddr, long offset, double[] buf, int index, int length); static native byte getByte(Pointer pointer, long baseaddr, long offset); static native char getChar(Pointer pointer, long baseaddr, long offset); static native short getShort(Pointer pointer, long baseaddr, long offset); static native int getInt(Pointer pointer, long baseaddr, long offset); static native long getLong(Pointer pointer, long baseaddr, long offset); static native float getFloat(Pointer pointer, long baseaddr, long offset); static native double getDouble(Pointer pointer, long baseaddr, long offset); static Pointer getPointer(long addr) { long peer = _getPointer(addr); return peer == 0 ? null : new Pointer(peer); } private static native long _getPointer(long addr); static native String getWideString(Pointer pointer, long baseaddr, long offset); static String getString(Pointer pointer, long offset) { return getString(pointer, offset, getDefaultStringEncoding()); } static String getString(Pointer pointer, long offset, String encoding) { byte[] data = getStringBytes(pointer, pointer.peer, offset); if (encoding != null) { try { return new String(data, encoding); } catch(UnsupportedEncodingException e) { } } return new String(data); } static native byte[] getStringBytes(Pointer pointer, long baseaddr, long offset); static native void setMemory(Pointer pointer, long baseaddr, long offset, long length, byte value); static native void setByte(Pointer pointer, long baseaddr, long offset, byte value); static native void setShort(Pointer pointer, long baseaddr, long offset, short value); static native void setChar(Pointer pointer, long baseaddr, long offset, char value); static native void setInt(Pointer pointer, long baseaddr, long offset, int value); static native void setLong(Pointer pointer, long baseaddr, long offset, long value); static native void setFloat(Pointer pointer, long baseaddr, long offset, float value); static native void setDouble(Pointer pointer, long baseaddr, long offset, double value); static native void setPointer(Pointer pointer, long baseaddr, long offset, long value); static native void setWideString(Pointer pointer, long baseaddr, long offset, String value); static native ByteBuffer getDirectByteBuffer(Pointer pointer, long addr, long offset, long length); /** * Call the real native malloc * @param size size of the memory to be allocated * @return native address of the allocated memory block; zero if the * allocation failed. */ public static native long malloc(long size); /** * Call the real native free * @param ptr native address to be freed; a value of zero has no effect, * passing an already-freed pointer will cause pain. */ public static native void free(long ptr); private static final ThreadLocal<Memory> nativeThreadTerminationFlag = new ThreadLocal<Memory>() { @Override protected Memory initialValue() { Memory m = new Memory(4); m.clear(); return m; } }; private static final Map<Thread, Pointer> nativeThreads = Collections.synchronizedMap(new WeakHashMap<Thread, Pointer>()); /** <p>Indicate whether the JVM should detach the current native thread when the current Java code finishes execution. Generally this is used to avoid detaching native threads when it is known that a given thread will be relatively long-lived and call back to Java code frequently. </p> This call is lightweight; it only results in an additional JNI crossing if the desired state changes from its last setting. @throws IllegalStateException if {@link #detach detach(true)} is called on a thread created by the JVM. */ public static void detach(boolean detach) { Thread thread = Thread.currentThread(); if (detach) { // If a CallbackThreadInitializer was used to avoid detach, // we won't have put that thread into the nativeThreads map. // Performance is not as critical in that case, and since // detach is the default behavior, force an update of the detach // state every time. Clear the termination flag, since it's not // needed when the native thread is detached normally. nativeThreads.remove(thread); Pointer p = nativeThreadTerminationFlag.get(); setDetachState(true, 0); } else { if (!nativeThreads.containsKey(thread)) { Pointer p = nativeThreadTerminationFlag.get(); nativeThreads.put(thread, p); setDetachState(false, p.peer); } } } static Pointer getTerminationFlag(Thread t) { return nativeThreads.get(t); } private static native void setDetachState(boolean detach, long terminationFlag); private static class Buffers { static boolean isBuffer(Class<?> cls) { return Buffer.class.isAssignableFrom(cls); } } /** Provides separation of JAWT functionality for the sake of J2ME * ports which do not include AWT support. */ private static class AWT { static long getWindowID(Window w) throws HeadlessException { return getComponentID(w); } // Declaring the argument as Object rather than Component avoids class not // found errors on phoneME foundation profile. static long getComponentID(Object o) throws HeadlessException { if (GraphicsEnvironment.isHeadless()) { throw new HeadlessException("No native windows when headless"); } Component c = (Component)o; if (c.isLightweight()) { throw new IllegalArgumentException("Component must be heavyweight"); } if (!c.isDisplayable()) throw new IllegalStateException("Component must be displayable"); // On X11 VMs prior to 1.5, the window must be visible if (Platform.isX11() && System.getProperty("java.version").startsWith("1.4")) { if (!c.isVisible()) { throw new IllegalStateException("Component must be visible"); } } // By this point, we're certain that Toolkit.loadLibraries() has // been called, thus avoiding AWT/JAWT link errors // (see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6539705). return Native.getWindowHandle0(c); } } }
java-native-access/jna
src/com/sun/jna/Native.java
10
/* * Copyright (C) 2010 Google 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.google.gson.stream; import static com.google.gson.stream.JsonScope.DANGLING_NAME; import static com.google.gson.stream.JsonScope.EMPTY_ARRAY; import static com.google.gson.stream.JsonScope.EMPTY_DOCUMENT; import static com.google.gson.stream.JsonScope.EMPTY_OBJECT; import static com.google.gson.stream.JsonScope.NONEMPTY_ARRAY; import static com.google.gson.stream.JsonScope.NONEMPTY_DOCUMENT; import static com.google.gson.stream.JsonScope.NONEMPTY_OBJECT; import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.google.gson.FormattingStyle; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.Strictness; import java.io.Closeable; import java.io.Flushable; import java.io.IOException; import java.io.Writer; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Arrays; import java.util.Objects; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.regex.Pattern; /** * Writes a JSON (<a href="https://www.ietf.org/rfc/rfc8259.txt">RFC 8259</a>) encoded value to a * stream, one token at a time. The stream includes both literal values (strings, numbers, booleans * and nulls) as well as the begin and end delimiters of objects and arrays. * * <h2>Encoding JSON</h2> * * To encode your data as JSON, create a new {@code JsonWriter}. Call methods on the writer as you * walk the structure's contents, nesting arrays and objects as necessary: * * <ul> * <li>To write <strong>arrays</strong>, first call {@link #beginArray()}. Write each of the * array's elements with the appropriate {@link #value} methods or by nesting other arrays and * objects. Finally close the array using {@link #endArray()}. * <li>To write <strong>objects</strong>, first call {@link #beginObject()}. Write each of the * object's properties by alternating calls to {@link #name} with the property's value. Write * property values with the appropriate {@link #value} method or by nesting other objects or * arrays. Finally close the object using {@link #endObject()}. * </ul> * * <h2>Configuration</h2> * * The behavior of this writer can be customized with the following methods: * * <ul> * <li>{@link #setFormattingStyle(FormattingStyle)}, the default is {@link * FormattingStyle#COMPACT} * <li>{@link #setHtmlSafe(boolean)}, by default HTML characters are not escaped in the JSON * output * <li>{@link #setStrictness(Strictness)}, the default is {@link Strictness#LEGACY_STRICT} * <li>{@link #setSerializeNulls(boolean)}, by default {@code null} is serialized * </ul> * * The default configuration of {@code JsonWriter} instances used internally by the {@link Gson} * class differs, and can be adjusted with the various {@link GsonBuilder} methods. * * <h2>Example</h2> * * Suppose we'd like to encode a stream of messages such as the following: * * <pre>{@code * [ * { * "id": 912345678901, * "text": "How do I stream JSON in Java?", * "geo": null, * "user": { * "name": "json_newb", * "followers_count": 41 * } * }, * { * "id": 912345678902, * "text": "@json_newb just use JsonWriter!", * "geo": [50.454722, -104.606667], * "user": { * "name": "jesse", * "followers_count": 2 * } * } * ] * }</pre> * * This code encodes the above structure: * * <pre>{@code * public void writeJsonStream(OutputStream out, List<Message> messages) throws IOException { * JsonWriter writer = new JsonWriter(new OutputStreamWriter(out, "UTF-8")); * writer.setIndent(" "); * writeMessagesArray(writer, messages); * writer.close(); * } * * public void writeMessagesArray(JsonWriter writer, List<Message> messages) throws IOException { * writer.beginArray(); * for (Message message : messages) { * writeMessage(writer, message); * } * writer.endArray(); * } * * public void writeMessage(JsonWriter writer, Message message) throws IOException { * writer.beginObject(); * writer.name("id").value(message.getId()); * writer.name("text").value(message.getText()); * if (message.getGeo() != null) { * writer.name("geo"); * writeDoublesArray(writer, message.getGeo()); * } else { * writer.name("geo").nullValue(); * } * writer.name("user"); * writeUser(writer, message.getUser()); * writer.endObject(); * } * * public void writeUser(JsonWriter writer, User user) throws IOException { * writer.beginObject(); * writer.name("name").value(user.getName()); * writer.name("followers_count").value(user.getFollowersCount()); * writer.endObject(); * } * * public void writeDoublesArray(JsonWriter writer, List<Double> doubles) throws IOException { * writer.beginArray(); * for (Double value : doubles) { * writer.value(value); * } * writer.endArray(); * } * }</pre> * * <p>Each {@code JsonWriter} may be used to write a single JSON stream. Instances of this class are * not thread safe. Calls that would result in a malformed JSON string will fail with an {@link * IllegalStateException}. * * @author Jesse Wilson * @since 1.6 */ public class JsonWriter implements Closeable, Flushable { // Syntax as defined by https://datatracker.ietf.org/doc/html/rfc8259#section-6 private static final Pattern VALID_JSON_NUMBER_PATTERN = Pattern.compile("-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][-+]?[0-9]+)?"); /* * From RFC 8259, "All Unicode characters may be placed within the * quotation marks except for the characters that must be escaped: * quotation mark, reverse solidus, and the control characters * (U+0000 through U+001F)." * * We also escape '\u2028' and '\u2029', which JavaScript interprets as * newline characters. This prevents eval() from failing with a syntax * error. http://code.google.com/p/google-gson/issues/detail?id=341 */ private static final String[] REPLACEMENT_CHARS; private static final String[] HTML_SAFE_REPLACEMENT_CHARS; static { REPLACEMENT_CHARS = new String[128]; for (int i = 0; i <= 0x1f; i++) { REPLACEMENT_CHARS[i] = String.format("\\u%04x", i); } REPLACEMENT_CHARS['"'] = "\\\""; REPLACEMENT_CHARS['\\'] = "\\\\"; REPLACEMENT_CHARS['\t'] = "\\t"; REPLACEMENT_CHARS['\b'] = "\\b"; REPLACEMENT_CHARS['\n'] = "\\n"; REPLACEMENT_CHARS['\r'] = "\\r"; REPLACEMENT_CHARS['\f'] = "\\f"; HTML_SAFE_REPLACEMENT_CHARS = REPLACEMENT_CHARS.clone(); HTML_SAFE_REPLACEMENT_CHARS['<'] = "\\u003c"; HTML_SAFE_REPLACEMENT_CHARS['>'] = "\\u003e"; HTML_SAFE_REPLACEMENT_CHARS['&'] = "\\u0026"; HTML_SAFE_REPLACEMENT_CHARS['='] = "\\u003d"; HTML_SAFE_REPLACEMENT_CHARS['\''] = "\\u0027"; } /** The JSON output destination */ private final Writer out; private int[] stack = new int[32]; private int stackSize = 0; { push(EMPTY_DOCUMENT); } private FormattingStyle formattingStyle; // These fields cache data derived from the formatting style, to avoid having to // re-evaluate it every time something is written private String formattedColon; private String formattedComma; private boolean usesEmptyNewlineAndIndent; private Strictness strictness = Strictness.LEGACY_STRICT; private boolean htmlSafe; private String deferredName; private boolean serializeNulls = true; /** * Creates a new instance that writes a JSON-encoded stream to {@code out}. For best performance, * ensure {@link Writer} is buffered; wrapping in {@link java.io.BufferedWriter BufferedWriter} if * necessary. */ public JsonWriter(Writer out) { this.out = Objects.requireNonNull(out, "out == null"); setFormattingStyle(FormattingStyle.COMPACT); } /** * Sets the indentation string to be repeated for each level of indentation in the encoded * document. If {@code indent.isEmpty()} the encoded document will be compact. Otherwise the * encoded document will be more human-readable. * * <p>This is a convenience method which overwrites any previously {@linkplain * #setFormattingStyle(FormattingStyle) set formatting style} with either {@link * FormattingStyle#COMPACT} if the given indent string is empty, or {@link FormattingStyle#PRETTY} * with the given indent if not empty. * * @param indent a string containing only whitespace. */ public final void setIndent(String indent) { if (indent.isEmpty()) { setFormattingStyle(FormattingStyle.COMPACT); } else { setFormattingStyle(FormattingStyle.PRETTY.withIndent(indent)); } } /** * Sets the formatting style to be used in the encoded document. * * <p>The formatting style specifies for example the indentation string to be repeated for each * level of indentation, or the newline style, to accommodate various OS styles. * * @param formattingStyle the formatting style to use, must not be {@code null}. * @since $next-version$ */ public final void setFormattingStyle(FormattingStyle formattingStyle) { this.formattingStyle = Objects.requireNonNull(formattingStyle); this.formattedComma = ","; if (this.formattingStyle.usesSpaceAfterSeparators()) { this.formattedColon = ": "; // Only add space if no newline is written if (this.formattingStyle.getNewline().isEmpty()) { this.formattedComma = ", "; } } else { this.formattedColon = ":"; } this.usesEmptyNewlineAndIndent = this.formattingStyle.getNewline().isEmpty() && this.formattingStyle.getIndent().isEmpty(); } /** * Returns the pretty printing style used by this writer. * * @return the {@code FormattingStyle} that will be used. * @since $next-version$ */ public final FormattingStyle getFormattingStyle() { return formattingStyle; } /** * Sets the strictness of this writer. * * @deprecated Please use {@link #setStrictness(Strictness)} instead. {@code * JsonWriter.setLenient(true)} should be replaced by {@code * JsonWriter.setStrictness(Strictness.LENIENT)} and {@code JsonWriter.setLenient(false)} * should be replaced by {@code JsonWriter.setStrictness(Strictness.LEGACY_STRICT)}.<br> * However, if you used {@code setLenient(false)} before, you might prefer {@link * Strictness#STRICT} now instead. * @param lenient whether this writer should be lenient. If true, the strictness is set to {@link * Strictness#LENIENT}. If false, the strictness is set to {@link Strictness#LEGACY_STRICT}. * @see #setStrictness(Strictness) */ @Deprecated // Don't specify @InlineMe, so caller with `setLenient(false)` becomes aware of new // Strictness.STRICT @SuppressWarnings("InlineMeSuggester") public final void setLenient(boolean lenient) { setStrictness(lenient ? Strictness.LENIENT : Strictness.LEGACY_STRICT); } /** * Returns true if the {@link Strictness} of this writer is equal to {@link Strictness#LENIENT}. * * @see #getStrictness() */ public boolean isLenient() { return strictness == Strictness.LENIENT; } /** * Configures how strict this writer is with regard to the syntax rules specified in <a * href="https://www.ietf.org/rfc/rfc8259.txt">RFC 8259</a>. By default, {@link * Strictness#LEGACY_STRICT} is used. * * <dl> * <dt>{@link Strictness#STRICT} &amp; {@link Strictness#LEGACY_STRICT} * <dd>The behavior of these is currently identical. In these strictness modes, the writer only * writes JSON in accordance with RFC 8259. * <dt>{@link Strictness#LENIENT} * <dd>This mode relaxes the behavior of the writer to allow the writing of {@link * Double#isNaN() NaNs} and {@link Double#isInfinite() infinities}. It also allows writing * multiple top level values. * </dl> * * @param strictness the new strictness of this writer. May not be {@code null}. * @see #getStrictness() * @since $next-version$ */ public final void setStrictness(Strictness strictness) { this.strictness = Objects.requireNonNull(strictness); } /** * Returns the {@linkplain Strictness strictness} of this writer. * * @see #setStrictness(Strictness) * @since $next-version$ */ public final Strictness getStrictness() { return strictness; } /** * Configures this writer to emit JSON that's safe for direct inclusion in HTML and XML documents. * This escapes the HTML characters {@code <}, {@code >}, {@code &}, {@code =} and {@code '} * before writing them to the stream. Without this setting, your XML/HTML encoder should replace * these characters with the corresponding escape sequences. */ public final void setHtmlSafe(boolean htmlSafe) { this.htmlSafe = htmlSafe; } /** * Returns true if this writer writes JSON that's safe for inclusion in HTML and XML documents. */ public final boolean isHtmlSafe() { return htmlSafe; } /** * Sets whether object members are serialized when their value is null. This has no impact on * array elements. The default is true. */ public final void setSerializeNulls(boolean serializeNulls) { this.serializeNulls = serializeNulls; } /** * Returns true if object members are serialized when their value is null. This has no impact on * array elements. The default is true. */ public final boolean getSerializeNulls() { return serializeNulls; } /** * Begins encoding a new array. Each call to this method must be paired with a call to {@link * #endArray}. * * @return this writer. */ @CanIgnoreReturnValue public JsonWriter beginArray() throws IOException { writeDeferredName(); return openScope(EMPTY_ARRAY, '['); } /** * Ends encoding the current array. * * @return this writer. */ @CanIgnoreReturnValue public JsonWriter endArray() throws IOException { return closeScope(EMPTY_ARRAY, NONEMPTY_ARRAY, ']'); } /** * Begins encoding a new object. Each call to this method must be paired with a call to {@link * #endObject}. * * @return this writer. */ @CanIgnoreReturnValue public JsonWriter beginObject() throws IOException { writeDeferredName(); return openScope(EMPTY_OBJECT, '{'); } /** * Ends encoding the current object. * * @return this writer. */ @CanIgnoreReturnValue public JsonWriter endObject() throws IOException { return closeScope(EMPTY_OBJECT, NONEMPTY_OBJECT, '}'); } /** Enters a new scope by appending any necessary whitespace and the given bracket. */ @CanIgnoreReturnValue private JsonWriter openScope(int empty, char openBracket) throws IOException { beforeValue(); push(empty); out.write(openBracket); return this; } /** Closes the current scope by appending any necessary whitespace and the given bracket. */ @CanIgnoreReturnValue private JsonWriter closeScope(int empty, int nonempty, char closeBracket) throws IOException { int context = peek(); if (context != nonempty && context != empty) { throw new IllegalStateException("Nesting problem."); } if (deferredName != null) { throw new IllegalStateException("Dangling name: " + deferredName); } stackSize--; if (context == nonempty) { newline(); } out.write(closeBracket); return this; } private void push(int newTop) { if (stackSize == stack.length) { stack = Arrays.copyOf(stack, stackSize * 2); } stack[stackSize++] = newTop; } /** Returns the value on the top of the stack. */ private int peek() { if (stackSize == 0) { throw new IllegalStateException("JsonWriter is closed."); } return stack[stackSize - 1]; } /** Replace the value on the top of the stack with the given value. */ private void replaceTop(int topOfStack) { stack[stackSize - 1] = topOfStack; } /** * Encodes the property name. * * @param name the name of the forthcoming value. May not be {@code null}. * @return this writer. */ @CanIgnoreReturnValue public JsonWriter name(String name) throws IOException { Objects.requireNonNull(name, "name == null"); if (deferredName != null) { throw new IllegalStateException("Already wrote a name, expecting a value."); } int context = peek(); if (context != EMPTY_OBJECT && context != NONEMPTY_OBJECT) { throw new IllegalStateException("Please begin an object before writing a name."); } deferredName = name; return this; } private void writeDeferredName() throws IOException { if (deferredName != null) { beforeName(); string(deferredName); deferredName = null; } } /** * Encodes {@code value}. * * @param value the literal string value, or null to encode a null literal. * @return this writer. */ @CanIgnoreReturnValue public JsonWriter value(String value) throws IOException { if (value == null) { return nullValue(); } writeDeferredName(); beforeValue(); string(value); return this; } /** * Encodes {@code value}. * * @return this writer. */ @CanIgnoreReturnValue public JsonWriter value(boolean value) throws IOException { writeDeferredName(); beforeValue(); out.write(value ? "true" : "false"); return this; } /** * Encodes {@code value}. * * @return this writer. * @since 2.7 */ @CanIgnoreReturnValue public JsonWriter value(Boolean value) throws IOException { if (value == null) { return nullValue(); } writeDeferredName(); beforeValue(); out.write(value ? "true" : "false"); return this; } /** * Encodes {@code value}. * * @param value a finite value, or if {@link #setStrictness(Strictness) lenient}, also {@link * Float#isNaN() NaN} or {@link Float#isInfinite() infinity}. * @return this writer. * @throws IllegalArgumentException if the value is NaN or Infinity and this writer is not {@link * #setStrictness(Strictness) lenient}. * @since 2.9.1 */ @CanIgnoreReturnValue public JsonWriter value(float value) throws IOException { writeDeferredName(); if (strictness != Strictness.LENIENT && (Float.isNaN(value) || Float.isInfinite(value))) { throw new IllegalArgumentException("Numeric values must be finite, but was " + value); } beforeValue(); out.append(Float.toString(value)); return this; } /** * Encodes {@code value}. * * @param value a finite value, or if {@link #setStrictness(Strictness) lenient}, also {@link * Double#isNaN() NaN} or {@link Double#isInfinite() infinity}. * @return this writer. * @throws IllegalArgumentException if the value is NaN or Infinity and this writer is not {@link * #setStrictness(Strictness) lenient}. */ @CanIgnoreReturnValue public JsonWriter value(double value) throws IOException { writeDeferredName(); if (strictness != Strictness.LENIENT && (Double.isNaN(value) || Double.isInfinite(value))) { throw new IllegalArgumentException("Numeric values must be finite, but was " + value); } beforeValue(); out.append(Double.toString(value)); return this; } /** * Encodes {@code value}. * * @return this writer. */ @CanIgnoreReturnValue public JsonWriter value(long value) throws IOException { writeDeferredName(); beforeValue(); out.write(Long.toString(value)); return this; } /** * Encodes {@code value}. The value is written by directly writing the {@link Number#toString()} * result to JSON. Implementations must make sure that the result represents a valid JSON number. * * @param value a finite value, or if {@link #setStrictness(Strictness) lenient}, also {@link * Double#isNaN() NaN} or {@link Double#isInfinite() infinity}. * @return this writer. * @throws IllegalArgumentException if the value is NaN or Infinity and this writer is not {@link * #setStrictness(Strictness) lenient}; or if the {@code toString()} result is not a valid * JSON number. */ @CanIgnoreReturnValue public JsonWriter value(Number value) throws IOException { if (value == null) { return nullValue(); } writeDeferredName(); String string = value.toString(); if (string.equals("-Infinity") || string.equals("Infinity") || string.equals("NaN")) { if (strictness != Strictness.LENIENT) { throw new IllegalArgumentException("Numeric values must be finite, but was " + string); } } else { Class<? extends Number> numberClass = value.getClass(); // Validate that string is valid before writing it directly to JSON output if (!isTrustedNumberType(numberClass) && !VALID_JSON_NUMBER_PATTERN.matcher(string).matches()) { throw new IllegalArgumentException( "String created by " + numberClass + " is not a valid JSON number: " + string); } } beforeValue(); out.append(string); return this; } /** * Encodes {@code null}. * * @return this writer. */ @CanIgnoreReturnValue public JsonWriter nullValue() throws IOException { if (deferredName != null) { if (serializeNulls) { writeDeferredName(); } else { deferredName = null; return this; // skip the name and the value } } beforeValue(); out.write("null"); return this; } /** * Writes {@code value} directly to the writer without quoting or escaping. This might not be * supported by all implementations, if not supported an {@code UnsupportedOperationException} is * thrown. * * @param value the literal string value, or null to encode a null literal. * @return this writer. * @throws UnsupportedOperationException if this writer does not support writing raw JSON values. * @since 2.4 */ @CanIgnoreReturnValue public JsonWriter jsonValue(String value) throws IOException { if (value == null) { return nullValue(); } writeDeferredName(); beforeValue(); out.append(value); return this; } /** * Ensures all buffered data is written to the underlying {@link Writer} and flushes that writer. */ @Override public void flush() throws IOException { if (stackSize == 0) { throw new IllegalStateException("JsonWriter is closed."); } out.flush(); } /** * Flushes and closes this writer and the underlying {@link Writer}. * * @throws IOException if the JSON document is incomplete. */ @Override public void close() throws IOException { out.close(); int size = stackSize; if (size > 1 || (size == 1 && stack[size - 1] != NONEMPTY_DOCUMENT)) { throw new IOException("Incomplete document"); } stackSize = 0; } /** * Returns whether the {@code toString()} of {@code c} can be trusted to return a valid JSON * number. */ private static boolean isTrustedNumberType(Class<? extends Number> c) { // Note: Don't consider LazilyParsedNumber trusted because it could contain // an arbitrary malformed string return c == Integer.class || c == Long.class || c == Double.class || c == Float.class || c == Byte.class || c == Short.class || c == BigDecimal.class || c == BigInteger.class || c == AtomicInteger.class || c == AtomicLong.class; } private void string(String value) throws IOException { String[] replacements = htmlSafe ? HTML_SAFE_REPLACEMENT_CHARS : REPLACEMENT_CHARS; out.write('\"'); int last = 0; int length = value.length(); for (int i = 0; i < length; i++) { char c = value.charAt(i); String replacement; if (c < 128) { replacement = replacements[c]; if (replacement == null) { continue; } } else if (c == '\u2028') { replacement = "\\u2028"; } else if (c == '\u2029') { replacement = "\\u2029"; } else { continue; } if (last < i) { out.write(value, last, i - last); } out.write(replacement); last = i + 1; } if (last < length) { out.write(value, last, length - last); } out.write('\"'); } private void newline() throws IOException { if (usesEmptyNewlineAndIndent) { return; } out.write(formattingStyle.getNewline()); for (int i = 1, size = stackSize; i < size; i++) { out.write(formattingStyle.getIndent()); } } /** * Inserts any necessary separators and whitespace before a name. Also adjusts the stack to expect * the name's value. */ private void beforeName() throws IOException { int context = peek(); if (context == NONEMPTY_OBJECT) { // first in object out.write(formattedComma); } else if (context != EMPTY_OBJECT) { // not in an object! throw new IllegalStateException("Nesting problem."); } newline(); replaceTop(DANGLING_NAME); } /** * Inserts any necessary separators and whitespace before a literal value, inline array, or inline * object. Also adjusts the stack to expect either a closing bracket or another element. */ @SuppressWarnings("fallthrough") private void beforeValue() throws IOException { switch (peek()) { case NONEMPTY_DOCUMENT: if (strictness != Strictness.LENIENT) { throw new IllegalStateException("JSON must have only one top-level value."); } // fall-through case EMPTY_DOCUMENT: // first in document replaceTop(NONEMPTY_DOCUMENT); break; case EMPTY_ARRAY: // first in array replaceTop(NONEMPTY_ARRAY); newline(); break; case NONEMPTY_ARRAY: // another in array out.append(formattedComma); newline(); break; case DANGLING_NAME: // value for name out.append(formattedColon); replaceTop(NONEMPTY_OBJECT); break; default: throw new IllegalStateException("Nesting problem."); } } }
google/gson
gson/src/main/java/com/google/gson/stream/JsonWriter.java
11
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.hexagonal.sampledata; import com.iluwatar.hexagonal.banking.InMemoryBank; import com.iluwatar.hexagonal.domain.LotteryConstants; import com.iluwatar.hexagonal.domain.LotteryNumbers; import com.iluwatar.hexagonal.domain.LotteryService; import com.iluwatar.hexagonal.domain.LotteryTicket; import com.iluwatar.hexagonal.domain.LotteryTicketId; import com.iluwatar.hexagonal.domain.PlayerDetails; import java.security.SecureRandom; import java.util.AbstractMap.SimpleEntry; import java.util.List; import java.util.stream.Collectors; /** * Utilities for creating sample lottery tickets. */ public class SampleData { private static final List<PlayerDetails> PLAYERS; private static final SecureRandom RANDOM = new SecureRandom(); static { PLAYERS = List.of( new PlayerDetails("john@google.com", "312-342", "+3242434242"), new PlayerDetails("mary@google.com", "234-987", "+23452346"), new PlayerDetails("steve@google.com", "833-836", "+63457543"), new PlayerDetails("wayne@google.com", "319-826", "+24626"), new PlayerDetails("johnie@google.com", "983-322", "+3635635"), new PlayerDetails("andy@google.com", "934-734", "+0898245"), new PlayerDetails("richard@google.com", "536-738", "+09845325"), new PlayerDetails("kevin@google.com", "453-936", "+2423532"), new PlayerDetails("arnold@google.com", "114-988", "+5646346524"), new PlayerDetails("ian@google.com", "663-765", "+928394235"), new PlayerDetails("robin@google.com", "334-763", "+35448"), new PlayerDetails("ted@google.com", "735-964", "+98752345"), new PlayerDetails("larry@google.com", "734-853", "+043842423"), new PlayerDetails("calvin@google.com", "334-746", "+73294135"), new PlayerDetails("jacob@google.com", "444-766", "+358042354"), new PlayerDetails("edwin@google.com", "895-345", "+9752435"), new PlayerDetails("mary@google.com", "760-009", "+34203542"), new PlayerDetails("lolita@google.com", "425-907", "+9872342"), new PlayerDetails("bruno@google.com", "023-638", "+673824122"), new PlayerDetails("peter@google.com", "335-886", "+5432503945"), new PlayerDetails("warren@google.com", "225-946", "+9872341324"), new PlayerDetails("monica@google.com", "265-748", "+134124"), new PlayerDetails("ollie@google.com", "190-045", "+34453452"), new PlayerDetails("yngwie@google.com", "241-465", "+9897641231"), new PlayerDetails("lars@google.com", "746-936", "+42345298345"), new PlayerDetails("bobbie@google.com", "946-384", "+79831742"), new PlayerDetails("tyron@google.com", "310-992", "+0498837412"), new PlayerDetails("tyrell@google.com", "032-045", "+67834134"), new PlayerDetails("nadja@google.com", "000-346", "+498723"), new PlayerDetails("wendy@google.com", "994-989", "+987324454"), new PlayerDetails("luke@google.com", "546-634", "+987642435"), new PlayerDetails("bjorn@google.com", "342-874", "+7834325"), new PlayerDetails("lisa@google.com", "024-653", "+980742154"), new PlayerDetails("anton@google.com", "834-935", "+876423145"), new PlayerDetails("bruce@google.com", "284-936", "+09843212345"), new PlayerDetails("ray@google.com", "843-073", "+678324123"), new PlayerDetails("ron@google.com", "637-738", "+09842354"), new PlayerDetails("xavier@google.com", "143-947", "+375245"), new PlayerDetails("harriet@google.com", "842-404", "+131243252") ); var wireTransfers = new InMemoryBank(); PLAYERS.stream() .map(PlayerDetails::bankAccount) .map(e -> new SimpleEntry<>(e, RANDOM.nextInt(LotteryConstants.PLAYER_MAX_BALANCE))) .collect(Collectors.toMap(SimpleEntry::getKey, SimpleEntry::getValue)) .forEach(wireTransfers::setFunds); } /** * Inserts lottery tickets into the database based on the sample data. */ public static void submitTickets(LotteryService lotteryService, int numTickets) { for (var i = 0; i < numTickets; i++) { var randomPlayerDetails = getRandomPlayerDetails(); var lotteryNumbers = LotteryNumbers.createRandom(); var lotteryTicketId = new LotteryTicketId(); var ticket = new LotteryTicket(lotteryTicketId, randomPlayerDetails, lotteryNumbers); lotteryService.submitTicket(ticket); } } private static PlayerDetails getRandomPlayerDetails() { return PLAYERS.get(RANDOM.nextInt(PLAYERS.size())); } }
iluwatar/java-design-patterns
hexagonal/src/main/java/com/iluwatar/hexagonal/sampledata/SampleData.java
12
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.react.bridge; import static com.facebook.infer.annotation.ThreadConfined.UI; import static com.facebook.systrace.Systrace.TRACE_TAG_REACT_JAVA_BRIDGE; import android.content.res.AssetManager; import androidx.annotation.Nullable; import com.facebook.common.logging.FLog; import com.facebook.infer.annotation.Assertions; import com.facebook.infer.annotation.ThreadConfined; import com.facebook.jni.HybridData; import com.facebook.proguard.annotations.DoNotStrip; import com.facebook.proguard.annotations.DoNotStripAny; import com.facebook.react.bridge.queue.MessageQueueThread; import com.facebook.react.bridge.queue.QueueThreadExceptionHandler; import com.facebook.react.bridge.queue.ReactQueueConfiguration; import com.facebook.react.bridge.queue.ReactQueueConfigurationImpl; import com.facebook.react.bridge.queue.ReactQueueConfigurationSpec; import com.facebook.react.common.ReactConstants; import com.facebook.react.common.annotations.VisibleForTesting; import com.facebook.react.config.ReactFeatureFlags; import com.facebook.react.internal.turbomodule.core.interfaces.TurboModuleRegistry; import com.facebook.react.module.annotations.ReactModule; import com.facebook.react.turbomodule.core.CallInvokerHolderImpl; import com.facebook.react.turbomodule.core.NativeMethodCallInvokerHolderImpl; import com.facebook.systrace.Systrace; import com.facebook.systrace.TraceListener; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Collection; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicInteger; /** * This provides an implementation of the public CatalystInstance instance. It is public because it * is built by XReactInstanceManager which is in a different package. */ @DoNotStrip public class CatalystInstanceImpl implements CatalystInstance { static { ReactBridge.staticInit(); } private static final AtomicInteger sNextInstanceIdForTrace = new AtomicInteger(1); public static class PendingJSCall { public String mModule; public String mMethod; public @Nullable NativeArray mArguments; public PendingJSCall(String module, String method, @Nullable NativeArray arguments) { mModule = module; mMethod = method; mArguments = arguments; } void call(CatalystInstanceImpl catalystInstance) { NativeArray arguments = mArguments != null ? mArguments : new WritableNativeArray(); catalystInstance.jniCallJSFunction(mModule, mMethod, arguments); } public String toString() { return mModule + "." + mMethod + "(" + (mArguments == null ? "" : mArguments.toString()) + ")"; } } // Access from any thread private final ReactQueueConfigurationImpl mReactQueueConfiguration; private final CopyOnWriteArrayList<NotThreadSafeBridgeIdleDebugListener> mBridgeIdleListeners; private final AtomicInteger mPendingJSCalls = new AtomicInteger(0); private final String mJsPendingCallsTitleForTrace = "pending_js_calls_instance" + sNextInstanceIdForTrace.getAndIncrement(); private volatile boolean mDestroyed = false; private final TraceListener mTraceListener; private final JavaScriptModuleRegistry mJSModuleRegistry; private final JSBundleLoader mJSBundleLoader; private final ArrayList<PendingJSCall> mJSCallsPendingInit = new ArrayList<PendingJSCall>(); private final Object mJSCallsPendingInitLock = new Object(); private final NativeModuleRegistry mNativeModuleRegistry; private final JSExceptionHandler mJSExceptionHandler; private final MessageQueueThread mNativeModulesQueueThread; private boolean mInitialized = false; private volatile boolean mAcceptCalls = false; private boolean mJSBundleHasLoaded; private @Nullable String mSourceURL; private JavaScriptContextHolder mJavaScriptContextHolder; private @Nullable TurboModuleRegistry mTurboModuleRegistry; private @Nullable UIManager mFabricUIManager; // C++ parts private final HybridData mHybridData; private static native HybridData initHybrid(); public native CallInvokerHolderImpl getJSCallInvokerHolder(); public native NativeMethodCallInvokerHolderImpl getNativeMethodCallInvokerHolder(); private CatalystInstanceImpl( final ReactQueueConfigurationSpec reactQueueConfigurationSpec, final JavaScriptExecutor jsExecutor, final NativeModuleRegistry nativeModuleRegistry, final JSBundleLoader jsBundleLoader, JSExceptionHandler jSExceptionHandler, @Nullable ReactInstanceManagerInspectorTarget inspectorTarget) { FLog.d(ReactConstants.TAG, "Initializing React Xplat Bridge."); Systrace.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "createCatalystInstanceImpl"); mHybridData = initHybrid(); mReactQueueConfiguration = ReactQueueConfigurationImpl.create( reactQueueConfigurationSpec, new NativeExceptionHandler()); mBridgeIdleListeners = new CopyOnWriteArrayList<>(); mNativeModuleRegistry = nativeModuleRegistry; mJSModuleRegistry = new JavaScriptModuleRegistry(); mJSBundleLoader = jsBundleLoader; mJSExceptionHandler = jSExceptionHandler; mNativeModulesQueueThread = mReactQueueConfiguration.getNativeModulesQueueThread(); mTraceListener = new JSProfilerTraceListener(this); Systrace.endSection(TRACE_TAG_REACT_JAVA_BRIDGE); FLog.d(ReactConstants.TAG, "Initializing React Xplat Bridge before initializeBridge"); Systrace.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "initializeCxxBridge"); initializeBridge( new InstanceCallback(this), jsExecutor, mReactQueueConfiguration.getJSQueueThread(), mNativeModulesQueueThread, mNativeModuleRegistry.getJavaModules(this), mNativeModuleRegistry.getCxxModules(), inspectorTarget); FLog.d(ReactConstants.TAG, "Initializing React Xplat Bridge after initializeBridge"); Systrace.endSection(TRACE_TAG_REACT_JAVA_BRIDGE); mJavaScriptContextHolder = new JavaScriptContextHolder(getJavaScriptContext()); } @DoNotStripAny private static class InstanceCallback { // We do this so the callback doesn't keep the CatalystInstanceImpl alive. // In this case, the callback is held in C++ code, so the GC can't see it // and determine there's an inaccessible cycle. private final WeakReference<CatalystInstanceImpl> mOuter; InstanceCallback(CatalystInstanceImpl outer) { mOuter = new WeakReference<>(outer); } public void onBatchComplete() { CatalystInstanceImpl impl = mOuter.get(); if (impl != null) { impl.mNativeModulesQueueThread.runOnQueue( () -> { impl.mNativeModuleRegistry.onBatchComplete(); }); } } public void incrementPendingJSCalls() { CatalystInstanceImpl impl = mOuter.get(); if (impl != null) { impl.incrementPendingJSCalls(); } } public void decrementPendingJSCalls() { CatalystInstanceImpl impl = mOuter.get(); if (impl != null) { impl.decrementPendingJSCalls(); } } } /** * This method and the native below permits a CatalystInstance to extend the known Native modules. * This registry contains only the new modules to load. The registry {@code mNativeModuleRegistry} * updates internally to contain all the new modules, and generates the new registry for * extracting just the new collections. */ @Override public void extendNativeModules(NativeModuleRegistry modules) { // Extend the Java-visible registry of modules mNativeModuleRegistry.registerModules(modules); Collection<JavaModuleWrapper> javaModules = modules.getJavaModules(this); Collection<ModuleHolder> cxxModules = modules.getCxxModules(); // Extend the Cxx-visible registry of modules wrapped in appropriate interfaces jniExtendNativeModules(javaModules, cxxModules); } private native void jniExtendNativeModules( Collection<JavaModuleWrapper> javaModules, Collection<ModuleHolder> cxxModules); private native void initializeBridge( InstanceCallback callback, JavaScriptExecutor jsExecutor, MessageQueueThread jsQueue, MessageQueueThread moduleQueue, Collection<JavaModuleWrapper> javaModules, Collection<ModuleHolder> cxxModules, @Nullable ReactInstanceManagerInspectorTarget inspectorTarget); @Override public void setSourceURLs(String deviceURL, String remoteURL) { mSourceURL = deviceURL; jniSetSourceURL(remoteURL); } @Override public void registerSegment(int segmentId, String path) { jniRegisterSegment(segmentId, path); } @Override public void loadScriptFromAssets( AssetManager assetManager, String assetURL, boolean loadSynchronously) { mSourceURL = assetURL; jniLoadScriptFromAssets(assetManager, assetURL, loadSynchronously); } @Override public void loadScriptFromFile(String fileName, String sourceURL, boolean loadSynchronously) { mSourceURL = sourceURL; jniLoadScriptFromFile(fileName, sourceURL, loadSynchronously); } @Override public void loadSplitBundleFromFile(String fileName, String sourceURL) { jniLoadScriptFromFile(fileName, sourceURL, false); } private native void jniSetSourceURL(String sourceURL); private native void jniRegisterSegment(int segmentId, String path); private native void jniLoadScriptFromAssets( AssetManager assetManager, String assetURL, boolean loadSynchronously); private native void jniLoadScriptFromFile( String fileName, String sourceURL, boolean loadSynchronously); @Override public void runJSBundle() { FLog.d(ReactConstants.TAG, "CatalystInstanceImpl.runJSBundle()"); Assertions.assertCondition(!mJSBundleHasLoaded, "JS bundle was already loaded!"); // incrementPendingJSCalls(); mJSBundleLoader.loadScript(CatalystInstanceImpl.this); synchronized (mJSCallsPendingInitLock) { // Loading the bundle is queued on the JS thread, but may not have // run yet. It's safe to set this here, though, since any work it // gates will be queued on the JS thread behind the load. mAcceptCalls = true; for (PendingJSCall function : mJSCallsPendingInit) { function.call(this); } mJSCallsPendingInit.clear(); mJSBundleHasLoaded = true; } // This is registered after JS starts since it makes a JS call Systrace.registerListener(mTraceListener); } @Override public boolean hasRunJSBundle() { synchronized (mJSCallsPendingInitLock) { return mJSBundleHasLoaded && mAcceptCalls; } } @Override public @Nullable String getSourceURL() { return mSourceURL; } private native void jniCallJSFunction(String module, String method, NativeArray arguments); @Override public void callFunction(final String module, final String method, final NativeArray arguments) { callFunction(new PendingJSCall(module, method, arguments)); } public void callFunction(PendingJSCall function) { if (mDestroyed) { final String call = function.toString(); FLog.w(ReactConstants.TAG, "Calling JS function after bridge has been destroyed: " + call); return; } if (!mAcceptCalls) { // Most of the time the instance is initialized and we don't need to acquire the lock synchronized (mJSCallsPendingInitLock) { if (!mAcceptCalls) { mJSCallsPendingInit.add(function); return; } } } function.call(this); } private native void jniCallJSCallback(int callbackID, NativeArray arguments); @Override public void invokeCallback(final int callbackID, final NativeArrayInterface arguments) { if (mDestroyed) { FLog.w(ReactConstants.TAG, "Invoking JS callback after bridge has been destroyed."); return; } jniCallJSCallback(callbackID, (NativeArray) arguments); } private native void unregisterFromInspector(); /** * Destroys this catalyst instance, waiting for any other threads in ReactQueueConfiguration * (besides the UI thread) to finish running. Must be called from the UI thread so that we can * fully shut down other threads. */ @Override @ThreadConfined(UI) public void destroy() { FLog.d(ReactConstants.TAG, "CatalystInstanceImpl.destroy() start"); UiThreadUtil.assertOnUiThread(); if (mDestroyed) { return; } unregisterFromInspector(); // TODO: tell all APIs to shut down ReactMarker.logMarker(ReactMarkerConstants.DESTROY_CATALYST_INSTANCE_START); mDestroyed = true; mNativeModulesQueueThread.runOnQueue( () -> { mNativeModuleRegistry.notifyJSInstanceDestroy(); if (mFabricUIManager != null) { mFabricUIManager.invalidate(); } boolean wasIdle = (mPendingJSCalls.getAndSet(0) == 0); if (!mBridgeIdleListeners.isEmpty()) { for (NotThreadSafeBridgeIdleDebugListener listener : mBridgeIdleListeners) { if (!wasIdle) { listener.onTransitionToBridgeIdle(); } listener.onBridgeDestroyed(); } } getReactQueueConfiguration() .getJSQueueThread() .runOnQueue( () -> { // We need to destroy the TurboModuleManager on the JS Thread if (mTurboModuleRegistry != null) { mTurboModuleRegistry.invalidate(); } // Kill non-UI threads from neutral third party // potentially expensive, so don't run on UI thread new Thread( () -> { // contextHolder is used as a lock to guard against // other users of the JS VM having the VM destroyed // underneath them, so notify them before we reset // Native mJavaScriptContextHolder.clear(); mHybridData.resetNative(); getReactQueueConfiguration().destroy(); FLog.w(ReactConstants.TAG, "CatalystInstanceImpl.destroy() end"); ReactMarker.logMarker( ReactMarkerConstants.DESTROY_CATALYST_INSTANCE_END); }, "destroy_react_context") .start(); }); }); // This is a noop if the listener was not yet registered. Systrace.unregisterListener(mTraceListener); } @Override public boolean isDestroyed() { return mDestroyed; } /** Initialize all the native modules */ @VisibleForTesting @Override public void initialize() { FLog.d(ReactConstants.TAG, "CatalystInstanceImpl.initialize()"); Assertions.assertCondition( !mInitialized, "This catalyst instance has already been initialized"); // We assume that the instance manager blocks on running the JS bundle. If // that changes, then we need to set mAcceptCalls just after posting the // task that will run the js bundle. Assertions.assertCondition(mAcceptCalls, "RunJSBundle hasn't completed."); mInitialized = true; mNativeModulesQueueThread.runOnQueue( () -> { mNativeModuleRegistry.notifyJSInstanceInitialized(); }); } @Override public ReactQueueConfiguration getReactQueueConfiguration() { return mReactQueueConfiguration; } @Override public <T extends JavaScriptModule> T getJSModule(Class<T> jsInterface) { return mJSModuleRegistry.getJavaScriptModule(this, jsInterface); } @Override public <T extends NativeModule> boolean hasNativeModule(Class<T> nativeModuleInterface) { String moduleName = getNameFromAnnotation(nativeModuleInterface); return getTurboModuleRegistry() != null && getTurboModuleRegistry().hasModule(moduleName) ? true : mNativeModuleRegistry.hasModule(moduleName); } @Override @Nullable public <T extends NativeModule> T getNativeModule(Class<T> nativeModuleInterface) { return (T) getNativeModule(getNameFromAnnotation(nativeModuleInterface)); } private TurboModuleRegistry getTurboModuleRegistry() { if (ReactFeatureFlags.useTurboModules) { return Assertions.assertNotNull( mTurboModuleRegistry, "TurboModules are enabled, but mTurboModuleRegistry hasn't been set."); } return null; } @Override @Nullable public NativeModule getNativeModule(String moduleName) { if (getTurboModuleRegistry() != null) { NativeModule module = getTurboModuleRegistry().getModule(moduleName); if (module != null) { return module; } } return mNativeModuleRegistry.hasModule(moduleName) ? mNativeModuleRegistry.getModule(moduleName) : null; } private <T extends NativeModule> String getNameFromAnnotation(Class<T> nativeModuleInterface) { ReactModule annotation = nativeModuleInterface.getAnnotation(ReactModule.class); if (annotation == null) { throw new IllegalArgumentException( "Could not find @ReactModule annotation in " + nativeModuleInterface.getCanonicalName()); } return annotation.name(); } // This is only used by com.facebook.react.modules.common.ModuleDataCleaner @Override public Collection<NativeModule> getNativeModules() { Collection<NativeModule> nativeModules = new ArrayList<>(); nativeModules.addAll(mNativeModuleRegistry.getAllModules()); if (getTurboModuleRegistry() != null) { for (NativeModule module : getTurboModuleRegistry().getModules()) { nativeModules.add(module); } } return nativeModules; } private native void jniHandleMemoryPressure(int level); @Override public void handleMemoryPressure(int level) { if (mDestroyed) { return; } jniHandleMemoryPressure(level); } /** * Adds a idle listener for this Catalyst instance. The listener will receive notifications * whenever the bridge transitions from idle to busy and vice-versa, where the busy state is * defined as there being some non-zero number of calls to JS that haven't resolved via a * onBatchComplete call. The listener should be purely passive and not affect application logic. */ @Override public void addBridgeIdleDebugListener(NotThreadSafeBridgeIdleDebugListener listener) { mBridgeIdleListeners.add(listener); } /** * Removes a NotThreadSafeBridgeIdleDebugListener previously added with {@link * #addBridgeIdleDebugListener} */ @Override public void removeBridgeIdleDebugListener(NotThreadSafeBridgeIdleDebugListener listener) { mBridgeIdleListeners.remove(listener); } @Override public native void setGlobalVariable(String propName, String jsonValue); @Override public JavaScriptContextHolder getJavaScriptContextHolder() { return mJavaScriptContextHolder; } public native RuntimeExecutor getRuntimeExecutor(); public native RuntimeScheduler getRuntimeScheduler(); private native long getJavaScriptContext(); private void incrementPendingJSCalls() { int oldPendingCalls = mPendingJSCalls.getAndIncrement(); boolean wasIdle = oldPendingCalls == 0; Systrace.traceCounter( Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, mJsPendingCallsTitleForTrace, oldPendingCalls + 1); if (wasIdle && !mBridgeIdleListeners.isEmpty()) { mNativeModulesQueueThread.runOnQueue( () -> { for (NotThreadSafeBridgeIdleDebugListener listener : mBridgeIdleListeners) { listener.onTransitionToBridgeBusy(); } }); } } @Override public void setTurboModuleRegistry(TurboModuleRegistry turboModuleRegistry) { mTurboModuleRegistry = turboModuleRegistry; } @Override public void setFabricUIManager(UIManager fabricUIManager) { mFabricUIManager = fabricUIManager; } @Override public UIManager getFabricUIManager() { return mFabricUIManager; } private void decrementPendingJSCalls() { int newPendingCalls = mPendingJSCalls.decrementAndGet(); // TODO(9604406): handle case of web workers injecting messages to main thread // Assertions.assertCondition(newPendingCalls >= 0); boolean isNowIdle = newPendingCalls == 0; Systrace.traceCounter( Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, mJsPendingCallsTitleForTrace, newPendingCalls); if (isNowIdle && !mBridgeIdleListeners.isEmpty()) { mNativeModulesQueueThread.runOnQueue( () -> { for (NotThreadSafeBridgeIdleDebugListener listener : mBridgeIdleListeners) { listener.onTransitionToBridgeIdle(); } }); } } private void onNativeException(Exception e) { mJSExceptionHandler.handleException(e); mReactQueueConfiguration .getUIQueueThread() .runOnQueue( () -> { destroy(); }); } private class NativeExceptionHandler implements QueueThreadExceptionHandler { @Override public void handleException(Exception e) { // Any Exception caught here is because of something in JS. Even if it's a bug in the // framework/native code, it was triggered by JS and theoretically since we were able // to set up the bridge, JS could change its logic, reload, and not trigger that crash. onNativeException(e); } } private static class JSProfilerTraceListener implements TraceListener { // We do this so the callback doesn't keep the CatalystInstanceImpl alive. // In this case, Systrace will keep the registered listener around forever // if the CatalystInstanceImpl is not explicitly destroyed. These instances // can still leak, but they are at least small. private final WeakReference<CatalystInstanceImpl> mOuter; public JSProfilerTraceListener(CatalystInstanceImpl outer) { mOuter = new WeakReference<CatalystInstanceImpl>(outer); } @Override public void onTraceStarted() { CatalystInstanceImpl impl = mOuter.get(); if (impl != null) { impl.getJSModule(com.facebook.react.bridge.Systrace.class).setEnabled(true); } } @Override public void onTraceStopped() { CatalystInstanceImpl impl = mOuter.get(); if (impl != null) { impl.getJSModule(com.facebook.react.bridge.Systrace.class).setEnabled(false); } } } public static class Builder { private @Nullable ReactQueueConfigurationSpec mReactQueueConfigurationSpec; private @Nullable JSBundleLoader mJSBundleLoader; private @Nullable NativeModuleRegistry mRegistry; private @Nullable JavaScriptExecutor mJSExecutor; private @Nullable JSExceptionHandler mJSExceptionHandler; private @Nullable ReactInstanceManagerInspectorTarget mInspectorTarget; public Builder setReactQueueConfigurationSpec( ReactQueueConfigurationSpec ReactQueueConfigurationSpec) { mReactQueueConfigurationSpec = ReactQueueConfigurationSpec; return this; } public Builder setRegistry(NativeModuleRegistry registry) { mRegistry = registry; return this; } public Builder setJSBundleLoader(JSBundleLoader jsBundleLoader) { mJSBundleLoader = jsBundleLoader; return this; } public Builder setJSExecutor(JavaScriptExecutor jsExecutor) { mJSExecutor = jsExecutor; return this; } public Builder setJSExceptionHandler(JSExceptionHandler handler) { mJSExceptionHandler = handler; return this; } public Builder setInspectorTarget( @Nullable ReactInstanceManagerInspectorTarget inspectorTarget) { mInspectorTarget = inspectorTarget; return this; } public CatalystInstanceImpl build() { return new CatalystInstanceImpl( Assertions.assertNotNull(mReactQueueConfigurationSpec), Assertions.assertNotNull(mJSExecutor), Assertions.assertNotNull(mRegistry), Assertions.assertNotNull(mJSBundleLoader), Assertions.assertNotNull(mJSExceptionHandler), mInspectorTarget); } } }
facebook/react-native
packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/CatalystInstanceImpl.java
13
/** * The company Assistance for Critical Moments (ACM) is helping other companies to overcome the * current economical crisis. As experts in computing machinery, their job is to calculate the cost/benefit * balance of the other companies. They receive two numbers, indicating the total amount of benefits and * costs, and they have to compute the final balance. * You have to solve the complex business problem of computing balances. You are given two positive * integer numbers, corresponding to the benefits and the costs. You have to obtain the total balance, * i.e., the difference between benefits and costs. * Input * The first line of the input contains an integer indicating the number of test cases. * For each test case, there is a line with two positive integer numbers, A and B, corresponding to the * benefits and the costs, respectively. Both numbers are between 0 and a googol (10100) to the power of * a hundred. * Output * For each test case, the output should consist of a line indicating the balance: A − B. * Sample Input * 4 * 10 3 * 4 9 * 0 8 * 5 2 * Sample Output * 7 * -5 * -8 * 3 */ //https://uva.onlinejudge.org/index.php?option=onlinejudge&Itemid=99999999&page=show_problem&category=&problem=2443 import java.math.BigInteger; import java.util.Scanner; public class WhoSaidCrisis { public static void main(String[] args) { Scanner input = new Scanner(System.in); int numberOfTestCases = input.nextInt(); while (numberOfTestCases != 0) { BigInteger first = input.nextBigInteger(); BigInteger second = input.nextBigInteger(); System.out.println(first.subtract(second)); numberOfTestCases--; } } }
kdn251/interviews
uva/WhoSaidCrisis.java
14
/* * Copyright (c) 2007 Mockito contributors * This program is made available under the terms of the MIT License. */ package org.mockito; import org.mockito.exceptions.misusing.PotentialStubbingProblem; import org.mockito.exceptions.misusing.UnnecessaryStubbingException; import org.mockito.internal.MockitoCore; import org.mockito.internal.creation.MockSettingsImpl; import org.mockito.internal.framework.DefaultMockitoFramework; import org.mockito.internal.session.DefaultMockitoSessionBuilder; import org.mockito.internal.util.MockUtil; import org.mockito.internal.verification.VerificationModeFactory; import org.mockito.invocation.Invocation; import org.mockito.invocation.InvocationFactory; import org.mockito.invocation.MockHandler; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoJUnitRunner; import org.mockito.junit.MockitoJUnitRunner.Strict; import org.mockito.junit.MockitoRule; import org.mockito.listeners.VerificationStartedEvent; import org.mockito.listeners.VerificationStartedListener; import org.mockito.mock.SerializableMode; import org.mockito.plugins.MockMaker; import org.mockito.plugins.MockitoPlugins; import org.mockito.quality.MockitoHint; import org.mockito.quality.Strictness; import org.mockito.session.MockitoSessionBuilder; import org.mockito.session.MockitoSessionLogger; import org.mockito.stubbing.Answer; import org.mockito.stubbing.Answer1; import org.mockito.stubbing.LenientStubber; import org.mockito.stubbing.OngoingStubbing; import org.mockito.stubbing.Stubber; import org.mockito.stubbing.VoidAnswer1; import org.mockito.verification.After; import org.mockito.verification.Timeout; import org.mockito.verification.VerificationAfterDelay; import org.mockito.verification.VerificationMode; import org.mockito.verification.VerificationWithTimeout; import java.util.function.Consumer; import java.util.function.Function; /** * <p align="left"><img src="logo.png" srcset="logo@2x.png 2x" alt="Mockito logo"/></p> * The Mockito library enables mock creation, verification and stubbing. * * <p> * This javadoc content is also available on the <a href="https://site.mockito.org/">https://site.mockito.org/</a> web page. * All documentation is kept in javadocs because it guarantees consistency between what's on the web and what's in the source code. * It allows access to documentation straight from the IDE even if you work offline. * It motivates Mockito developers to keep documentation up-to-date with the code that they write, * every day, with every commit. * * <h1>Contents</h1> * * <b> * <a href="#0">0. Migrating to Mockito 2</a><br/> * <a href="#0.1">0.1 Mockito Android support</a><br/> * <a href="#0.2">0.2 Configuration-free inline mock making</a><br/> * <a href="#1">1. Let's verify some behaviour! </a><br/> * <a href="#2">2. How about some stubbing? </a><br/> * <a href="#3">3. Argument matchers </a><br/> * <a href="#4">4. Verifying exact number of invocations / at least once / never </a><br/> * <a href="#5">5. Stubbing void methods with exceptions </a><br/> * <a href="#6">6. Verification in order </a><br/> * <a href="#7">7. Making sure interaction(s) never happened on mock </a><br/> * <a href="#8">8. Finding redundant invocations </a><br/> * <a href="#9">9. Shorthand for mocks creation - <code>&#064;Mock</code> annotation </a><br/> * <a href="#10">10. Stubbing consecutive calls (iterator-style stubbing) </a><br/> * <a href="#11">11. Stubbing with callbacks </a><br/> * <a href="#12">12. <code>doReturn()</code>|<code>doThrow()</code>|<code>doAnswer()</code>|<code>doNothing()</code>|<code>doCallRealMethod()</code> family of methods</a><br/> * <a href="#13">13. Spying on real objects </a><br/> * <a href="#14">14. Changing default return values of un-stubbed invocations (Since 1.7) </a><br/> * <a href="#15">15. Capturing arguments for further assertions (Since 1.8.0) </a><br/> * <a href="#16">16. Real partial mocks (Since 1.8.0) </a><br/> * <a href="#17">17. Resetting mocks (Since 1.8.0) </a><br/> * <a href="#18">18. Troubleshooting and validating framework usage (Since 1.8.0) </a><br/> * <a href="#19">19. Aliases for behavior driven development (Since 1.8.0) </a><br/> * <a href="#20">20. Serializable mocks (Since 1.8.1) </a><br/> * <a href="#21">21. New annotations: <code>&#064;Captor</code>, <code>&#064;Spy</code>, <code>&#064;InjectMocks</code> (Since 1.8.3) </a><br/> * <a href="#22">22. Verification with timeout (Since 1.8.5) </a><br/> * <a href="#23">23. Automatic instantiation of <code>&#064;Spies</code>, <code>&#064;InjectMocks</code> and constructor injection goodness (Since 1.9.0)</a><br/> * <a href="#24">24. One-liner stubs (Since 1.9.0)</a><br/> * <a href="#25">25. Verification ignoring stubs (Since 1.9.0)</a><br/> * <a href="#26">26. Mocking details (Improved in 2.2.x)</a><br/> * <a href="#27">27. Delegate calls to real instance (Since 1.9.5)</a><br/> * <a href="#28">28. <code>MockMaker</code> API (Since 1.9.5)</a><br/> * <a href="#29">29. BDD style verification (Since 1.10.0)</a><br/> * <a href="#30">30. Spying or mocking abstract classes (Since 1.10.12, further enhanced in 2.7.13 and 2.7.14)</a><br/> * <a href="#31">31. Mockito mocks can be <em>serialized</em> / <em>deserialized</em> across classloaders (Since 1.10.0)</a></h3><br/> * <a href="#32">32. Better generic support with deep stubs (Since 1.10.0)</a></h3><br/> * <a href="#33">33. Mockito JUnit rule (Since 1.10.17)</a><br/> * <a href="#34">34. Switch <em>on</em> or <em>off</em> plugins (Since 1.10.15)</a><br/> * <a href="#35">35. Custom verification failure message (Since 2.1.0)</a><br/> * <a href="#36">36. Java 8 Lambda Matcher Support (Since 2.1.0)</a><br/> * <a href="#37">37. Java 8 Custom Answer Support (Since 2.1.0)</a><br/> * <a href="#38">38. Meta data and generic type retention (Since 2.1.0)</a><br/> * <a href="#39">39. Mocking final types, enums and final methods (Since 2.1.0)</a><br/> * <a href="#40">40. Improved productivity and cleaner tests with "stricter" Mockito (Since 2.+)</a><br/> * <a href="#41">41. Advanced public API for framework integrations (Since 2.10.+)</a><br/> * <a href="#42">42. New API for integrations: listening on verification start events (Since 2.11.+)</a><br/> * <a href="#43">43. New API for integrations: <code>MockitoSession</code> is usable by testing frameworks (Since 2.15.+)</a><br/> * <a href="#44">44. Deprecated <code>org.mockito.plugins.InstantiatorProvider</code> as it was leaking internal API. it was replaced by <code>org.mockito.plugins.InstantiatorProvider2 (Since 2.15.4)</code></a><br/> * <a href="#45">45. New JUnit Jupiter (JUnit5+) extension</a><br/> * <a href="#46">46. New <code>Mockito.lenient()</code> and <code>MockSettings.lenient()</code> methods (Since 2.20.0)</a><br/> * <a href="#47">47. New API for clearing mock state in inline mocking (Since 2.25.0)</a><br/> * <a href="#48">48. New API for mocking static methods (Since 3.4.0)</a><br/> * <a href="#49">49. New API for mocking object construction (Since 3.5.0)</a><br/> * <a href="#50">50. Avoiding code generation when restricting mocks to interfaces (Since 3.12.2)</a><br/> * <a href="#51">51. New API for marking classes as unmockable (Since 4.1.0)</a><br/> * <a href="#52">52. New strictness attribute for @Mock annotation and <code>MockSettings.strictness()</code> methods (Since 4.6.0)</a><br/> * <a href="#53">53. Specifying mock maker for individual mocks (Since 4.8.0)</a><br/> * <a href="#54">54. Mocking/spying without specifying class (Since 4.10.0)</a><br/> * </b> * * <h3 id="0">0. <a class="meaningful_link" href="#mockito2" name="mockito2">Migrating to Mockito 2</a></h3> * * In order to continue improving Mockito and further improve the unit testing experience, we want you to upgrade to 2.1.0! * Mockito follows <a href="https://semver.org/">semantic versioning</a> and contains breaking changes only on major version upgrades. * In the lifecycle of a library, breaking changes are necessary * to roll out a set of brand new features that alter the existing behavior or even change the API. * For a comprehensive guide on the new release including incompatible changes, * see '<a href="https://github.com/mockito/mockito/wiki/What%27s-new-in-Mockito-2">What's new in Mockito 2</a>' wiki page. * We hope that you enjoy Mockito 2! * * <h3 id="0.1">0.1. <a class="meaningful_link" href="#mockito-android" name="mockito-android">Mockito Android support</a></h3> * * With Mockito version 2.6.1 we ship "native" Android support. To enable Android support, add the `mockito-android` library as dependency * to your project. This artifact is published to the same Mockito organization and can be imported for Android as follows: * * <pre class="code"><code> * repositories { * mavenCentral() * } * dependencies { * testCompile "org.mockito:mockito-core:+" * androidTestCompile "org.mockito:mockito-android:+" * } * </code></pre> * * You can continue to run the same unit tests on a regular VM by using the `mockito-core` artifact in your "testCompile" scope as shown * above. Be aware that you cannot use the <a href="#39">inline mock maker</a> on Android due to limitations in the Android VM. * * If you encounter issues with mocking on Android, please open an issue * <a href="https://github.com/mockito/mockito/issues/new">on the official issue tracker</a>. * Do provide the version of Android you are working on and dependencies of your project. * * <h3 id="0.2">0.2. <a class="meaningful_link" href="#mockito-inline" name="mockito-inline">Configuration-free inline mock making</a></h3> * * Starting with version 2.7.6, we offer the 'mockito-inline' artifact that enables <a href="#39">inline mock making</a> without configuring * the MockMaker extension file. To use this, add the `mockito-inline` instead of the `mockito-core` artifact as follows: * * <pre class="code"><code> * repositories { * mavenCentral() * } * dependencies { * testCompile "org.mockito:mockito-inline:+" * } * </code></pre> * * Be aware that starting from 5.0.0 the <a href="#39">inline mock maker</a> became the default mock maker and this * artifact may be abolished in future versions. * * <p> * For more information about inline mock making, see <a href="#39">section 39</a>. * * <h3 id="1">1. <a class="meaningful_link" href="#verification" name="verification">Let's verify some behaviour!</a></h3> * * The following examples mock a List, because most people are familiar with the interface (such as the * <code>add()</code>, <code>get()</code>, <code>clear()</code> methods). <br> * In reality, please don't mock the List class. Use a real instance instead. * * <pre class="code"><code class="java"> * //Let's import Mockito statically so that the code looks clearer * import static org.mockito.Mockito.*; * * //mock creation * List mockedList = mock(List.class); * * //using mock object * mockedList.add("one"); * mockedList.clear(); * * //verification * verify(mockedList).add("one"); * verify(mockedList).clear(); * </code></pre> * * <p> * Once created, a mock will remember all interactions. Then you can selectively * verify whatever interactions you are interested in. * </p> * * * * <h3 id="2">2. <a class="meaningful_link" href="#stubbing" name="stubbing">How about some stubbing?</a></h3> * * <pre class="code"><code class="java"> * //You can mock concrete classes, not just interfaces * LinkedList mockedList = mock(LinkedList.class); * * //stubbing * when(mockedList.get(0)).thenReturn("first"); * when(mockedList.get(1)).thenThrow(new RuntimeException()); * * //following prints "first" * System.out.println(mockedList.get(0)); * * //following throws runtime exception * System.out.println(mockedList.get(1)); * * //following prints "null" because get(999) was not stubbed * System.out.println(mockedList.get(999)); * * //Although it is possible to verify a stubbed invocation, usually <b>it's just redundant</b> * //If your code cares what get(0) returns, then something else breaks (often even before verify() gets executed). * //If your code doesn't care what get(0) returns, then it should not be stubbed. * verify(mockedList).get(0); * </code></pre> * * <ul> * <li> By default, for all methods that return a value, a mock will return either null, * a primitive/primitive wrapper value, or an empty collection, as appropriate. * For example 0 for an int/Integer and false for a boolean/Boolean. </li> * * <li> Stubbing can be overridden: for example common stubbing can go to * fixture setup but the test methods can override it. * Please note that overriding stubbing is a potential code smell that points out too much stubbing</li> * * <li> Once stubbed, the method will always return a stubbed value, regardless * of how many times it is called. </li> * * <li> Last stubbing is more important - when you stubbed the same method with * the same arguments many times. * Other words: <b>the order of stubbing matters</b> but it is only meaningful rarely, * e.g. when stubbing exactly the same method calls or sometimes when argument matchers are used, etc.</li> * * </ul> * * * * <h3 id="3">3. <a class="meaningful_link" href="#argument_matchers" name="argument_matchers">Argument matchers</a></h3> * * Mockito verifies argument values in natural java style: by using an <code>equals()</code> method. * Sometimes, when extra flexibility is required then you might use argument matchers: * * <pre class="code"><code class="java"> * //stubbing using built-in anyInt() argument matcher * when(mockedList.get(anyInt())).thenReturn("element"); * * //stubbing using custom matcher (let's say isValid() returns your own matcher implementation): * when(mockedList.contains(argThat(isValid()))).thenReturn(true); * * //following prints "element" * System.out.println(mockedList.get(999)); * * //<b>you can also verify using an argument matcher</b> * verify(mockedList).get(anyInt()); * * //<b>argument matchers can also be written as Java 8 Lambdas</b> * verify(mockedList).add(argThat(someString -&gt; someString.length() &gt; 5)); * * </code></pre> * * <p> * Argument matchers allow flexible verification or stubbing. * {@link ArgumentMatchers Click here} {@link org.mockito.hamcrest.MockitoHamcrest or here} to see more built-in matchers * and examples of <b>custom argument matchers / hamcrest matchers</b>. * <p> * For information solely on <b>custom argument matchers</b> check out javadoc for {@link ArgumentMatcher} class. * <p> * Be reasonable with using complicated argument matching. * The natural matching style using <code>equals()</code> with occasional <code>anyX()</code> matchers tend to give clean and simple tests. * Sometimes it's just better to refactor the code to allow <code>equals()</code> matching or even implement <code>equals()</code> method to help out with testing. * <p> * Also, read <a href="#15">section 15</a> or javadoc for {@link ArgumentCaptor} class. * {@link ArgumentCaptor} is a special implementation of an argument matcher that captures argument values for further assertions. * <p> * <b>Warning on argument matchers:</b> * <p> * If you are using argument matchers, <b>all arguments</b> have to be provided * by matchers. * <p> * The following example shows verification but the same applies to stubbing: * * <pre class="code"><code class="java"> * verify(mock).someMethod(anyInt(), anyString(), <b>eq("third argument")</b>); * //above is correct - eq() is also an argument matcher * * verify(mock).someMethod(anyInt(), anyString(), <b>"third argument"</b>); * //above is incorrect - exception will be thrown because third argument is given without an argument matcher. * </code></pre> * * <p> * Matcher methods like <code>any()</code>, <code>eq()</code> <b>do not</b> return matchers. * Internally, they record a matcher on a stack and return a dummy value (usually null). * This implementation is due to static type safety imposed by the java compiler. * The consequence is that you cannot use <code>any()</code>, <code>eq()</code> methods outside of verified/stubbed method. * * * * * <h3 id="4">4. <a class="meaningful_link" href="#exact_verification" name="exact_verification">Verifying exact number of invocations</a> / * <a class="meaningful_link" href="#at_least_verification" name="at_least_verification">at least x</a> / never</h3> * * <pre class="code"><code class="java"> * //using mock * mockedList.add("once"); * * mockedList.add("twice"); * mockedList.add("twice"); * * mockedList.add("three times"); * mockedList.add("three times"); * mockedList.add("three times"); * * //following two verifications work exactly the same - times(1) is used by default * verify(mockedList).add("once"); * verify(mockedList, times(1)).add("once"); * * //exact number of invocations verification * verify(mockedList, times(2)).add("twice"); * verify(mockedList, times(3)).add("three times"); * * //verification using never(). never() is an alias to times(0) * verify(mockedList, never()).add("never happened"); * * //verification using atLeast()/atMost() * verify(mockedList, atMostOnce()).add("once"); * verify(mockedList, atLeastOnce()).add("three times"); * verify(mockedList, atLeast(2)).add("three times"); * verify(mockedList, atMost(5)).add("three times"); * * </code></pre> * * <p> * <b>times(1) is the default.</b> Therefore using times(1) explicitly can be * omitted. * * * * * <h3 id="5">5. <a class="meaningful_link" href="#stubbing_with_exceptions" name="stubbing_with_exceptions">Stubbing void methods with exceptions</a></h3> * * <pre class="code"><code class="java"> * doThrow(new RuntimeException()).when(mockedList).clear(); * * //following throws RuntimeException: * mockedList.clear(); * </code></pre> * * Read more about <code>doThrow()</code>|<code>doAnswer()</code> family of methods in <a href="#12">section 12</a>. * <p> * * <h3 id="6">6. <a class="meaningful_link" href="#in_order_verification" name="in_order_verification">Verification in order</a></h3> * * <pre class="code"><code class="java"> * // A. Single mock whose methods must be invoked in a particular order * List singleMock = mock(List.class); * * //using a single mock * singleMock.add("was added first"); * singleMock.add("was added second"); * * //create an inOrder verifier for a single mock * InOrder inOrder = inOrder(singleMock); * * //following will make sure that add is first called with "was added first", then with "was added second" * inOrder.verify(singleMock).add("was added first"); * inOrder.verify(singleMock).add("was added second"); * * // B. Multiple mocks that must be used in a particular order * List firstMock = mock(List.class); * List secondMock = mock(List.class); * * //using mocks * firstMock.add("was called first"); * secondMock.add("was called second"); * * //create inOrder object passing any mocks that need to be verified in order * InOrder inOrder = inOrder(firstMock, secondMock); * * //following will make sure that firstMock was called before secondMock * inOrder.verify(firstMock).add("was called first"); * inOrder.verify(secondMock).add("was called second"); * * // Oh, and A + B can be mixed together at will * </code></pre> * * Verification in order is flexible - <b>you don't have to verify all * interactions</b> one-by-one but only those that you are interested in * testing in order. * <p> * Also, you can create an InOrder object passing only the mocks that are relevant for * in-order verification. * * * * * <h3 id="7">7. <a class="meaningful_link" href="#never_verification" name="never_verification">Making sure interaction(s) never happened on mock</a></h3> * * <pre class="code"><code class="java"> * //using mocks - only mockOne is interacted * mockOne.add("one"); * * //ordinary verification * verify(mockOne).add("one"); * * //verify that method was never called on a mock * verify(mockOne, never()).add("two"); * * </code></pre> * * * * * <h3 id="8">8. <a class="meaningful_link" href="#finding_redundant_invocations" name="finding_redundant_invocations">Finding redundant invocations</a></h3> * * <pre class="code"><code class="java"> * //using mocks * mockedList.add("one"); * mockedList.add("two"); * * verify(mockedList).add("one"); * * //following verification will fail * verifyNoMoreInteractions(mockedList); * </code></pre> * * A word of <b>warning</b>: * Some users who did a lot of classic, expect-run-verify mocking tend to use <code>verifyNoMoreInteractions()</code> very often, even in every test method. * <code>verifyNoMoreInteractions()</code> is not recommended to use in every test method. * <code>verifyNoMoreInteractions()</code> is a handy assertion from the interaction testing toolkit. Use it only when it's relevant. * Abusing it leads to <strong>overspecified</strong>, <strong>less maintainable</strong> tests. * * <p> * See also {@link Mockito#never()} - it is more explicit and * communicates the intent well. * <p> * * * * * <h3 id="9">9. <a class="meaningful_link" href="#mock_annotation" name="mock_annotation">Shorthand for mocks creation - <code>&#064;Mock</code> annotation</a></h3> * * <ul> * <li>Minimizes repetitive mock creation code.</li> * <li>Makes the test class more readable.</li> * <li>Makes the verification error easier to read because the <b>field name</b> * is used to identify the mock.</li> * </ul> * * <pre class="code"><code class="java"> * public class ArticleManagerTest { * * &#064;Mock private ArticleCalculator calculator; * &#064;Mock private ArticleDatabase database; * &#064;Mock private UserProvider userProvider; * * private ArticleManager manager; * * &#064;org.junit.jupiter.api.Test * void testSomethingInJunit5(&#064;Mock ArticleDatabase database) { * </code></pre> * * <b>Important!</b> This needs to be somewhere in the base class or a test * runner: * * <pre class="code"><code class="java"> * MockitoAnnotations.openMocks(testClass); * </code></pre> * * You can use built-in runner: {@link MockitoJUnitRunner} or a rule: {@link MockitoRule}. * For JUnit5 tests, refer to the JUnit5 extension described in <a href="#45">section 45</a>. * <p> * Read more here: {@link MockitoAnnotations} * * * * * <h3 id="10">10. <a class="meaningful_link" href="#stubbing_consecutive_calls" name="stubbing_consecutive_calls">Stubbing consecutive calls</a> (iterator-style stubbing)</h3> * * Sometimes we need to stub with different return value/exception for the same * method call. Typical use case could be mocking iterators. * Original version of Mockito did not have this feature to promote simple mocking. * For example, instead of iterators one could use {@link Iterable} or simply * collections. Those offer natural ways of stubbing (e.g. using real * collections). In rare scenarios stubbing consecutive calls could be useful, * though: * <p> * * <pre class="code"><code class="java"> * when(mock.someMethod("some arg")) * .thenThrow(new RuntimeException()) * .thenReturn("foo"); * * //First call: throws runtime exception: * mock.someMethod("some arg"); * * //Second call: prints "foo" * System.out.println(mock.someMethod("some arg")); * * //Any consecutive call: prints "foo" as well (last stubbing wins). * System.out.println(mock.someMethod("some arg")); * </code></pre> * * Alternative, shorter version of consecutive stubbing: * * <pre class="code"><code class="java"> * when(mock.someMethod("some arg")) * .thenReturn("one", "two", "three"); * </code></pre> * * <strong>Warning</strong> : if instead of chaining {@code .thenReturn()} calls, multiple stubbing with the same matchers or arguments * is used, then each stubbing will override the previous one: * * <pre class="code"><code class="java"> * //All mock.someMethod("some arg") calls will return "two" * when(mock.someMethod("some arg")) * .thenReturn("one") * when(mock.someMethod("some arg")) * .thenReturn("two") * </code></pre> * * * * <h3 id="11">11. <a class="meaningful_link" href="#answer_stubs" name="answer_stubs">Stubbing with callbacks</a></h3> * * Allows stubbing with generic {@link Answer} interface. * <p> * Yet another controversial feature which was not included in Mockito * originally. We recommend simply stubbing with <code>thenReturn()</code> or * <code>thenThrow()</code>, which should be enough to test/test-drive * any clean and simple code. However, if you do have a need to stub with the generic Answer interface, here is an example: * * <pre class="code"><code class="java"> * when(mock.someMethod(anyString())).thenAnswer( * new Answer() { * public Object answer(InvocationOnMock invocation) { * Object[] args = invocation.getArguments(); * Object mock = invocation.getMock(); * return "called with arguments: " + Arrays.toString(args); * } * }); * * //Following prints "called with arguments: [foo]" * System.out.println(mock.someMethod("foo")); * </code></pre> * * * * * <h3 id="12">12. <a class="meaningful_link" href="#do_family_methods_stubs" name="do_family_methods_stubs"><code>doReturn()</code>|<code>doThrow()</code>| * <code>doAnswer()</code>|<code>doNothing()</code>|<code>doCallRealMethod()</code> family of methods</a></h3> * * Stubbing void methods requires a different approach from {@link Mockito#when(Object)} because the compiler does not * like void methods inside brackets... * <p> * Use <code>doThrow()</code> when you want to stub a void method with an exception: * <pre class="code"><code class="java"> * doThrow(new RuntimeException()).when(mockedList).clear(); * * //following throws RuntimeException: * mockedList.clear(); * </code></pre> * </p> * * <p> * You can use <code>doThrow()</code>, <code>doAnswer()</code>, <code>doNothing()</code>, <code>doReturn()</code> * and <code>doCallRealMethod()</code> in place of the corresponding call with <code>when()</code>, for any method. * It is necessary when you * <ul> * <li>stub void methods</li> * <li>stub methods on spy objects (see below)</li> * <li>stub the same method more than once, to change the behaviour of a mock in the middle of a test.</li> * </ul> * but you may prefer to use these methods in place of the alternative with <code>when()</code>, for all of your stubbing calls. * <p> * Read more about these methods: * <p> * {@link Mockito#doReturn(Object)} * <p> * {@link Mockito#doThrow(Throwable...)} * <p> * {@link Mockito#doThrow(Class)} * <p> * {@link Mockito#doAnswer(Answer)} * <p> * {@link Mockito#doNothing()} * <p> * {@link Mockito#doCallRealMethod()} * * * * * <h3 id="13">13. <a class="meaningful_link" href="#spy" name="spy">Spying on real objects</a></h3> * * You can create spies of real objects. When you use the spy then the <b>real</b> methods are called * (unless a method was stubbed). * <p> * Real spies should be used <b>carefully and occasionally</b>, for example when dealing with legacy code. * * <p> * Spying on real objects can be associated with "partial mocking" concept. * <b>Before the release 1.8</b>, Mockito spies were not real partial mocks. * The reason was we thought partial mock is a code smell. * At some point we found legitimate use cases for partial mocks * (3rd party interfaces, interim refactoring of legacy code). * <p> * * <pre class="code"><code class="java"> * List list = new LinkedList(); * List spy = spy(list); * * //optionally, you can stub out some methods: * when(spy.size()).thenReturn(100); * * //using the spy calls <b>*real*</b> methods * spy.add("one"); * spy.add("two"); * * //prints "one" - the first element of a list * System.out.println(spy.get(0)); * * //size() method was stubbed - 100 is printed * System.out.println(spy.size()); * * //optionally, you can verify * verify(spy).add("one"); * verify(spy).add("two"); * </code></pre> * * <h4>Important gotcha on spying real objects!</h4> * <ol> * <li>Sometimes it's impossible or impractical to use {@link Mockito#when(Object)} for stubbing spies. * Therefore when using spies please consider <code>doReturn</code>|<code>Answer</code>|<code>Throw()</code> family of * methods for stubbing. Example: * * <pre class="code"><code class="java"> * List list = new LinkedList(); * List spy = spy(list); * * //Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty) * when(spy.get(0)).thenReturn("foo"); * * //You have to use doReturn() for stubbing * doReturn("foo").when(spy).get(0); * </code></pre> * </li> * * <li>Mockito <b>*does not*</b> delegate calls to the passed real instance, instead it actually creates a copy of it. * So if you keep the real instance and interact with it, don't expect the spied to be aware of those interaction * and their effect on real instance state. * The corollary is that when an <b>*un-stubbed*</b> method is called <b>*on the spy*</b> but <b>*not on the real instance*</b>, * you won't see any effects on the real instance. * </li> * * <li>Watch out for final methods. * Mockito doesn't mock final methods so the bottom line is: when you spy on real objects + you try to stub a final method = trouble. * Also you won't be able to verify those method as well. * </li> * </ol> * * * * * <h3 id="14">14. Changing <a class="meaningful_link" href="#defaultreturn" name="defaultreturn">default return values of un-stubbed invocations</a> (Since 1.7)</h3> * * You can create a mock with specified strategy for its return values. * It's quite an advanced feature and typically you don't need it to write decent tests. * However, it can be helpful for working with <b>legacy systems</b>. * <p> * It is the default answer so it will be used <b>only when you don't</b> stub the method call. * * <pre class="code"><code class="java"> * Foo mock = mock(Foo.class, Mockito.RETURNS_SMART_NULLS); * Foo mockTwo = mock(Foo.class, new YourOwnAnswer()); * </code></pre> * * <p> * Read more about this interesting implementation of <i>Answer</i>: {@link Mockito#RETURNS_SMART_NULLS} * * * * * <h3 id="15">15. <a class="meaningful_link" href="#captors" name="captors">Capturing arguments</a> for further assertions (Since 1.8.0)</h3> * * Mockito verifies argument values in natural java style: by using an <code>equals()</code> method. * This is also the recommended way of matching arguments because it makes tests clean and simple. * In some situations though, it is helpful to assert on certain arguments after the actual verification. * For example: * <pre class="code"><code class="java"> * ArgumentCaptor&lt;Person&gt; argument = ArgumentCaptor.forClass(Person.class); * verify(mock).doSomething(argument.capture()); * assertEquals("John", argument.getValue().getName()); * </code></pre> * * <b>Warning:</b> it is recommended to use ArgumentCaptor with verification <b>but not</b> with stubbing. * Using ArgumentCaptor with stubbing may decrease test readability because captor is created outside of assert (aka verify or 'then') block. * Also it may reduce defect localization because if stubbed method was not called then no argument is captured. * <p> * In a way ArgumentCaptor is related to custom argument matchers (see javadoc for {@link ArgumentMatcher} class). * Both techniques can be used for making sure certain arguments were passed to mocks. * However, ArgumentCaptor may be a better fit if: * <ul> * <li>custom argument matcher is not likely to be reused</li> * <li>you just need it to assert on argument values to complete verification</li> * </ul> * Custom argument matchers via {@link ArgumentMatcher} are usually better for stubbing. * * * * * <h3 id="16">16. <a class="meaningful_link" href="#partial_mocks" name="partial_mocks">Real partial mocks</a> (Since 1.8.0)</h3> * * Finally, after many internal debates and discussions on the mailing list, partial mock support was added to Mockito. * Previously we considered partial mocks as code smells. However, we found a legitimate use case for partial mocks. * <p> * <b>Before release 1.8</b> <code>spy()</code> was not producing real partial mocks and it was confusing for some users. * Read more about spying: <a href="#13">here</a> or in javadoc for {@link Mockito#spy(Object)} method. * <p> * <pre class="code"><code class="java"> * //you can create partial mock with spy() method: * List list = spy(new LinkedList()); * * //you can enable partial mock capabilities selectively on mocks: * Foo mock = mock(Foo.class); * //Be sure the real implementation is 'safe'. * //If real implementation throws exceptions or depends on specific state of the object then you're in trouble. * when(mock.someMethod()).thenCallRealMethod(); * </code></pre> * * As usual you are going to read <b>the partial mock warning</b>: * Object oriented programming is more less tackling complexity by dividing the complexity into separate, specific, SRPy objects. * How does partial mock fit into this paradigm? Well, it just doesn't... * Partial mock usually means that the complexity has been moved to a different method on the same object. * In most cases, this is not the way you want to design your application. * <p> * However, there are rare cases when partial mocks come handy: * dealing with code you cannot change easily (3rd party interfaces, interim refactoring of legacy code etc.) * However, I wouldn't use partial mocks for new, test-driven and well-designed code. * * * * * <h3 id="17">17. <a class="meaningful_link" href="#resetting_mocks" name="resetting_mocks">Resetting mocks</a> (Since 1.8.0)</h3> * * Using this method could be an indication of poor testing. * Normally, you don't need to reset your mocks, just create new mocks for each test method. * <p> * Instead of <code>reset()</code> please consider writing simple, small and focused test methods over lengthy, over-specified tests. * <b>First potential code smell is <code>reset()</code> in the middle of the test method.</b> This probably means you're testing too much. * Follow the whisper of your test methods: "Please keep us small and focused on single behavior". * There are several threads about it on mockito mailing list. * <p> * The only reason we added <code>reset()</code> method is to * make it possible to work with container-injected mocks. * For more information see FAQ (<a href="https://github.com/mockito/mockito/wiki/FAQ">here</a>). * <p> * <b>Don't harm yourself.</b> <code>reset()</code> in the middle of the test method is a code smell (you're probably testing too much). * <pre class="code"><code class="java"> * List mock = mock(List.class); * when(mock.size()).thenReturn(10); * mock.add(1); * * reset(mock); * //at this point the mock forgot any interactions and stubbing * </code></pre> * * * * * <h3 id="18">18. <a class="meaningful_link" href="#framework_validation" name="framework_validation">Troubleshooting and validating framework usage</a> (Since 1.8.0)</h3> * * First of all, in case of any trouble, I encourage you to read the Mockito FAQ: * <a href="https://github.com/mockito/mockito/wiki/FAQ">https://github.com/mockito/mockito/wiki/FAQ</a> * <p> * In case of questions you may also post to mockito mailing list: * <a href="https://groups.google.com/group/mockito">https://groups.google.com/group/mockito</a> * <p> * Next, you should know that Mockito validates if you use it correctly <b>all the time</b>. * However, there's a gotcha so please read the javadoc for {@link Mockito#validateMockitoUsage()} * * * * * <h3 id="19">19. <a class="meaningful_link" href="#bdd_mockito" name="bdd_mockito">Aliases for behavior driven development</a> (Since 1.8.0)</h3> * * Behavior Driven Development style of writing tests uses <b>//given //when //then</b> comments as fundamental parts of your test methods. * This is exactly how we write our tests and we warmly encourage you to do so! * <p> * Start learning about BDD here: <a href="https://en.wikipedia.org/wiki/Behavior-driven_development">https://en.wikipedia.org/wiki/Behavior-driven_development</a> * <p> * The problem is that current stubbing api with canonical role of <b>when</b> word does not integrate nicely with <b>//given //when //then</b> comments. * It's because stubbing belongs to <b>given</b> component of the test and not to the <b>when</b> component of the test. * Hence {@link BDDMockito} class introduces an alias so that you stub method calls with {@link BDDMockito#given(Object)} method. * Now it really nicely integrates with the <b>given</b> component of a BDD style test! * <p> * Here is how the test might look like: * <pre class="code"><code class="java"> * import static org.mockito.BDDMockito.*; * * Seller seller = mock(Seller.class); * Shop shop = new Shop(seller); * * public void shouldBuyBread() throws Exception { * //given * given(seller.askForBread()).willReturn(new Bread()); * * //when * Goods goods = shop.buyBread(); * * //then * assertThat(goods, containBread()); * } * </code></pre> * * * * * <h3 id="20">20. <a class="meaningful_link" href="#serializable_mocks" name="serializable_mocks">Serializable mocks</a> (Since 1.8.1)</h3> * * Mocks can be made serializable. With this feature you can use a mock in a place that requires dependencies to be serializable. * <p> * WARNING: This should be rarely used in unit testing. * <p> * The behaviour was implemented for a specific use case of a BDD spec that had an unreliable external dependency. This * was in a web environment and the objects from the external dependency were being serialized to pass between layers. * <p> * To create serializable mock use {@link MockSettings#serializable()}: * <pre class="code"><code class="java"> * List serializableMock = mock(List.class, withSettings().serializable()); * </code></pre> * <p> * The mock can be serialized assuming all the normal <a href='https://docs.oracle.com/javase/8/docs/api/java/io/Serializable.html'> * serialization requirements</a> are met by the class. * <p> * Making a real object spy serializable is a bit more effort as the spy(...) method does not have an overloaded version * which accepts MockSettings. No worries, you will hardly ever use it. * * <pre class="code"><code class="java"> * List&lt;Object&gt; list = new ArrayList&lt;Object&gt;(); * List&lt;Object&gt; spy = mock(ArrayList.class, withSettings() * .spiedInstance(list) * .defaultAnswer(CALLS_REAL_METHODS) * .serializable()); * </code></pre> * * * * * <h3 id="21">21. New annotations: <a class="meaningful_link" href="#captor_annotation" name="captor_annotation"><code>&#064;Captor</code></a>, * <a class="meaningful_link" href="#spy_annotation" name="spy_annotation"><code>&#064;Spy</code></a>, * <a class="meaningful_link" href="#injectmocks_annotation" name="injectmocks_annotation"><code>&#064;InjectMocks</code></a> (Since 1.8.3)</h3> * * <p> * Release 1.8.3 brings new annotations that may be helpful on occasion: * * <ul> * <li>&#064;{@link Captor} simplifies creation of {@link ArgumentCaptor} * - useful when the argument to capture is a nasty generic class and you want to avoid compiler warnings * <li>&#064;{@link Spy} - you can use it instead {@link Mockito#spy(Object)}. * <li>&#064;{@link InjectMocks} - injects mock or spy fields into tested object automatically. * </ul> * * <p> * Note that &#064;{@link InjectMocks} can also be used in combination with the &#064;{@link Spy} annotation, it means * that Mockito will inject mocks into the partial mock under test. This complexity is another good reason why you * should only use partial mocks as a last resort. See point 16 about partial mocks. * * <p> * All new annotations are <b>*only*</b> processed on {@link MockitoAnnotations#openMocks(Object)}. * Just like for &#064;{@link Mock} annotation you can use the built-in runner: {@link MockitoJUnitRunner} or rule: * {@link MockitoRule}. * <p> * * * * * <h3 id="22">22. <a class="meaningful_link" href="#verification_timeout" name="verification_timeout">Verification with timeout</a> (Since 1.8.5)</h3> * <p> * Allows verifying with timeout. It causes a verify to wait for a specified period of time for a desired * interaction rather than fails immediately if had not already happened. May be useful for testing in concurrent * conditions. * <p> * This feature should be used rarely - figure out a better way of testing your multi-threaded system. * <p> * Not yet implemented to work with InOrder verification. * <p> * Examples: * <p> * <pre class="code"><code class="java"> * //passes when someMethod() is called no later than within 100 ms * //exits immediately when verification is satisfied (e.g. may not wait full 100 ms) * verify(mock, timeout(100)).someMethod(); * //above is an alias to: * verify(mock, timeout(100).times(1)).someMethod(); * * //passes as soon as someMethod() has been called 2 times under 100 ms * verify(mock, timeout(100).times(2)).someMethod(); * * //equivalent: this also passes as soon as someMethod() has been called 2 times under 100 ms * verify(mock, timeout(100).atLeast(2)).someMethod(); * </code></pre> * * * * * <h3 id="23">23. <a class="meaningful_link" href="#automatic_instantiation" name="automatic_instantiation">Automatic instantiation of <code>&#064;Spies</code>, * <code>&#064;InjectMocks</code></a> and <a class="meaningful_link" href="#constructor_injection" name="constructor_injection">constructor injection goodness</a> (Since 1.9.0)</h3> * * <p> * Mockito will now try to instantiate &#064;{@link Spy} and will instantiate &#064;{@link InjectMocks} fields * using <b>constructor</b> injection, <b>setter</b> injection, or <b>field</b> injection. * <p> * To take advantage of this feature you need to use {@link MockitoAnnotations#openMocks(Object)}, {@link MockitoJUnitRunner} * or {@link MockitoRule}. * <p> * Read more about available tricks and the rules of injection in the javadoc for {@link InjectMocks} * <pre class="code"><code class="java"> * //instead: * &#064;Spy BeerDrinker drinker = new BeerDrinker(); * //you can write: * &#064;Spy BeerDrinker drinker; * * //same applies to &#064;InjectMocks annotation: * &#064;InjectMocks LocalPub; * </code></pre> * * * * * <h3 id="24">24. <a class="meaningful_link" href="#one_liner_stub" name="one_liner_stub">One-liner stubs</a> (Since 1.9.0)</h3> * <p> * Mockito will now allow you to create mocks when stubbing. * Basically, it allows to create a stub in one line of code. * This can be helpful to keep test code clean. * For example, some boring stub can be created and stubbed at field initialization in a test: * <pre class="code"><code class="java"> * public class CarTest { * Car boringStubbedCar = when(mock(Car.class).shiftGear()).thenThrow(EngineNotStarted.class).getMock(); * * &#064;Test public void should... {} * </code></pre> * * * * * <h3 id="25">25. <a class="meaningful_link" href="#ignore_stubs_verification" name="ignore_stubs_verification">Verification ignoring stubs</a> (Since 1.9.0)</h3> * <p> * Mockito will now allow to ignore stubbing for the sake of verification. * Sometimes useful when coupled with <code>verifyNoMoreInteractions()</code> or verification <code>inOrder()</code>. * Helps avoiding redundant verification of stubbed calls - typically we're not interested in verifying stubs. * <p> * <b>Warning</b>, <code>ignoreStubs()</code> might lead to overuse of verifyNoMoreInteractions(ignoreStubs(...)); * Bear in mind that Mockito does not recommend bombarding every test with <code>verifyNoMoreInteractions()</code> * for the reasons outlined in javadoc for {@link Mockito#verifyNoMoreInteractions(Object...)} * <p>Some examples: * <pre class="code"><code class="java"> * verify(mock).foo(); * verify(mockTwo).bar(); * * //ignores all stubbed methods: * verifyNoMoreInteractions(ignoreStubs(mock, mockTwo)); * * //creates InOrder that will ignore stubbed * InOrder inOrder = inOrder(ignoreStubs(mock, mockTwo)); * inOrder.verify(mock).foo(); * inOrder.verify(mockTwo).bar(); * inOrder.verifyNoMoreInteractions(); * </code></pre> * <p> * Advanced examples and more details can be found in javadoc for {@link Mockito#ignoreStubs(Object...)} * * * * * <h3 id="26">26. <a class="meaningful_link" href="#mocking_details" name="mocking_details">Mocking details</a> (Improved in 2.2.x)</h3> * <p> * * Mockito offers API to inspect the details of a mock object. * This API is useful for advanced users and mocking framework integrators. * * <pre class="code"><code class="java"> * //To identify whether a particular object is a mock or a spy: * Mockito.mockingDetails(someObject).isMock(); * Mockito.mockingDetails(someObject).isSpy(); * * //Getting details like type to mock or default answer: * MockingDetails details = mockingDetails(mock); * details.getMockCreationSettings().getTypeToMock(); * details.getMockCreationSettings().getDefaultAnswer(); * * //Getting invocations and stubbings of the mock: * MockingDetails details = mockingDetails(mock); * details.getInvocations(); * details.getStubbings(); * * //Printing all interactions (including stubbing, unused stubs) * System.out.println(mockingDetails(mock).printInvocations()); * </code></pre> * * For more information see javadoc for {@link MockingDetails}. * * <h3 id="27">27. <a class="meaningful_link" href="#delegating_call_to_real_instance" name="delegating_call_to_real_instance">Delegate calls to real instance</a> (Since 1.9.5)</h3> * * <p>Useful for spies or partial mocks of objects <strong>that are difficult to mock or spy</strong> using the usual spy API. * Since Mockito 1.10.11, the delegate may or may not be of the same type as the mock. * If the type is different, a matching method needs to be found on delegate type otherwise an exception is thrown. * * Possible use cases for this feature: * <ul> * <li>Final classes but with an interface</li> * <li>Already custom proxied object</li> * <li>Special objects with a finalize method, i.e. to avoid executing it 2 times</li> * </ul> * * <p>The difference with the regular spy: * <ul> * <li> * The regular spy ({@link #spy(Object)}) contains <strong>all</strong> state from the spied instance * and the methods are invoked on the spy. The spied instance is only used at mock creation to copy the state from. * If you call a method on a regular spy and it internally calls other methods on this spy, those calls are remembered * for verifications, and they can be effectively stubbed. * </li> * <li> * The mock that delegates simply delegates all methods to the delegate. * The delegate is used all the time as methods are delegated onto it. * If you call a method on a mock that delegates and it internally calls other methods on this mock, * those calls are <strong>not</strong> remembered for verifications, stubbing does not have effect on them, too. * Mock that delegates is less powerful than the regular spy but it is useful when the regular spy cannot be created. * </li> * </ul> * * <p> * See more information in docs for {@link AdditionalAnswers#delegatesTo(Object)}. * * * * * <h3 id="28">28. <a class="meaningful_link" href="#mock_maker_plugin" name="mock_maker_plugin"><code>MockMaker</code> API</a> (Since 1.9.5)</h3> * <p>Driven by requirements and patches from Google Android guys Mockito now offers an extension point * that allows replacing the proxy generation engine. By default, Mockito uses <a href="https://github.com/raphw/byte-buddy">Byte Buddy</a> * to create dynamic proxies. * <p>The extension point is for advanced users that want to extend Mockito. For example, it is now possible * to use Mockito for Android testing with a help of <a href="https://github.com/crittercism/dexmaker">dexmaker</a>. * <p>For more details, motivations and examples please refer to * the docs for {@link org.mockito.plugins.MockMaker}. * * * * * <h3 id="29">29. <a class="meaningful_link" href="#BDD_behavior_verification" name="BDD_behavior_verification">BDD style verification</a> (Since 1.10.0)</h3> * * Enables Behavior Driven Development (BDD) style verification by starting verification with the BDD <b>then</b> keyword. * * <pre class="code"><code class="java"> * given(dog.bark()).willReturn(2); * * // when * ... * * then(person).should(times(2)).ride(bike); * </code></pre> * * For more information and an example see {@link BDDMockito#then(Object)} * * * * * <h3 id="30">30. <a class="meaningful_link" href="#spying_abstract_classes" name="spying_abstract_classes">Spying or mocking abstract classes (Since 1.10.12, further enhanced in 2.7.13 and 2.7.14)</a></h3> * * It is now possible to conveniently spy on abstract classes. Note that overusing spies hints at code design smells (see {@link #spy(Object)}). * <p> * Previously, spying was only possible on instances of objects. * New API makes it possible to use constructor when creating an instance of the mock. * This is particularly useful for mocking abstract classes because the user is no longer required to provide an instance of the abstract class. * At the moment, only parameter-less constructor is supported, let us know if it is not enough. * * <pre class="code"><code class="java"> * //convenience API, new overloaded spy() method: * SomeAbstract spy = spy(SomeAbstract.class); * * //Mocking abstract methods, spying default methods of an interface (only available since 2.7.13) * Function&lt;Foo, Bar&gt; function = spy(Function.class); * * //Robust API, via settings builder: * OtherAbstract spy = mock(OtherAbstract.class, withSettings() * .useConstructor().defaultAnswer(CALLS_REAL_METHODS)); * * //Mocking an abstract class with constructor arguments (only available since 2.7.14) * SomeAbstract spy = mock(SomeAbstract.class, withSettings() * .useConstructor("arg1", 123).defaultAnswer(CALLS_REAL_METHODS)); * * //Mocking a non-static inner abstract class: * InnerAbstract spy = mock(InnerAbstract.class, withSettings() * .useConstructor().outerInstance(outerInstance).defaultAnswer(CALLS_REAL_METHODS)); * </code></pre> * * For more information please see {@link MockSettings#useConstructor(Object...)}. * * * * * <h3 id="31">31. <a class="meaningful_link" href="#serilization_across_classloader" name="serilization_across_classloader">Mockito mocks can be <em>serialized</em> / <em>deserialized</em> across classloaders (Since 1.10.0)</a></h3> * * Mockito introduces serialization across classloader. * * Like with any other form of serialization, all types in the mock hierarchy have to serializable, including answers. * As this serialization mode require considerably more work, this is an opt-in setting. * * <pre class="code"><code class="java"> * // use regular serialization * mock(Book.class, withSettings().serializable()); * * // use serialization across classloaders * mock(Book.class, withSettings().serializable(ACROSS_CLASSLOADERS)); * </code></pre> * * For more details see {@link MockSettings#serializable(SerializableMode)}. * * * * * <h3 id="32">32. <a class="meaningful_link" href="#better_generic_support_with_deep_stubs" name="better_generic_support_with_deep_stubs">Better generic support with deep stubs (Since 1.10.0)</a></h3> * * Deep stubbing has been improved to find generic information if available in the class. * That means that classes like this can be used without having to mock the behavior. * * <pre class="code"><code class="java"> * class Lines extends List&lt;Line&gt; { * // ... * } * * lines = mock(Lines.class, RETURNS_DEEP_STUBS); * * // Now Mockito understand this is not an Object but a Line * Line line = lines.iterator().next(); * </code></pre> * * Please note that in most scenarios a mock returning a mock is wrong. * * * * * <h3 id="33">33. <a class="meaningful_link" href="#mockito_junit_rule" name="mockito_junit_rule">Mockito JUnit rule (Since 1.10.17)</a></h3> * * Mockito now offers a JUnit rule. Until now in JUnit there were two ways to initialize fields annotated by Mockito annotations * such as <code>&#064;{@link Mock}</code>, <code>&#064;{@link Spy}</code>, <code>&#064;{@link InjectMocks}</code>, etc. * * <ul> * <li>Annotating the JUnit test class with a <code>&#064;{@link org.junit.runner.RunWith}({@link MockitoJUnitRunner}.class)</code></li> * <li>Invoking <code>{@link MockitoAnnotations#openMocks(Object)}</code> in the <code>&#064;{@link org.junit.Before}</code> method</li> * </ul> * * Now you can choose to use a rule : * * <pre class="code"><code class="java"> * &#064;RunWith(YetAnotherRunner.class) * public class TheTest { * &#064;Rule public MockitoRule mockito = MockitoJUnit.rule(); * // ... * } * </code></pre> * * For more information see {@link MockitoJUnit#rule()}. * * * * * <h3 id="34">34. <a class="meaningful_link" href="#plugin_switch" name="plugin_switch">Switch <em>on</em> or <em>off</em> plugins (Since 1.10.15)</a></h3> * * An incubating feature made it's way in mockito that will allow to toggle a mockito-plugin. * * More information here {@link org.mockito.plugins.PluginSwitch}. * * * <h3 id="35">35. <a class="meaningful_link" href="#Custom_verification_failure_message" name="Custom_verification_failure_message">Custom verification failure message</a> (Since 2.1.0)</h3> * <p> * Allows specifying a custom message to be printed if verification fails. * <p> * Examples: * <p> * <pre class="code"><code class="java"> * * // will print a custom message on verification failure * verify(mock, description("This will print on failure")).someMethod(); * * // will work with any verification mode * verify(mock, times(2).description("someMethod should be called twice")).someMethod(); * </code></pre> * * <h3 id="36">36. <a class="meaningful_link" href="#Java_8_Lambda_Matching" name="Java_8_Lambda_Matching">Java 8 Lambda Matcher Support</a> (Since 2.1.0)</h3> * <p> * You can use Java 8 lambda expressions with {@link ArgumentMatcher} to reduce the dependency on {@link ArgumentCaptor}. * If you need to verify that the input to a function call on a mock was correct, then you would normally * use the {@link ArgumentCaptor} to find the operands used and then do subsequent assertions on them. While * for complex examples this can be useful, it's also long-winded.<p> * Writing a lambda to express the match is quite easy. The argument to your function, when used in conjunction * with argThat, will be passed to the ArgumentMatcher as a strongly typed object, so it is possible * to do anything with it. * <p> * Examples: * <p> * <pre class="code"><code class="java"> * * // verify a list only had strings of a certain length added to it * // note - this will only compile under Java 8 * verify(list, times(2)).add(argThat(string -&gt; string.length() &lt; 5)); * * // Java 7 equivalent - not as neat * verify(list, times(2)).add(argThat(new ArgumentMatcher&lt;String&gt;(){ * public boolean matches(String arg) { * return arg.length() &lt; 5; * } * })); * * // more complex Java 8 example - where you can specify complex verification behaviour functionally * verify(target, times(1)).receiveComplexObject(argThat(obj -&gt; obj.getSubObject().get(0).equals("expected"))); * * // this can also be used when defining the behaviour of a mock under different inputs * // in this case if the input list was fewer than 3 items the mock returns null * when(mock.someMethod(argThat(list -&gt; list.size()&lt;3))).thenReturn(null); * </code></pre> * * <h3 id="37">37. <a class="meaningful_link" href="#Java_8_Custom_Answers" name="Java_8_Custom_Answers">Java 8 Custom Answer Support</a> (Since 2.1.0)</h3> * <p> * As the {@link Answer} interface has just one method it is already possible to implement it in Java 8 using * a lambda expression for very simple situations. The more you need to use the parameters of the method call, * the more you need to typecast the arguments from {@link org.mockito.invocation.InvocationOnMock}. * * <p> * Examples: * <p> * <pre class="code"><code class="java"> * // answer by returning 12 every time * doAnswer(invocation -&gt; 12).when(mock).doSomething(); * * // answer by using one of the parameters - converting into the right * // type as your go - in this case, returning the length of the second string parameter * // as the answer. This gets long-winded quickly, with casting of parameters. * doAnswer(invocation -&gt; ((String)invocation.getArgument(1)).length()) * .when(mock).doSomething(anyString(), anyString(), anyString()); * </code></pre> * * For convenience it is possible to write custom answers/actions, which use the parameters to the method call, * as Java 8 lambdas. Even in Java 7 and lower these custom answers based on a typed interface can reduce boilerplate. * In particular, this approach will make it easier to test functions which use callbacks. * * The methods {@link AdditionalAnswers#answer(Answer1)}} and {@link AdditionalAnswers#answerVoid(VoidAnswer1)} * can be used to create the answer. They rely on the related answer interfaces in org.mockito.stubbing that * support answers up to 5 parameters. * * <p> * Examples: * <p> * <pre class="code"><code class="java"> * * // Example interface to be mocked has a function like: * void execute(String operand, Callback callback); * * // the example callback has a function and the class under test * // will depend on the callback being invoked * void receive(String item); * * // Java 8 - style 1 * doAnswer(AdditionalAnswers.&lt;String,Callback&gt;answerVoid((operand, callback) -&gt; callback.receive("dummy"))) * .when(mock).execute(anyString(), any(Callback.class)); * * // Java 8 - style 2 - assuming static import of AdditionalAnswers * doAnswer(answerVoid((String operand, Callback callback) -&gt; callback.receive("dummy"))) * .when(mock).execute(anyString(), any(Callback.class)); * * // Java 8 - style 3 - where mocking function to is a static member of test class * private static void dummyCallbackImpl(String operation, Callback callback) { * callback.receive("dummy"); * } * * doAnswer(answerVoid(TestClass::dummyCallbackImpl)) * .when(mock).execute(anyString(), any(Callback.class)); * * // Java 7 * doAnswer(answerVoid(new VoidAnswer2&lt;String, Callback&gt;() { * public void answer(String operation, Callback callback) { * callback.receive("dummy"); * }})).when(mock).execute(anyString(), any(Callback.class)); * * // returning a value is possible with the answer() function * // and the non-void version of the functional interfaces * // so if the mock interface had a method like * boolean isSameString(String input1, String input2); * * // this could be mocked * // Java 8 * doAnswer(AdditionalAnswers.&lt;Boolean,String,String&gt;answer((input1, input2) -&gt; input1.equals(input2))) * .when(mock).execute(anyString(), anyString()); * * // Java 7 * doAnswer(answer(new Answer2&lt;String, String, String&gt;() { * public String answer(String input1, String input2) { * return input1 + input2; * }})).when(mock).execute(anyString(), anyString()); * </code></pre> * * <h3 id="38">38. <a class="meaningful_link" href="#Meta_Data_And_Generics" name="Meta_Data_And_Generics">Meta data and generic type retention</a> (Since 2.1.0)</h3> * * <p> * Mockito now preserves annotations on mocked methods and types as well as generic meta data. Previously, a mock type did not preserve * annotations on types unless they were explicitly inherited and never retained annotations on methods. As a consequence, the following * conditions now hold true: * * <pre class="code"><code class="java"> * {@literal @}{@code MyAnnotation * class Foo { * List<String> bar() { ... } * } * * Class<?> mockType = mock(Foo.class).getClass(); * assert mockType.isAnnotationPresent(MyAnnotation.class); * assert mockType.getDeclaredMethod("bar").getGenericReturnType() instanceof ParameterizedType; * }</code></pre> * * <p> * When using Java 8, Mockito now also preserves type annotations. This is default behavior and might not hold <a href="#28">if an * alternative {@link org.mockito.plugins.MockMaker} is used</a>. * * <h3 id="39">39. <a class="meaningful_link" href="#Mocking_Final" name="Mocking_Final">Mocking final types, enums and final methods</a> (Since 2.1.0)</h3> * * Mockito now offers support for mocking final classes and methods by default. * This is a fantastic improvement that demonstrates Mockito's everlasting quest for improving testing experience. * Our ambition is that Mockito "just works" with final classes and methods. * Previously they were considered <em>unmockable</em>, preventing the user from mocking. * Since 5.0.0, this feature is enabled by default. * * <p> * This alternative mock maker which uses * a combination of both Java instrumentation API and sub-classing rather than creating a new class to represent * a mock. This way, it becomes possible to mock final types and methods. * * <p> * In versions preceding 5.0.0, this mock maker is <strong>turned off by default</strong> because it is based on * completely different mocking mechanism that required more feedback from the community. It can be activated * explicitly by the mockito extension mechanism, just create in the classpath a file * <code>/mockito-extensions/org.mockito.plugins.MockMaker</code> containing the value <code>mock-maker-inline</code>. * * <p> * As a convenience, the Mockito team provides an artifact where this mock maker is preconfigured. Instead of using the * <i>mockito-core</i> artifact, include the <i>mockito-inline</i> artifact in your project. Note that this artifact is * likely to be discontinued once mocking of final classes and methods gets integrated into the default mock maker. * * <p> * Some noteworthy notes about this mock maker: * <ul> * <li>Mocking final types and enums is incompatible with mock settings like : * <ul> * <li>explicitly serialization support <code>withSettings().serializable()</code></li> * <li>extra-interfaces <code>withSettings().extraInterfaces()</code></li> * </ul> * </li> * <li>Some methods cannot be mocked * <ul> * <li>Package-visible methods of <code>java.*</code></li> * <li><code>native</code> methods</li> * </ul> * </li> * <li>This mock maker has been designed around Java Agent runtime attachment ; this require a compatible JVM, * that is part of the JDK (or Java 9 VM). When running on a non-JDK VM prior to Java 9, it is however possible to * manually add the <a href="https://bytebuddy.net">Byte Buddy Java agent jar</a> using the <code>-javaagent</code> * parameter upon starting the JVM. * </li> * </ul> * * <p> * If you are interested in more details of this feature please read the javadoc of * <code>org.mockito.internal.creation.bytebuddy.InlineByteBuddyMockMaker</code> * * <h3 id="40">40. <a class="meaningful_link" href="#strict_mockito" name="strict_mockito"> * Improved productivity and cleaner tests with "stricter" Mockito</a> (Since 2.+)</h3> * * To quickly find out how "stricter" Mockito can make you more productive and get your tests cleaner, see: * <ul> * <li>Strict stubbing with JUnit4 Rules - {@link MockitoRule#strictness(Strictness)} with {@link Strictness#STRICT_STUBS}</li> * <li>Strict stubbing with JUnit4 Runner - {@link Strict MockitoJUnitRunner.Strict}</li> * <li>Strict stubbing with JUnit5 Extension - <code>org.mockito.junit.jupiter.MockitoExtension</code></li> * <li>Strict stubbing with TestNG Listener <a href="https://github.com/mockito/mockito-testng">MockitoTestNGListener</a></li> * <li>Strict stubbing if you cannot use runner/rule - {@link MockitoSession}</li> * <li>Unnecessary stubbing detection with {@link MockitoJUnitRunner}</li> * <li>Stubbing argument mismatch warnings, documented in {@link MockitoHint}</li> * </ul> * * Mockito is a "loose" mocking framework by default. * Mocks can be interacted with without setting any expectations beforehand. * This is intentional and it improves the quality of tests by forcing users to be explicit about what they want to stub / verify. * It is also very intuitive, easy to use and blends nicely with "given", "when", "then" template of clean test code. * This is also different from the classic mocking frameworks of the past, they were "strict" by default. * <p> * Being "loose" by default makes Mockito tests harder to debug at times. * There are scenarios where misconfigured stubbing (like using a wrong argument) forces the user to run the test with a debugger. * Ideally, tests failures are immediately obvious and don't require debugger to identify the root cause. * Starting with version 2.1 Mockito has been getting new features that nudge the framework towards "strictness". * We want Mockito to offer fantastic debuggability while not losing its core mocking style, optimized for * intuitiveness, explicitness and clean test code. * <p> * Help Mockito! Try the new features, give us feedback, join the discussion about Mockito strictness at GitHub * <a href="https://github.com/mockito/mockito/issues/769">issue 769</a>. * * <h3 id="41">41. <a class="meaningful_link" href="#framework_integrations_api" name="framework_integrations_api"> * Advanced public API for framework integrations (Since 2.10.+)</a></h3> * * In Summer 2017 we decided that Mockito * <a href="https://www.linkedin.com/pulse/mockito-vs-powermock-opinionated-dogmatic-static-mocking-faber"> * should offer better API * </a> * for advanced framework integrations. * The new API is not intended for users who want to write unit tests. * It is intended for other test tools and mocking frameworks that need to extend or wrap Mockito with some custom logic. * During the design and implementation process (<a href="https://github.com/mockito/mockito/issues/1110">issue 1110</a>) * we have developed and changed following public API elements: * <ul> * <li>New {@link MockitoPlugins} - * Enables framework integrators to get access to default Mockito plugins. * Useful when one needs to implement custom plugin such as {@link MockMaker} * and delegate some behavior to the default Mockito implementation. * </li> * <li>New {@link MockSettings#build(Class)} - * Creates immutable view of mock settings used later by Mockito. * Useful for creating invocations with {@link InvocationFactory} or when implementing custom {@link MockHandler}. * </li> * <li>New {@link MockingDetails#getMockHandler()} - * Other frameworks may use the mock handler to programmatically simulate invocations on mock objects. * </li> * <li>New {@link MockHandler#getMockSettings()} - * Useful to get hold of the setting the mock object was created with. * </li> * <li>New {@link InvocationFactory} - * Provides means to create instances of {@link Invocation} objects. * Useful for framework integrations that need to programmatically simulate method calls on mock objects. * </li> * <li>New {@link MockHandler#getInvocationContainer()} - * Provides access to invocation container object which has no methods (marker interface). * Container is needed to hide the internal implementation and avoid leaking it to the public API. * </li> * <li>Changed {@link org.mockito.stubbing.Stubbing} - * it now extends {@link Answer} interface. * It is backwards compatible because Stubbing interface is not extensible (see {@link NotExtensible}). * The change should be seamless to our users. * </li> * <li>{@link NotExtensible} - * Public annotation that indicates to the user that she should not provide custom implementations of given type. * Helps framework integrators and our users understand how to use Mockito API safely. * </li> * </ul> * Do you have feedback? Please leave comment in <a href="https://github.com/mockito/mockito/issues/1110">issue 1110</a>. * * <h3 id="42">42. <a class="meaningful_link" href="#verifiation_started_listener" name="verifiation_started_listener"> * New API for integrations: listening on verification start events (Since 2.11.+)</a></h3> * * Framework integrations such as <a href="https://projects.spring.io/spring-boot">Spring Boot</a> needs public API to tackle double-proxy use case * (<a href="https://github.com/mockito/mockito/issues/1191">issue 1191</a>). * We added: * <ul> * <li>New {@link VerificationStartedListener} and {@link VerificationStartedEvent} * enable framework integrators to replace the mock object for verification. * The main driving use case is <a href="https://projects.spring.io/spring-boot/">Spring Boot</a> integration. * For details see Javadoc for {@link VerificationStartedListener}. * </li> * <li>New public method {@link MockSettings#verificationStartedListeners(VerificationStartedListener...)} * allows to supply verification started listeners at mock creation time. * </li> * <li>New handy method {@link MockingDetails#getMock()} was added to make the {@code MockingDetails} API more complete. * We found this method useful during the implementation. * </li> * </ul> * * <h3 id="43">43. <a class="meaningful_link" href="#mockito_session_testing_frameworks" name="mockito_session_testing_frameworks"> * New API for integrations: <code>MockitoSession</code> is usable by testing frameworks (Since 2.15.+)</a></h3> * * <p>{@link MockitoSessionBuilder} and {@link MockitoSession} were enhanced to enable reuse by testing framework * integrations (e.g. {@link MockitoRule} for JUnit):</p> * <ul> * <li>{@link MockitoSessionBuilder#initMocks(Object...)} allows to pass in multiple test class instances for * initialization of fields annotated with Mockito annotations like {@link org.mockito.Mock}. * This method is useful for advanced framework integrations (e.g. JUnit Jupiter), when a test uses multiple, * e.g. nested, test class instances. * </li> * <li>{@link MockitoSessionBuilder#name(String)} allows to pass a name from the testing framework to the * {@link MockitoSession} that will be used for printing warnings when {@link Strictness#WARN} is used. * </li> * <li>{@link MockitoSessionBuilder#logger(MockitoSessionLogger)} makes it possible to customize the logger used * for hints/warnings produced when finishing mocking (useful for testing and to connect reporting capabilities * provided by testing frameworks such as JUnit Jupiter). * </li> * <li>{@link MockitoSession#setStrictness(Strictness)} allows to change the strictness of a {@link MockitoSession} * for one-off scenarios, e.g. it enables configuring a default strictness for all tests in a class but makes it * possible to change the strictness for a single or a few tests. * </li> * <li>{@link MockitoSession#finishMocking(Throwable)} was added to avoid confusion that may arise because * there are multiple competing failures. It will disable certain checks when the supplied <em>failure</em> * is not {@code null}. * </li> * </ul> * * <h3 id="44">44. <a class="meaningful_link" href="#mockito_instantiator_provider_deprecation" name="mockito_instantiator_provider_deprecation"> * Deprecated <code>org.mockito.plugins.InstantiatorProvider</code> as it was leaking internal API. it was * replaced by <code>org.mockito.plugins.InstantiatorProvider2 (Since 2.15.4)</code></a></h3> * * <p>org.mockito.plugins.InstantiatorProvider returned an internal API. Hence it was deprecated and replaced * by {@link org.mockito.plugins.InstantiatorProvider2}. org.mockito.plugins.InstantiatorProvider * has now been removed.</p> * * <h3 id="45">45. <a class="meaningful_link" href="#junit5_mockito" name="junit5_mockito">New JUnit Jupiter (JUnit5+) extension</a></h3> * * For integration with JUnit Jupiter (JUnit5+), use the `org.mockito:mockito-junit-jupiter` artifact. * For more information about the usage of the integration, see <a href="https://javadoc.io/doc/org.mockito/mockito-junit-jupiter/latest/org/mockito/junit/jupiter/MockitoExtension.html">the JavaDoc of <code>MockitoExtension</code></a>. * * <h3 id="46">46. <a class="meaningful_link" href="#mockito_lenient" name="mockito_lenient"> * New <code>Mockito.lenient()</code> and <code>MockSettings.lenient()</code> methods (Since 2.20.0)</a></h3> * * Strict stubbing feature is available since early Mockito 2. * It is very useful because it drives cleaner tests and improved productivity. * Strict stubbing reports unnecessary stubs, detects stubbing argument mismatch and makes the tests more DRY ({@link Strictness#STRICT_STUBS}). * This comes with a trade-off: in some cases, you may get false negatives from strict stubbing. * To remedy those scenarios you can now configure specific stubbing to be lenient, while all the other stubbings and mocks use strict stubbing: * * <pre class="code"><code class="java"> * lenient().when(mock.foo()).thenReturn("ok"); * </code></pre> * * If you want all the stubbings on a given mock to be lenient, you can configure the mock accordingly: * * <pre class="code"><code class="java"> * Foo mock = Mockito.mock(Foo.class, withSettings().lenient()); * </code></pre> * * For more information refer to {@link Mockito#lenient()}. * Let us know how do you find the new feature by opening a GitHub issue to discuss! * * <h3 id="47">47. <a class="meaningful_link" href="#clear_inline_mocks" name="clear_inline_mocks">New API for clearing mock state in inline mocking (Since 2.25.0)</a></h3> * * In certain specific, rare scenarios (issue <a href="https://github.com/mockito/mockito/pull/1619">#1619</a>) * inline mocking causes memory leaks. * There is no clean way to mitigate this problem completely. * Hence, we introduced a new API to explicitly clear mock state (only make sense in inline mocking!). * See example usage in {@link MockitoFramework#clearInlineMocks()}. * If you have feedback or a better idea how to solve the problem please reach out. * * * <h3 id="48">48. <a class="meaningful_link" href="#static_mocks" name="static_mocks">Mocking static methods</a> (since 3.4.0)</h3> * * When using the <a href="#0.2">inline mock maker</a>, it is possible to mock static method invocations within the current * thread and a user-defined scope. This way, Mockito assures that concurrently and sequentially running tests do not interfere. * * To make sure a static mock remains temporary, it is recommended to define the scope within a try-with-resources construct. * In the following example, the <code>Foo</code> type's static method would return <code>foo</code> unless mocked: * * <pre class="code"><code class="java"> * assertEquals("foo", Foo.method()); * try (MockedStatic<Foo> mocked = mockStatic(Foo.class)) { * mocked.when(Foo::method).thenReturn("bar"); * assertEquals("bar", Foo.method()); * mocked.verify(Foo::method); * } * assertEquals("foo", Foo.method()); * </code></pre> * * Due to the defined scope of the static mock, it returns to its original behavior once the scope is released. To define mock * behavior and to verify static method invocations, use the <code>MockedStatic</code> that is returned. * <p> * * <h3 id="49">49. <a class="meaningful_link" href="#mocked_construction" name="mocked_construction">Mocking object construction</a> (since 3.5.0)</h3> * * When using the <a href="#0.2">inline mock maker</a>, it is possible to generate mocks on constructor invocations within the current * thread and a user-defined scope. This way, Mockito assures that concurrently and sequentially running tests do not interfere. * * To make sure a constructor mocks remain temporary, it is recommended to define the scope within a try-with-resources construct. * In the following example, the <code>Foo</code> type's construction would generate a mock: * * <pre class="code"><code class="java"> * assertEquals("foo", new Foo().method()); * try (MockedConstruction<Foo> mocked = mockConstruction(Foo.class)) { * Foo foo = new Foo(); * when(foo.method()).thenReturn("bar"); * assertEquals("bar", foo.method()); * verify(foo).method(); * } * assertEquals("foo", new Foo().method()); * </code></pre> * * Due to the defined scope of the mocked construction, object construction returns to its original behavior once the scope is * released. To define mock behavior and to verify method invocations, use the <code>MockedConstruction</code> that is returned. * <p> * * <h3 id="50">50. <a class="meaningful_link" href="#proxy_mock_maker" name="proxy_mock_maker">Avoiding code generation when only interfaces are mocked</a> (since 3.12.2)</h3> * * The JVM offers the {@link java.lang.reflect.Proxy} facility for creating dynamic proxies of interface types. For most applications, Mockito * must be capable of mocking classes as supported by the default mock maker, or even final classes, as supported by the inline mock maker. To * create such mocks, Mockito requires to setup diverse JVM facilities and must apply code generation. If only interfaces are supposed to be * mocked, one can however choose to use a org.mockito.internal.creation.proxy.ProxyMockMaker that is based on the {@link java.lang.reflect.Proxy} * API which avoids diverse overhead of the other mock makers but also limits mocking to interfaces. * * This mock maker can be activated explicitly by the mockito extension mechanism, just create in the classpath a file * <code>/mockito-extensions/org.mockito.plugins.MockMaker</code> containing the value <code>mock-maker-proxy</code>. * * <h3 id="51">51. <a class="meaningful_link" href="#do_not_mock" name="do_not_mock">Mark classes as unmockable</a> (since 4.1.0)</h3> * * In some cases, mocking a class/interface can lead to unexpected runtime behavior. For example, mocking a <code>java.util.List</code> * is difficult, given the requirements imposed by the interface. This means that on runtime, depending on what methods the application * calls on the list, your mock might behave in such a way that it violates the interface. * * <p> * For any class/interface you own that is problematic to mock, you can now mark the class with {@link org.mockito.DoNotMock @DoNotMock}. For usage * of the annotation and how to ship your own (to avoid a compile time dependency on a test artifact), please see its JavaDoc. * <p> * * <h3 id="52">52. <a class="meaningful_link" href="#mockito_strictness" name="mockito_strictness"> * New strictness attribute for @Mock annotation and <code>MockSettings.strictness()</code> methods</a> (Since 4.6.0)</h3> * * You can now customize the strictness level for a single mock, either using `@Mock` annotation strictness attribute or * using `MockSettings.strictness()`. This can be useful if you want all of your mocks to be strict, * but one of the mocks to be lenient. * * <pre class="code"><code class="java"> * &#064;Mock(strictness = Strictness.LENIENT) * Foo mock; * // using MockSettings.withSettings() * Foo mock = Mockito.mock(Foo.class, withSettings().strictness(Strictness.WARN)); * </code></pre> * * <h3 id="53">53. <a class="meaningful_link" href="#individual_mock_maker" name="individual_mock_maker"> * Specifying mock maker for individual mocks</a> (Since 4.8.0)</h3> * * You may encounter situations where you want to use a different mock maker for a specific test only. * In such case, you can (temporarily) use {@link MockSettings#mockMaker(String)} and {@link Mock#mockMaker()} * to specify the mock maker for a specific mock which is causing the problem. * * <pre class="code"><code class="java"> * // using annotation * &#064;Mock(mockMaker = MockMakers.SUBCLASS) * Foo mock; * // using MockSettings.withSettings() * Foo mock = Mockito.mock(Foo.class, withSettings().mockMaker(MockMakers.SUBCLASS)); * </code></pre> * * <h3 id="54">54. <a class="meaningful_link" href="#mock_without_class" name="mock_without_class"> * Mocking/spying without specifying class</a> (Since 4.10.0)</h3> * * Instead of calling method {@link Mockito#mock(Class)} or {@link Mockito#spy(Class)} with Class parameter, you can * now call method {@code mock()} or {@code spy()} <strong>without parameters</strong>: * * <pre class="code"><code class="java"> * Foo foo = Mockito.mock(); * Bar bar = Mockito.spy(); * </code></pre> * * Mockito will automatically detect the needed class. * <p> * It works only if you assign result of {@code mock()} or {@code spy()} to a variable or field with an explicit type. * With an implicit type, the Java compiler is unable to automatically determine the type of a mock and you need * to pass in the {@code Class} explicitly. * </p> * * <h3 id="55">55. <a class="meaningful_link" href="#verification_with_assertions" name="verification_with_assertions"> * Verification with assertions</a> (Since 5.3.0)</h3> * * To validate arguments during verification, instead of capturing them with {@link ArgumentCaptor}, you can now * use {@link ArgumentMatchers#assertArg(Consumer)}}: * * <pre class="code"><code class="java"> * verify(serviceMock).doStuff(assertArg(param -&gt; { * assertThat(param.getField1()).isEqualTo("foo"); * assertThat(param.getField2()).isEqualTo("bar"); * })); * </code></pre> */ @CheckReturnValue @SuppressWarnings("unchecked") public class Mockito extends ArgumentMatchers { static final MockitoCore MOCKITO_CORE = new MockitoCore(); /** * The default <code>Answer</code> of every mock <b>if</b> the mock was not stubbed. * * Typically, it just returns some empty value. * <p> * {@link Answer} can be used to define the return values of un-stubbed invocations. * <p> * This implementation first tries the global configuration and if there is no global configuration then * it will use a default answer that returns zeros, empty collections, nulls, etc. */ public static final Answer<Object> RETURNS_DEFAULTS = Answers.RETURNS_DEFAULTS; /** * Optional <code>Answer</code> to be used with {@link Mockito#mock(Class, Answer)}. * <p> * {@link Answer} can be used to define the return values of un-stubbed invocations. * <p> * This implementation can be helpful when working with legacy code. * Un-stubbed methods often return null. If your code uses the object returned by an un-stubbed call, * you get a NullPointerException. * This implementation of Answer <b>returns SmartNull instead of null</b>. * <code>SmartNull</code> gives nicer exception messages than NPEs, because it points out the * line where the un-stubbed method was called. You just click on the stack trace. * <p> * <code>ReturnsSmartNulls</code> first tries to return ordinary values (zeros, empty collections, empty string, etc.) * then it tries to return SmartNull. If the return type is final then plain <code>null</code> is returned. * <p> * Example: * <pre class="code"><code class="java"> * Foo mock = mock(Foo.class, RETURNS_SMART_NULLS); * * //calling un-stubbed method here: * Stuff stuff = mock.getStuff(); * * //using object returned by un-stubbed call: * stuff.doSomething(); * * //Above doesn't yield NullPointerException this time! * //Instead, SmartNullPointerException is thrown. * //Exception's cause links to un-stubbed <i>mock.getStuff()</i> - just click on the stack trace. * </code></pre> */ public static final Answer<Object> RETURNS_SMART_NULLS = Answers.RETURNS_SMART_NULLS; /** * Optional <code>Answer</code> to be used with {@link Mockito#mock(Class, Answer)} * <p> * {@link Answer} can be used to define the return values of un-stubbed invocations. * <p> * This implementation can be helpful when working with legacy code. * <p> * ReturnsMocks first tries to return ordinary values (zeros, empty collections, empty string, etc.) * then it tries to return mocks. If the return type cannot be mocked (e.g. is final) then plain <code>null</code> is returned. * <p> */ public static final Answer<Object> RETURNS_MOCKS = Answers.RETURNS_MOCKS; /** * Optional <code>Answer</code> to be used with {@link Mockito#mock(Class, Answer)}. * <p> * Example that shows how deep stub works: * <pre class="code"><code class="java"> * Foo mock = mock(Foo.class, RETURNS_DEEP_STUBS); * * // note that we're stubbing a chain of methods here: getBar().getName() * when(mock.getBar().getName()).thenReturn("deep"); * * // note that we're chaining method calls: getBar().getName() * assertEquals("deep", mock.getBar().getName()); * </code></pre> * </p> * * <p> * <strong>WARNING: </strong> * This feature should rarely be required for regular clean code! Leave it for legacy code. * Mocking a mock to return a mock, to return a mock, (...), to return something meaningful * hints at violation of Law of Demeter or mocking a value object (a well known anti-pattern). * </p> * * <p> * Good quote I've seen one day on the web: <strong>every time a mock returns a mock a fairy dies</strong>. * </p> * * <p> * Please note that this answer will return existing mocks that matches the stub. This * behavior is ok with deep stubs and allows verification to work on the last mock of the chain. * <pre class="code"><code class="java"> * when(mock.getBar(anyString()).getThingy().getName()).thenReturn("deep"); * * mock.getBar("candy bar").getThingy().getName(); * * assertSame(mock.getBar(anyString()).getThingy().getName(), mock.getBar(anyString()).getThingy().getName()); * verify(mock.getBar("candy bar").getThingy()).getName(); * verify(mock.getBar(anyString()).getThingy()).getName(); * </code></pre> * </p> * * <p> * Verification only works with the last mock in the chain. You can use verification modes. * <pre class="code"><code class="java"> * when(person.getAddress(anyString()).getStreet().getName()).thenReturn("deep"); * when(person.getAddress(anyString()).getStreet(Locale.ITALIAN).getName()).thenReturn("deep"); * when(person.getAddress(anyString()).getStreet(Locale.CHINESE).getName()).thenReturn("deep"); * * person.getAddress("the docks").getStreet().getName(); * person.getAddress("the docks").getStreet().getLongName(); * person.getAddress("the docks").getStreet(Locale.ITALIAN).getName(); * person.getAddress("the docks").getStreet(Locale.CHINESE).getName(); * * // note that we are actually referring to the very last mock in the stubbing chain. * InOrder inOrder = inOrder( * person.getAddress("the docks").getStreet(), * person.getAddress("the docks").getStreet(Locale.CHINESE), * person.getAddress("the docks").getStreet(Locale.ITALIAN) * ); * inOrder.verify(person.getAddress("the docks").getStreet(), times(1)).getName(); * inOrder.verify(person.getAddress("the docks").getStreet()).getLongName(); * inOrder.verify(person.getAddress("the docks").getStreet(Locale.ITALIAN), atLeast(1)).getName(); * inOrder.verify(person.getAddress("the docks").getStreet(Locale.CHINESE)).getName(); * </code></pre> * </p> * * <p> * How deep stub work internally? * <pre class="code"><code class="java"> * //this: * Foo mock = mock(Foo.class, RETURNS_DEEP_STUBS); * when(mock.getBar().getName(), "deep"); * * //is equivalent of * Foo foo = mock(Foo.class); * Bar bar = mock(Bar.class); * when(foo.getBar()).thenReturn(bar); * when(bar.getName()).thenReturn("deep"); * </code></pre> * </p> * * <p> * This feature will not work when any return type of methods included in the chain cannot be mocked * (for example: is a primitive or a final class). This is because of java type system. * </p> */ public static final Answer<Object> RETURNS_DEEP_STUBS = Answers.RETURNS_DEEP_STUBS; /** * Optional <code>Answer</code> to be used with {@link Mockito#mock(Class, Answer)} * * <p> * {@link Answer} can be used to define the return values of un-stubbed invocations. * <p> * This implementation can be helpful when working with legacy code. * When this implementation is used, un-stubbed methods will delegate to the real implementation. * This is a way to create a partial mock object that calls real methods by default. * <p> * As usual, you are going to read <b>the partial mock warning</b>: * Object oriented programming is more-or-less tackling complexity by dividing the complexity into separate, specific, SRPy objects. * How does partial mock fit into this paradigm? Well, it just doesn't... * Partial mock usually means that the complexity has been moved to a different method on the same object. * In most cases, this is not the way you want to design your application. * <p> * However, there are rare cases when partial mocks come handy: * dealing with code you cannot change easily (3rd party interfaces, interim refactoring of legacy code etc.) * However, I wouldn't use partial mocks for new, test-driven and well-designed code. * <p> * Example: * <pre class="code"><code class="java"> * Foo mock = mock(Foo.class, CALLS_REAL_METHODS); * * // this calls the real implementation of Foo.getSomething() * value = mock.getSomething(); * * doReturn(fakeValue).when(mock).getSomething(); * * // now fakeValue is returned * value = mock.getSomething(); * </code></pre> * * <p> * <u>Note 1:</u> Stubbing partial mocks using <code>when(mock.getSomething()).thenReturn(fakeValue)</code> * syntax will call the real method. For partial mock it's recommended to use <code>doReturn</code> syntax. * <p> * <u>Note 2:</u> If the mock is serialized then deserialized, then this answer will not be able to understand * generics metadata. */ public static final Answer<Object> CALLS_REAL_METHODS = Answers.CALLS_REAL_METHODS; /** * Optional <code>Answer</code> to be used with {@link Mockito#mock(Class, Answer)}. * * Allows Builder mocks to return itself whenever a method is invoked that returns a Type equal * to the class or a superclass. * * <p><b>Keep in mind this answer uses the return type of a method. * If this type is assignable to the class of the mock, it will return the mock. * Therefore if you have a method returning a superclass (for example {@code Object}) it will match and return the mock.</b></p> * * Consider a HttpBuilder used in a HttpRequesterWithHeaders. * * <pre class="code"><code class="java"> * public class HttpRequesterWithHeaders { * * private HttpBuilder builder; * * public HttpRequesterWithHeaders(HttpBuilder builder) { * this.builder = builder; * } * * public String request(String uri) { * return builder.withUrl(uri) * .withHeader("Content-type: application/json") * .withHeader("Authorization: Bearer") * .request(); * } * } * * private static class HttpBuilder { * * private String uri; * private List&lt;String&gt; headers; * * public HttpBuilder() { * this.headers = new ArrayList&lt;String&gt;(); * } * * public HttpBuilder withUrl(String uri) { * this.uri = uri; * return this; * } * * public HttpBuilder withHeader(String header) { * this.headers.add(header); * return this; * } * * public String request() { * return uri + headers.toString(); * } * } * </code></pre> * * The following test will succeed * * <pre><code> * &#064;Test * public void use_full_builder_with_terminating_method() { * HttpBuilder builder = mock(HttpBuilder.class, RETURNS_SELF); * HttpRequesterWithHeaders requester = new HttpRequesterWithHeaders(builder); * String response = "StatusCode: 200"; * * when(builder.request()).thenReturn(response); * * assertThat(requester.request("URI")).isEqualTo(response); * } * </code></pre> */ public static final Answer<Object> RETURNS_SELF = Answers.RETURNS_SELF; /** * Creates a mock object of the requested class or interface. * <p> * See examples in javadoc for the {@link Mockito} class. * * @param reified don't pass any values to it. It's a trick to detect the class/interface you * want to mock. * @return the mock object. * @since 4.10.0 */ @SafeVarargs public static <T> T mock(T... reified) { return mock(withSettings(), reified); } /** * Creates a mock object of the requested class or interface with the given default answer. * <p> * See examples in javadoc for the {@link Mockito} class. * * @param defaultAnswer the default answer to use. * @param reified don't pass any values to it. It's a trick to detect the class/interface you * want to mock. * @return the mock object. * @since 5.1.0 */ @SafeVarargs public static <T> T mock(@SuppressWarnings("rawtypes") Answer defaultAnswer, T... reified) { return mock(withSettings().defaultAnswer(defaultAnswer), reified); } /** * Creates a mock object of the requested class or interface with the given name. * <p> * See examples in javadoc for the {@link Mockito} class. * * @param name the mock name to use. * @param reified don't pass any values to it. It's a trick to detect the class/interface you * want to mock. * @return the mock object. * @since 5.1.0 */ @SafeVarargs public static <T> T mock(String name, T... reified) { return mock(withSettings().name(name).defaultAnswer(RETURNS_DEFAULTS), reified); } /** * Creates a mock object of the requested class or interface with the given settings. * <p> * See examples in javadoc for the {@link Mockito} class. * * @param settings the mock settings to use. * @param reified don't pass any values to it. It's a trick to detect the class/interface you * want to mock. * @return the mock object. * @since 5.1.0 */ @SafeVarargs public static <T> T mock(MockSettings settings, T... reified) { if (reified == null || reified.length > 0) { throw new IllegalArgumentException( "Please don't pass any values here. Java will detect class automagically."); } return mock(getClassOf(reified), settings); } /** * Creates mock object of given class or interface. * <p> * See examples in javadoc for {@link Mockito} class * * @param classToMock class or interface to mock * @return mock object */ public static <T> T mock(Class<T> classToMock) { return mock(classToMock, withSettings()); } /** * Specifies mock name. Naming mocks can be helpful for debugging - the name is used in all verification errors. * <p> * Beware that naming mocks is not a solution for complex code which uses too many mocks or collaborators. * <b>If you have too many mocks then refactor the code</b> so that it's easy to test/debug without necessity of naming mocks. * <p> * <b>If you use <code>&#064;Mock</code> annotation then you've got naming mocks for free!</b> <code>&#064;Mock</code> uses field name as mock name. {@link Mock Read more.} * <p> * * See examples in javadoc for {@link Mockito} class * * @param classToMock class or interface to mock * @param name of the mock * @return mock object */ public static <T> T mock(Class<T> classToMock, String name) { return mock(classToMock, withSettings().name(name).defaultAnswer(RETURNS_DEFAULTS)); } /** * Returns a MockingDetails instance that enables inspecting a particular object for Mockito related information. * Can be used to find out if given object is a Mockito mock * or to find out if a given mock is a spy or mock. * <p> * In future Mockito versions MockingDetails may grow and provide other useful information about the mock, * e.g. invocations, stubbing info, etc. * * @param toInspect - object to inspect. null input is allowed. * @return A {@link org.mockito.MockingDetails} instance. * @since 1.9.5 */ public static MockingDetails mockingDetails(Object toInspect) { return MOCKITO_CORE.mockingDetails(toInspect); } /** * Creates mock with a specified strategy for its answers to interactions. * It's quite an advanced feature and typically you don't need it to write decent tests. * However it can be helpful when working with legacy systems. * <p> * It is the default answer so it will be used <b>only when you don't</b> stub the method call. * * <pre class="code"><code class="java"> * Foo mock = mock(Foo.class, RETURNS_SMART_NULLS); * Foo mockTwo = mock(Foo.class, new YourOwnAnswer()); * </code></pre> * * <p>See examples in javadoc for {@link Mockito} class</p> * * @param classToMock class or interface to mock * @param defaultAnswer default answer for un-stubbed methods * * @return mock object */ public static <T> T mock(Class<T> classToMock, Answer defaultAnswer) { return mock(classToMock, withSettings().defaultAnswer(defaultAnswer)); } /** * Creates a mock with some non-standard settings. * <p> * The number of configuration points for a mock will grow, * so we need a fluent way to introduce new configuration without adding more and more overloaded Mockito.mock() methods. * Hence {@link MockSettings}. * <pre class="code"><code class="java"> * Listener mock = mock(Listener.class, withSettings() * .name("firstListner").defaultBehavior(RETURNS_SMART_NULLS)); * ); * </code></pre> * <b>Use it carefully and occasionally</b>. What might be reason your test needs non-standard mocks? * Is the code under test so complicated that it requires non-standard mocks? * Wouldn't you prefer to refactor the code under test, so that it is testable in a simple way? * <p> * See also {@link Mockito#withSettings()} * <p> * See examples in javadoc for {@link Mockito} class * * @param classToMock class or interface to mock * @param mockSettings additional mock settings * @return mock object */ public static <T> T mock(Class<T> classToMock, MockSettings mockSettings) { return MOCKITO_CORE.mock(classToMock, mockSettings); } /** * Creates a spy of the real object. The spy calls <b>real</b> methods unless they are stubbed. * <p> * Real spies should be used <b>carefully and occasionally</b>, for example when dealing with legacy code. * <p> * As usual, you are going to read <b>the partial mock warning</b>: * Object oriented programming tackles complexity by dividing the complexity into separate, specific, SRPy objects. * How does partial mock fit into this paradigm? Well, it just doesn't... * Partial mock usually means that the complexity has been moved to a different method on the same object. * In most cases, this is not the way you want to design your application. * <p> * However, there are rare cases when partial mocks come handy: * dealing with code you cannot change easily (3rd party interfaces, interim refactoring of legacy code etc.) * However, I wouldn't use partial mocks for new, test-driven and well-designed code. * <p> * Example: * * <pre class="code"><code class="java"> * List list = new LinkedList(); * List spy = spy(list); * * //optionally, you can stub out some methods: * when(spy.size()).thenReturn(100); * * //using the spy calls <b>real</b> methods * spy.add("one"); * spy.add("two"); * * //prints "one" - the first element of a list * System.out.println(spy.get(0)); * * //size() method was stubbed - 100 is printed * System.out.println(spy.size()); * * //optionally, you can verify * verify(spy).add("one"); * verify(spy).add("two"); * </code></pre> * * <h4>Important gotcha on spying real objects!</h4> * <ol> * <li>Sometimes it's impossible or impractical to use {@link Mockito#when(Object)} for stubbing spies. * Therefore for spies it is recommended to always use <code>doReturn</code>|<code>Answer</code>|<code>Throw()</code>|<code>CallRealMethod</code> * family of methods for stubbing. Example: * * <pre class="code"><code class="java"> * List list = new LinkedList(); * List spy = spy(list); * * //Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty) * when(spy.get(0)).thenReturn("foo"); * * //You have to use doReturn() for stubbing * doReturn("foo").when(spy).get(0); * </code></pre> * </li> * * <li>Mockito <b>*does not*</b> delegate calls to the passed real instance, instead it actually creates a copy of it. * So if you keep the real instance and interact with it, don't expect the spied to be aware of those interaction * and their effect on real instance state. * The corollary is that when an <b>*un-stubbed*</b> method is called <b>*on the spy*</b> but <b>*not on the real instance*</b>, * you won't see any effects on the real instance.</li> * * <li>Watch out for final methods. * Mockito doesn't mock final methods so the bottom line is: when you spy on real objects + you try to stub a final method = trouble. * Also you won't be able to verify those method as well. * </li> * </ol> * <p> * See examples in javadoc for {@link Mockito} class * * <p>Note that the spy won't have any annotations of the spied type, because CGLIB won't rewrite them. * It may troublesome for code that rely on the spy to have these annotations.</p> * * * @param object * to spy on * @return a spy of the real object */ public static <T> T spy(T object) { if (MockUtil.isMock(object)) { throw new IllegalArgumentException( "Please don't pass mock here. Spy is not allowed on mock."); } return MOCKITO_CORE.mock( (Class<T>) object.getClass(), withSettings().spiedInstance(object).defaultAnswer(CALLS_REAL_METHODS)); } /** * Please refer to the documentation of {@link #spy(Object)}. * Overusing spies hints at code design smells. * <p> * This method, in contrast to the original {@link #spy(Object)}, creates a spy based on class instead of an object. * Sometimes it is more convenient to create spy based on the class and avoid providing an instance of a spied object. * This is particularly useful for spying on abstract classes because they cannot be instantiated. * See also {@link MockSettings#useConstructor(Object...)}. * <p> * Examples: * <pre class="code"><code class="java"> * SomeAbstract spy = spy(SomeAbstract.class); * * //Robust API, via settings builder: * OtherAbstract spy = mock(OtherAbstract.class, withSettings() * .useConstructor().defaultAnswer(CALLS_REAL_METHODS)); * * //Mocking a non-static inner abstract class: * InnerAbstract spy = mock(InnerAbstract.class, withSettings() * .useConstructor().outerInstance(outerInstance).defaultAnswer(CALLS_REAL_METHODS)); * </code></pre> * * @param classToSpy the class to spy * @param <T> type of the spy * @return a spy of the provided class * @since 1.10.12 */ public static <T> T spy(Class<T> classToSpy) { return MOCKITO_CORE.mock( classToSpy, withSettings().useConstructor().defaultAnswer(CALLS_REAL_METHODS)); } /** * Please refer to the documentation of {@link #spy(Class)}. * * @param reified don't pass any values to it. It's a trick to detect the class/interface you want to mock. * @return spy object * @since 4.10.0 */ @SafeVarargs public static <T> T spy(T... reified) { if (reified.length > 0) { throw new IllegalArgumentException( "Please don't pass any values here. Java will detect class automagically."); } return spy(getClassOf(reified)); } private static <T> Class<T> getClassOf(T[] array) { return (Class<T>) array.getClass().getComponentType(); } /** * Creates a thread-local mock controller for all static methods of the given class or interface. * The returned object's {@link MockedStatic#close()} method must be called upon completing the * test or the mock will remain active on the current thread. * <p> * <b>Note</b>: We recommend against mocking static methods of classes in the standard library or * classes used by custom class loaders used to execute the block with the mocked class. A mock * maker might forbid mocking static methods of know classes that are known to cause problems. * Also, if a static method is a JVM-intrinsic, it cannot typically be mocked even if not * explicitly forbidden. * <p> * See examples in javadoc for {@link Mockito} class * * @param classToMock class or interface of which static mocks should be mocked. * @return mock controller */ public static <T> MockedStatic<T> mockStatic(Class<T> classToMock) { return mockStatic(classToMock, withSettings()); } /** * Creates a thread-local mock controller for all static methods of the given class or interface. * The returned object's {@link MockedStatic#close()} method must be called upon completing the * test or the mock will remain active on the current thread. * <p> * <b>Note</b>: We recommend against mocking static methods of classes in the standard library or * classes used by custom class loaders used to execute the block with the mocked class. A mock * maker might forbid mocking static methods of know classes that are known to cause problems. * Also, if a static method is a JVM-intrinsic, it cannot typically be mocked even if not * explicitly forbidden. * <p> * See examples in javadoc for {@link Mockito} class * * @param classToMock class or interface of which static mocks should be mocked. * @param defaultAnswer the default answer when invoking static methods. * @return mock controller */ public static <T> MockedStatic<T> mockStatic(Class<T> classToMock, Answer defaultAnswer) { return mockStatic(classToMock, withSettings().defaultAnswer(defaultAnswer)); } /** * Creates a thread-local mock controller for all static methods of the given class or interface. * The returned object's {@link MockedStatic#close()} method must be called upon completing the * test or the mock will remain active on the current thread. * <p> * <b>Note</b>: We recommend against mocking static methods of classes in the standard library or * classes used by custom class loaders used to execute the block with the mocked class. A mock * maker might forbid mocking static methods of know classes that are known to cause problems. * Also, if a static method is a JVM-intrinsic, it cannot typically be mocked even if not * explicitly forbidden. * <p> * See examples in javadoc for {@link Mockito} class * * @param classToMock class or interface of which static mocks should be mocked. * @param name the name of the mock to use in error messages. * @return mock controller */ public static <T> MockedStatic<T> mockStatic(Class<T> classToMock, String name) { return mockStatic(classToMock, withSettings().name(name)); } /** * Creates a thread-local mock controller for all static methods of the given class or interface. * The returned object's {@link MockedStatic#close()} method must be called upon completing the * test or the mock will remain active on the current thread. * <p> * <b>Note</b>: We recommend against mocking static methods of classes in the standard library or * classes used by custom class loaders used to execute the block with the mocked class. A mock * maker might forbid mocking static methods of know classes that are known to cause problems. * Also, if a static method is a JVM-intrinsic, it cannot typically be mocked even if not * explicitly forbidden. * <p> * See examples in javadoc for {@link Mockito} class * * @param classToMock class or interface of which static mocks should be mocked. * @param mockSettings the settings to use where only name and default answer are considered. * @return mock controller */ public static <T> MockedStatic<T> mockStatic(Class<T> classToMock, MockSettings mockSettings) { return MOCKITO_CORE.mockStatic(classToMock, mockSettings); } /** * Creates a thread-local mock controller for all constructions of the given class. * The returned object's {@link MockedConstruction#close()} method must be called upon completing the * test or the mock will remain active on the current thread. * <p> * See examples in javadoc for {@link Mockito} class * * @param classToMock non-abstract class of which constructions should be mocked. * @param defaultAnswer the default answer for the first created mock. * @param additionalAnswers the default answer for all additional mocks. For any access mocks, the * last answer is used. If this array is empty, the {@code defaultAnswer} is used. * @return mock controller */ public static <T> MockedConstruction<T> mockConstructionWithAnswer( Class<T> classToMock, Answer defaultAnswer, Answer... additionalAnswers) { return mockConstruction( classToMock, context -> { if (context.getCount() == 1 || additionalAnswers.length == 0) { return withSettings().defaultAnswer(defaultAnswer); } else if (context.getCount() > additionalAnswers.length) { return withSettings() .defaultAnswer(additionalAnswers[additionalAnswers.length - 1]); } else { return withSettings() .defaultAnswer(additionalAnswers[context.getCount() - 2]); } }, (mock, context) -> {}); } /** * Creates a thread-local mock controller for all constructions of the given class. * The returned object's {@link MockedConstruction#close()} method must be called upon completing the * test or the mock will remain active on the current thread. * <p> * See examples in javadoc for {@link Mockito} class * * @param classToMock non-abstract class of which constructions should be mocked. * @return mock controller */ public static <T> MockedConstruction<T> mockConstruction(Class<T> classToMock) { return mockConstruction(classToMock, index -> withSettings(), (mock, context) -> {}); } /** * Creates a thread-local mock controller for all constructions of the given class. * The returned object's {@link MockedConstruction#close()} method must be called upon completing the * test or the mock will remain active on the current thread. * <p> * See examples in javadoc for {@link Mockito} class * * @param classToMock non-abstract class of which constructions should be mocked. * @param mockInitializer a callback to prepare the methods on a mock after its instantiation. * @return mock controller */ public static <T> MockedConstruction<T> mockConstruction( Class<T> classToMock, MockedConstruction.MockInitializer<T> mockInitializer) { return mockConstruction(classToMock, withSettings(), mockInitializer); } /** * Creates a thread-local mock controller for all constructions of the given class. * The returned object's {@link MockedConstruction#close()} method must be called upon completing the * test or the mock will remain active on the current thread. * <p> * See examples in javadoc for {@link Mockito} class * * @param classToMock non-abstract class of which constructions should be mocked. * @param mockSettings the mock settings to use. * @return mock controller */ public static <T> MockedConstruction<T> mockConstruction( Class<T> classToMock, MockSettings mockSettings) { return mockConstruction(classToMock, context -> mockSettings); } /** * Creates a thread-local mock controller for all constructions of the given class. * The returned object's {@link MockedConstruction#close()} method must be called upon completing the * test or the mock will remain active on the current thread. * <p> * See examples in javadoc for {@link Mockito} class * * @param classToMock non-abstract class of which constructions should be mocked. * @param mockSettingsFactory the mock settings to use. * @return mock controller */ public static <T> MockedConstruction<T> mockConstruction( Class<T> classToMock, Function<MockedConstruction.Context, MockSettings> mockSettingsFactory) { return mockConstruction(classToMock, mockSettingsFactory, (mock, context) -> {}); } /** * Creates a thread-local mock controller for all constructions of the given class. * The returned object's {@link MockedConstruction#close()} method must be called upon completing the * test or the mock will remain active on the current thread. * <p> * See examples in javadoc for {@link Mockito} class * * @param classToMock non-abstract class of which constructions should be mocked. * @param mockSettings the settings to use. * @param mockInitializer a callback to prepare the methods on a mock after its instantiation. * @return mock controller */ public static <T> MockedConstruction<T> mockConstruction( Class<T> classToMock, MockSettings mockSettings, MockedConstruction.MockInitializer<T> mockInitializer) { return mockConstruction(classToMock, index -> mockSettings, mockInitializer); } /** * Creates a thread-local mock controller for all constructions of the given class. * The returned object's {@link MockedConstruction#close()} method must be called upon completing the * test or the mock will remain active on the current thread. * <p> * See examples in javadoc for {@link Mockito} class * * @param classToMock non-abstract class of which constructions should be mocked. * @param mockSettingsFactory a function to create settings to use. * @param mockInitializer a callback to prepare the methods on a mock after its instantiation. * @return mock controller */ public static <T> MockedConstruction<T> mockConstruction( Class<T> classToMock, Function<MockedConstruction.Context, MockSettings> mockSettingsFactory, MockedConstruction.MockInitializer<T> mockInitializer) { return MOCKITO_CORE.mockConstruction(classToMock, mockSettingsFactory, mockInitializer); } /** * Enables stubbing methods. Use it when you want the mock to return particular value when particular method is called. * <p> * Simply put: "<b>When</b> the x method is called <b>then</b> return y". * * <p> * Examples: * * <pre class="code"><code class="java"> * <b>when</b>(mock.someMethod()).<b>thenReturn</b>(10); * * //you can use flexible argument matchers, e.g: * when(mock.someMethod(<b>anyString()</b>)).thenReturn(10); * * //setting exception to be thrown: * when(mock.someMethod("some arg")).thenThrow(new RuntimeException()); * * //you can set different behavior for consecutive method calls. * //Last stubbing (e.g: thenReturn("foo")) determines the behavior of further consecutive calls. * when(mock.someMethod("some arg")) * .thenThrow(new RuntimeException()) * .thenReturn("foo"); * * //Alternative, shorter version for consecutive stubbing: * when(mock.someMethod("some arg")) * .thenReturn("one", "two"); * //is the same as: * when(mock.someMethod("some arg")) * .thenReturn("one") * .thenReturn("two"); * * //shorter version for consecutive method calls throwing exceptions: * when(mock.someMethod("some arg")) * .thenThrow(new RuntimeException(), new NullPointerException(); * * </code></pre> * * For stubbing void methods with throwables see: {@link Mockito#doThrow(Throwable...)} * <p> * Stubbing can be overridden: for example common stubbing can go to fixture * setup but the test methods can override it. * Please note that overriding stubbing is a potential code smell that points out too much stubbing. * <p> * Once stubbed, the method will always return stubbed value regardless * of how many times it is called. * <p> * Last stubbing is more important - when you stubbed the same method with * the same arguments many times. * <p> * Although it is possible to verify a stubbed invocation, usually <b>it's just redundant</b>. * Let's say you've stubbed <code>foo.bar()</code>. * If your code cares what <code>foo.bar()</code> returns then something else breaks(often before even <code>verify()</code> gets executed). * If your code doesn't care what <code>get(0)</code> returns then it should not be stubbed. * * <p> * See examples in javadoc for {@link Mockito} class * @param methodCall method to be stubbed * @return OngoingStubbing object used to stub fluently. * <strong>Do not</strong> create a reference to this returned object. */ public static <T> OngoingStubbing<T> when(T methodCall) { return MOCKITO_CORE.when(methodCall); } /** * Verifies certain behavior <b>happened once</b>. * <p> * Alias to <code>verify(mock, times(1))</code> E.g: * <pre class="code"><code class="java"> * verify(mock).someMethod("some arg"); * </code></pre> * Above is equivalent to: * <pre class="code"><code class="java"> * verify(mock, times(1)).someMethod("some arg"); * </code></pre> * <p> * Arguments passed are compared using <code>equals()</code> method. * Read about {@link ArgumentCaptor} or {@link ArgumentMatcher} to find out other ways of matching / asserting arguments passed. * <p> * Although it is possible to verify a stubbed invocation, usually <b>it's just redundant</b>. * Let's say you've stubbed <code>foo.bar()</code>. * If your code cares what <code>foo.bar()</code> returns then something else breaks(often before even <code>verify()</code> gets executed). * If your code doesn't care what <code>foo.bar()</code> returns then it should not be stubbed. * * <p> * See examples in javadoc for {@link Mockito} class * * @param mock to be verified * @return mock object itself */ public static <T> T verify(T mock) { return MOCKITO_CORE.verify(mock, times(1)); } /** * Verifies certain behavior happened at least once / exact number of times / never. E.g: * <pre class="code"><code class="java"> * verify(mock, times(5)).someMethod("was called five times"); * * verify(mock, atLeast(2)).someMethod("was called at least two times"); * * //you can use flexible argument matchers, e.g: * verify(mock, atLeastOnce()).someMethod(<b>anyString()</b>); * </code></pre> * * <b>times(1) is the default</b> and can be omitted * <p> * Arguments passed are compared using <code>equals()</code> method. * Read about {@link ArgumentCaptor} or {@link ArgumentMatcher} to find out other ways of matching / asserting arguments passed. * <p> * * @param mock to be verified * @param mode times(x), atLeastOnce() or never() * * @return mock object itself */ public static <T> T verify(T mock, VerificationMode mode) { return MOCKITO_CORE.verify(mock, mode); } /** * Smart Mockito users hardly use this feature because they know it could be a sign of poor tests. * Normally, you don't need to reset your mocks, just create new mocks for each test method. * <p> * Instead of <code>#reset()</code> please consider writing simple, small and focused test methods over lengthy, over-specified tests. * <b>First potential code smell is <code>reset()</code> in the middle of the test method.</b> This probably means you're testing too much. * Follow the whisper of your test methods: "Please keep us small and focused on single behavior". * There are several threads about it on mockito mailing list. * <p> * The only reason we added <code>reset()</code> method is to * make it possible to work with container-injected mocks. * For more information see the FAQ (<a href="https://github.com/mockito/mockito/wiki/FAQ">here</a>). * <p> * <b>Don't harm yourself.</b> <code>reset()</code> in the middle of the test method is a code smell (you're probably testing too much). * <pre class="code"><code class="java"> * List mock = mock(List.class); * when(mock.size()).thenReturn(10); * mock.add(1); * * reset(mock); * //at this point the mock forgot any interactions and stubbing * </code></pre> * * @param <T> The Type of the mocks * @param mocks to be reset */ public static <T> void reset(T... mocks) { MOCKITO_CORE.reset(mocks); } /** * Clears all mocks, type caches and instrumentations. * <p> * By clearing Mockito's state, previously created mocks might begin to malfunction. This option can be used if * Mockito's caches take up too much space or if the inline mock maker's instrumentation is causing performance * issues in code where mocks are no longer used. Normally, you would not need to use this option. */ public static void clearAllCaches() { MOCKITO_CORE.clearAllCaches(); } /** * Use this method in order to only clear invocations, when stubbing is non-trivial. Use-cases can be: * <ul> * <li>You are using a dependency injection framework to inject your mocks.</li> * <li>The mock is used in a stateful scenario. For example a class is Singleton which depends on your mock.</li> * </ul> * * <b>Try to avoid this method at all costs. Only clear invocations if you are unable to efficiently test your program.</b> * @param <T> The type of the mocks * @param mocks The mocks to clear the invocations for */ public static <T> void clearInvocations(T... mocks) { MOCKITO_CORE.clearInvocations(mocks); } /** * Checks if any of given mocks has any unverified interaction. * <p> * You can use this method after you verified your mocks - to make sure that nothing * else was invoked on your mocks. * <p> * See also {@link Mockito#never()} - it is more explicit and communicates the intent well. * <p> * Stubbed invocations (if called) are also treated as interactions. * If you want stubbed invocations automatically verified, check out {@link Strictness#STRICT_STUBS} feature * introduced in Mockito 2.3.0. * If you want to ignore stubs for verification, see {@link #ignoreStubs(Object...)}. * <p> * A word of <b>warning</b>: * Some users who did a lot of classic, expect-run-verify mocking tend to use <code>verifyNoMoreInteractions()</code> very often, even in every test method. * <code>verifyNoMoreInteractions()</code> is not recommended to use in every test method. * <code>verifyNoMoreInteractions()</code> is a handy assertion from the interaction testing toolkit. Use it only when it's relevant. * Abusing it leads to over-specified, less maintainable tests. * <p> * This method will also detect unverified invocations that occurred before the test method, * for example: in <code>setUp()</code>, <code>&#064;Before</code> method or in constructor. * Consider writing nice code that makes interactions only in test methods. * * <p> * Example: * * <pre class="code"><code class="java"> * //interactions * mock.doSomething(); * mock.doSomethingUnexpected(); * * //verification * verify(mock).doSomething(); * * //following will fail because 'doSomethingUnexpected()' is unexpected * verifyNoMoreInteractions(mock); * * </code></pre> * * See examples in javadoc for {@link Mockito} class * * @param mocks to be verified */ public static void verifyNoMoreInteractions(Object... mocks) { MOCKITO_CORE.verifyNoMoreInteractions(mocks); } /** * Verifies that no interactions happened on given mocks. * <pre class="code"><code class="java"> * verifyNoInteractions(mockOne, mockTwo); * </code></pre> * This method will also detect invocations * that occurred before the test method, for example: in <code>setUp()</code>, <code>&#064;Before</code> method or in constructor. * Consider writing nice code that makes interactions only in test methods. * <p> * See also {@link Mockito#never()} - it is more explicit and communicates the intent well. * <p> * See examples in javadoc for {@link Mockito} class * * @param mocks to be verified * @since 3.0.1 */ public static void verifyNoInteractions(Object... mocks) { MOCKITO_CORE.verifyNoInteractions(mocks); } /** * Use <code>doThrow()</code> when you want to stub the void method with an exception. * <p> * Stubbing voids requires different approach from {@link Mockito#when(Object)} because the compiler * does not like void methods inside brackets... * <p> * Example: * * <pre class="code"><code class="java"> * doThrow(new RuntimeException()).when(mock).someVoidMethod(); * </code></pre> * * @param toBeThrown to be thrown when the stubbed method is called * @return stubber - to select a method for stubbing */ public static Stubber doThrow(Throwable... toBeThrown) { return MOCKITO_CORE.stubber().doThrow(toBeThrown); } /** * Use <code>doThrow()</code> when you want to stub the void method with an exception. * <p> * A new exception instance will be created for each method invocation. * <p> * Stubbing voids requires different approach from {@link Mockito#when(Object)} because the compiler * does not like void methods inside brackets... * <p> * Example: * * <pre class="code"><code class="java"> * doThrow(RuntimeException.class).when(mock).someVoidMethod(); * </code></pre> * * @param toBeThrown to be thrown when the stubbed method is called * @return stubber - to select a method for stubbing * @since 2.1.0 */ public static Stubber doThrow(Class<? extends Throwable> toBeThrown) { return MOCKITO_CORE.stubber().doThrow(toBeThrown); } /** * Same as {@link #doThrow(Class)} but sets consecutive exception classes to be thrown. Remember to use * <code>doThrow()</code> when you want to stub the void method to throw several exceptions * that are instances of the specified class. * <p> * A new exception instance will be created for each method invocation. * <p> * Stubbing voids requires different approach from {@link Mockito#when(Object)} because the compiler * does not like void methods inside brackets... * <p> * Example: * * <pre class="code"><code class="java"> * doThrow(RuntimeException.class, BigFailure.class).when(mock).someVoidMethod(); * </code></pre> * * @param toBeThrown to be thrown when the stubbed method is called * @param toBeThrownNext next to be thrown when the stubbed method is called * @return stubber - to select a method for stubbing * @since 2.1.0 */ // Additional method helps users of JDK7+ to hide heap pollution / unchecked generics array // creation @SuppressWarnings({"unchecked", "varargs"}) public static Stubber doThrow( Class<? extends Throwable> toBeThrown, Class<? extends Throwable>... toBeThrownNext) { return MOCKITO_CORE.stubber().doThrow(toBeThrown, toBeThrownNext); } /** * Use <code>doCallRealMethod()</code> when you want to call the real implementation of a method. * <p> * As usual, you are going to read <b>the partial mock warning</b>: * Object oriented programming is more-or-less tackling complexity by dividing the complexity into separate, specific, SRPy objects. * How does partial mock fit into this paradigm? Well, it just doesn't... * Partial mock usually means that the complexity has been moved to a different method on the same object. * In most cases, this is not the way you want to design your application. * <p> * However, there are rare cases when partial mocks come handy: * dealing with code you cannot change easily (3rd party interfaces, interim refactoring of legacy code etc.) * However, I wouldn't use partial mocks for new, test-driven and well-designed code. * <p> * See also javadoc {@link Mockito#spy(Object)} to find out more about partial mocks. * <b>Mockito.spy() is a recommended way of creating partial mocks.</b> * The reason is it guarantees real methods are called against correctly constructed object because you're responsible for constructing the object passed to spy() method. * <p> * Example: * <pre class="code"><code class="java"> * Foo mock = mock(Foo.class); * doCallRealMethod().when(mock).someVoidMethod(); * * // this will call the real implementation of Foo.someVoidMethod() * mock.someVoidMethod(); * </code></pre> * <p> * See examples in javadoc for {@link Mockito} class * * @return stubber - to select a method for stubbing * @since 1.9.5 */ public static Stubber doCallRealMethod() { return MOCKITO_CORE.stubber().doCallRealMethod(); } /** * Use <code>doAnswer()</code> when you want to stub a void method with generic {@link Answer}. * <p> * Stubbing voids requires different approach from {@link Mockito#when(Object)} because the compiler does not like void methods inside brackets... * <p> * Example: * * <pre class="code"><code class="java"> * doAnswer(new Answer() { * public Object answer(InvocationOnMock invocation) { * Object[] args = invocation.getArguments(); * Mock mock = invocation.getMock(); * return null; * }}) * .when(mock).someMethod(); * </code></pre> * <p> * See examples in javadoc for {@link Mockito} class * * @param answer to answer when the stubbed method is called * @return stubber - to select a method for stubbing */ public static Stubber doAnswer(Answer answer) { return MOCKITO_CORE.stubber().doAnswer(answer); } /** * Use <code>doNothing()</code> for setting void methods to do nothing. <b>Beware that void methods on mocks do nothing by default!</b> * However, there are rare situations when doNothing() comes handy: * <p> * <ol> * <li>Stubbing consecutive calls on a void method: * <pre class="code"><code class="java"> * doNothing(). * doThrow(new RuntimeException()) * .when(mock).someVoidMethod(); * * //does nothing the first time: * mock.someVoidMethod(); * * //throws RuntimeException the next time: * mock.someVoidMethod(); * </code></pre> * </li> * <li>When you spy real objects and you want the void method to do nothing: * <pre class="code"><code class="java"> * List list = new LinkedList(); * List spy = spy(list); * * //let's make clear() do nothing * doNothing().when(spy).clear(); * * spy.add("one"); * * //clear() does nothing, so the list still contains "one" * spy.clear(); * </code></pre> * </li> * </ol> * <p> * See examples in javadoc for {@link Mockito} class * * @return stubber - to select a method for stubbing */ public static Stubber doNothing() { return MOCKITO_CORE.stubber().doNothing(); } /** * Use <code>doReturn()</code> in those rare occasions when you cannot use {@link Mockito#when(Object)}. * <p> * <b>Beware that {@link Mockito#when(Object)} is always recommended for stubbing because it is argument type-safe * and more readable</b> (especially when stubbing consecutive calls). * <p> * Here are those rare occasions when doReturn() comes handy: * <p> * * <ol> * <li>When spying real objects and calling real methods on a spy brings side effects * * <pre class="code"><code class="java"> * List list = new LinkedList(); * List spy = spy(list); * * //Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty) * when(spy.get(0)).thenReturn("foo"); * * //You have to use doReturn() for stubbing: * doReturn("foo").when(spy).get(0); * </code></pre> * </li> * * <li>Overriding a previous exception-stubbing: * <pre class="code"><code class="java"> * when(mock.foo()).thenThrow(new RuntimeException()); * * //Impossible: the exception-stubbed foo() method is called so RuntimeException is thrown. * when(mock.foo()).thenReturn("bar"); * * //You have to use doReturn() for stubbing: * doReturn("bar").when(mock).foo(); * </code></pre> * </li> * </ol> * * Above scenarios shows a tradeoff of Mockito's elegant syntax. Note that the scenarios are very rare, though. * Spying should be sporadic and overriding exception-stubbing is very rare. Not to mention that in general * overriding stubbing is a potential code smell that points out too much stubbing. * <p> * See examples in javadoc for {@link Mockito} class * * @param toBeReturned to be returned when the stubbed method is called * @return stubber - to select a method for stubbing */ public static Stubber doReturn(Object toBeReturned) { return MOCKITO_CORE.stubber().doReturn(toBeReturned); } /** * Same as {@link #doReturn(Object)} but sets consecutive values to be returned. Remember to use * <code>doReturn()</code> in those rare occasions when you cannot use {@link Mockito#when(Object)}. * <p> * <b>Beware that {@link Mockito#when(Object)} is always recommended for stubbing because it is argument type-safe * and more readable</b> (especially when stubbing consecutive calls). * <p> * Here are those rare occasions when doReturn() comes handy: * <p> * * <ol> * <li>When spying real objects and calling real methods on a spy brings side effects * * <pre class="code"><code class="java"> * List list = new LinkedList(); * List spy = spy(list); * * //Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty) * when(spy.get(0)).thenReturn("foo", "bar", "qix"); * * //You have to use doReturn() for stubbing: * doReturn("foo", "bar", "qix").when(spy).get(0); * </code></pre> * </li> * * <li>Overriding a previous exception-stubbing: * <pre class="code"><code class="java"> * when(mock.foo()).thenThrow(new RuntimeException()); * * //Impossible: the exception-stubbed foo() method is called so RuntimeException is thrown. * when(mock.foo()).thenReturn("bar", "foo", "qix"); * * //You have to use doReturn() for stubbing: * doReturn("bar", "foo", "qix").when(mock).foo(); * </code></pre> * </li> * </ol> * * Above scenarios shows a trade-off of Mockito's elegant syntax. Note that the scenarios are very rare, though. * Spying should be sporadic and overriding exception-stubbing is very rare. Not to mention that in general * overriding stubbing is a potential code smell that points out too much stubbing. * <p> * See examples in javadoc for {@link Mockito} class * * @param toBeReturned to be returned when the stubbed method is called * @param toBeReturnedNext to be returned in consecutive calls when the stubbed method is called * @return stubber - to select a method for stubbing * @since 2.1.0 */ @SuppressWarnings({"unchecked", "varargs"}) public static Stubber doReturn(Object toBeReturned, Object... toBeReturnedNext) { return MOCKITO_CORE.stubber().doReturn(toBeReturned, toBeReturnedNext); } /** * Creates {@link org.mockito.InOrder} object that allows verifying mocks in order. * * <pre class="code"><code class="java"> * InOrder inOrder = inOrder(firstMock, secondMock); * * inOrder.verify(firstMock).add("was called first"); * inOrder.verify(secondMock).add("was called second"); * </code></pre> * * Verification in order is flexible - <b>you don't have to verify all interactions</b> one-by-one * but only those that you are interested in testing in order. * <p> * Also, you can create InOrder object passing only mocks that are relevant for in-order verification. * <p> * <code>InOrder</code> verification is 'greedy', but you will hardly ever notice it. * If you want to find out more, read * <a href="https://github.com/mockito/mockito/wiki/Greedy-algorithm-of-verification-InOrder">this wiki page</a>. * <p> * As of Mockito 1.8.4 you can verifyNoMoreInteractions() in order-sensitive way. Read more: {@link InOrder#verifyNoMoreInteractions()} * <p> * See examples in javadoc for {@link Mockito} class * * @param mocks to be verified in order * * @return InOrder object to be used to verify in order */ public static InOrder inOrder(Object... mocks) { return MOCKITO_CORE.inOrder(mocks); } /** * Ignores stubbed methods of given mocks for the sake of verification. * Please consider using {@link Strictness#STRICT_STUBS} feature which eliminates the need for <code>ignoreStubs()</code> * and provides other benefits. * <p> * <code>ignoreStubs()</code> is sometimes useful when coupled with <code>verifyNoMoreInteractions()</code> or verification <code>inOrder()</code>. * Helps to avoid redundant verification of stubbed calls - typically we're not interested in verifying stubs. * <p> * <b>Warning</b>, <code>ignoreStubs()</code> might lead to overuse of <code>verifyNoMoreInteractions(ignoreStubs(...));</code> * Bear in mind that Mockito does not recommend bombarding every test with <code>verifyNoMoreInteractions()</code> * for the reasons outlined in javadoc for {@link Mockito#verifyNoMoreInteractions(Object...)} * Other words: all <b>*stubbed*</b> methods of given mocks are marked <b>*verified*</b> so that they don't get in a way during verifyNoMoreInteractions(). * <p> * This method <b>changes the input mocks</b>! This method returns input mocks just for convenience. * <p> * Ignored stubs will also be ignored for verification inOrder, including {@link org.mockito.InOrder#verifyNoMoreInteractions()}. * See the second example. * <p> * Example: * <pre class="code"><code class="java"> * //mocking lists for the sake of the example (if you mock List in real you will burn in hell) * List mock1 = mock(List.class), mock2 = mock(List.class); * * //stubbing mocks: * when(mock1.get(0)).thenReturn(10); * when(mock2.get(0)).thenReturn(20); * * //using mocks by calling stubbed get(0) methods: * System.out.println(mock1.get(0)); //prints 10 * System.out.println(mock2.get(0)); //prints 20 * * //using mocks by calling clear() methods: * mock1.clear(); * mock2.clear(); * * //verification: * verify(mock1).clear(); * verify(mock2).clear(); * * //verifyNoMoreInteractions() fails because get() methods were not accounted for. * try { verifyNoMoreInteractions(mock1, mock2); } catch (NoInteractionsWanted e); * * //However, if we ignore stubbed methods then we can verifyNoMoreInteractions() * verifyNoMoreInteractions(ignoreStubs(mock1, mock2)); * * //Remember that ignoreStubs() <b>*changes*</b> the input mocks and returns them for convenience. * </code></pre> * Ignoring stubs can be used with <b>verification in order</b>: * <pre class="code"><code class="java"> * List list = mock(List.class); * when(list.get(0)).thenReturn("foo"); * * list.add(0); * list.clear(); * System.out.println(list.get(0)); //we don't want to verify this * * InOrder inOrder = inOrder(ignoreStubs(list)); * inOrder.verify(list).add(0); * inOrder.verify(list).clear(); * inOrder.verifyNoMoreInteractions(); * </code></pre> * Stubbed invocations are automatically verified with {@link Strictness#STRICT_STUBS} feature * and it eliminates the need for <code>ignoreStubs()</code>. Example below uses JUnit Rules: * <pre class="code"><code class="java"> * &#064;Rule public MockitoRule mockito = MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS); * * List list = mock(List.class); * when(list.get(0)).thenReturn("foo"); * * list.size(); * verify(list).size(); * * list.get(0); // Automatically verified by STRICT_STUBS * verifyNoMoreInteractions(list); // No need of ignoreStubs() * </code></pre> * * @since 1.9.0 * @param mocks input mocks that will be changed * @return the same mocks that were passed in as parameters */ public static Object[] ignoreStubs(Object... mocks) { return MOCKITO_CORE.ignoreStubs(mocks); } /** * Allows verifying exact number of invocations. E.g: * <pre class="code"><code class="java"> * verify(mock, times(2)).someMethod("some arg"); * </code></pre> * * See examples in javadoc for {@link Mockito} class * * @param wantedNumberOfInvocations wanted number of invocations * * @return verification mode */ public static VerificationMode times(int wantedNumberOfInvocations) { return VerificationModeFactory.times(wantedNumberOfInvocations); } /** * Alias to <code>times(0)</code>, see {@link Mockito#times(int)} * <p> * Verifies that interaction did not happen. E.g: * <pre class="code"><code class="java"> * verify(mock, never()).someMethod(); * </code></pre> * * <p> * If you want to verify there were NO interactions with the mock * check out {@link Mockito#verifyNoMoreInteractions(Object...)} * <p> * See examples in javadoc for {@link Mockito} class * * @return verification mode */ public static VerificationMode never() { return times(0); } /** * Allows at-least-once verification. E.g: * <pre class="code"><code class="java"> * verify(mock, atLeastOnce()).someMethod("some arg"); * </code></pre> * Alias to <code>atLeast(1)</code>. * <p> * See examples in javadoc for {@link Mockito} class * * @return verification mode */ public static VerificationMode atLeastOnce() { return VerificationModeFactory.atLeastOnce(); } /** * Allows at-least-x verification. E.g: * <pre class="code"><code class="java"> * verify(mock, atLeast(3)).someMethod("some arg"); * </code></pre> * * See examples in javadoc for {@link Mockito} class * * @param minNumberOfInvocations minimum number of invocations * * @return verification mode */ public static VerificationMode atLeast(int minNumberOfInvocations) { return VerificationModeFactory.atLeast(minNumberOfInvocations); } /** * Allows at-most-once verification. E.g: * <pre class="code"><code class="java"> * verify(mock, atMostOnce()).someMethod("some arg"); * </code></pre> * Alias to <code>atMost(1)</code>. * <p> * See examples in javadoc for {@link Mockito} class * * @return verification mode */ public static VerificationMode atMostOnce() { return VerificationModeFactory.atMostOnce(); } /** * Allows at-most-x verification. E.g: * <pre class="code"><code class="java"> * verify(mock, atMost(3)).someMethod("some arg"); * </code></pre> * * See examples in javadoc for {@link Mockito} class * * @param maxNumberOfInvocations max number of invocations * * @return verification mode */ public static VerificationMode atMost(int maxNumberOfInvocations) { return VerificationModeFactory.atMost(maxNumberOfInvocations); } /** * Allows non-greedy verification in order. For example * <pre class="code"><code class="java"> * inOrder.verify( mock, calls( 2 )).someMethod( "some arg" ); * </code></pre> * <ul> * <li>will not fail if the method is called 3 times, unlike times( 2 )</li> * <li>will not mark the third invocation as verified, unlike atLeast( 2 )</li> * </ul> * This verification mode can only be used with in order verification. * @param wantedNumberOfInvocations number of invocations to verify * @return verification mode */ public static VerificationMode calls(int wantedNumberOfInvocations) { return VerificationModeFactory.calls(wantedNumberOfInvocations); } /** * Allows checking if given method was the only one invoked. E.g: * <pre class="code"><code class="java"> * verify(mock, only()).someMethod(); * //above is a shorthand for following 2 lines of code: * verify(mock).someMethod(); * verifyNoMoreInteractions(mock); * </code></pre> * * <p> * See also {@link Mockito#verifyNoMoreInteractions(Object...)} * <p> * See examples in javadoc for {@link Mockito} class * * @return verification mode */ public static VerificationMode only() { return VerificationModeFactory.only(); } /** * Verification will be triggered over and over until the given amount of millis, allowing testing of async code. * Useful when interactions with the mock object did not happened yet. * Extensive use of {@code timeout()} method can be a code smell - there are better ways of testing concurrent code. * <p> * See also {@link #after(long)} method for testing async code. * Differences between {@code timeout()} and {@code after} are explained in Javadoc for {@link #after(long)}. * * <pre class="code"><code class="java"> * //passes when someMethod() is called no later than within 100 ms * //exits immediately when verification is satisfied (e.g. may not wait full 100 ms) * verify(mock, timeout(100)).someMethod(); * //above is an alias to: * verify(mock, timeout(100).times(1)).someMethod(); * * //passes as soon as someMethod() has been called 2 times under 100 ms * verify(mock, timeout(100).times(2)).someMethod(); * * //equivalent: this also passes as soon as someMethod() has been called 2 times under 100 ms * verify(mock, timeout(100).atLeast(2)).someMethod(); * </code></pre> * * See examples in javadoc for {@link Mockito} class * * @param millis - duration in milliseconds * * @return object that allows fluent specification of the verification (times(x), atLeast(y), etc.) */ public static VerificationWithTimeout timeout(long millis) { return new Timeout(millis, VerificationModeFactory.times(1)); } /** * Verification will be triggered after given amount of millis, allowing testing of async code. * Useful when interactions with the mock object have yet to occur. * Extensive use of {@code after()} method can be a code smell - there are better ways of testing concurrent code. * <p> * Not yet implemented to work with InOrder verification. * <p> * See also {@link #timeout(long)} method for testing async code. * Differences between {@code timeout()} and {@code after()} are explained below. * * <pre class="code"><code class="java"> * //passes after 100ms, if someMethod() has only been called once at that time. * verify(mock, after(100)).someMethod(); * //above is an alias to: * verify(mock, after(100).times(1)).someMethod(); * * //passes if someMethod() is called <b>*exactly*</b> 2 times, as tested after 100 millis * verify(mock, after(100).times(2)).someMethod(); * * //passes if someMethod() has not been called, as tested after 100 millis * verify(mock, after(100).never()).someMethod(); * * //verifies someMethod() after a given time span using given verification mode * //useful only if you have your own custom verification modes. * verify(mock, new After(100, yourOwnVerificationMode)).someMethod(); * </code></pre> * * <strong>timeout() vs. after()</strong> * <ul> * <li>timeout() exits immediately with success when verification passes</li> * <li>after() awaits full duration to check if verification passes</li> * </ul> * Examples: * <pre class="code"><code class="java"> * //1. * mock.foo(); * verify(mock, after(1000)).foo(); * //waits 1000 millis and succeeds * * //2. * mock.foo(); * verify(mock, timeout(1000)).foo(); * //succeeds immediately * </code></pre> * * See examples in javadoc for {@link Mockito} class * * @param millis - duration in milliseconds * * @return object that allows fluent specification of the verification */ public static VerificationAfterDelay after(long millis) { return new After(millis, VerificationModeFactory.times(1)); } /** * First of all, in case of any trouble, I encourage you to read the Mockito FAQ: <a href="https://github.com/mockito/mockito/wiki/FAQ">https://github.com/mockito/mockito/wiki/FAQ</a> * <p> * In case of questions you may also post to mockito mailing list: <a href="https://groups.google.com/group/mockito">https://groups.google.com/group/mockito</a> * <p> * <code>validateMockitoUsage()</code> <b>explicitly validates</b> the framework state to detect invalid use of Mockito. * However, this feature is optional <b>because Mockito validates the usage all the time...</b> but there is a gotcha so read on. * <p> * Examples of incorrect use: * <pre class="code"><code class="java"> * //Oops, thenReturn() part is missing: * when(mock.get()); * * //Oops, verified method call is inside verify() where it should be on the outside: * verify(mock.execute()); * * //Oops, missing method to verify: * verify(mock); * </code></pre> * * Mockito throws exceptions if you misuse it so that you know if your tests are written correctly. * The gotcha is that Mockito does the validation <b>next time</b> you use the framework (e.g. next time you verify, stub, call mock etc.). * But even though the exception might be thrown in the next test, * the exception <b>message contains a navigable stack trace element</b> with location of the defect. * Hence you can click and find the place where Mockito was misused. * <p> * Sometimes though, you might want to validate the framework usage explicitly. * For example, one of the users wanted to put <code>validateMockitoUsage()</code> in his <code>&#064;After</code> method * so that he knows immediately when he misused Mockito. * Without it, he would have known about it not sooner than <b>next time</b> he used the framework. * One more benefit of having <code>validateMockitoUsage()</code> in <code>&#064;After</code> is that jUnit runner and rule will always fail in the test method with defect * whereas ordinary 'next-time' validation might fail the <b>next</b> test method. * But even though JUnit might report next test as red, don't worry about it * and just click at navigable stack trace element in the exception message to instantly locate the place where you misused mockito. * <p> * <b>Both built-in runner: {@link MockitoJUnitRunner} and rule: {@link MockitoRule}</b> do validateMockitoUsage() after each test method. * <p> * Bear in mind that <b>usually you don't have to <code>validateMockitoUsage()</code></b> * and framework validation triggered on next-time basis should be just enough, * mainly because of enhanced exception message with clickable location of defect. * However, I would recommend validateMockitoUsage() if you already have sufficient test infrastructure * (like your own runner or base class for all tests) because adding a special action to <code>&#064;After</code> has zero cost. * <p> * See examples in javadoc for {@link Mockito} class */ public static void validateMockitoUsage() { MOCKITO_CORE.validateMockitoUsage(); } /** * Allows mock creation with additional mock settings. * <p> * Don't use it too often. * Consider writing simple tests that use simple mocks. * Repeat after me: simple tests push simple, KISSy, readable and maintainable code. * If you cannot write a test in a simple way - refactor the code under test. * <p> * Examples of mock settings: * <pre class="code"><code class="java"> * //Creates mock with different default answer and name * Foo mock = mock(Foo.class, withSettings() * .defaultAnswer(RETURNS_SMART_NULLS) * .name("cool mockie")); * * //Creates mock with different default answer, descriptive name and extra interfaces * Foo mock = mock(Foo.class, withSettings() * .defaultAnswer(RETURNS_SMART_NULLS) * .name("cool mockie") * .extraInterfaces(Bar.class)); * </code></pre> * {@link MockSettings} has been introduced for two reasons. * Firstly, to make it easy to add another mock settings when the demand comes. * Secondly, to enable combining different mock settings without introducing zillions of overloaded mock() methods. * <p> * See javadoc for {@link MockSettings} to learn about possible mock settings. * <p> * * @return mock settings instance with defaults. */ public static MockSettings withSettings() { return new MockSettingsImpl().defaultAnswer(RETURNS_DEFAULTS); } /** * Adds a description to be printed if verification fails. * <pre class="code"><code class="java"> * verify(mock, description("This will print on failure")).someMethod("some arg"); * </code></pre> * @param description The description to print on failure. * @return verification mode * @since 2.1.0 */ public static VerificationMode description(String description) { return times(1).description(description); } /** * For advanced users or framework integrators. See {@link MockitoFramework} class. * * @since 2.1.0 */ public static MockitoFramework framework() { return new DefaultMockitoFramework(); } /** * {@code MockitoSession} is an optional, highly recommended feature * that drives writing cleaner tests by eliminating boilerplate code and adding extra validation. * <p> * For more information, including use cases and sample code, see the javadoc for {@link MockitoSession}. * * @since 2.7.0 */ public static MockitoSessionBuilder mockitoSession() { return new DefaultMockitoSessionBuilder(); } /** * Lenient stubs bypass "strict stubbing" validation (see {@link Strictness#STRICT_STUBS}). * When stubbing is declared as lenient, it will not be checked for potential stubbing problems such as * 'unnecessary stubbing' ({@link UnnecessaryStubbingException}) or for 'stubbing argument mismatch' {@link PotentialStubbingProblem}. * * <pre class="code"><code class="java"> * lenient().when(mock.foo()).thenReturn("ok"); * </code></pre> * * Most mocks in most tests don't need leniency and should happily prosper with {@link Strictness#STRICT_STUBS}. * <ul> * <li>If a specific stubbing needs to be lenient - use this method</li> * <li>If a specific mock need to have lenient stubbings - use {@link MockSettings#strictness(Strictness)}</li> * <li>If a specific test method / test class needs to have all stubbings lenient * - configure strictness using our JUnit support ({@link MockitoJUnit} or Mockito Session ({@link MockitoSession})</li> * * <h3>Elaborate example</h3> * * In below example, 'foo.foo()' is a stubbing that was moved to 'before()' method to avoid duplication. * Doing so makes one of the test methods ('test3()') fail with 'unnecessary stubbing'. * To resolve it we can configure 'foo.foo()' stubbing in 'before()' method to be lenient. * Alternatively, we can configure entire 'foo' mock as lenient. * <p> * This example is simplified and not realistic. * Pushing stubbings to 'before()' method may cause tests to be less readable. * Some repetition in tests is OK, use your own judgement to write great tests! * It is not desired to eliminate all possible duplication from the test code * because it may add complexity and conceal important test information. * * <pre class="code"><code class="java"> * public class SomeTest { * * &#064;Rule public MockitoRule mockito = MockitoJUnit.rule().strictness(STRICT_STUBS); * * &#064;Mock Foo foo; * &#064;Mock Bar bar; * * &#064;Before public void before() { * when(foo.foo()).thenReturn("ok"); * * // it is better to configure the stubbing to be lenient: * // lenient().when(foo.foo()).thenReturn("ok"); * * // or the entire mock to be lenient: * // foo = mock(Foo.class, withSettings().lenient()); * } * * &#064;Test public void test1() { * foo.foo(); * } * * &#064;Test public void test2() { * foo.foo(); * } * * &#064;Test public void test3() { * bar.bar(); * } * } * </code></pre> * * @since 2.20.0 */ public static LenientStubber lenient() { return MOCKITO_CORE.lenient(); } }
mockito/mockito
src/main/java/org/mockito/Mockito.java
15
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. 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 org.tensorflow.op.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Annotation used by classes to make TensorFlow operations conveniently accessible via {@code * org.tensorflow.op.Ops}. * * <p>An annotation processor ({@code org.tensorflow.processor.OperatorProcessor}) builds the * {@code Ops} class by aggregating all classes annotated as {@code @Operator}s. Each annotated * class <b>must</b> have at least one public static factory method named {@code create} that * accepts a {@link org.tensorflow.op.Scope} as its first argument. The processor then adds a * convenience method in the {@code Ops} class. For example: * * <pre>{@code * @Operator * public final class MyOp implements Op { * public static MyOp create(Scope scope, Operand operand) { * ... * } * } * }</pre> * * <p>results in a method in the {@code Ops} class * * <pre>{@code * import org.tensorflow.op.Ops; * ... * Ops ops = Ops.create(graph); * ... * ops.myOp(operand); * // and has exactly the same effect as calling * // MyOp.create(ops.getScope(), operand); * }</pre> */ @Documented @Target(ElementType.TYPE) @Retention(RetentionPolicy.SOURCE) public @interface Operator { /** * Specify an optional group within the {@code Ops} class. * * <p>By default, an annotation processor will create convenience methods directly in the {@code * Ops} class. An annotated operator may optionally choose to place the method within a group. For * example: * * <pre>{@code * @Operator(group="math") * public final class Add extends PrimitiveOp implements Operand { * ... * } * }</pre> * * <p>results in the {@code add} method placed within a {@code math} group within the {@code Ops} * class. * * <pre>{@code * ops.math().add(...); * }</pre> * * <p>The group name must be a <a * href="https://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.8">valid Java * identifier</a>. */ String group() default ""; /** * Name for the wrapper method used in the {@code Ops} class. * * <p>By default, a processor derives the method name in the {@code Ops} class from the class name * of the operator. This attribute allow you to provide a different name instead. For example: * * <pre>{@code * @Operator(name="myOperation") * public final class MyRealOperation implements Operand { * public static MyRealOperation create(...) * } * }</pre> * * <p>results in this method added to the {@code Ops} class * * <pre>{@code * ops.myOperation(...); * // and is the same as calling * // MyRealOperation.create(...) * }</pre> * * <p>The name must be a <a * href="https://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.8">valid Java * identifier</a>. */ String name() default ""; }
tensorflow/tensorflow
tensorflow/java/src/main/java/org/tensorflow/op/annotation/Operator.java
16
/* * Copyright (c) 2016-present, RxJava Contributors. * * 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 io.reactivex.rxjava3.core; import io.reactivex.rxjava3.annotations.NonNull; /** * Convenience interface and callback used by the {@link Maybe#to} operator to turn a {@link Maybe} into another * value fluently. * <p>History: 2.1.7 - experimental * @param <T> the upstream type * @param <R> the output type * @since 2.2 */ @FunctionalInterface public interface MaybeConverter<@NonNull T, @NonNull R> { /** * Applies a function to the upstream {@link Maybe} and returns a converted value of type {@code R}. * * @param upstream the upstream {@code Maybe} instance * @return the converted value */ @NonNull R apply(@NonNull Maybe<T> upstream); }
ReactiveX/RxJava
src/main/java/io/reactivex/rxjava3/core/MaybeConverter.java
17
/* * Copyright 2014 The gRPC Authors * * 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 io.grpc; import static com.google.common.base.Charsets.US_ASCII; import static com.google.common.base.Charsets.UTF_8; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Throwables.getStackTraceAsString; import com.google.common.base.MoreObjects; import com.google.common.base.Objects; import io.grpc.Metadata.TrustedAsciiMarshaller; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.TreeMap; import javax.annotation.CheckReturnValue; import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; /** * Defines the status of an operation by providing a standard {@link Code} in conjunction with an * optional descriptive message. Instances of {@code Status} are created by starting with the * template for the appropriate {@link Status.Code} and supplementing it with additional * information: {@code Status.NOT_FOUND.withDescription("Could not find 'important_file.txt'");} * * <p>For clients, every remote call will return a status on completion. In the case of errors this * status may be propagated to blocking stubs as a {@link RuntimeException} or to a listener as an * explicit parameter. * * <p>Similarly servers can report a status by throwing {@link StatusRuntimeException} * or by passing the status to a callback. * * <p>Utility functions are provided to convert a status to an exception and to extract them * back out. * * <p>Extended descriptions, including a list of codes that should not be generated by the library, * can be found at * <a href="https://github.com/grpc/grpc/blob/master/doc/statuscodes.md">doc/statuscodes.md</a> */ @Immutable @CheckReturnValue public final class Status { /** * The set of canonical status codes. If new codes are added over time they must choose * a numerical value that does not collide with any previously used value. */ public enum Code { /** * The operation completed successfully. */ OK(0), /** * The operation was cancelled (typically by the caller). */ CANCELLED(1), /** * Unknown error. An example of where this error may be returned is * if a Status value received from another address space belongs to * an error-space that is not known in this address space. Also * errors raised by APIs that do not return enough error information * may be converted to this error. */ UNKNOWN(2), /** * Client specified an invalid argument. Note that this differs * from FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments * that are problematic regardless of the state of the system * (e.g., a malformed file name). */ INVALID_ARGUMENT(3), /** * Deadline expired before operation could complete. For operations * that change the state of the system, this error may be returned * even if the operation has completed successfully. For example, a * successful response from a server could have been delayed long * enough for the deadline to expire. */ DEADLINE_EXCEEDED(4), /** * Some requested entity (e.g., file or directory) was not found. */ NOT_FOUND(5), /** * Some entity that we attempted to create (e.g., file or directory) already exists. */ ALREADY_EXISTS(6), /** * The caller does not have permission to execute the specified * operation. PERMISSION_DENIED must not be used for rejections * caused by exhausting some resource (use RESOURCE_EXHAUSTED * instead for those errors). PERMISSION_DENIED must not be * used if the caller cannot be identified (use UNAUTHENTICATED * instead for those errors). */ PERMISSION_DENIED(7), /** * Some resource has been exhausted, perhaps a per-user quota, or * perhaps the entire file system is out of space. */ RESOURCE_EXHAUSTED(8), /** * Operation was rejected because the system is not in a state * required for the operation's execution. For example, directory * to be deleted may be non-empty, an rmdir operation is applied to * a non-directory, etc. * * <p>A litmus test that may help a service implementor in deciding * between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE: * (a) Use UNAVAILABLE if the client can retry just the failing call. * (b) Use ABORTED if the client should retry at a higher-level * (e.g., restarting a read-modify-write sequence). * (c) Use FAILED_PRECONDITION if the client should not retry until * the system state has been explicitly fixed. E.g., if an "rmdir" * fails because the directory is non-empty, FAILED_PRECONDITION * should be returned since the client should not retry unless * they have first fixed up the directory by deleting files from it. */ FAILED_PRECONDITION(9), /** * The operation was aborted, typically due to a concurrency issue * like sequencer check failures, transaction aborts, etc. * * <p>See litmus test above for deciding between FAILED_PRECONDITION, * ABORTED, and UNAVAILABLE. */ ABORTED(10), /** * Operation was attempted past the valid range. E.g., seeking or * reading past end of file. * * <p>Unlike INVALID_ARGUMENT, this error indicates a problem that may * be fixed if the system state changes. For example, a 32-bit file * system will generate INVALID_ARGUMENT if asked to read at an * offset that is not in the range [0,2^32-1], but it will generate * OUT_OF_RANGE if asked to read from an offset past the current * file size. * * <p>There is a fair bit of overlap between FAILED_PRECONDITION and OUT_OF_RANGE. * We recommend using OUT_OF_RANGE (the more specific error) when it applies * so that callers who are iterating through * a space can easily look for an OUT_OF_RANGE error to detect when they are done. */ OUT_OF_RANGE(11), /** * Operation is not implemented or not supported/enabled in this service. */ UNIMPLEMENTED(12), /** * Internal errors. Means some invariants expected by underlying * system has been broken. If you see one of these errors, * something is very broken. */ INTERNAL(13), /** * The service is currently unavailable. This is a most likely a * transient condition and may be corrected by retrying with * a backoff. Note that it is not always safe to retry * non-idempotent operations. * * <p>See litmus test above for deciding between FAILED_PRECONDITION, * ABORTED, and UNAVAILABLE. */ UNAVAILABLE(14), /** * Unrecoverable data loss or corruption. */ DATA_LOSS(15), /** * The request does not have valid authentication credentials for the * operation. */ UNAUTHENTICATED(16); private final int value; @SuppressWarnings("ImmutableEnumChecker") // we make sure the byte[] can't be modified private final byte[] valueAscii; private Code(int value) { this.value = value; this.valueAscii = Integer.toString(value).getBytes(US_ASCII); } /** * The numerical value of the code. */ public int value() { return value; } /** * Returns a {@link Status} object corresponding to this status code. */ public Status toStatus() { return STATUS_LIST.get(value); } private byte[] valueAscii() { return valueAscii; } } // Create the canonical list of Status instances indexed by their code values. private static final List<Status> STATUS_LIST = buildStatusList(); private static List<Status> buildStatusList() { TreeMap<Integer, Status> canonicalizer = new TreeMap<>(); for (Code code : Code.values()) { Status replaced = canonicalizer.put(code.value(), new Status(code)); if (replaced != null) { throw new IllegalStateException("Code value duplication between " + replaced.getCode().name() + " & " + code.name()); } } return Collections.unmodifiableList(new ArrayList<>(canonicalizer.values())); } // A pseudo-enum of Status instances mapped 1:1 with values in Code. This simplifies construction // patterns for derived instances of Status. /** The operation completed successfully. */ public static final Status OK = Code.OK.toStatus(); /** The operation was cancelled (typically by the caller). */ public static final Status CANCELLED = Code.CANCELLED.toStatus(); /** Unknown error. See {@link Code#UNKNOWN}. */ public static final Status UNKNOWN = Code.UNKNOWN.toStatus(); /** Client specified an invalid argument. See {@link Code#INVALID_ARGUMENT}. */ public static final Status INVALID_ARGUMENT = Code.INVALID_ARGUMENT.toStatus(); /** Deadline expired before operation could complete. See {@link Code#DEADLINE_EXCEEDED}. */ public static final Status DEADLINE_EXCEEDED = Code.DEADLINE_EXCEEDED.toStatus(); /** Some requested entity (e.g., file or directory) was not found. */ public static final Status NOT_FOUND = Code.NOT_FOUND.toStatus(); /** Some entity that we attempted to create (e.g., file or directory) already exists. */ public static final Status ALREADY_EXISTS = Code.ALREADY_EXISTS.toStatus(); /** * The caller does not have permission to execute the specified operation. See {@link * Code#PERMISSION_DENIED}. */ public static final Status PERMISSION_DENIED = Code.PERMISSION_DENIED.toStatus(); /** The request does not have valid authentication credentials for the operation. */ public static final Status UNAUTHENTICATED = Code.UNAUTHENTICATED.toStatus(); /** * Some resource has been exhausted, perhaps a per-user quota, or perhaps the entire file system * is out of space. */ public static final Status RESOURCE_EXHAUSTED = Code.RESOURCE_EXHAUSTED.toStatus(); /** * Operation was rejected because the system is not in a state required for the operation's * execution. See {@link Code#FAILED_PRECONDITION}. */ public static final Status FAILED_PRECONDITION = Code.FAILED_PRECONDITION.toStatus(); /** * The operation was aborted, typically due to a concurrency issue like sequencer check failures, * transaction aborts, etc. See {@link Code#ABORTED}. */ public static final Status ABORTED = Code.ABORTED.toStatus(); /** Operation was attempted past the valid range. See {@link Code#OUT_OF_RANGE}. */ public static final Status OUT_OF_RANGE = Code.OUT_OF_RANGE.toStatus(); /** Operation is not implemented or not supported/enabled in this service. */ public static final Status UNIMPLEMENTED = Code.UNIMPLEMENTED.toStatus(); /** Internal errors. See {@link Code#INTERNAL}. */ public static final Status INTERNAL = Code.INTERNAL.toStatus(); /** The service is currently unavailable. See {@link Code#UNAVAILABLE}. */ public static final Status UNAVAILABLE = Code.UNAVAILABLE.toStatus(); /** Unrecoverable data loss or corruption. */ public static final Status DATA_LOSS = Code.DATA_LOSS.toStatus(); /** * Return a {@link Status} given a canonical error {@link Code} value. */ public static Status fromCodeValue(int codeValue) { if (codeValue < 0 || codeValue >= STATUS_LIST.size()) { return UNKNOWN.withDescription("Unknown code " + codeValue); } else { return STATUS_LIST.get(codeValue); } } private static Status fromCodeValue(byte[] asciiCodeValue) { if (asciiCodeValue.length == 1 && asciiCodeValue[0] == '0') { return Status.OK; } return fromCodeValueSlow(asciiCodeValue); } @SuppressWarnings("fallthrough") private static Status fromCodeValueSlow(byte[] asciiCodeValue) { int index = 0; int codeValue = 0; switch (asciiCodeValue.length) { case 2: if (asciiCodeValue[index] < '0' || asciiCodeValue[index] > '9') { break; } codeValue += (asciiCodeValue[index++] - '0') * 10; // fall through case 1: if (asciiCodeValue[index] < '0' || asciiCodeValue[index] > '9') { break; } codeValue += asciiCodeValue[index] - '0'; if (codeValue < STATUS_LIST.size()) { return STATUS_LIST.get(codeValue); } break; default: break; } return UNKNOWN.withDescription("Unknown code " + new String(asciiCodeValue, US_ASCII)); } /** * Return a {@link Status} given a canonical error {@link Code} object. */ public static Status fromCode(Code code) { return code.toStatus(); } /** * Key to bind status code to trailing metadata. */ static final Metadata.Key<Status> CODE_KEY = Metadata.Key.of("grpc-status", false /* not pseudo */, new StatusCodeMarshaller()); /** * Marshals status messages for ({@link #MESSAGE_KEY}. gRPC does not use binary coding of * status messages by default, which makes sending arbitrary strings difficult. This marshaller * uses ASCII printable characters by default, and percent encodes (e.g. %0A) all non ASCII bytes. * This leads to normal text being mostly readable (especially useful for debugging), and special * text still being sent. * * <p>By default, the HTTP spec says that header values must be encoded using a strict subset of * ASCII (See RFC 7230 section 3.2.6). HTTP/2 HPACK allows use of arbitrary binary headers, but * we do not use them for interoperating with existing HTTP/1.1 code. Since the grpc-message * is encoded to such a header, it needs to not use forbidden characters. * * <p>This marshaller works by converting the passed in string into UTF-8, checking to see if * each individual byte is an allowable byte, and then either percent encoding or passing it * through. When percent encoding, the byte is converted into hexadecimal notation with a '%' * prepended. * * <p>When unmarshalling, bytes are passed through unless they match the "%XX" pattern. If they * do match, the unmarshaller attempts to convert them back into their original UTF-8 byte * sequence. After the input header bytes are converted into UTF-8 bytes, the new byte array is * reinterpretted back as a string. */ private static final TrustedAsciiMarshaller<String> STATUS_MESSAGE_MARSHALLER = new StatusMessageMarshaller(); /** * Key to bind status message to trailing metadata. */ static final Metadata.Key<String> MESSAGE_KEY = Metadata.Key.of("grpc-message", false /* not pseudo */, STATUS_MESSAGE_MARSHALLER); /** * Extract an error {@link Status} from the causal chain of a {@link Throwable}. * If no status can be found, a status is created with {@link Code#UNKNOWN} as its code and * {@code t} as its cause. * * @return non-{@code null} status */ public static Status fromThrowable(Throwable t) { Throwable cause = checkNotNull(t, "t"); while (cause != null) { if (cause instanceof StatusException) { return ((StatusException) cause).getStatus(); } else if (cause instanceof StatusRuntimeException) { return ((StatusRuntimeException) cause).getStatus(); } cause = cause.getCause(); } // Couldn't find a cause with a Status return UNKNOWN.withCause(t); } /** * Extract an error trailers from the causal chain of a {@link Throwable}. * * @return the trailers or {@code null} if not found. */ @Nullable public static Metadata trailersFromThrowable(Throwable t) { Throwable cause = checkNotNull(t, "t"); while (cause != null) { if (cause instanceof StatusException) { return ((StatusException) cause).getTrailers(); } else if (cause instanceof StatusRuntimeException) { return ((StatusRuntimeException) cause).getTrailers(); } cause = cause.getCause(); } return null; } static String formatThrowableMessage(Status status) { if (status.description == null) { return status.code.toString(); } else { return status.code + ": " + status.description; } } private final Code code; private final String description; private final Throwable cause; private Status(Code code) { this(code, null, null); } private Status(Code code, @Nullable String description, @Nullable Throwable cause) { this.code = checkNotNull(code, "code"); this.description = description; this.cause = cause; } /** * Create a derived instance of {@link Status} with the given cause. * However, the cause is not transmitted from server to client. */ public Status withCause(Throwable cause) { if (Objects.equal(this.cause, cause)) { return this; } return new Status(this.code, this.description, cause); } /** * Create a derived instance of {@link Status} with the given description. Leading and trailing * whitespace may be removed; this may change in the future. */ public Status withDescription(String description) { if (Objects.equal(this.description, description)) { return this; } return new Status(this.code, description, this.cause); } /** * Create a derived instance of {@link Status} augmenting the current description with * additional detail. Leading and trailing whitespace may be removed; this may change in the * future. */ public Status augmentDescription(String additionalDetail) { if (additionalDetail == null) { return this; } else if (this.description == null) { return new Status(this.code, additionalDetail, this.cause); } else { return new Status(this.code, this.description + "\n" + additionalDetail, this.cause); } } /** * The canonical status code. */ public Code getCode() { return code; } /** * A description of this status for human consumption. */ @Nullable public String getDescription() { return description; } /** * The underlying cause of an error. * Note that the cause is not transmitted from server to client. */ @Nullable public Throwable getCause() { return cause; } /** * Is this status OK, i.e., not an error. */ public boolean isOk() { return Code.OK == code; } /** * Convert this {@link Status} to a {@link RuntimeException}. Use {@link #fromThrowable} * to recover this {@link Status} instance when the returned exception is in the causal chain. */ public StatusRuntimeException asRuntimeException() { return new StatusRuntimeException(this); } /** * Same as {@link #asRuntimeException()} but includes the provided trailers in the returned * exception. */ public StatusRuntimeException asRuntimeException(@Nullable Metadata trailers) { return new StatusRuntimeException(this, trailers); } /** * Convert this {@link Status} to an {@link Exception}. Use {@link #fromThrowable} * to recover this {@link Status} instance when the returned exception is in the causal chain. */ public StatusException asException() { return new StatusException(this); } /** * Same as {@link #asException()} but includes the provided trailers in the returned exception. */ public StatusException asException(@Nullable Metadata trailers) { return new StatusException(this, trailers); } /** A string representation of the status useful for debugging. */ @Override public String toString() { return MoreObjects.toStringHelper(this) .add("code", code.name()) .add("description", description) .add("cause", cause != null ? getStackTraceAsString(cause) : cause) .toString(); } private static final class StatusCodeMarshaller implements TrustedAsciiMarshaller<Status> { @Override public byte[] toAsciiString(Status status) { return status.getCode().valueAscii(); } @Override public Status parseAsciiString(byte[] serialized) { return fromCodeValue(serialized); } } private static final class StatusMessageMarshaller implements TrustedAsciiMarshaller<String> { private static final byte[] HEX = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; @Override public byte[] toAsciiString(String value) { byte[] valueBytes = value.getBytes(UTF_8); for (int i = 0; i < valueBytes.length; i++) { byte b = valueBytes[i]; // If there are only non escaping characters, skip the slow path. if (isEscapingChar(b)) { return toAsciiStringSlow(valueBytes, i); } } return valueBytes; } private static boolean isEscapingChar(byte b) { return b < ' ' || b >= '~' || b == '%'; } /** * Percent encode bytes to make them ASCII. * * @param valueBytes the UTF-8 bytes * @param ri The reader index, pointed at the first byte that needs escaping. */ private static byte[] toAsciiStringSlow(byte[] valueBytes, int ri) { byte[] escapedBytes = new byte[ri + (valueBytes.length - ri) * 3]; // copy over the good bytes if (ri != 0) { System.arraycopy(valueBytes, 0, escapedBytes, 0, ri); } int wi = ri; for (; ri < valueBytes.length; ri++) { byte b = valueBytes[ri]; // Manually implement URL encoding, per the gRPC spec. if (isEscapingChar(b)) { escapedBytes[wi] = '%'; escapedBytes[wi + 1] = HEX[(b >> 4) & 0xF]; escapedBytes[wi + 2] = HEX[b & 0xF]; wi += 3; continue; } escapedBytes[wi++] = b; } return Arrays.copyOf(escapedBytes, wi); } @SuppressWarnings("deprecation") // Use fast but deprecated String ctor @Override public String parseAsciiString(byte[] value) { for (int i = 0; i < value.length; i++) { byte b = value[i]; if (b < ' ' || b >= '~' || (b == '%' && i + 2 < value.length)) { return parseAsciiStringSlow(value); } } return new String(value, 0); } private static String parseAsciiStringSlow(byte[] value) { ByteBuffer buf = ByteBuffer.allocate(value.length); for (int i = 0; i < value.length;) { if (value[i] == '%' && i + 2 < value.length) { try { buf.put((byte)Integer.parseInt(new String(value, i + 1, 2, US_ASCII), 16)); i += 3; continue; } catch (NumberFormatException e) { // ignore, fall through, just push the bytes. } } buf.put(value[i]); i += 1; } return new String(buf.array(), 0, buf.position(), UTF_8); } } /** * Equality on Statuses is not well defined. Instead, do comparison based on their Code with * {@link #getCode}. The description and cause of the Status are unlikely to be stable, and * additional fields may be added to Status in the future. */ @Override public boolean equals(Object obj) { return super.equals(obj); } /** * Hash codes on Statuses are not well defined. * * @see #equals */ @Override public int hashCode() { return super.hashCode(); } }
grpc/grpc-java
api/src/main/java/io/grpc/Status.java
18
/* ### * IP: GHIDRA * * 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 docking; import java.awt.Cursor; /** * An enum that represents available drag-n-drop options for a docking tool. There are also * convenience methods for translating this drop code into a cursor and window position. */ enum DropCode { INVALID, STACK, LEFT, RIGHT, TOP, BOTTOM, ROOT, WINDOW; public Cursor getCursor() { Cursor c = HeaderCursor.NO_DROP; switch (this) { case LEFT: c = HeaderCursor.LEFT; break; case RIGHT: c = HeaderCursor.RIGHT; break; case TOP: c = HeaderCursor.TOP; break; case BOTTOM: c = HeaderCursor.BOTTOM; break; case STACK: c = HeaderCursor.STACK; break; case ROOT: c = HeaderCursor.STACK; break; case WINDOW: c = HeaderCursor.NEW_WINDOW; break; case INVALID: break; } return c; } public WindowPosition getWindowPosition() { switch (this) { case BOTTOM: return WindowPosition.BOTTOM; case LEFT: return WindowPosition.LEFT; case RIGHT: return WindowPosition.RIGHT; case STACK: return WindowPosition.STACK; case TOP: return WindowPosition.TOP; default: return WindowPosition.STACK; } } }
NationalSecurityAgency/ghidra
Ghidra/Framework/Docking/src/main/java/docking/DropCode.java
19
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.index.query; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.io.stream.Writeable; import org.elasticsearch.common.util.CollectionUtils; import java.io.IOException; /** * This enum is used to determine how to deal with invalid geo coordinates in geo related * queries: * * On STRICT validation invalid coordinates cause an exception to be thrown. * On IGNORE_MALFORMED invalid coordinates are being accepted. * On COERCE invalid coordinates are being corrected to the most likely valid coordinate. * */ public enum GeoValidationMethod implements Writeable { COERCE, IGNORE_MALFORMED, STRICT; public static final GeoValidationMethod DEFAULT = STRICT; public static final boolean DEFAULT_LENIENT_PARSING = (DEFAULT != STRICT); public static GeoValidationMethod readFromStream(StreamInput in) throws IOException { return GeoValidationMethod.values()[in.readVInt()]; } @Override public void writeTo(StreamOutput out) throws IOException { out.writeVInt(this.ordinal()); } public static GeoValidationMethod fromString(String op) { for (GeoValidationMethod method : GeoValidationMethod.values()) { if (method.name().equalsIgnoreCase(op)) { return method; } } throw new IllegalArgumentException( "operator needs to be either " + CollectionUtils.arrayAsArrayList(GeoValidationMethod.values()) + ", but not [" + op + "]" ); } /** Returns whether or not to skip bounding box validation. */ public static boolean isIgnoreMalformed(GeoValidationMethod method) { return (method == GeoValidationMethod.IGNORE_MALFORMED || method == GeoValidationMethod.COERCE); } /** Returns whether or not to try and fix broken/wrapping bounding boxes. */ public static boolean isCoerce(GeoValidationMethod method) { return method == GeoValidationMethod.COERCE; } /** Returns validation method corresponding to given coerce and ignoreMalformed values. */ public static GeoValidationMethod infer(boolean coerce, boolean ignoreMalformed) { if (coerce) { return GeoValidationMethod.COERCE; } else if (ignoreMalformed) { return GeoValidationMethod.IGNORE_MALFORMED; } else { return GeoValidationMethod.STRICT; } } }
elastic/elasticsearch
server/src/main/java/org/elasticsearch/index/query/GeoValidationMethod.java
20
/**************************************************************************/ /* XRMode.java */ /**************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /**************************************************************************/ /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /**************************************************************************/ package org.godotengine.godot.xr; /** * Godot available XR modes. */ public enum XRMode { REGULAR(0, "Regular", "--xr_mode_regular", "Default Android Gamepad"), // Regular/flatscreen OPENXR(1, "OpenXR", "--xr_mode_openxr", ""); final int index; final String label; public final String cmdLineArg; public final String inputFallbackMapping; XRMode(int index, String label, String cmdLineArg, String inputFallbackMapping) { this.index = index; this.label = label; this.cmdLineArg = cmdLineArg; this.inputFallbackMapping = inputFallbackMapping; } }
godotengine/godot
platform/android/java/lib/src/org/godotengine/godot/xr/XRMode.java
21
/* * Copyright (C) 2009-2020 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.core; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import lombok.core.AST.Kind; /** * An instance of this class wraps an Eclipse/javac internal node object. * * @param A Type of our owning AST. * @param L self-type. * @param N The common type of all AST nodes in the internal representation of the target platform. * For example, JCTree for javac, and ASTNode for Eclipse. */ public abstract class LombokNode<A extends AST<A, L, N>, L extends LombokNode<A, L, N>, N> implements DiagnosticsReceiver { protected final Kind kind; protected final N node; protected LombokImmutableList<L> children; protected L parent; /** structurally significant are those nodes that can be annotated in java 1.6 or are method-like toplevels, * so fields, local declarations, method arguments, methods, types, the Compilation Unit itself, and initializers. */ protected boolean isStructurallySignificant; /** * Creates a new Node object that represents the provided node. * * @param ast The owning AST - this node is part of this AST's tree of nodes. * @param node The AST object in the target parser's own internal AST tree that this node object will represent. * @param children A list of child nodes. Passing in null results in the children list being empty, not null. * @param kind The kind of node represented by this object. */ @SuppressWarnings("unchecked") protected LombokNode(N node, List<L> children, Kind kind) { this.kind = kind; this.node = node; this.children = children != null ? LombokImmutableList.copyOf(children) : LombokImmutableList.<L>of(); for (L child : this.children) { child.parent = (L) this; if (!child.isStructurallySignificant) child.isStructurallySignificant = calculateIsStructurallySignificant(node); } this.isStructurallySignificant = calculateIsStructurallySignificant(null); } public abstract A getAst(); /** {@inheritDoc} */ @Override public String toString() { return String.format("NODE %s (%s) %s", kind, node == null ? "(NULL)" : node.getClass(), node == null ? "" : node); } /** * Convenient shortcut to the owning ast object's {@code getPackageDeclaration} method. * * @see AST#getPackageDeclaration() */ public String getPackageDeclaration() { return getAst().getPackageDeclaration(); } /** * Convenient shortcut to the owning ast object's {@code getImportList} method. * * @see AST#getImportList() */ public ImportList getImportList() { return getAst().getImportList(); } /** * Convenient shortcut to the owning ast object's {@code getImportListAsTypeResolver} method. * * @see AST#getImportListAsTypeResolver() */ public TypeResolver getImportListAsTypeResolver() { return getAst().getImportListAsTypeResolver(); } /** * See {@link #isStructurallySignificant}. */ protected abstract boolean calculateIsStructurallySignificant(N parent); /** * Convenient shortcut to the owning ast object's get method. * * @see AST#get(Object) */ public L getNodeFor(N obj) { return getAst().get(obj); } /** * @return The javac/Eclipse internal AST object wrapped by this LombokNode object. */ public N get() { return node; } public Kind getKind() { return kind; } /** * Return the name of your type (simple name), method, field, or local variable. Return null if this * node doesn't really have a name, such as initializers, while statements, etc. */ public abstract String getName(); /** Returns the structurally significant node that encloses this one. * * @see #isStructurallySignificant() */ public L up() { L result = parent; while (result != null && !result.isStructurallySignificant) result = result.parent; return result; } /** * {@code @Foo int x, y;} is stored in both javac and ecj as 2 FieldDeclarations, both with the same annotation as child. * The normal {@code up()} method can't handle having multiple parents, but this one can. */ public Collection<L> upFromAnnotationToFields() { if (getKind() != Kind.ANNOTATION) return Collections.emptyList(); L field = up(); if (field == null || field.getKind() != Kind.FIELD) return Collections.emptyList(); L type = field.up(); if (type == null || type.getKind() != Kind.TYPE) return Collections.emptyList(); List<L> fields = new ArrayList<L>(); for (L potentialField : type.down()) { if (potentialField.getKind() != Kind.FIELD) continue; for (L child : potentialField.down()) { if (child.getKind() != Kind.ANNOTATION) continue; if (child.get() == get()) fields.add(potentialField); } } return fields; } /** * Returns the direct parent node in the AST tree of this node. For example, a local variable declaration's * direct parent can be e.g. an If block, but its {@code up()} {@code LombokNode} is the {@code Method} that contains it. */ public L directUp() { return parent; } /** * Returns all children nodes. */ public LombokImmutableList<L> down() { return children; } /** * Convenient shortcut to the owning ast object's getLatestJavaSpecSupported method. * * @see AST#getLatestJavaSpecSupported() */ public int getLatestJavaSpecSupported() { return getAst().getLatestJavaSpecSupported(); } /** * Convenient shortcut to the owning ast object's getSourceVersion method. * * @see AST#getSourceVersion() */ public int getSourceVersion() { return getAst().getSourceVersion(); } /** * Convenient shortcut to the owning ast object's top method. * * @see AST#top() */ public L top() { return getAst().top(); } /** * Convenient shortcut to the owning ast object's getFileName method. * * @see AST#getFileName() */ public String getFileName() { return getAst().getFileName(); } /** * Adds the stated node as a direct child of this node. * * Does not change the underlying (javac/Eclipse) AST, only the wrapped view. */ @SuppressWarnings({"unchecked"}) public L add(N newChild, Kind newChildKind) { getAst().setChanged(); L n = getAst().buildTree(newChild, newChildKind); if (n == null) return null; n.parent = (L) this; children = children.append(n); return n; } /** * Reparses the AST node represented by this node. Any existing nodes that occupy a different space in the AST are rehomed, any * nodes that no longer exist are removed, and new nodes are created. * * Careful - the node you call this on must not itself have been removed or rehomed - it rebuilds <i>all children</i>. */ public void rebuild() { Map<N, L> oldNodes = new IdentityHashMap<N, L>(); gatherAndRemoveChildren(oldNodes); L newNode = getAst().buildTree(get(), kind); getAst().setChanged(); getAst().replaceNewWithExistingOld(oldNodes, newNode); } @SuppressWarnings({"unchecked", "rawtypes"}) private void gatherAndRemoveChildren(Map<N, L> map) { for (LombokNode child : children) child.gatherAndRemoveChildren(map); getAst().identityDetector.remove(get()); map.put(get(), (L) this); children = LombokImmutableList.of(); getAst().getNodeMap().remove(get()); } /** * Removes the stated node, which must be a direct child of this node, from the AST. * * Does not change the underlying (javac/Eclipse) AST, only the wrapped view. */ public void removeChild(L child) { getAst().setChanged(); children = children.removeElement(child); } /** * Structurally significant means: LocalDeclaration, TypeDeclaration, MethodDeclaration, ConstructorDeclaration, * FieldDeclaration, Initializer, and CompilationUnitDeclaration. * The rest is e.g. if statements, while loops, etc. */ public boolean isStructurallySignificant() { return isStructurallySignificant; } public abstract boolean hasAnnotation(Class<? extends Annotation> type); public abstract <Z extends Annotation> AnnotationValues<Z> findAnnotation(Class<Z> type); public abstract boolean isStatic(); public abstract boolean isFinal(); public abstract boolean isTransient(); public abstract boolean isPrimitive(); public abstract boolean isEnumMember(); public abstract boolean isEnumType(); /** * The 'type' of the field or method, or {@code null} if this node is neither. * * The type is as it is written in the code (no resolution), includes array dimensions, * but not necessarily generics. * * The main purpose of this method is to verify this type against a list of known types, * like primitives or primitive wrappers. * * @return The 'type' of the field or method, or {@code null} if this node is neither. */ public abstract String fieldOrMethodBaseType(); public abstract int countMethodParameters(); public abstract int getStartPos(); }
projectlombok/lombok
src/core/lombok/core/LombokNode.java
22
404: Not Found
halo-dev/halo
api/src/main/java/run/halo/app/extension/Secret.java
23
package me.chanjar.weixin.cp.bean; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import me.chanjar.weixin.cp.util.json.WxCpGsonBuilder; import java.io.Serializable; /** * Created by Daniel Qian. * * @author Daniel Qian */ @Data @AllArgsConstructor @NoArgsConstructor public class WxCpTag implements Serializable { private static final long serialVersionUID = -7243320279646928402L; private String id; private String name; /** * From json wx cp tag. * * @param json the json * @return the wx cp tag */ public static WxCpTag fromJson(String json) { return WxCpGsonBuilder.create().fromJson(json, WxCpTag.class); } /** * To json string. * * @return the string */ public String toJson() { return WxCpGsonBuilder.create().toJson(this); } }
Wechat-Group/WxJava
weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpTag.java
24
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * Project Info: https://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * https://plantuml.com/patreon (only 1$ per month!) * https://plantuml.com/paypal * * This file is part of Smetana. * Smetana is a partial translation of Graphviz/Dot sources from C to Java. * * (C) Copyright 2009-2024, Arnaud Roques * * This translation is distributed under the same Licence as the original C program: * ************************************************************************* * Copyright (c) 2011 AT&T Intellectual Property * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: See CVS logs. Details at http://www.graphviz.org/ ************************************************************************* * * THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC * LICENSE ("AGREEMENT"). [Eclipse Public License - v 1.0] * * ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES * RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. * * You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * 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 h; public enum EN_api_t { API_render, API_layout, API_textlayout, API_device, API_loadimage, _DUMMY_ELEM_ } // typedef enum { API_render, API_layout, API_textlayout, API_device, API_loadimage, _DUMMY_ELEM_=0 } api_t;
plantuml/plantuml
src/h/EN_api_t.java
25
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * Project Info: https://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * https://plantuml.com/patreon (only 1$ per month!) * https://plantuml.com/paypal * * This file is part of Smetana. * Smetana is a partial translation of Graphviz/Dot sources from C to Java. * * (C) Copyright 2009-2024, Arnaud Roques * * This translation is distributed under the same Licence as the original C program: * ************************************************************************* * Copyright (c) 2011 AT&T Intellectual Property * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: See CVS logs. Details at http://www.graphviz.org/ ************************************************************************* * * THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC * LICENSE ("AGREEMENT"). [Eclipse Public License - v 1.0] * * ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES * RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. * * You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * 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 h; public enum EN_ratio_t { R_NONE, R_VALUE, R_FILL, R_COMPRESS, R_AUTO, R_EXPAND } // typedef enum { R_NONE = // 0, R_VALUE, R_FILL, R_COMPRESS, R_AUTO, R_EXPAND } ratio_t;
plantuml/plantuml
src/h/EN_ratio_t.java
26
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * Project Info: https://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * https://plantuml.com/patreon (only 1$ per month!) * https://plantuml.com/paypal * * This file is part of Smetana. * Smetana is a partial translation of Graphviz/Dot sources from C to Java. * * (C) Copyright 2009-2022, Arnaud Roques * * This translation is distributed under the same Licence as the original C program: * ************************************************************************* * Copyright (c) 2011 AT&T Intellectual Property * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: See CVS logs. Details at http://www.graphviz.org/ ************************************************************************* * * THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC * LICENSE ("AGREEMENT"). [Eclipse Public License - v 1.0] * * ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES * RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. * * You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * 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 h; import smetana.core.UnsupportedStarStruct; final public class ST_tna_t extends UnsupportedStarStruct { public double t; public final ST_pointf a[] = new ST_pointf[] { new ST_pointf(), new ST_pointf() }; } // typedef struct tna_t { // double t; // Ppoint_t a[2]; // } tna_t;
plantuml/plantuml
src/h/ST_tna_t.java
27
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file or at // https://developers.google.com/open-source/licenses/bsd package com.google.protobuf; import java.io.IOException; import java.io.InputStream; import java.util.Map; /** * Abstract interface implemented by Protocol Message objects. * * <p>See also {@link MessageLite}, which defines most of the methods that typical users care about. * {@link Message} adds methods that are not available in the "lite" runtime. The biggest added * features are introspection and reflection; that is, getting descriptors for the message type and * accessing the field values dynamically. * * @author kenton@google.com Kenton Varda */ @CheckReturnValue public interface Message extends MessageLite, MessageOrBuilder { // (From MessageLite, re-declared here only for return type covariance.) @Override Parser<? extends Message> getParserForType(); // ----------------------------------------------------------------- // Comparison and hashing /** * Compares the specified object with this message for equality. Returns {@code true} if the given * object is a message of the same type (as defined by {@code getDescriptorForType()}) and has * identical values for all of its fields. Subclasses must implement this; inheriting {@code * Object.equals()} is incorrect. * * @param other object to be compared for equality with this message * @return {@code true} if the specified object is equal to this message */ @Override boolean equals(Object other); /** * Returns the hash code value for this message. The hash code of a message should mix the * message's type (object identity of the descriptor) with its contents (known and unknown field * values). Subclasses must implement this; inheriting {@code Object.hashCode()} is incorrect. * * @return the hash code value for this message * @see Map#hashCode() */ @Override int hashCode(); // ----------------------------------------------------------------- // Convenience methods. /** * Converts the message to a string in protocol buffer text format. This is just a trivial wrapper * around {@link TextFormat.Printer#printToString(MessageOrBuilder)}. */ @Override String toString(); // ================================================================= // Builders // (From MessageLite, re-declared here only for return type covariance.) @Override Builder newBuilderForType(); @Override Builder toBuilder(); /** Abstract interface implemented by Protocol Message builders. */ interface Builder extends MessageLite.Builder, MessageOrBuilder { // (From MessageLite.Builder, re-declared here only for return type // covariance.) @Override @CanIgnoreReturnValue Builder clear(); /** * Merge {@code other} into the message being built. {@code other} must have the exact same type * as {@code this} (i.e. {@code getDescriptorForType() == other.getDescriptorForType()}). * * <p>Merging occurs as follows. For each field:<br> * * For singular primitive fields, if the field is set in {@code other}, then {@code other}'s * value overwrites the value in this message.<br> * * For singular message fields, if the field is set in {@code other}, it is merged into the * corresponding sub-message of this message using the same merging rules.<br> * * For repeated fields, the elements in {@code other} are concatenated with the elements in * this message.<br> * * For oneof groups, if the other message has one of the fields set, the group of this message * is cleared and replaced by the field of the other message, so that the oneof constraint is * preserved. * * <p>This is equivalent to the {@code Message::MergeFrom} method in C++. */ @CanIgnoreReturnValue Builder mergeFrom(Message other); // (From MessageLite.Builder, re-declared here only for return type // covariance.) @Override Message build(); @Override Message buildPartial(); @Override Builder clone(); @Override @CanIgnoreReturnValue Builder mergeFrom(CodedInputStream input) throws IOException; @Override @CanIgnoreReturnValue Builder mergeFrom(CodedInputStream input, ExtensionRegistryLite extensionRegistry) throws IOException; /** Get the message's type's descriptor. See {@link Message#getDescriptorForType()}. */ @Override Descriptors.Descriptor getDescriptorForType(); /** * Create a builder for messages of the appropriate type for the given field. The * builder is NOT nested in the current builder. However, messages built with the * builder can then be passed to the {@link #setField(Descriptors.FieldDescriptor, Object)}, * {@link #setRepeatedField(Descriptors.FieldDescriptor, int, Object)}, or * {@link #addRepeatedField(Descriptors.FieldDescriptor, Object)} * method of the current builder. * * <p>To obtain a builder nested in the current builder, use * {@link #getFieldBuilder(Descriptors.FieldDescriptor)} instead. */ Builder newBuilderForField(Descriptors.FieldDescriptor field); /** * Get a nested builder instance for the given field. * * <p>Normally, we hold a reference to the immutable message object for the message type field. * Some implementations (the generated message builders) can also hold a reference to * the builder object (a nested builder) for the field. * * <p>If the field is already backed up by a nested builder, the nested builder is * returned. Otherwise, a new field builder is created and returned. The original message * field (if one exists) is merged into the field builder, which is then nested into its * parent builder. */ Builder getFieldBuilder(Descriptors.FieldDescriptor field); /** * Get a nested builder instance for the given repeated field instance. * * <p>Normally, we hold a reference to the immutable message object for the message type field. * Some implementations (the generated message builders) can also hold a reference to * the builder object (a nested builder) for the field. * * <p>If the field is already backed up by a nested builder, the nested builder is * returned. Otherwise, a new field builder is created and returned. The original message * field (if one exists) is merged into the field builder, which is then nested into its * parent builder. */ Builder getRepeatedFieldBuilder(Descriptors.FieldDescriptor field, int index); /** * Sets a field to the given value. The value must be of the correct type for this field, that * is, the same type that {@link Message#getField(Descriptors.FieldDescriptor)} returns. */ @CanIgnoreReturnValue Builder setField(Descriptors.FieldDescriptor field, Object value); /** * Clears the field. This is exactly equivalent to calling the generated "clear" accessor method * corresponding to the field. */ @CanIgnoreReturnValue Builder clearField(Descriptors.FieldDescriptor field); /** * Clears the oneof. This is exactly equivalent to calling the generated "clear" accessor method * corresponding to the oneof. */ @CanIgnoreReturnValue Builder clearOneof(Descriptors.OneofDescriptor oneof); /** * Sets an element of a repeated field to the given value. The value must be of the correct type * for this field; that is, the same type that {@link * Message#getRepeatedField(Descriptors.FieldDescriptor,int)} returns. * * @throws IllegalArgumentException if the field is not a repeated field, or {@code * field.getContainingType() != getDescriptorForType()}. */ @CanIgnoreReturnValue Builder setRepeatedField(Descriptors.FieldDescriptor field, int index, Object value); /** * Like {@code setRepeatedField}, but appends the value as a new element. * * @throws IllegalArgumentException if the field is not a repeated field, or {@code * field.getContainingType() != getDescriptorForType()} */ @CanIgnoreReturnValue Builder addRepeatedField(Descriptors.FieldDescriptor field, Object value); /** Set the {@link UnknownFieldSet} for this message. */ @CanIgnoreReturnValue Builder setUnknownFields(UnknownFieldSet unknownFields); /** Merge some unknown fields into the {@link UnknownFieldSet} for this message. */ @CanIgnoreReturnValue Builder mergeUnknownFields(UnknownFieldSet unknownFields); // --------------------------------------------------------------- // Convenience methods. // (From MessageLite.Builder, re-declared here only for return type // covariance.) @Override @CanIgnoreReturnValue Builder mergeFrom(ByteString data) throws InvalidProtocolBufferException; @Override @CanIgnoreReturnValue Builder mergeFrom(ByteString data, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException; @Override @CanIgnoreReturnValue Builder mergeFrom(byte[] data) throws InvalidProtocolBufferException; @Override @CanIgnoreReturnValue Builder mergeFrom(byte[] data, int off, int len) throws InvalidProtocolBufferException; @Override @CanIgnoreReturnValue Builder mergeFrom(byte[] data, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException; @Override @CanIgnoreReturnValue Builder mergeFrom(byte[] data, int off, int len, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException; @Override @CanIgnoreReturnValue Builder mergeFrom(InputStream input) throws IOException; @Override @CanIgnoreReturnValue Builder mergeFrom(InputStream input, ExtensionRegistryLite extensionRegistry) throws IOException; @Override boolean mergeDelimitedFrom(InputStream input) throws IOException; @Override boolean mergeDelimitedFrom(InputStream input, ExtensionRegistryLite extensionRegistry) throws IOException; } }
protocolbuffers/protobuf
java/core/src/main/java/com/google/protobuf/Message.java
28
/* * Copyright 2002-2024 the original author or authors. * * 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 * * https://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 org.springframework.scheduling.support; import java.time.Instant; import java.time.ZoneId; import java.time.ZonedDateTime; import java.util.TimeZone; import org.springframework.lang.Nullable; import org.springframework.scheduling.Trigger; import org.springframework.scheduling.TriggerContext; import org.springframework.util.Assert; /** * {@link Trigger} implementation for cron expressions. Wraps a * {@link CronExpression} which parses according to common crontab conventions. * * <p>Supports a Quartz day-of-month/week field with an L/# expression. Follows * common cron conventions in every other respect, including 0-6 for SUN-SAT * (plus 7 for SUN as well). Note that Quartz deviates from the day-of-week * convention in cron through 1-7 for SUN-SAT whereas Spring strictly follows * cron even in combination with the optional Quartz-specific L/# expressions. * * @author Juergen Hoeller * @author Arjen Poutsma * @since 3.0 * @see CronExpression */ public class CronTrigger implements Trigger { private final CronExpression expression; @Nullable private final ZoneId zoneId; /** * Build a {@code CronTrigger} from the pattern provided in the default time zone. * <p>This is equivalent to the {@link CronTrigger#forLenientExecution} factory * method. Original trigger firings may be skipped if the previous task is still * running; if this is not desirable, consider {@link CronTrigger#forFixedExecution}. * @param expression a space-separated list of time fields, following cron * expression conventions * @see CronTrigger#forLenientExecution * @see CronTrigger#forFixedExecution */ public CronTrigger(String expression) { this.expression = CronExpression.parse(expression); this.zoneId = null; } /** * Build a {@code CronTrigger} from the pattern provided in the given time zone, * with the same lenient execution as {@link CronTrigger#CronTrigger(String)}. * <p>Note that such explicit time zone customization is usually not necessary, * using {@link org.springframework.scheduling.TaskScheduler#getClock()} instead. * @param expression a space-separated list of time fields, following cron * expression conventions * @param timeZone a time zone in which the trigger times will be generated */ public CronTrigger(String expression, TimeZone timeZone) { this.expression = CronExpression.parse(expression); Assert.notNull(timeZone, "TimeZone must not be null"); this.zoneId = timeZone.toZoneId(); } /** * Build a {@code CronTrigger} from the pattern provided in the given time zone, * with the same lenient execution as {@link CronTrigger#CronTrigger(String)}. * <p>Note that such explicit time zone customization is usually not necessary, * using {@link org.springframework.scheduling.TaskScheduler#getClock()} instead. * @param expression a space-separated list of time fields, following cron * expression conventions * @param zoneId a time zone in which the trigger times will be generated * @since 5.3 * @see CronExpression#parse(String) */ public CronTrigger(String expression, ZoneId zoneId) { this.expression = CronExpression.parse(expression); Assert.notNull(zoneId, "ZoneId must not be null"); this.zoneId = zoneId; } /** * Return the cron pattern that this trigger has been built with. */ public String getExpression() { return this.expression.toString(); } /** * Determine the next execution time according to the given trigger context. * <p>Next execution times are calculated based on the * {@linkplain TriggerContext#lastCompletion completion time} of the * previous execution; therefore, overlapping executions won't occur. */ @Override @Nullable public Instant nextExecution(TriggerContext triggerContext) { Instant timestamp = determineLatestTimestamp(triggerContext); ZoneId zone = (this.zoneId != null ? this.zoneId : triggerContext.getClock().getZone()); ZonedDateTime zonedTimestamp = ZonedDateTime.ofInstant(timestamp, zone); ZonedDateTime nextTimestamp = this.expression.next(zonedTimestamp); return (nextTimestamp != null ? nextTimestamp.toInstant() : null); } Instant determineLatestTimestamp(TriggerContext triggerContext) { Instant timestamp = triggerContext.lastCompletion(); if (timestamp != null) { Instant scheduled = triggerContext.lastScheduledExecution(); if (scheduled != null && timestamp.isBefore(scheduled)) { // Previous task apparently executed too early... // Let's simply use the last calculated execution time then, // in order to prevent accidental re-fires in the same second. timestamp = scheduled; } } else { timestamp = determineInitialTimestamp(triggerContext); } return timestamp; } Instant determineInitialTimestamp(TriggerContext triggerContext) { return triggerContext.getClock().instant(); } @Override public boolean equals(@Nullable Object other) { return (this == other || (other instanceof CronTrigger that && this.expression.equals(that.expression))); } @Override public int hashCode() { return this.expression.hashCode(); } @Override public String toString() { return this.expression.toString(); } /** * Create a {@link CronTrigger} for lenient execution, to be rescheduled * after every task based on the completion time. * <p>This variant does not make up for missed trigger firings if the * associated task has taken too long. As a consequence, original trigger * firings may be skipped if the previous task is still running. * <p>This is equivalent to the regular {@link CronTrigger} constructor. * Note that lenient execution is scheduler-dependent: it may skip trigger * firings with long-running tasks on a thread pool while executing at * {@link #forFixedExecution}-like precision with new threads per task. * @param expression a space-separated list of time fields, following cron * expression conventions * @since 6.1.3 * @see #resumeLenientExecution */ public static CronTrigger forLenientExecution(String expression) { return new CronTrigger(expression); } /** * Create a {@link CronTrigger} for lenient execution, to be rescheduled * after every task based on the completion time. * <p>This variant does not make up for missed trigger firings if the * associated task has taken too long. As a consequence, original trigger * firings may be skipped if the previous task is still running. * @param expression a space-separated list of time fields, following cron * expression conventions * @param resumptionTimestamp the timestamp to resume from (the last-known * completion timestamp), with the new trigger calculated from there and * possibly immediately firing (but only once, every subsequent calculation * will start from the completion time of that first resumed trigger) * @since 6.1.3 * @see #forLenientExecution */ public static CronTrigger resumeLenientExecution(String expression, Instant resumptionTimestamp) { return new CronTrigger(expression) { @Override Instant determineInitialTimestamp(TriggerContext triggerContext) { return resumptionTimestamp; } }; } /** * Create a {@link CronTrigger} for fixed execution, to be rescheduled * after every task based on the last scheduled time. * <p>This variant makes up for missed trigger firings if the associated task * has taken too long, scheduling a task for every original trigger firing. * Such follow-up tasks may execute late but will never be skipped. * <p>Immediate versus late execution in case of long-running tasks may * be scheduler-dependent but the guarantee to never skip a task is portable. * @param expression a space-separated list of time fields, following cron * expression conventions * @since 6.1.3 * @see #resumeFixedExecution */ public static CronTrigger forFixedExecution(String expression) { return new CronTrigger(expression) { @Override protected Instant determineLatestTimestamp(TriggerContext triggerContext) { Instant scheduled = triggerContext.lastScheduledExecution(); return (scheduled != null ? scheduled : super.determineInitialTimestamp(triggerContext)); } }; } /** * Create a {@link CronTrigger} for fixed execution, to be rescheduled * after every task based on the last scheduled time. * <p>This variant makes up for missed trigger firings if the associated task * has taken too long, scheduling a task for every original trigger firing. * Such follow-up tasks may execute late but will never be skipped. * @param expression a space-separated list of time fields, following cron * expression conventions * @param resumptionTimestamp the timestamp to resume from (the last-known * scheduled timestamp), with every trigger in-between immediately firing * to make up for every execution that would have happened in the meantime * @since 6.1.3 * @see #forFixedExecution */ public static CronTrigger resumeFixedExecution(String expression, Instant resumptionTimestamp) { return new CronTrigger(expression) { @Override protected Instant determineLatestTimestamp(TriggerContext triggerContext) { Instant scheduled = triggerContext.lastScheduledExecution(); return (scheduled != null ? scheduled : super.determineLatestTimestamp(triggerContext)); } @Override Instant determineInitialTimestamp(TriggerContext triggerContext) { return resumptionTimestamp; } }; } }
spring-projects/spring-framework
spring-context/src/main/java/org/springframework/scheduling/support/CronTrigger.java
29
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * Project Info: https://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * https://plantuml.com/patreon (only 1$ per month!) * https://plantuml.com/paypal * * This file is part of Smetana. * Smetana is a partial translation of Graphviz/Dot sources from C to Java. * * (C) Copyright 2009-2022, Arnaud Roques * * This translation is distributed under the same Licence as the original C program: * ************************************************************************* * Copyright (c) 2011 AT&T Intellectual Property * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: See CVS logs. Details at http://www.graphviz.org/ ************************************************************************* * * THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC * LICENSE ("AGREEMENT"). [Eclipse Public License - v 1.0] * * ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES * RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. * * You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * 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 h; import smetana.core.UnsupportedStarStruct; public class ST_Agobj_s extends UnsupportedStarStruct { public final ST_Agtag_s tag = new ST_Agtag_s(); public ST_Agrec_s data; } // struct Agobj_s { // Agtag_t tag; // Agrec_t *data; // };
plantuml/plantuml
src/h/ST_Agobj_s.java
30
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * Project Info: https://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * https://plantuml.com/patreon (only 1$ per month!) * https://plantuml.com/paypal * * This file is part of Smetana. * Smetana is a partial translation of Graphviz/Dot sources from C to Java. * * (C) Copyright 2009-2024, Arnaud Roques * * This translation is distributed under the same Licence as the original C program: * ************************************************************************* * Copyright (c) 2011 AT&T Intellectual Property * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: See CVS logs. Details at http://www.graphviz.org/ ************************************************************************* * * THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC * LICENSE ("AGREEMENT"). [Eclipse Public License - v 1.0] * * ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES * RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. * * You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * 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 h; public enum EN_pack_mode { l_undef, l_clust, l_node, l_graph, l_array, l_aspect } // typedef enum { l_undef, l_clust, l_node, l_graph, l_array, l_aspect } pack_mode;
plantuml/plantuml
src/h/EN_pack_mode.java
31
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * Project Info: https://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * https://plantuml.com/patreon (only 1$ per month!) * https://plantuml.com/paypal * * This file is part of Smetana. * Smetana is a partial translation of Graphviz/Dot sources from C to Java. * * (C) Copyright 2009-2022, Arnaud Roques * * This translation is distributed under the same Licence as the original C program: * ************************************************************************* * Copyright (c) 2011 AT&T Intellectual Property * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: See CVS logs. Details at http://www.graphviz.org/ ************************************************************************* * * THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC * LICENSE ("AGREEMENT"). [Eclipse Public License - v 1.0] * * ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES * RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. * * You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * 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 h; import smetana.core.UnsupportedStarStruct; final public class ST_Pedge_t extends UnsupportedStarStruct { public final ST_pointf a = new ST_pointf(); public final ST_pointf b = new ST_pointf(); } // typedef struct Pedge_t { // Ppoint_t a, b; // } Pedge_t;
plantuml/plantuml
src/h/ST_Pedge_t.java
32
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * Project Info: https://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * https://plantuml.com/patreon (only 1$ per month!) * https://plantuml.com/paypal * * This file is part of Smetana. * Smetana is a partial translation of Graphviz/Dot sources from C to Java. * * (C) Copyright 2009-2022, Arnaud Roques * * This translation is distributed under the same Licence as the original C program: * ************************************************************************* * Copyright (c) 2011 AT&T Intellectual Property * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: See CVS logs. Details at http://www.graphviz.org/ ************************************************************************* * * THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC * LICENSE ("AGREEMENT"). [Eclipse Public License - v 1.0] * * ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES * RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. * * You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * 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 h; import smetana.core.CArray; import smetana.core.UnsupportedStarStruct; final public class ST_splines extends UnsupportedStarStruct { public CArray<ST_bezier> list; public int size; } // typedef struct splines { // bezier *list; // int size; // boxf bb; // } splines;
plantuml/plantuml
src/h/ST_splines.java
33
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * Project Info: https://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * https://plantuml.com/patreon (only 1$ per month!) * https://plantuml.com/paypal * * This file is part of Smetana. * Smetana is a partial translation of Graphviz/Dot sources from C to Java. * * (C) Copyright 2009-2022, Arnaud Roques * * This translation is distributed under the same Licence as the original C program: * ************************************************************************* * Copyright (c) 2011 AT&T Intellectual Property * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: See CVS logs. Details at http://www.graphviz.org/ ************************************************************************* * * THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC * LICENSE ("AGREEMENT"). [Eclipse Public License - v 1.0] * * ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES * RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. * * You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * 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 h; import smetana.core.CArrayOfStar; import smetana.core.UnsupportedStarStruct; final public class ST_nlist_t extends UnsupportedStarStruct { public CArrayOfStar<ST_Agnode_s> list; public int size; } // typedef struct nlist_t { // node_t **list; // int size; // } nlist_t;
plantuml/plantuml
src/h/ST_nlist_t.java
34
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * Project Info: https://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * https://plantuml.com/patreon (only 1$ per month!) * https://plantuml.com/paypal * * This file is part of Smetana. * Smetana is a partial translation of Graphviz/Dot sources from C to Java. * * (C) Copyright 2009-2022, Arnaud Roques * * This translation is distributed under the same Licence as the original C program: * ************************************************************************* * Copyright (c) 2011 AT&T Intellectual Property * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: See CVS logs. Details at http://www.graphviz.org/ ************************************************************************* * * THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC * LICENSE ("AGREEMENT"). [Eclipse Public License - v 1.0] * * ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES * RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. * * You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * 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 h; import smetana.core.__ptr__; final public class ST_dthold_s extends ST_dtlink_s { public final ST_dtlink_s hdr = this; public __ptr__ obj; } // struct _dthold_s // { Dtlink_t hdr; /* header */ // void* obj; /* user object */ // };
plantuml/plantuml
src/h/ST_dthold_s.java
35
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * Project Info: https://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * https://plantuml.com/patreon (only 1$ per month!) * https://plantuml.com/paypal * * This file is part of Smetana. * Smetana is a partial translation of Graphviz/Dot sources from C to Java. * * (C) Copyright 2009-2022, Arnaud Roques * * This translation is distributed under the same Licence as the original C program: * ************************************************************************* * Copyright (c) 2011 AT&T Intellectual Property * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: See CVS logs. Details at http://www.graphviz.org/ ************************************************************************* * * THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC * LICENSE ("AGREEMENT"). [Eclipse Public License - v 1.0] * * ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES * RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. * * You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * 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 h; import smetana.core.CArrayOfStar; import smetana.core.UnsupportedStarStruct; final public class ST_blk_t extends UnsupportedStarStruct { public CArrayOfStar<ST_Agnode_s> data; public CArrayOfStar<ST_Agnode_s> endp; public ST_blk_t prev; public ST_blk_t next; } //typedef struct blk_t { //Agnode_t **data; //Agnode_t **endp; //struct blk_t *prev; //struct blk_t *next; //} blk_t;
plantuml/plantuml
src/h/ST_blk_t.java
36
package me.chanjar.weixin.cp.bean; import lombok.Data; import me.chanjar.weixin.cp.util.json.WxCpGsonBuilder; import java.io.Serializable; /** * 企业微信的部门. * * @author Daniel Qian */ @Data public class WxCpTpDepart implements Serializable { private static final long serialVersionUID = -5028321625140879571L; private Integer id; private String name; private String enName; private Integer parentid; private Integer order; /** * From json wx cp tp depart. * * @param json the json * @return the wx cp tp depart */ public static WxCpTpDepart fromJson(String json) { return WxCpGsonBuilder.create().fromJson(json, WxCpTpDepart.class); } /** * To json string. * * @return the string */ public String toJson() { return WxCpGsonBuilder.create().toJson(this); } }
Wechat-Group/WxJava
weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpTpDepart.java
37
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * Project Info: https://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * https://plantuml.com/patreon (only 1$ per month!) * https://plantuml.com/paypal * * This file is part of Smetana. * Smetana is a partial translation of Graphviz/Dot sources from C to Java. * * (C) Copyright 2009-2022, Arnaud Roques * * This translation is distributed under the same Licence as the original C program: * ************************************************************************* * Copyright (c) 2011 AT&T Intellectual Property * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: See CVS logs. Details at http://www.graphviz.org/ ************************************************************************* * * THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC * LICENSE ("AGREEMENT"). [Eclipse Public License - v 1.0] * * ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES * RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. * * You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * 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 h; import smetana.core.UnsupportedStarStruct; final public class ST_path extends UnsupportedStarStruct { final public ST_port start = new ST_port(), end = new ST_port(); public int nbox; public ST_boxf boxes[]; public ST_Agedge_s data; } // typedef struct path { /* internal specification for an edge spline */ // port start, end; // int nbox; /* number of subdivisions */ // boxf *boxes; /* rectangular regions of subdivision */ // void *data; // } path;
plantuml/plantuml
src/h/ST_path.java
38
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * Project Info: https://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * https://plantuml.com/patreon (only 1$ per month!) * https://plantuml.com/paypal * * This file is part of Smetana. * Smetana is a partial translation of Graphviz/Dot sources from C to Java. * * (C) Copyright 2009-2022, Arnaud Roques * * This translation is distributed under the same Licence as the original C program: * ************************************************************************* * Copyright (c) 2011 AT&T Intellectual Property * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: See CVS logs. Details at http://www.graphviz.org/ ************************************************************************* * * THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC * LICENSE ("AGREEMENT"). [Eclipse Public License - v 1.0] * * ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES * RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. * * You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * 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 h; import smetana.core.CArrayOfStar; import smetana.core.UnsupportedStarStruct; final public class ST_STheap_t extends UnsupportedStarStruct { public CArrayOfStar<ST_subtree_t> elt; public int size; } //typedef struct STheap_s { //subtree_t **elt; //int size; //} STheap_t;
plantuml/plantuml
src/h/ST_STheap_t.java
39
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * Project Info: https://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * https://plantuml.com/patreon (only 1$ per month!) * https://plantuml.com/paypal * * This file is part of Smetana. * Smetana is a partial translation of Graphviz/Dot sources from C to Java. * * (C) Copyright 2009-2022, Arnaud Roques * * This translation is distributed under the same Licence as the original C program: * ************************************************************************* * Copyright (c) 2011 AT&T Intellectual Property * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: See CVS logs. Details at http://www.graphviz.org/ ************************************************************************* * * THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC * LICENSE ("AGREEMENT"). [Eclipse Public License - v 1.0] * * ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES * RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. * * You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * 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 h; import smetana.core.UnsupportedStarStruct; final public class ST_Agdisc_s extends UnsupportedStarStruct { public ST_Agmemdisc_s mem; public ST_Agiddisc_s id; public ST_Agiodisc_s io; } // struct Agdisc_s { /* user's discipline */ // Agmemdisc_t *mem; // Agiddisc_t *id; // Agiodisc_t *io; // };
plantuml/plantuml
src/h/ST_Agdisc_s.java
40
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * Project Info: https://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * https://plantuml.com/patreon (only 1$ per month!) * https://plantuml.com/paypal * * This file is part of Smetana. * Smetana is a partial translation of Graphviz/Dot sources from C to Java. * * (C) Copyright 2009-2022, Arnaud Roques * * This translation is distributed under the same Licence as the original C program: * ************************************************************************* * Copyright (c) 2011 AT&T Intellectual Property * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: See CVS logs. Details at http://www.graphviz.org/ ************************************************************************* * * THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC * LICENSE ("AGREEMENT"). [Eclipse Public License - v 1.0] * * ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES * RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. * * You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * 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 h; import smetana.core.UnsupportedStarStruct; import smetana.core.__struct__; final public class ST_point extends UnsupportedStarStruct { public int x, y; @Override public __struct__ copy() { final ST_point result = new ST_point(); result.x = this.x; result.y = this.y; return result; } @Override public void ___(__struct__ other) { ST_point this2 = (ST_point) other; this.x = this2.x; this.y = this2.y; } } // typedef struct { int x, y; } point;
plantuml/plantuml
src/h/ST_point.java
41
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * Project Info: https://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * https://plantuml.com/patreon (only 1$ per month!) * https://plantuml.com/paypal * * This file is part of Smetana. * Smetana is a partial translation of Graphviz/Dot sources from C to Java. * * (C) Copyright 2009-2022, Arnaud Roques * * This translation is distributed under the same Licence as the original C program: * ************************************************************************* * Copyright (c) 2011 AT&T Intellectual Property * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: See CVS logs. Details at http://www.graphviz.org/ ************************************************************************* * * THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC * LICENSE ("AGREEMENT"). [Eclipse Public License - v 1.0] * * ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES * RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. * * You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * 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 h; import smetana.core.CArray; import smetana.core.UnsupportedStarStruct; final public class ST_Ppoly_t extends UnsupportedStarStruct { public CArray<ST_pointf> ps; public int pn; @Override public ST_Ppoly_t copy() { ST_Ppoly_t result = new ST_Ppoly_t(); result.ps = this.ps; result.pn = this.pn; return result; } } // typedef struct Ppoly_t { // Ppoint_t *ps; // int pn; // } Ppoly_t;
plantuml/plantuml
src/h/ST_Ppoly_t.java
42
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * Project Info: https://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * https://plantuml.com/patreon (only 1$ per month!) * https://plantuml.com/paypal * * This file is part of Smetana. * Smetana is a partial translation of Graphviz/Dot sources from C to Java. * * (C) Copyright 2009-2022, Arnaud Roques * * This translation is distributed under the same Licence as the original C program: * ************************************************************************* * Copyright (c) 2011 AT&T Intellectual Property * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: See CVS logs. Details at http://www.graphviz.org/ ************************************************************************* * * THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC * LICENSE ("AGREEMENT"). [Eclipse Public License - v 1.0] * * ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES * RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. * * You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * 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 h; import smetana.core.CArray; import smetana.core.UnsupportedStarStruct; final public class ST_tedge_t extends UnsupportedStarStruct { public ST_pointnlink_t pnl0p; public ST_pointnlink_t pnl1p; public CArray<ST_triangle_t> lrp; public CArray<ST_triangle_t> rtp; } // typedef struct tedge_t { // pointnlink_t *pnl0p; // pointnlink_t *pnl1p; // struct triangle_t *ltp; // struct triangle_t *rtp; // } tedge_t;
plantuml/plantuml
src/h/ST_tedge_t.java
43
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * Project Info: https://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * https://plantuml.com/patreon (only 1$ per month!) * https://plantuml.com/paypal * * This file is part of Smetana. * Smetana is a partial translation of Graphviz/Dot sources from C to Java. * * (C) Copyright 2009-2022, Arnaud Roques * * This translation is distributed under the same Licence as the original C program: * ************************************************************************* * Copyright (c) 2011 AT&T Intellectual Property * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: See CVS logs. Details at http://www.graphviz.org/ ************************************************************************* * * THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC * LICENSE ("AGREEMENT"). [Eclipse Public License - v 1.0] * * ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES * RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. * * You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * 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 h; import smetana.core.UnsupportedStarStruct; import smetana.core.__struct__; final public class ST_Rect_t extends UnsupportedStarStruct { public final int[] boundary = new int[2 * 2]; @Override public void ___(__struct__ other) { ST_Rect_t other2 = (ST_Rect_t) other; this.boundary[0] = other2.boundary[0]; this.boundary[1] = other2.boundary[1]; this.boundary[2] = other2.boundary[2]; this.boundary[3] = other2.boundary[3]; } // typedef struct Rect { // int boundary[2*2]; // } Rect_t; }
plantuml/plantuml
src/h/ST_Rect_t.java
44
// Companion Code to the paper "Generative Forests" by R. Nock and M. Guillame-Bert. import java.io.*; import java.util.*; /************************************************************************************************************************************** * Class Tree *****/ class Tree implements Debuggable{ int name, depth; Node root; // root of the tree Node star_node; // for data generation GenerativeModelBasedOnEnsembleOfTrees myGET; HashSet <Node> leaves; Vector <Node> temporary_leaves; // TEMPORARY convenience to map the leaves of the tree in a vector (gives access to an index); int number_nodes; //includes leaves int [] statistics_number_of_nodes_for_each_feature; Tree(GenerativeModelBasedOnEnsembleOfTrees eot, int v){ myGET = eot; root = new Node(this, 0, 0, myGET.myDS.all_indexes(-1), myGET.myDS.domain_support()); root.p_reach = 1.0; star_node = root; leaves = new HashSet <> (); leaves.add(root); name = v; depth = 0; number_nodes = 1; temporary_leaves = null; statistics_number_of_nodes_for_each_feature = new int[eot.myDS.features.size()]; } public void compute_temporary_leaves(){ temporary_leaves = new Vector<>(); Iterator it = leaves.iterator(); while(it.hasNext()){ temporary_leaves.addElement((Node) it.next()); } } public void discard_temporary_leaves(){ temporary_leaves = null; } public void checkConsistency(){ int i, totn = 0; Node dumn; Iterator it = leaves.iterator(); while(it.hasNext()){ dumn = (Node) it.next(); totn += (dumn.observations_in_node) ? dumn.observation_indexes_in_node.length : 0; } if (totn != myGET.myDS.observations_from_file.size()) Dataset.perror( "Tree.class :: total number of examples reaching leaves != from the dataset size"); } public void add_leaf_to_tree_structure(Node n){ n.is_leaf = true; boolean ok; ok = leaves.add(n); if (!ok) Dataset.perror("Tree.class :: adding a leaf already in leaves"); } public boolean remove_leaf_from_tree_structure(Node n){ if (!leaves.contains(n)) Dataset.perror("Tree.class :: Node " + n + " not in leaves "); boolean ok; ok = leaves.remove(n); if (!ok) return false; return true; } public String toString(){ int i; String v = "(name = #" + myGET.name + "." + name + " | depth = " + depth + " | #nodes = " + number_nodes + ")\n"; Node dumn; v += root.display(new HashSet <Integer> (), myGET, -1.0); v += "Leaves:"; Iterator it = leaves.iterator(); while(it.hasNext()){ v += " "; dumn = (Node) it.next(); v += "#" + dumn.name + dumn.observations_string(-1.0); } v += ".\n"; return v; } // generation related stuff public void init_generation(){ star_node = root; } public boolean generation_done(){ return star_node.is_leaf; } // generation related stuff public MeasuredSupport update_star_node_and_support(MeasuredSupport gs){ if (star_node.is_leaf) return gs; if (!gs.support.is_subset_of(star_node.node_support)) Dataset.perror("Tree.class :: generative support not a subset of the star node's"); if (gs.local_empirical_measure.observations_indexes.length == 0) Dataset.perror("Tree.class :: current generative support has 0 empirical measure"); MeasuredSupport generative_support_left = new MeasuredSupport(gs.myGET, star_node.left_child.node_support.cap(gs.support, false)); MeasuredSupport generative_support_right = new MeasuredSupport(gs.myGET, star_node.right_child.node_support.cap(gs.support, false)); int index_feature_split = star_node.node_feature_split_index; Feature feature_in_star_node = star_node.node_support.feature(index_feature_split); Feature feature_in_measured_support = gs.support.feature(index_feature_split); FeatureTest ft = FeatureTest.copyOf(star_node.node_feature_test, feature_in_star_node); // check if branching trivial, does not seek non zero measure sets because there might be observations on [a,a] for generation String ttb = ft.check_trivial_branching(myGET.myDS, feature_in_measured_support, false); if (ttb.equals(FeatureTest.TRIVIAL_BRANCHING_LEFT)){ generative_support_left.local_empirical_measure = gs.local_empirical_measure; star_node = star_node.left_child; return generative_support_left; }else if (ttb.equals(FeatureTest.TRIVIAL_BRANCHING_RIGHT)){ generative_support_right.local_empirical_measure = gs.local_empirical_measure; star_node = star_node.right_child; return generative_support_right; } // no trivial branching // fast trick: use the star_node split to split gs.support and get the observed measure left / right LocalEmpiricalMeasure [] split_measure_at_support = ft.split_measure_soft(gs.local_empirical_measure, myGET.myDS, feature_in_measured_support); // Note: observations w/ missing values are subject to the (biased) random assignation again (we do not reuse the results of training's random assignations) // the supports obtained may thus be of variable empirical measure depending on missing values at generation time generative_support_left.local_empirical_measure = split_measure_at_support[0]; generative_support_right.local_empirical_measure = split_measure_at_support[1]; boolean pick_left; double p_left = -1.0, p_u_left, p_u_right, p_r_left, p_r_right, tw, gw; if (split_measure_at_support[1] == null) pick_left = true; else if (split_measure_at_support[0] == null) pick_left = false; else{ if (myGET.generative_forest){ tw = (double) split_measure_at_support[0].total_weight; gw = (double) gs.local_empirical_measure.total_weight; p_left = tw / gw; }else if (myGET.ensemble_of_generative_trees){ // Using prop assumption, see draft p_r_left = star_node.left_child.p_reach * generative_support_left.support.volume / star_node.left_child.node_support.volume; p_r_right = star_node.right_child.p_reach * generative_support_right.support.volume / star_node.right_child.node_support.volume; p_left = p_r_left / (p_r_left + p_r_right); }else Dataset.perror("Tree.class :: cannot generate observations"); if (Statistics.RANDOM_P_NOT(p_left) < p_left) pick_left = true; else pick_left = false; } if (pick_left){ star_node = star_node.left_child; return generative_support_left; }else{ star_node = star_node.right_child; return generative_support_right; } } }
google-research/google-research
generative_forests/src/Tree.java
45
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * Project Info: https://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * https://plantuml.com/patreon (only 1$ per month!) * https://plantuml.com/paypal * * This file is part of Smetana. * Smetana is a partial translation of Graphviz/Dot sources from C to Java. * * (C) Copyright 2009-2022, Arnaud Roques * * This translation is distributed under the same Licence as the original C program: * ************************************************************************* * Copyright (c) 2011 AT&T Intellectual Property * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: See CVS logs. Details at http://www.graphviz.org/ ************************************************************************* * * THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC * LICENSE ("AGREEMENT"). [Eclipse Public License - v 1.0] * * ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES * RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. * * You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * 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 h; import smetana.core.CArrayOfStar; import smetana.core.UnsupportedStarStruct; import smetana.core.__struct__; //typedef struct elist { //edge_t **list; //int size; //} elist; final public class ST_elist extends UnsupportedStarStruct { public int size; public CArrayOfStar<ST_Agedge_s> list; @Override public void ___(__struct__ other) { ST_elist other2 = (ST_elist) other; this.size = other2.size; this.list = other2.list; } @Override public ST_elist copy() { final ST_elist result = new ST_elist(); result.size = this.size; result.list = this.list; return result; } }
plantuml/plantuml
src/h/ST_elist.java
46
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * Project Info: https://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * https://plantuml.com/patreon (only 1$ per month!) * https://plantuml.com/paypal * * This file is part of Smetana. * Smetana is a partial translation of Graphviz/Dot sources from C to Java. * * (C) Copyright 2009-2022, Arnaud Roques * * This translation is distributed under the same Licence as the original C program: * ************************************************************************* * Copyright (c) 2011 AT&T Intellectual Property * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: See CVS logs. Details at http://www.graphviz.org/ ************************************************************************* * * THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC * LICENSE ("AGREEMENT"). [Eclipse Public License - v 1.0] * * ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES * RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. * * You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * 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 h; import java.util.List; import smetana.core.CString; final public class ST_Agattr_s extends ST_Agrec_s { public ST_dt_s dict; /* shared dict to interpret attr field */ public List<CString> str; /* the attribute string values */ } // struct Agattr_s { /* dynamic string attributes */ // Agrec_t h; /* common data header */ // Dict_t *dict; /* shared dict to interpret attr field */ // char **str; /* the attribute string values */ // };
plantuml/plantuml
src/h/ST_Agattr_s.java
47
/* * Copyright (C) 2009-2021 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.javac; import java.lang.annotation.Annotation; import java.util.List; import javax.lang.model.element.Element; import javax.tools.Diagnostic; import com.sun.tools.javac.code.Flags; import com.sun.tools.javac.code.Symtab; import com.sun.tools.javac.model.JavacTypes; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCAnnotation; import com.sun.tools.javac.tree.JCTree.JCBlock; import com.sun.tools.javac.tree.JCTree.JCClassDecl; import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; import com.sun.tools.javac.tree.JCTree.JCMethodDecl; import com.sun.tools.javac.tree.JCTree.JCModifiers; import com.sun.tools.javac.tree.JCTree.JCVariableDecl; import com.sun.tools.javac.util.Context; import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition; import com.sun.tools.javac.util.Name; import lombok.core.AST.Kind; import lombok.core.AnnotationValues; import lombok.javac.handlers.JavacHandlerUtil; /** * Javac specific version of the LombokNode class. */ public class JavacNode extends lombok.core.LombokNode<JavacAST, JavacNode, JCTree> { private JavacAST ast; /** * Passes through to the parent constructor. */ public JavacNode(JavacAST ast, JCTree node, List<JavacNode> children, Kind kind) { super(node, children, kind); this.ast = ast; } @Override public JavacAST getAst() { return ast; } public Element getElement() { if (node instanceof JCClassDecl) return ((JCClassDecl) node).sym; if (node instanceof JCMethodDecl) return ((JCMethodDecl) node).sym; if (node instanceof JCVariableDecl) return ((JCVariableDecl) node).sym; return null; } public int getEndPosition(DiagnosticPosition pos) { JCCompilationUnit cu = (JCCompilationUnit) top().get(); return Javac.getEndPosition(pos, cu); } public int getEndPosition() { return getEndPosition(node); } /** * Visits this node and all child nodes depth-first, calling the provided visitor's visit methods. */ public void traverse(JavacASTVisitor visitor) { switch (this.getKind()) { case COMPILATION_UNIT: visitor.visitCompilationUnit(this, (JCCompilationUnit) get()); ast.traverseChildren(visitor, this); visitor.endVisitCompilationUnit(this, (JCCompilationUnit) get()); break; case TYPE: visitor.visitType(this, (JCClassDecl) get()); ast.traverseChildren(visitor, this); visitor.endVisitType(this, (JCClassDecl) get()); break; case FIELD: visitor.visitField(this, (JCVariableDecl) get()); ast.traverseChildren(visitor, this); visitor.endVisitField(this, (JCVariableDecl) get()); break; case METHOD: visitor.visitMethod(this, (JCMethodDecl) get()); ast.traverseChildren(visitor, this); visitor.endVisitMethod(this, (JCMethodDecl) get()); break; case INITIALIZER: visitor.visitInitializer(this, (JCBlock) get()); ast.traverseChildren(visitor, this); visitor.endVisitInitializer(this, (JCBlock) get()); break; case ARGUMENT: JCMethodDecl parentMethod = (JCMethodDecl) up().get(); visitor.visitMethodArgument(this, (JCVariableDecl) get(), parentMethod); ast.traverseChildren(visitor, this); visitor.endVisitMethodArgument(this, (JCVariableDecl) get(), parentMethod); break; case LOCAL: visitor.visitLocal(this, (JCVariableDecl) get()); ast.traverseChildren(visitor, this); visitor.endVisitLocal(this, (JCVariableDecl) get()); break; case STATEMENT: visitor.visitStatement(this, get()); ast.traverseChildren(visitor, this); visitor.endVisitStatement(this, get()); break; case ANNOTATION: switch (up().getKind()) { case TYPE: visitor.visitAnnotationOnType((JCClassDecl) up().get(), this, (JCAnnotation) get()); break; case FIELD: visitor.visitAnnotationOnField((JCVariableDecl) up().get(), this, (JCAnnotation) get()); break; case METHOD: visitor.visitAnnotationOnMethod((JCMethodDecl) up().get(), this, (JCAnnotation) get()); break; case ARGUMENT: JCVariableDecl argument = (JCVariableDecl) up().get(); JCMethodDecl method = (JCMethodDecl) up().up().get(); visitor.visitAnnotationOnMethodArgument(argument, method, this, (JCAnnotation) get()); break; case LOCAL: visitor.visitAnnotationOnLocal((JCVariableDecl) up().get(), this, (JCAnnotation) get()); break; case TYPE_USE: visitor.visitAnnotationOnTypeUse(up().get(), this, (JCAnnotation) get()); break; default: throw new AssertionError("Annotion not expected as child of a " + up().getKind()); } break; case TYPE_USE: visitor.visitTypeUse(this, get()); ast.traverseChildren(visitor, this); visitor.endVisitTypeUse(this, get()); break; default: throw new AssertionError("Unexpected kind during node traversal: " + getKind()); } } /** {@inheritDoc} */ @Override public String getName() { final Name n; if (node instanceof JCClassDecl) n = ((JCClassDecl) node).name; else if (node instanceof JCMethodDecl) n = ((JCMethodDecl) node).name; else if (node instanceof JCVariableDecl) n = ((JCVariableDecl) node).name; else n = null; return n == null ? null : n.toString(); } /** {@inheritDoc} */ @Override protected boolean calculateIsStructurallySignificant(JCTree parent) { if (node instanceof JCClassDecl) return true; if (node instanceof JCMethodDecl) return true; if (node instanceof JCVariableDecl) return true; if (node instanceof JCCompilationUnit) return true; //Static and instance initializers if (node instanceof JCBlock) return parent instanceof JCClassDecl; return false; } /** * Convenient shortcut to the owning JavacAST object's getTreeMaker method. * * @see JavacAST#getTreeMaker() */ public JavacTreeMaker getTreeMaker() { return ast.getTreeMaker(); } /** * Convenient shortcut to the owning JavacAST object's getSymbolTable method. * * @see JavacAST#getSymbolTable() */ public Symtab getSymbolTable() { return ast.getSymbolTable(); } /** * Convenient shortcut to the owning JavacAST object's getTypesUtil method. * * @see JavacAST#getTypesUtil() */ public JavacTypes getTypesUtil() { return ast.getTypesUtil(); } /** * Convenient shortcut to the owning JavacAST object's getContext method. * * @see JavacAST#getContext() */ public Context getContext() { return ast.getContext(); } public boolean shouldDeleteLombokAnnotations() { return LombokOptions.shouldDeleteLombokAnnotations(ast.getContext()); } /** * Convenient shortcut to the owning JavacAST object's toName method. * * @see JavacAST#toName(String) */ public Name toName(String name) { return ast.toName(name); } public void removeDeferredErrors() { ast.removeDeferredErrors(this); } /** * Generates an compiler error focused on the AST node represented by this node object. */ @Override public void addError(String message) { ast.printMessage(Diagnostic.Kind.ERROR, message, this, null, true); } /** * Generates an compiler error focused on the AST node represented by this node object. */ public void addError(String message, DiagnosticPosition pos) { ast.printMessage(Diagnostic.Kind.ERROR, message, null, pos, true); } /** * Generates a compiler warning focused on the AST node represented by this node object. */ @Override public void addWarning(String message) { ast.printMessage(Diagnostic.Kind.WARNING, message, this, null, false); } /** * Generates a compiler warning focused on the AST node represented by this node object. */ public void addWarning(String message, DiagnosticPosition pos) { ast.printMessage(Diagnostic.Kind.WARNING, message, null, pos, false); } @Override public boolean hasAnnotation(Class<? extends Annotation> type) { return JavacHandlerUtil.hasAnnotationAndDeleteIfNeccessary(type, this); } @Override public <Z extends Annotation> AnnotationValues<Z> findAnnotation(Class<Z> type) { JavacNode annotation = JavacHandlerUtil.findAnnotation(type, this, true); if (annotation == null) return null; return JavacHandlerUtil.createAnnotation(type, annotation); } private JCModifiers getModifiers() { if (node instanceof JCClassDecl) return ((JCClassDecl) node).getModifiers(); if (node instanceof JCMethodDecl) return ((JCMethodDecl) node).getModifiers(); if (node instanceof JCVariableDecl) return ((JCVariableDecl) node).getModifiers(); return null; } @Override public boolean isStatic() { if (node instanceof JCClassDecl) { JCClassDecl t = (JCClassDecl) node; long f = t.mods.flags; if (((Flags.INTERFACE | Flags.ENUM | Javac.RECORD) & f) != 0) return true; JavacNode directUp = directUp(); if (directUp == null || directUp.getKind() == Kind.COMPILATION_UNIT) return true; if (!(directUp.get() instanceof JCClassDecl)) return false; JCClassDecl p = (JCClassDecl) directUp.get(); f = p.mods.flags; if (((Flags.INTERFACE | Flags.ENUM) & f) != 0) return true; } if (node instanceof JCVariableDecl) { JavacNode directUp = directUp(); if (directUp != null && directUp.get() instanceof JCClassDecl) { JCClassDecl p = (JCClassDecl) directUp.get(); long f = p.mods.flags; if ((Flags.INTERFACE & f) != 0) return true; } } JCModifiers mods = getModifiers(); if (mods == null) return false; return (mods.flags & Flags.STATIC) != 0; } @Override public boolean isFinal() { if (node instanceof JCVariableDecl) { JavacNode directUp = directUp(); if (directUp != null && directUp.get() instanceof JCClassDecl) { JCClassDecl p = (JCClassDecl) directUp.get(); long f = p.mods.flags; if (((Flags.INTERFACE | Flags.ENUM) & f) != 0) return true; } } JCModifiers mods = getModifiers(); return mods != null && (Flags.FINAL & mods.flags) != 0; } @Override public boolean isEnumMember() { if (getKind() != Kind.FIELD) return false; JCModifiers mods = getModifiers(); return mods != null && (Flags.ENUM & mods.flags) != 0; } @Override public boolean isEnumType() { if (getKind() != Kind.TYPE) return false; JCModifiers mods = getModifiers(); return mods != null && (Flags.ENUM & mods.flags) != 0; } @Override public boolean isPrimitive() { if (node instanceof JCVariableDecl && !isEnumMember()) { return Javac.isPrimitive(((JCVariableDecl) node).vartype); } if (node instanceof JCMethodDecl) { return Javac.isPrimitive(((JCMethodDecl) node).restype); } return false; } /** * {@inheritDoc} */ @Override public String fieldOrMethodBaseType() { if (node instanceof JCVariableDecl && !isEnumMember()) { return (((JCVariableDecl) node).vartype).toString(); } if (node instanceof JCMethodDecl) { return (((JCMethodDecl) node).restype).toString(); } return null; } @Override public boolean isTransient() { if (getKind() != Kind.FIELD) return false; JCModifiers mods = getModifiers(); return mods != null && (Flags.TRANSIENT & mods.flags) != 0; } @Override public int countMethodParameters() { if (getKind() != Kind.METHOD) return 0; com.sun.tools.javac.util.List<JCVariableDecl> params = ((JCMethodDecl) node).params; if (params == null) return 0; return params.size(); } @Override public int getStartPos() { return node.getPreferredPosition(); } }
projectlombok/lombok
src/core/lombok/javac/JavacNode.java
48
package com.genymobile.scrcpy; import com.genymobile.scrcpy.wrappers.DisplayManager; import com.genymobile.scrcpy.wrappers.ServiceManager; import android.graphics.Rect; import android.hardware.camera2.CameraAccessException; import android.hardware.camera2.CameraCharacteristics; import android.hardware.camera2.CameraManager; import android.hardware.camera2.params.StreamConfigurationMap; import android.media.MediaCodec; import android.util.Range; import java.util.List; import java.util.SortedSet; import java.util.TreeSet; public final class LogUtils { private LogUtils() { // not instantiable } public static String buildVideoEncoderListMessage() { StringBuilder builder = new StringBuilder("List of video encoders:"); List<CodecUtils.DeviceEncoder> videoEncoders = CodecUtils.listVideoEncoders(); if (videoEncoders.isEmpty()) { builder.append("\n (none)"); } else { for (CodecUtils.DeviceEncoder encoder : videoEncoders) { builder.append("\n --video-codec=").append(encoder.getCodec().getName()); builder.append(" --video-encoder='").append(encoder.getInfo().getName()).append("'"); } } return builder.toString(); } public static String buildAudioEncoderListMessage() { StringBuilder builder = new StringBuilder("List of audio encoders:"); List<CodecUtils.DeviceEncoder> audioEncoders = CodecUtils.listAudioEncoders(); if (audioEncoders.isEmpty()) { builder.append("\n (none)"); } else { for (CodecUtils.DeviceEncoder encoder : audioEncoders) { builder.append("\n --audio-codec=").append(encoder.getCodec().getName()); builder.append(" --audio-encoder='").append(encoder.getInfo().getName()).append("'"); } } return builder.toString(); } public static String buildDisplayListMessage() { StringBuilder builder = new StringBuilder("List of displays:"); DisplayManager displayManager = ServiceManager.getDisplayManager(); int[] displayIds = displayManager.getDisplayIds(); if (displayIds == null || displayIds.length == 0) { builder.append("\n (none)"); } else { for (int id : displayIds) { builder.append("\n --display-id=").append(id).append(" ("); DisplayInfo displayInfo = displayManager.getDisplayInfo(id); if (displayInfo != null) { Size size = displayInfo.getSize(); builder.append(size.getWidth()).append("x").append(size.getHeight()); } else { builder.append("size unknown"); } builder.append(")"); } } return builder.toString(); } private static String getCameraFacingName(int facing) { switch (facing) { case CameraCharacteristics.LENS_FACING_FRONT: return "front"; case CameraCharacteristics.LENS_FACING_BACK: return "back"; case CameraCharacteristics.LENS_FACING_EXTERNAL: return "external"; default: return "unknown"; } } public static String buildCameraListMessage(boolean includeSizes) { StringBuilder builder = new StringBuilder("List of cameras:"); CameraManager cameraManager = ServiceManager.getCameraManager(); try { String[] cameraIds = cameraManager.getCameraIdList(); if (cameraIds == null || cameraIds.length == 0) { builder.append("\n (none)"); } else { for (String id : cameraIds) { builder.append("\n --camera-id=").append(id); CameraCharacteristics characteristics = cameraManager.getCameraCharacteristics(id); int facing = characteristics.get(CameraCharacteristics.LENS_FACING); builder.append(" (").append(getCameraFacingName(facing)).append(", "); Rect activeSize = characteristics.get(CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE); builder.append(activeSize.width()).append("x").append(activeSize.height()); try { // Capture frame rates for low-FPS mode are the same for every resolution Range<Integer>[] lowFpsRanges = characteristics.get(CameraCharacteristics.CONTROL_AE_AVAILABLE_TARGET_FPS_RANGES); SortedSet<Integer> uniqueLowFps = getUniqueSet(lowFpsRanges); builder.append(", fps=").append(uniqueLowFps); } catch (Exception e) { // Some devices may provide invalid ranges, causing an IllegalArgumentException "lower must be less than or equal to upper" Ln.w("Could not get available frame rates for camera " + id, e); } builder.append(')'); if (includeSizes) { StreamConfigurationMap configs = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP); android.util.Size[] sizes = configs.getOutputSizes(MediaCodec.class); for (android.util.Size size : sizes) { builder.append("\n - ").append(size.getWidth()).append('x').append(size.getHeight()); } android.util.Size[] highSpeedSizes = configs.getHighSpeedVideoSizes(); if (highSpeedSizes.length > 0) { builder.append("\n High speed capture (--camera-high-speed):"); for (android.util.Size size : highSpeedSizes) { Range<Integer>[] highFpsRanges = configs.getHighSpeedVideoFpsRanges(); SortedSet<Integer> uniqueHighFps = getUniqueSet(highFpsRanges); builder.append("\n - ").append(size.getWidth()).append("x").append(size.getHeight()); builder.append(" (fps=").append(uniqueHighFps).append(')'); } } } } } } catch (CameraAccessException e) { builder.append("\n (access denied)"); } return builder.toString(); } private static SortedSet<Integer> getUniqueSet(Range<Integer>[] ranges) { SortedSet<Integer> set = new TreeSet<>(); for (Range<Integer> range : ranges) { set.add(range.getUpper()); } return set; } }
Genymobile/scrcpy
server/src/main/java/com/genymobile/scrcpy/LogUtils.java
49
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * Project Info: https://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * https://plantuml.com/patreon (only 1$ per month!) * https://plantuml.com/paypal * * This file is part of Smetana. * Smetana is a partial translation of Graphviz/Dot sources from C to Java. * * (C) Copyright 2009-2022, Arnaud Roques * * This translation is distributed under the same Licence as the original C program: * ************************************************************************* * Copyright (c) 2011 AT&T Intellectual Property * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: See CVS logs. Details at http://www.graphviz.org/ ************************************************************************* * * THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC * LICENSE ("AGREEMENT"). [Eclipse Public License - v 1.0] * * ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES * RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. * * You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * 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 h; import smetana.core.UnsupportedStarStruct; import smetana.core.__ptr__; final public class ST_Agdstate_s extends UnsupportedStarStruct { public __ptr__ mem; public __ptr__ id; } // struct Agdstate_s { // void *mem; // void *id; // /* IO must be initialized and finalized outside Cgraph, // * and channels (FILES) are passed as void* arguments. */ // };
plantuml/plantuml
src/h/ST_Agdstate_s.java
50
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * Project Info: https://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * https://plantuml.com/patreon (only 1$ per month!) * https://plantuml.com/paypal * * This file is part of Smetana. * Smetana is a partial translation of Graphviz/Dot sources from C to Java. * * (C) Copyright 2009-2022, Arnaud Roques * * This translation is distributed under the same Licence as the original C program: * ************************************************************************* * Copyright (c) 2011 AT&T Intellectual Property * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: See CVS logs. Details at http://www.graphviz.org/ ************************************************************************* * * THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC * LICENSE ("AGREEMENT"). [Eclipse Public License - v 1.0] * * ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES * RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. * * You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * 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 h; import smetana.core.CString; import smetana.core.UnsupportedStarStruct; import smetana.core.__ptr__; public class ST_Agrec_s extends UnsupportedStarStruct { // ::remove folder when __HAXE__ public CString name; public ST_Agrec_s next; /* following this would be any programmer-defined data */ @Override public boolean isSameThan(__ptr__ other) { ST_Agrec_s other2 = (ST_Agrec_s) other; return this == other2; } } // struct Agrec_s { // char *name; // Agrec_t *next; // /* following this would be any programmer-defined data */ // };
plantuml/plantuml
src/h/ST_Agrec_s.java
51
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * Project Info: https://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * https://plantuml.com/patreon (only 1$ per month!) * https://plantuml.com/paypal * * This file is part of Smetana. * Smetana is a partial translation of Graphviz/Dot sources from C to Java. * * (C) Copyright 2009-2022, Arnaud Roques * * This translation is distributed under the same Licence as the original C program: * ************************************************************************* * Copyright (c) 2011 AT&T Intellectual Property * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: See CVS logs. Details at http://www.graphviz.org/ ************************************************************************* * * THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC * LICENSE ("AGREEMENT"). [Eclipse Public License - v 1.0] * * ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES * RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. * * You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * 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 h; import smetana.core.FieldOffset; import smetana.core.UnsupportedStarStruct; final public class ST_HDict_t extends UnsupportedStarStruct { public final ST_dtlink_s link = new ST_dtlink_s(this); public int key; public final ST_Branch_t d = new ST_Branch_t(); /* Should be ST_Leaf_t */ @Override public Object getTheField(FieldOffset offset) { if (offset == null || offset.getSign() == 0) return this; if (offset == FieldOffset.key) return key; throw new UnsupportedOperationException(); } } // typedef struct obyh { // Dtlink_t link; // int key; // Leaf_t d; // } HDict_t;
plantuml/plantuml
src/h/ST_HDict_t.java
52
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * Project Info: https://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * https://plantuml.com/patreon (only 1$ per month!) * https://plantuml.com/paypal * * This file is part of Smetana. * Smetana is a partial translation of Graphviz/Dot sources from C to Java. * * (C) Copyright 2009-2022, Arnaud Roques * * This translation is distributed under the same Licence as the original C program: * ************************************************************************* * Copyright (c) 2011 AT&T Intellectual Property * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: See CVS logs. Details at http://www.graphviz.org/ ************************************************************************* * * THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC * LICENSE ("AGREEMENT"). [Eclipse Public License - v 1.0] * * ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES * RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. * * You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * 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 h; import smetana.core.CArray; import smetana.core.UnsupportedStarStruct; import smetana.core.__struct__; final public class ST_bezier extends UnsupportedStarStruct { public CArray<ST_pointf> list; public int size; public int sflag, eflag; public final ST_pointf sp = new ST_pointf(), ep = new ST_pointf(); @Override public void ___(__struct__ other) { ST_bezier this2 = (ST_bezier) other; this.list = this2.list; this.size = this2.size; this.sflag = this2.sflag; this.eflag = this2.eflag; this.sp.___((__struct__) this2.sp); this.ep.___((__struct__) this2.ep); } } // typedef struct bezier { // pointf *list; // int size; // int sflag, eflag; // pointf sp, ep; // } bezier;
plantuml/plantuml
src/h/ST_bezier.java
53
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * Project Info: https://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * https://plantuml.com/patreon (only 1$ per month!) * https://plantuml.com/paypal * * This file is part of Smetana. * Smetana is a partial translation of Graphviz/Dot sources from C to Java. * * (C) Copyright 2009-2022, Arnaud Roques * * This translation is distributed under the same Licence as the original C program: * ************************************************************************* * Copyright (c) 2011 AT&T Intellectual Property * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: See CVS logs. Details at http://www.graphviz.org/ ************************************************************************* * * THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC * LICENSE ("AGREEMENT"). [Eclipse Public License - v 1.0] * * ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES * RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. * * You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * 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 h; import smetana.core.CArray; import smetana.core.UnsupportedStarStruct; import smetana.core.__struct__; final public class ST_cinfo_t extends UnsupportedStarStruct { public final ST_boxf bb = new ST_boxf(); public CArray<ST_object_t> objp; @Override public void ___(__struct__ value) { final ST_cinfo_t other = (ST_cinfo_t) value; this.bb.___(other.bb); this.objp = other.objp; } @Override public ST_cinfo_t copy() { final ST_cinfo_t result = new ST_cinfo_t(); result.bb.___((__struct__) this.bb); result.objp = this.objp; return result; } } // typedef struct { // boxf bb; // object_t* objp; // } cinfo_t;
plantuml/plantuml
src/h/ST_cinfo_t.java
54
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * Project Info: https://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * https://plantuml.com/patreon (only 1$ per month!) * https://plantuml.com/paypal * * This file is part of Smetana. * Smetana is a partial translation of Graphviz/Dot sources from C to Java. * * (C) Copyright 2009-2022, Arnaud Roques * * This translation is distributed under the same Licence as the original C program: * ************************************************************************* * Copyright (c) 2011 AT&T Intellectual Property * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: See CVS logs. Details at http://www.graphviz.org/ ************************************************************************* * * THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC * LICENSE ("AGREEMENT"). [Eclipse Public License - v 1.0] * * ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES * RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. * * You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * 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 h; import smetana.core.UnsupportedStarStruct; import smetana.core.__struct__; final public class ST_boxf extends UnsupportedStarStruct { public final ST_pointf LL = new ST_pointf(); public final ST_pointf UR = new ST_pointf(); @Override public String toString() { return "LL=" + LL + " UR=" + UR; } public static ST_boxf[] malloc(int nb) { final ST_boxf result[] = new ST_boxf[nb]; for (int i = 0; i < nb; i++) { result[i] = new ST_boxf(); } return result; } @Override public ST_boxf copy() { final ST_boxf result = new ST_boxf(); result.LL.___((__struct__) this.LL); result.UR.___((__struct__) this.UR); return result; } @Override public void ___(__struct__ value) { final ST_boxf other = (ST_boxf) value; this.LL.___(other.LL); this.UR.___(other.UR); } } // typedef struct { pointf LL, UR; } boxf;
plantuml/plantuml
src/h/ST_boxf.java
55
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file or at // https://developers.google.com/open-source/licenses/bsd package com.google.protobuf; import java.io.InputStream; import java.nio.ByteBuffer; /** * Abstract interface for parsing Protocol Messages. * * <p>The implementation should be stateless and thread-safe. * * <p>All methods may throw {@link InvalidProtocolBufferException}. In the event of invalid data, * like an encoding error, the cause of the thrown exception will be {@code null}. However, if an * I/O problem occurs, an exception is thrown with an {@link java.io.IOException} cause. * * @author liujisi@google.com (Pherl Liu) */ public interface Parser<MessageType> { // NB(jh): Other parts of the protobuf API that parse messages distinguish between an I/O problem // (like failure reading bytes from a socket) and invalid data (encoding error) via the type of // thrown exception. But it would be source-incompatible to make the methods in this interface do // so since they were originally spec'ed to only throw InvalidProtocolBufferException. So callers // must inspect the cause of the exception to distinguish these two cases. /** * Parses a message of {@code MessageType} from the input. * * <p>Note: The caller should call {@link CodedInputStream#checkLastTagWas(int)} after calling * this to verify that the last tag seen was the appropriate end-group tag, or zero for EOF. */ public MessageType parseFrom(CodedInputStream input) throws InvalidProtocolBufferException; /** * Like {@link #parseFrom(CodedInputStream)}, but also parses extensions. The extensions that you * want to be able to parse must be registered in {@code extensionRegistry}. Extensions not in the * registry will be treated as unknown fields. */ public MessageType parseFrom(CodedInputStream input, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException; /** * Like {@link #parseFrom(CodedInputStream)}, but does not throw an exception if the message is * missing required fields. Instead, a partial message is returned. */ public MessageType parsePartialFrom(CodedInputStream input) throws InvalidProtocolBufferException; /** * Like {@link #parseFrom(CodedInputStream input, ExtensionRegistryLite)}, but does not throw an * exception if the message is missing required fields. Instead, a partial message is returned. */ public MessageType parsePartialFrom( CodedInputStream input, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException; // --------------------------------------------------------------- // Convenience methods. /** * Parses {@code data} as a message of {@code MessageType}. This is just a small wrapper around * {@link #parseFrom(CodedInputStream)}. */ public MessageType parseFrom(ByteBuffer data) throws InvalidProtocolBufferException; /** * Parses {@code data} as a message of {@code MessageType}. This is just a small wrapper around * {@link #parseFrom(CodedInputStream, ExtensionRegistryLite)}. */ public MessageType parseFrom(ByteBuffer data, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException; /** * Parses {@code data} as a message of {@code MessageType}. This is just a small wrapper around * {@link #parseFrom(CodedInputStream)}. */ public MessageType parseFrom(ByteString data) throws InvalidProtocolBufferException; /** * Parses {@code data} as a message of {@code MessageType}. This is just a small wrapper around * {@link #parseFrom(CodedInputStream, ExtensionRegistryLite)}. */ public MessageType parseFrom(ByteString data, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException; /** * Like {@link #parseFrom(ByteString)}, but does not throw an exception if the message is missing * required fields. Instead, a partial message is returned. */ public MessageType parsePartialFrom(ByteString data) throws InvalidProtocolBufferException; /** * Like {@link #parseFrom(ByteString, ExtensionRegistryLite)}, but does not throw an exception if * the message is missing required fields. Instead, a partial message is returned. */ public MessageType parsePartialFrom(ByteString data, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException; /** * Parses {@code data} as a message of {@code MessageType}. This is just a small wrapper around * {@link #parseFrom(CodedInputStream)}. */ public MessageType parseFrom(byte[] data, int off, int len) throws InvalidProtocolBufferException; /** * Parses {@code data} as a message of {@code MessageType}. This is just a small wrapper around * {@link #parseFrom(CodedInputStream, ExtensionRegistryLite)}. */ public MessageType parseFrom( byte[] data, int off, int len, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException; /** * Parses {@code data} as a message of {@code MessageType}. This is just a small wrapper around * {@link #parseFrom(CodedInputStream)}. */ public MessageType parseFrom(byte[] data) throws InvalidProtocolBufferException; /** * Parses {@code data} as a message of {@code MessageType}. This is just a small wrapper around * {@link #parseFrom(CodedInputStream, ExtensionRegistryLite)}. */ public MessageType parseFrom(byte[] data, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException; /** * Like {@link #parseFrom(byte[], int, int)}, but does not throw an exception if the message is * missing required fields. Instead, a partial message is returned. */ public MessageType parsePartialFrom(byte[] data, int off, int len) throws InvalidProtocolBufferException; /** * Like {@link #parseFrom(ByteString, ExtensionRegistryLite)}, but does not throw an exception if * the message is missing required fields. Instead, a partial message is returned. */ public MessageType parsePartialFrom( byte[] data, int off, int len, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException; /** * Like {@link #parseFrom(byte[])}, but does not throw an exception if the message is missing * required fields. Instead, a partial message is returned. */ public MessageType parsePartialFrom(byte[] data) throws InvalidProtocolBufferException; /** * Like {@link #parseFrom(byte[], ExtensionRegistryLite)}, but does not throw an exception if the * message is missing required fields. Instead, a partial message is returned. */ public MessageType parsePartialFrom(byte[] data, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException; /** * Parse a message of {@code MessageType} from {@code input}. This is just a small wrapper around * {@link #parseFrom(CodedInputStream)}. Note that this method always reads the <i>entire</i> * input (unless it throws an exception). If you want it to stop earlier, you will need to wrap * your input in some wrapper stream that limits reading. Or, use {@link * MessageLite#writeDelimitedTo(java.io.OutputStream)} to write your message and {@link * #parseDelimitedFrom(InputStream)} to read it. * * <p>Despite usually reading the entire input, this does not close the stream. */ public MessageType parseFrom(InputStream input) throws InvalidProtocolBufferException; /** * Parses a message of {@code MessageType} from {@code input}. This is just a small wrapper around * {@link #parseFrom(CodedInputStream, ExtensionRegistryLite)}. */ public MessageType parseFrom(InputStream input, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException; /** * Like {@link #parseFrom(InputStream)}, but does not throw an exception if the message is missing * required fields. Instead, a partial message is returned. */ public MessageType parsePartialFrom(InputStream input) throws InvalidProtocolBufferException; /** * Like {@link #parseFrom(InputStream, ExtensionRegistryLite)}, but does not throw an exception if * the message is missing required fields. Instead, a partial message is returned. */ public MessageType parsePartialFrom(InputStream input, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException; /** * Like {@link #parseFrom(InputStream)}, but does not read until EOF. Instead, the size of message * (encoded as a varint) is read first, then the message data. Use {@link * MessageLite#writeDelimitedTo(java.io.OutputStream)} to write messages in this format. * * @return Parsed message if successful, or null if the stream is at EOF when the method starts. * Any other error (including reaching EOF during parsing) will cause an exception to be * thrown. */ public MessageType parseDelimitedFrom(InputStream input) throws InvalidProtocolBufferException; /** Like {@link #parseDelimitedFrom(InputStream)} but supporting extensions. */ public MessageType parseDelimitedFrom(InputStream input, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException; /** * Like {@link #parseDelimitedFrom(InputStream)}, but does not throw an exception if the message * is missing required fields. Instead, a partial message is returned. */ public MessageType parsePartialDelimitedFrom(InputStream input) throws InvalidProtocolBufferException; /** * Like {@link #parseDelimitedFrom(InputStream, ExtensionRegistryLite)}, but does not throw an * exception if the message is missing required fields. Instead, a partial message is returned. */ public MessageType parsePartialDelimitedFrom( InputStream input, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException; }
protocolbuffers/protobuf
java/core/src/main/java/com/google/protobuf/Parser.java
56
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * Project Info: https://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * https://plantuml.com/patreon (only 1$ per month!) * https://plantuml.com/paypal * * This file is part of Smetana. * Smetana is a partial translation of Graphviz/Dot sources from C to Java. * * (C) Copyright 2009-2022, Arnaud Roques * * This translation is distributed under the same Licence as the original C program: * ************************************************************************* * Copyright (c) 2011 AT&T Intellectual Property * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: See CVS logs. Details at http://www.graphviz.org/ ************************************************************************* * * THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC * LICENSE ("AGREEMENT"). [Eclipse Public License - v 1.0] * * ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES * RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. * * You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * 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 h; import smetana.core.CString; import smetana.core.FieldOffset; final public class ST_refstr_t extends ST_dtlink_s { public int refcnt; public CString s; @Override public Object getTheField(FieldOffset offset) { if (offset == null || offset.getSign() == 0) return this; if (offset == FieldOffset.s) return s; throw new UnsupportedOperationException(); } public void setString(CString newData) { this.s = newData; this.s.setParent(this); } } // typedef struct refstr_t { // Dtlink_t link; // unsigned long refcnt; // char *s; // char store[1]; /* this is actually a dynamic array */ // } refstr_t;
plantuml/plantuml
src/h/ST_refstr_t.java
57
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * Project Info: https://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * https://plantuml.com/patreon (only 1$ per month!) * https://plantuml.com/paypal * * This file is part of Smetana. * Smetana is a partial translation of Graphviz/Dot sources from C to Java. * * (C) Copyright 2009-2022, Arnaud Roques * * This translation is distributed under the same Licence as the original C program: * ************************************************************************* * Copyright (c) 2011 AT&T Intellectual Property * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: See CVS logs. Details at http://www.graphviz.org/ ************************************************************************* * * THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC * LICENSE ("AGREEMENT"). [Eclipse Public License - v 1.0] * * ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES * RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. * * You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * 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 h; import smetana.core.CArray; import smetana.core.UnsupportedStarStruct; final public class ST_XLabels_t extends UnsupportedStarStruct { public CArray<ST_object_t> objs; public int n_objs; public CArray<ST_xlabel_t> lbls; public int n_lbls; public ST_label_params_t params; public ST_dt_s hdx; public ST_RTree spdx; } // typedef struct XLabels_s { // object_t *objs; // int n_objs; // xlabel_t *lbls; // int n_lbls; // label_params_t *params; // // Dt_t *hdx; // splay tree keyed with hilbert spatial codes // RTree_t *spdx; // rtree // // } XLabels_t;
plantuml/plantuml
src/h/ST_XLabels_t.java
58
package mindustry.ai.types; import arc.struct.*; import arc.util.*; import mindustry.*; import mindustry.entities.units.*; import mindustry.gen.*; import mindustry.type.*; import mindustry.world.blocks.units.UnitCargoUnloadPoint.*; import mindustry.world.meta.*; import static mindustry.Vars.*; public class CargoAI extends AIController{ static Seq<Item> orderedItems = new Seq<>(); static Seq<UnitCargoUnloadPointBuild> targets = new Seq<>(); public static float emptyWaitTime = 60f * 2f, dropSpacing = 60f * 1.5f; public static float transferRange = 20f, moveRange = 6f, moveSmoothing = 20f; public @Nullable UnitCargoUnloadPointBuild unloadTarget; public @Nullable Item itemTarget; public float noDestTimer = 0f; public int targetIndex = 0; @Override public void updateMovement(){ if(!(unit instanceof BuildingTetherc tether) || tether.building() == null) return; var build = tether.building(); if(build.items == null) return; //empty, approach the loader, even if there's nothing to pick up (units hanging around doing nothing looks bad) if(!unit.hasItem()){ moveTo(build, moveRange, moveSmoothing); //check if ready to pick up if(build.items.any() && unit.within(build, transferRange)){ if(retarget()){ findAnyTarget(build); //target has been found, grab items and go if(unloadTarget != null){ Call.takeItems(build, itemTarget, Math.min(unit.type.itemCapacity, build.items.get(itemTarget)), unit); } } } }else{ //the unit has an item, deposit it somewhere. //there may be no current target, try to find one if(unloadTarget == null){ if(retarget()){ findDropTarget(unit.item(), 0, null); //if there is not even a single place to unload, dump items. if(unloadTarget == null){ unit.clearItem(); } } }else{ //what if some prankster reconfigures or picks up the target while the unit is moving? we can't have that! if(unloadTarget.item != itemTarget || unloadTarget.isPayload()){ unloadTarget = null; return; } moveTo(unloadTarget, moveRange, moveSmoothing); //deposit in bursts, unloading can take a while if(unit.within(unloadTarget, transferRange) && timer.get(timerTarget2, dropSpacing)){ int max = unloadTarget.acceptStack(unit.item(), unit.stack.amount, unit); //deposit items when it's possible if(max > 0){ noDestTimer = 0f; Call.transferItemTo(unit, unit.item(), max, unit.x, unit.y, unloadTarget); //try the next target later if(!unit.hasItem()){ targetIndex ++; } }else if((noDestTimer += dropSpacing) >= emptyWaitTime){ //oh no, it's out of space - wait for a while, and if nothing changes, try the next destination //next targeting attempt will try the next destination point targetIndex = findDropTarget(unit.item(), targetIndex, unloadTarget) + 1; //nothing found at all, clear item if(unloadTarget == null){ unit.clearItem(); } } } } } } /** find target for the unit's current item */ public int findDropTarget(Item item, int offset, UnitCargoUnloadPointBuild ignore){ unloadTarget = null; itemTarget = item; //autocast for convenience... I know all of these must be cargo unload points anyway targets.selectFrom((Seq<UnitCargoUnloadPointBuild>)(Seq)Vars.indexer.getFlagged(unit.team, BlockFlag.unitCargoUnloadPoint), u -> u.item == item); if(targets.isEmpty()) return 0; UnitCargoUnloadPointBuild lastStale = null; offset %= targets.size; int i = 0; for(var target : targets){ if(i >= offset && target != ignore){ if(target.stale){ lastStale = target; }else{ unloadTarget = target; targets.clear(); return i; } } i ++; } //it's still possible that the ignored target may become available at some point, try that, so it doesn't waste items if(ignore != null){ unloadTarget = ignore; }else if(lastStale != null){ //a stale target is better than nothing unloadTarget = lastStale; } targets.clear(); return -1; } public void findAnyTarget(Building build){ unloadTarget = null; itemTarget = null; //autocast for convenience... I know all of these must be cargo unload points anyway var baseTargets = (Seq<UnitCargoUnloadPointBuild>)(Seq)Vars.indexer.getFlagged(unit.team, BlockFlag.unitCargoUnloadPoint); if(baseTargets.isEmpty()) return; orderedItems.size = 0; for(Item item : content.items()){ if(build.items.get(item) > 0){ orderedItems.add(item); } } //sort by most items in descending order, and try each one. orderedItems.sort(i -> -build.items.get(i)); UnitCargoUnloadPointBuild lastStale = null; outer: for(Item item : orderedItems){ targets.selectFrom(baseTargets, u -> u.item == item); if(targets.size > 0) itemTarget = item; for(int i = 0; i < targets.size; i ++){ var target = targets.get((i + targetIndex) % targets.size); lastStale = target; if(!target.stale){ unloadTarget = target; break outer; } } } //if the only thing that was found was a "stale" target, at least try that... if(unloadTarget == null && lastStale != null){ unloadTarget = lastStale; } targets.clear(); } //unused, might change later void sortTargets(Seq<UnitCargoUnloadPointBuild> targets){ //find sort by "most desirable" first targets.sort(Structs.comps(Structs.comparingInt(b -> b.items.total()), Structs.comparingFloat(b -> b.dst2(unit)))); } }
Anuken/Mindustry
core/src/mindustry/ai/types/CargoAI.java
59
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file or at // https://developers.google.com/open-source/licenses/bsd package com.google.protobuf; import static com.google.protobuf.Internal.checkNotNull; import com.google.protobuf.Internal.IntList; import java.util.Arrays; import java.util.Collection; import java.util.RandomAccess; /** * An implementation of {@link IntList} on top of a primitive array. * * @author dweis@google.com (Daniel Weis) */ final class IntArrayList extends AbstractProtobufList<Integer> implements IntList, RandomAccess, PrimitiveNonBoxingCollection { private static final IntArrayList EMPTY_LIST = new IntArrayList(new int[0], 0, false); public static IntArrayList emptyList() { return EMPTY_LIST; } /** The backing store for the list. */ private int[] array; /** * The size of the list distinct from the length of the array. That is, it is the number of * elements set in the list. */ private int size; /** Constructs a new mutable {@code IntArrayList} with default capacity. */ IntArrayList() { this(new int[DEFAULT_CAPACITY], 0, true); } /** * Constructs a new mutable {@code IntArrayList} containing the same elements as {@code other}. */ private IntArrayList(int[] other, int size, boolean isMutable) { super(isMutable); this.array = other; this.size = size; } @Override protected void removeRange(int fromIndex, int toIndex) { ensureIsMutable(); if (toIndex < fromIndex) { throw new IndexOutOfBoundsException("toIndex < fromIndex"); } System.arraycopy(array, toIndex, array, fromIndex, size - toIndex); size -= (toIndex - fromIndex); modCount++; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof IntArrayList)) { return super.equals(o); } IntArrayList other = (IntArrayList) o; if (size != other.size) { return false; } final int[] arr = other.array; for (int i = 0; i < size; i++) { if (array[i] != arr[i]) { return false; } } return true; } @Override public int hashCode() { int result = 1; for (int i = 0; i < size; i++) { result = (31 * result) + array[i]; } return result; } @Override public IntList mutableCopyWithCapacity(int capacity) { if (capacity < size) { throw new IllegalArgumentException(); } return new IntArrayList(Arrays.copyOf(array, capacity), size, true); } @Override public Integer get(int index) { return getInt(index); } @Override public int getInt(int index) { ensureIndexInRange(index); return array[index]; } @Override public int indexOf(Object element) { if (!(element instanceof Integer)) { return -1; } int unboxedElement = (Integer) element; int numElems = size(); for (int i = 0; i < numElems; i++) { if (array[i] == unboxedElement) { return i; } } return -1; } @Override public boolean contains(Object element) { return indexOf(element) != -1; } @Override public int size() { return size; } @Override public Integer set(int index, Integer element) { return setInt(index, element); } @Override public int setInt(int index, int element) { ensureIsMutable(); ensureIndexInRange(index); int previousValue = array[index]; array[index] = element; return previousValue; } @Override public boolean add(Integer element) { addInt(element); return true; } @Override public void add(int index, Integer element) { addInt(index, element); } /** Like {@link #add(Integer)} but more efficient in that it doesn't box the element. */ @Override public void addInt(int element) { ensureIsMutable(); if (size == array.length) { // Resize to 1.5x the size int length = ((size * 3) / 2) + 1; int[] newArray = new int[length]; System.arraycopy(array, 0, newArray, 0, size); array = newArray; } array[size++] = element; } /** Like {@link #add(int, Integer)} but more efficient in that it doesn't box the element. */ private void addInt(int index, int element) { ensureIsMutable(); if (index < 0 || index > size) { throw new IndexOutOfBoundsException(makeOutOfBoundsExceptionMessage(index)); } if (size < array.length) { // Shift everything over to make room System.arraycopy(array, index, array, index + 1, size - index); } else { // Resize to 1.5x the size int length = ((size * 3) / 2) + 1; int[] newArray = new int[length]; // Copy the first part directly System.arraycopy(array, 0, newArray, 0, index); // Copy the rest shifted over by one to make room System.arraycopy(array, index, newArray, index + 1, size - index); array = newArray; } array[index] = element; size++; modCount++; } @Override public boolean addAll(Collection<? extends Integer> collection) { ensureIsMutable(); checkNotNull(collection); // We specialize when adding another IntArrayList to avoid boxing elements. if (!(collection instanceof IntArrayList)) { return super.addAll(collection); } IntArrayList list = (IntArrayList) collection; if (list.size == 0) { return false; } int overflow = Integer.MAX_VALUE - size; if (overflow < list.size) { // We can't actually represent a list this large. throw new OutOfMemoryError(); } int newSize = size + list.size; if (newSize > array.length) { array = Arrays.copyOf(array, newSize); } System.arraycopy(list.array, 0, array, size, list.size); size = newSize; modCount++; return true; } @Override public Integer remove(int index) { ensureIsMutable(); ensureIndexInRange(index); int value = array[index]; if (index < size - 1) { System.arraycopy(array, index + 1, array, index, size - index - 1); } size--; modCount++; return value; } /** * Ensures that the provided {@code index} is within the range of {@code [0, size]}. Throws an * {@link IndexOutOfBoundsException} if it is not. * * @param index the index to verify is in range */ private void ensureIndexInRange(int index) { if (index < 0 || index >= size) { throw new IndexOutOfBoundsException(makeOutOfBoundsExceptionMessage(index)); } } private String makeOutOfBoundsExceptionMessage(int index) { return "Index:" + index + ", Size:" + size; } }
protocolbuffers/protobuf
java/core/src/main/java/com/google/protobuf/IntArrayList.java
60
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * Project Info: https://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * https://plantuml.com/patreon (only 1$ per month!) * https://plantuml.com/paypal * * This file is part of Smetana. * Smetana is a partial translation of Graphviz/Dot sources from C to Java. * * (C) Copyright 2009-2022, Arnaud Roques * * This translation is distributed under the same Licence as the original C program: * ************************************************************************* * Copyright (c) 2011 AT&T Intellectual Property * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: See CVS logs. Details at http://www.graphviz.org/ ************************************************************************* * * THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC * LICENSE ("AGREEMENT"). [Eclipse Public License - v 1.0] * * ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES * RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. * * You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * 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 h; import smetana.core.CString; import smetana.core.UnsupportedStarStruct; import smetana.core.__struct__; final public class ST_arrowname_t extends UnsupportedStarStruct { public CString name; public int type; @Override public void ___(__struct__ other) { ST_arrowname_t other2 = (ST_arrowname_t) other; this.name = other2.name == null ? null : other2.name.duplicate(); this.type = other2.type; } } // typedef struct arrowname_t { // char *name; // int type; // } arrowname_t;
plantuml/plantuml
src/h/ST_arrowname_t.java
61
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * Project Info: https://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * https://plantuml.com/patreon (only 1$ per month!) * https://plantuml.com/paypal * * This file is part of Smetana. * Smetana is a partial translation of Graphviz/Dot sources from C to Java. * * (C) Copyright 2009-2022, Arnaud Roques * * This translation is distributed under the same Licence as the original C program: * ************************************************************************* * Copyright (c) 2011 AT&T Intellectual Property * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: See CVS logs. Details at http://www.graphviz.org/ ************************************************************************* * * THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC * LICENSE ("AGREEMENT"). [Eclipse Public License - v 1.0] * * ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES * RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. * * You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * 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 h; import smetana.core.CArray; import smetana.core.UnsupportedStarStruct; import smetana.core.__ptr__; final public class ST_object_t extends UnsupportedStarStruct implements ST_Node_t___or_object_t { public final ST_pointf pos = new ST_pointf(); public final ST_pointf sz = new ST_pointf(); public CArray<ST_xlabel_t> lbl; @Override public boolean isSameThan(__ptr__ other) { ST_object_t other2 = (ST_object_t) other; return this == other2; } } // typedef struct { // pointf pos; /* Position of lower-left corner of object */ // pointf sz; /* Size of object; may be zero for a point */ // xlabel_t *lbl; /* Label attached to object, or NULL */ // } object_t;
plantuml/plantuml
src/h/ST_object_t.java
62
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * Project Info: https://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * https://plantuml.com/patreon (only 1$ per month!) * https://plantuml.com/paypal * * This file is part of Smetana. * Smetana is a partial translation of Graphviz/Dot sources from C to Java. * * (C) Copyright 2009-2022, Arnaud Roques * * This translation is distributed under the same Licence as the original C program: * ************************************************************************* * Copyright (c) 2011 AT&T Intellectual Property * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: See CVS logs. Details at http://www.graphviz.org/ ************************************************************************* * * THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC * LICENSE ("AGREEMENT"). [Eclipse Public License - v 1.0] * * ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES * RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. * * You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * 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 h; import smetana.core.UnsupportedStarStruct; final public class ST_aspect_t extends UnsupportedStarStruct { public int prevIterations; public int curIterations; public int nextIter; public int nPasses; public int badGraph; } // typedef struct aspect_t { // double targetAR; /* target aspect ratio */ // double combiAR; // int prevIterations; /* no. of iterations in previous pass */ // int curIterations; /* no. of iterations in current pass */ // int nextIter; /* dynamically adjusted no. of iterations */ // int nPasses; /* bound on no. of top-level passes */ // int badGraph; /* hack: set if graph is disconnected or has // * clusters. If so, turn off aspect */ // } aspect_t;
plantuml/plantuml
src/h/ST_aspect_t.java
63
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file or at // https://developers.google.com/open-source/licenses/bsd package com.google.protobuf; import static com.google.protobuf.UnsafeUtil.addressOffset; import static com.google.protobuf.UnsafeUtil.hasUnsafeArrayOperations; import static com.google.protobuf.UnsafeUtil.hasUnsafeByteBufferOperations; import static java.lang.Character.MAX_SURROGATE; import static java.lang.Character.MIN_HIGH_SURROGATE; import static java.lang.Character.MIN_LOW_SURROGATE; import static java.lang.Character.MIN_SUPPLEMENTARY_CODE_POINT; import static java.lang.Character.MIN_SURROGATE; import static java.lang.Character.isSurrogatePair; import static java.lang.Character.toCodePoint; import java.nio.ByteBuffer; import java.util.Arrays; /** * A set of low-level, high-performance static utility methods related to the UTF-8 character * encoding. This class has no dependencies outside of the core JDK libraries. * * <p>There are several variants of UTF-8. The one implemented by this class is the restricted * definition of UTF-8 introduced in Unicode 3.1, which mandates the rejection of "overlong" byte * sequences as well as rejection of 3-byte surrogate codepoint byte sequences. Note that the UTF-8 * decoder included in Oracle's JDK has been modified to also reject "overlong" byte sequences, but * (as of 2011) still accepts 3-byte surrogate codepoint byte sequences. * * <p>The byte sequences considered valid by this class are exactly those that can be roundtrip * converted to Strings and back to bytes using the UTF-8 charset, without loss: * * <pre>{@code * Arrays.equals(bytes, new String(bytes, Internal.UTF_8).getBytes(Internal.UTF_8)) * }</pre> * * <p>See the Unicode Standard,</br> Table 3-6. <em>UTF-8 Bit Distribution</em>,</br> Table 3-7. * <em>Well Formed UTF-8 Byte Sequences</em>. * * <p>This class supports decoding of partial byte sequences, so that the bytes in a complete UTF-8 * byte sequence can be stored in multiple segments. Methods typically return {@link #MALFORMED} if * the partial byte sequence is definitely not well-formed; {@link #COMPLETE} if it is well-formed * in the absence of additional input; or, if the byte sequence apparently terminated in the middle * of a character, an opaque integer "state" value containing enough information to decode the * character when passed to a subsequent invocation of a partial decoding method. * * @author martinrb@google.com (Martin Buchholz) */ // TODO: Copy changes in this class back to Guava final class Utf8 { /** * UTF-8 is a runtime hot spot so we attempt to provide heavily optimized implementations * depending on what is available on the platform. The processor is the platform-optimized * delegate for which all methods are delegated directly to. */ private static final Processor processor = (UnsafeProcessor.isAvailable() && !Android.isOnAndroidDevice()) ? new UnsafeProcessor() : new SafeProcessor(); /** * A mask used when performing unsafe reads to determine if a long value contains any non-ASCII * characters (i.e. any byte >= 0x80). */ private static final long ASCII_MASK_LONG = 0x8080808080808080L; /** * Maximum number of bytes per Java UTF-16 char in UTF-8. * * @see java.nio.charset.CharsetEncoder#maxBytesPerChar() */ static final int MAX_BYTES_PER_CHAR = 3; /** * State value indicating that the byte sequence is well-formed and complete (no further bytes are * needed to complete a character). */ static final int COMPLETE = 0; /** State value indicating that the byte sequence is definitely not well-formed. */ static final int MALFORMED = -1; /** * Used by {@code Unsafe} UTF-8 string validation logic to determine the minimum string length * above which to employ an optimized algorithm for counting ASCII characters. The reason for this * threshold is that for small strings, the optimization may not be beneficial or may even * negatively impact performance since it requires additional logic to avoid unaligned reads (when * calling {@code Unsafe.getLong}). This threshold guarantees that even if the initial offset is * unaligned, we're guaranteed to make at least one call to {@code Unsafe.getLong()} which * provides a performance improvement that entirely subsumes the cost of the additional logic. */ private static final int UNSAFE_COUNT_ASCII_THRESHOLD = 16; // Other state values include the partial bytes of the incomplete // character to be decoded in the simplest way: we pack the bytes // into the state int in little-endian order. For example: // // int state = byte1 ^ (byte2 << 8) ^ (byte3 << 16); // // Such a state is unpacked thus (note the ~ operation for byte2 to // undo byte1's sign-extension bits): // // int byte1 = (byte) state; // int byte2 = (byte) ~(state >> 8); // int byte3 = (byte) (state >> 16); // // We cannot store a zero byte in the state because it would be // indistinguishable from the absence of a byte. But we don't need // to, because partial bytes must always be negative. When building // a state, we ensure that byte1 is negative and subsequent bytes // are valid trailing bytes. /** * Returns {@code true} if the given byte array is a well-formed UTF-8 byte sequence. * * <p>This is a convenience method, equivalent to a call to {@code isValidUtf8(bytes, 0, * bytes.length)}. */ static boolean isValidUtf8(byte[] bytes) { return processor.isValidUtf8(bytes, 0, bytes.length); } /** * Returns {@code true} if the given byte array slice is a well-formed UTF-8 byte sequence. The * range of bytes to be checked extends from index {@code index}, inclusive, to {@code limit}, * exclusive. * * <p>This is a convenience method, equivalent to {@code partialIsValidUtf8(bytes, index, limit) * == Utf8.COMPLETE}. */ static boolean isValidUtf8(byte[] bytes, int index, int limit) { return processor.isValidUtf8(bytes, index, limit); } /** * Tells whether the given byte array slice is a well-formed, malformed, or incomplete UTF-8 byte * sequence. The range of bytes to be checked extends from index {@code index}, inclusive, to * {@code limit}, exclusive. * * @param state either {@link Utf8#COMPLETE} (if this is the initial decoding operation) or the * value returned from a call to a partial decoding method for the previous bytes * @return {@link #MALFORMED} if the partial byte sequence is definitely not well-formed, {@link * #COMPLETE} if it is well-formed (no additional input needed), or if the byte sequence is * "incomplete", i.e. apparently terminated in the middle of a character, an opaque integer * "state" value containing enough information to decode the character when passed to a * subsequent invocation of a partial decoding method. */ static int partialIsValidUtf8(int state, byte[] bytes, int index, int limit) { return processor.partialIsValidUtf8(state, bytes, index, limit); } private static int incompleteStateFor(int byte1) { return (byte1 > (byte) 0xF4) ? MALFORMED : byte1; } private static int incompleteStateFor(int byte1, int byte2) { return (byte1 > (byte) 0xF4 || byte2 > (byte) 0xBF) ? MALFORMED : byte1 ^ (byte2 << 8); } private static int incompleteStateFor(int byte1, int byte2, int byte3) { return (byte1 > (byte) 0xF4 || byte2 > (byte) 0xBF || byte3 > (byte) 0xBF) ? MALFORMED : byte1 ^ (byte2 << 8) ^ (byte3 << 16); } private static int incompleteStateFor(byte[] bytes, int index, int limit) { int byte1 = bytes[index - 1]; switch (limit - index) { case 0: return incompleteStateFor(byte1); case 1: return incompleteStateFor(byte1, bytes[index]); case 2: return incompleteStateFor(byte1, bytes[index], bytes[index + 1]); default: throw new AssertionError(); } } private static int incompleteStateFor( final ByteBuffer buffer, final int byte1, final int index, final int remaining) { switch (remaining) { case 0: return incompleteStateFor(byte1); case 1: return incompleteStateFor(byte1, buffer.get(index)); case 2: return incompleteStateFor(byte1, buffer.get(index), buffer.get(index + 1)); default: throw new AssertionError(); } } // These UTF-8 handling methods are copied from Guava's Utf8 class with a modification to throw // a protocol buffer local exception. This exception is then caught in CodedOutputStream so it can // fallback to more lenient behavior. static class UnpairedSurrogateException extends IllegalArgumentException { UnpairedSurrogateException(int index, int length) { super("Unpaired surrogate at index " + index + " of " + length); } } /** * Returns the number of bytes in the UTF-8-encoded form of {@code sequence}. For a string, this * method is equivalent to {@code string.getBytes(UTF_8).length}, but is more efficient in both * time and space. * * @throws IllegalArgumentException if {@code sequence} contains ill-formed UTF-16 (unpaired * surrogates) */ static int encodedLength(String string) { // Warning to maintainers: this implementation is highly optimized. int utf16Length = string.length(); int utf8Length = utf16Length; int i = 0; // This loop optimizes for pure ASCII. while (i < utf16Length && string.charAt(i) < 0x80) { i++; } // This loop optimizes for chars less than 0x800. for (; i < utf16Length; i++) { char c = string.charAt(i); if (c < 0x800) { utf8Length += ((0x7f - c) >>> 31); // branch free! } else { utf8Length += encodedLengthGeneral(string, i); break; } } if (utf8Length < utf16Length) { // Necessary and sufficient condition for overflow because of maximum 3x expansion throw new IllegalArgumentException( "UTF-8 length does not fit in int: " + (utf8Length + (1L << 32))); } return utf8Length; } private static int encodedLengthGeneral(String string, int start) { int utf16Length = string.length(); int utf8Length = 0; for (int i = start; i < utf16Length; i++) { char c = string.charAt(i); if (c < 0x800) { utf8Length += (0x7f - c) >>> 31; // branch free! } else { utf8Length += 2; // jdk7+: if (Character.isSurrogate(c)) { if (Character.MIN_SURROGATE <= c && c <= Character.MAX_SURROGATE) { // Check that we have a well-formed surrogate pair. int cp = Character.codePointAt(string, i); if (cp < MIN_SUPPLEMENTARY_CODE_POINT) { throw new UnpairedSurrogateException(i, utf16Length); } i++; } } } return utf8Length; } static int encode(String in, byte[] out, int offset, int length) { return processor.encodeUtf8(in, out, offset, length); } // End Guava UTF-8 methods. /** * Determines if the given {@link ByteBuffer} is a valid UTF-8 string. * * <p>Selects an optimal algorithm based on the type of {@link ByteBuffer} (i.e. heap or direct) * and the capabilities of the platform. * * @param buffer the buffer to check. * @see Utf8#isValidUtf8(byte[], int, int) */ static boolean isValidUtf8(ByteBuffer buffer) { return processor.isValidUtf8(buffer, buffer.position(), buffer.remaining()); } /** * Determines if the given {@link ByteBuffer} is a partially valid UTF-8 string. * * <p>Selects an optimal algorithm based on the type of {@link ByteBuffer} (i.e. heap or direct) * and the capabilities of the platform. * * @param buffer the buffer to check. * @see Utf8#partialIsValidUtf8(int, byte[], int, int) */ static int partialIsValidUtf8(int state, ByteBuffer buffer, int index, int limit) { return processor.partialIsValidUtf8(state, buffer, index, limit); } /** * Decodes the given UTF-8 portion of the {@link ByteBuffer} into a {@link String}. * * @throws InvalidProtocolBufferException if the input is not valid UTF-8. */ static String decodeUtf8(ByteBuffer buffer, int index, int size) throws InvalidProtocolBufferException { return processor.decodeUtf8(buffer, index, size); } /** * Decodes the given UTF-8 encoded byte array slice into a {@link String}. * * @throws InvalidProtocolBufferException if the input is not valid UTF-8. */ static String decodeUtf8(byte[] bytes, int index, int size) throws InvalidProtocolBufferException { return processor.decodeUtf8(bytes, index, size); } /** * Encodes the given characters to the target {@link ByteBuffer} using UTF-8 encoding. * * <p>Selects an optimal algorithm based on the type of {@link ByteBuffer} (i.e. heap or direct) * and the capabilities of the platform. * * @param in the source string to be encoded * @param out the target buffer to receive the encoded string. * @see Utf8#encode(String, byte[], int, int) */ static void encodeUtf8(String in, ByteBuffer out) { processor.encodeUtf8(in, out); } /** * Counts (approximately) the number of consecutive ASCII characters in the given buffer. The byte * order of the {@link ByteBuffer} does not matter, so performance can be improved if native byte * order is used (i.e. no byte-swapping in {@link ByteBuffer#getLong(int)}). * * @param buffer the buffer to be scanned for ASCII chars * @param index the starting index of the scan * @param limit the limit within buffer for the scan * @return the number of ASCII characters found. The stopping position will be at or before the * first non-ASCII byte. */ private static int estimateConsecutiveAscii(ByteBuffer buffer, int index, int limit) { int i = index; final int lim = limit - 7; // This simple loop stops when we encounter a byte >= 0x80 (i.e. non-ASCII). // To speed things up further, we're reading longs instead of bytes so we use a mask to // determine if any byte in the current long is non-ASCII. for (; i < lim && (buffer.getLong(i) & ASCII_MASK_LONG) == 0; i += 8) {} return i - index; } /** A processor of UTF-8 strings, providing methods for checking validity and encoding. */ // TODO: Add support for Memory/MemoryBlock on Android. abstract static class Processor { /** * Returns {@code true} if the given byte array slice is a well-formed UTF-8 byte sequence. The * range of bytes to be checked extends from index {@code index}, inclusive, to {@code limit}, * exclusive. * * <p>This is a convenience method, equivalent to {@code partialIsValidUtf8(bytes, index, limit) * == Utf8.COMPLETE}. */ final boolean isValidUtf8(byte[] bytes, int index, int limit) { return partialIsValidUtf8(COMPLETE, bytes, index, limit) == COMPLETE; } /** * Tells whether the given byte array slice is a well-formed, malformed, or incomplete UTF-8 * byte sequence. The range of bytes to be checked extends from index {@code index}, inclusive, * to {@code limit}, exclusive. * * @param state either {@link Utf8#COMPLETE} (if this is the initial decoding operation) or the * value returned from a call to a partial decoding method for the previous bytes * @return {@link #MALFORMED} if the partial byte sequence is definitely not well-formed, {@link * #COMPLETE} if it is well-formed (no additional input needed), or if the byte sequence is * "incomplete", i.e. apparently terminated in the middle of a character, an opaque integer * "state" value containing enough information to decode the character when passed to a * subsequent invocation of a partial decoding method. */ abstract int partialIsValidUtf8(int state, byte[] bytes, int index, int limit); /** * Returns {@code true} if the given portion of the {@link ByteBuffer} is a well-formed UTF-8 * byte sequence. The range of bytes to be checked extends from index {@code index}, inclusive, * to {@code limit}, exclusive. * * <p>This is a convenience method, equivalent to {@code partialIsValidUtf8(bytes, index, limit) * == Utf8.COMPLETE}. */ final boolean isValidUtf8(ByteBuffer buffer, int index, int limit) { return partialIsValidUtf8(COMPLETE, buffer, index, limit) == COMPLETE; } /** * Indicates whether or not the given buffer contains a valid UTF-8 string. * * @param buffer the buffer to check. * @return {@code true} if the given buffer contains a valid UTF-8 string. */ final int partialIsValidUtf8( final int state, final ByteBuffer buffer, int index, final int limit) { if (buffer.hasArray()) { final int offset = buffer.arrayOffset(); return partialIsValidUtf8(state, buffer.array(), offset + index, offset + limit); } else if (buffer.isDirect()) { return partialIsValidUtf8Direct(state, buffer, index, limit); } return partialIsValidUtf8Default(state, buffer, index, limit); } /** Performs validation for direct {@link ByteBuffer} instances. */ abstract int partialIsValidUtf8Direct( final int state, final ByteBuffer buffer, int index, final int limit); /** * Performs validation for {@link ByteBuffer} instances using the {@link ByteBuffer} API rather * than potentially faster approaches. This first completes validation for the current character * (provided by {@code state}) and then finishes validation for the sequence. */ final int partialIsValidUtf8Default( final int state, final ByteBuffer buffer, int index, final int limit) { if (state != COMPLETE) { // The previous decoding operation was incomplete (or malformed). // We look for a well-formed sequence consisting of bytes from // the previous decoding operation (stored in state) together // with bytes from the array slice. // // We expect such "straddler characters" to be rare. if (index >= limit) { // No bytes? No progress. return state; } byte byte1 = (byte) state; // byte1 is never ASCII. if (byte1 < (byte) 0xE0) { // two-byte form // Simultaneously checks for illegal trailing-byte in // leading position and overlong 2-byte form. if (byte1 < (byte) 0xC2 // byte2 trailing-byte test || buffer.get(index++) > (byte) 0xBF) { return MALFORMED; } } else if (byte1 < (byte) 0xF0) { // three-byte form // Get byte2 from saved state or array byte byte2 = (byte) ~(state >> 8); if (byte2 == 0) { byte2 = buffer.get(index++); if (index >= limit) { return incompleteStateFor(byte1, byte2); } } if (byte2 > (byte) 0xBF // overlong? 5 most significant bits must not all be zero || (byte1 == (byte) 0xE0 && byte2 < (byte) 0xA0) // illegal surrogate codepoint? || (byte1 == (byte) 0xED && byte2 >= (byte) 0xA0) // byte3 trailing-byte test || buffer.get(index++) > (byte) 0xBF) { return MALFORMED; } } else { // four-byte form // Get byte2 and byte3 from saved state or array byte byte2 = (byte) ~(state >> 8); byte byte3 = 0; if (byte2 == 0) { byte2 = buffer.get(index++); if (index >= limit) { return incompleteStateFor(byte1, byte2); } } else { byte3 = (byte) (state >> 16); } if (byte3 == 0) { byte3 = buffer.get(index++); if (index >= limit) { return incompleteStateFor(byte1, byte2, byte3); } } // If we were called with state == MALFORMED, then byte1 is 0xFF, // which never occurs in well-formed UTF-8, and so we will return // MALFORMED again below. if (byte2 > (byte) 0xBF // Check that 1 <= plane <= 16. Tricky optimized form of: // if (byte1 > (byte) 0xF4 || // byte1 == (byte) 0xF0 && byte2 < (byte) 0x90 || // byte1 == (byte) 0xF4 && byte2 > (byte) 0x8F) || (((byte1 << 28) + (byte2 - (byte) 0x90)) >> 30) != 0 // byte3 trailing-byte test || byte3 > (byte) 0xBF // byte4 trailing-byte test || buffer.get(index++) > (byte) 0xBF) { return MALFORMED; } } } // Finish validation for the sequence. return partialIsValidUtf8(buffer, index, limit); } /** * Performs validation for {@link ByteBuffer} instances using the {@link ByteBuffer} API rather * than potentially faster approaches. */ private static int partialIsValidUtf8(final ByteBuffer buffer, int index, final int limit) { index += estimateConsecutiveAscii(buffer, index, limit); for (; ; ) { // Optimize for interior runs of ASCII bytes. // TODO: Consider checking 8 bytes at a time after some threshold? // Maybe after seeing a few in a row that are ASCII, go back to fast mode? int byte1; do { if (index >= limit) { return COMPLETE; } } while ((byte1 = buffer.get(index++)) >= 0); // If we're here byte1 is not ASCII. Only need to handle 2-4 byte forms. if (byte1 < (byte) 0xE0) { // Two-byte form (110xxxxx 10xxxxxx) if (index >= limit) { // Incomplete sequence return byte1; } // Simultaneously checks for illegal trailing-byte in // leading position and overlong 2-byte form. if (byte1 < (byte) 0xC2 || buffer.get(index) > (byte) 0xBF) { return MALFORMED; } index++; } else if (byte1 < (byte) 0xF0) { // Three-byte form (1110xxxx 10xxxxxx 10xxxxxx) if (index >= limit - 1) { // Incomplete sequence return incompleteStateFor(buffer, byte1, index, limit - index); } byte byte2 = buffer.get(index++); if (byte2 > (byte) 0xBF // overlong? 5 most significant bits must not all be zero || (byte1 == (byte) 0xE0 && byte2 < (byte) 0xA0) // check for illegal surrogate codepoints || (byte1 == (byte) 0xED && byte2 >= (byte) 0xA0) // byte3 trailing-byte test || buffer.get(index) > (byte) 0xBF) { return MALFORMED; } index++; } else { // Four-byte form (1110xxxx 10xxxxxx 10xxxxxx 10xxxxxx) if (index >= limit - 2) { // Incomplete sequence return incompleteStateFor(buffer, byte1, index, limit - index); } // TODO: Consider using getInt() to improve performance. int byte2 = buffer.get(index++); if (byte2 > (byte) 0xBF // Check that 1 <= plane <= 16. Tricky optimized form of: // if (byte1 > (byte) 0xF4 || // byte1 == (byte) 0xF0 && byte2 < (byte) 0x90 || // byte1 == (byte) 0xF4 && byte2 > (byte) 0x8F) || (((byte1 << 28) + (byte2 - (byte) 0x90)) >> 30) != 0 // byte3 trailing-byte test || buffer.get(index++) > (byte) 0xBF // byte4 trailing-byte test || buffer.get(index++) > (byte) 0xBF) { return MALFORMED; } } } } /** * Decodes the given byte array slice into a {@link String}. * * @throws InvalidProtocolBufferException if the byte array slice is not valid UTF-8 */ abstract String decodeUtf8(byte[] bytes, int index, int size) throws InvalidProtocolBufferException; /** * Decodes the given portion of the {@link ByteBuffer} into a {@link String}. * * @throws InvalidProtocolBufferException if the portion of the buffer is not valid UTF-8 */ final String decodeUtf8(ByteBuffer buffer, int index, int size) throws InvalidProtocolBufferException { if (buffer.hasArray()) { final int offset = buffer.arrayOffset(); return decodeUtf8(buffer.array(), offset + index, size); } else if (buffer.isDirect()) { return decodeUtf8Direct(buffer, index, size); } return decodeUtf8Default(buffer, index, size); } /** Decodes direct {@link ByteBuffer} instances into {@link String}. */ abstract String decodeUtf8Direct(ByteBuffer buffer, int index, int size) throws InvalidProtocolBufferException; /** * Decodes {@link ByteBuffer} instances using the {@link ByteBuffer} API rather than potentially * faster approaches. */ final String decodeUtf8Default(ByteBuffer buffer, int index, int size) throws InvalidProtocolBufferException { // Bitwise OR combines the sign bits so any negative value fails the check. if ((index | size | buffer.limit() - index - size) < 0) { throw new ArrayIndexOutOfBoundsException( String.format("buffer limit=%d, index=%d, limit=%d", buffer.limit(), index, size)); } int offset = index; int limit = offset + size; // The longest possible resulting String is the same as the number of input bytes, when it is // all ASCII. For other cases, this over-allocates and we will truncate in the end. char[] resultArr = new char[size]; int resultPos = 0; // Optimize for 100% ASCII (Hotspot loves small simple top-level loops like this). // This simple loop stops when we encounter a byte >= 0x80 (i.e. non-ASCII). while (offset < limit) { byte b = buffer.get(offset); if (!DecodeUtil.isOneByte(b)) { break; } offset++; DecodeUtil.handleOneByte(b, resultArr, resultPos++); } while (offset < limit) { byte byte1 = buffer.get(offset++); if (DecodeUtil.isOneByte(byte1)) { DecodeUtil.handleOneByte(byte1, resultArr, resultPos++); // It's common for there to be multiple ASCII characters in a run mixed in, so add an // extra optimized loop to take care of these runs. while (offset < limit) { byte b = buffer.get(offset); if (!DecodeUtil.isOneByte(b)) { break; } offset++; DecodeUtil.handleOneByte(b, resultArr, resultPos++); } } else if (DecodeUtil.isTwoBytes(byte1)) { if (offset >= limit) { throw InvalidProtocolBufferException.invalidUtf8(); } DecodeUtil.handleTwoBytes( byte1, /* byte2 */ buffer.get(offset++), resultArr, resultPos++); } else if (DecodeUtil.isThreeBytes(byte1)) { if (offset >= limit - 1) { throw InvalidProtocolBufferException.invalidUtf8(); } DecodeUtil.handleThreeBytes( byte1, /* byte2 */ buffer.get(offset++), /* byte3 */ buffer.get(offset++), resultArr, resultPos++); } else { if (offset >= limit - 2) { throw InvalidProtocolBufferException.invalidUtf8(); } DecodeUtil.handleFourBytes( byte1, /* byte2 */ buffer.get(offset++), /* byte3 */ buffer.get(offset++), /* byte4 */ buffer.get(offset++), resultArr, resultPos++); // 4-byte case requires two chars. resultPos++; } } return new String(resultArr, 0, resultPos); } /** * Encodes an input character sequence ({@code in}) to UTF-8 in the target array ({@code out}). * For a string, this method is similar to * * <pre>{@code * byte[] a = string.getBytes(UTF_8); * System.arraycopy(a, 0, bytes, offset, a.length); * return offset + a.length; * }</pre> * * but is more efficient in both time and space. One key difference is that this method requires * paired surrogates, and therefore does not support chunking. While {@code * String.getBytes(UTF_8)} replaces unpaired surrogates with the default replacement character, * this method throws {@link UnpairedSurrogateException}. * * <p>To ensure sufficient space in the output buffer, either call {@link #encodedLength} to * compute the exact amount needed, or leave room for {@code Utf8.MAX_BYTES_PER_CHAR * * sequence.length()}, which is the largest possible number of bytes that any input can be * encoded to. * * @param in the input character sequence to be encoded * @param out the target array * @param offset the starting offset in {@code bytes} to start writing at * @param length the length of the {@code bytes}, starting from {@code offset} * @throws UnpairedSurrogateException if {@code sequence} contains ill-formed UTF-16 (unpaired * surrogates) * @throws ArrayIndexOutOfBoundsException if {@code sequence} encoded in UTF-8 is longer than * {@code bytes.length - offset} * @return the new offset, equivalent to {@code offset + Utf8.encodedLength(sequence)} */ abstract int encodeUtf8(String in, byte[] out, int offset, int length); /** * Encodes an input character sequence ({@code in}) to UTF-8 in the target buffer ({@code out}). * Upon returning from this method, the {@code out} position will point to the position after * the last encoded byte. This method requires paired surrogates, and therefore does not support * chunking. * * <p>To ensure sufficient space in the output buffer, either call {@link #encodedLength} to * compute the exact amount needed, or leave room for {@code Utf8.MAX_BYTES_PER_CHAR * * in.length()}, which is the largest possible number of bytes that any input can be encoded to. * * @param in the source character sequence to be encoded * @param out the target buffer * @throws UnpairedSurrogateException if {@code in} contains ill-formed UTF-16 (unpaired * surrogates) * @throws ArrayIndexOutOfBoundsException if {@code in} encoded in UTF-8 is longer than {@code * out.remaining()} */ final void encodeUtf8(String in, ByteBuffer out) { if (out.hasArray()) { final int offset = out.arrayOffset(); int endIndex = Utf8.encode(in, out.array(), offset + out.position(), out.remaining()); Java8Compatibility.position(out, endIndex - offset); } else if (out.isDirect()) { encodeUtf8Direct(in, out); } else { encodeUtf8Default(in, out); } } /** Encodes the input character sequence to a direct {@link ByteBuffer} instance. */ abstract void encodeUtf8Direct(String in, ByteBuffer out); /** * Encodes the input character sequence to a {@link ByteBuffer} instance using the {@link * ByteBuffer} API, rather than potentially faster approaches. */ final void encodeUtf8Default(String in, ByteBuffer out) { final int inLength = in.length(); int outIx = out.position(); int inIx = 0; // Since ByteBuffer.putXXX() already checks boundaries for us, no need to explicitly check // access. Assume the buffer is big enough and let it handle the out of bounds exception // if it occurs. try { // Designed to take advantage of // https://wiki.openjdk.java.net/display/HotSpotInternals/RangeCheckElimination for (char c; inIx < inLength && (c = in.charAt(inIx)) < 0x80; ++inIx) { out.put(outIx + inIx, (byte) c); } if (inIx == inLength) { // Successfully encoded the entire string. Java8Compatibility.position(out, outIx + inIx); return; } outIx += inIx; for (char c; inIx < inLength; ++inIx, ++outIx) { c = in.charAt(inIx); if (c < 0x80) { // One byte (0xxx xxxx) out.put(outIx, (byte) c); } else if (c < 0x800) { // Two bytes (110x xxxx 10xx xxxx) // Benchmarks show put performs better than putShort here (for HotSpot). out.put(outIx++, (byte) (0xC0 | (c >>> 6))); out.put(outIx, (byte) (0x80 | (0x3F & c))); } else if (c < MIN_SURROGATE || MAX_SURROGATE < c) { // Three bytes (1110 xxxx 10xx xxxx 10xx xxxx) // Maximum single-char code point is 0xFFFF, 16 bits. // Benchmarks show put performs better than putShort here (for HotSpot). out.put(outIx++, (byte) (0xE0 | (c >>> 12))); out.put(outIx++, (byte) (0x80 | (0x3F & (c >>> 6)))); out.put(outIx, (byte) (0x80 | (0x3F & c))); } else { // Four bytes (1111 xxxx 10xx xxxx 10xx xxxx 10xx xxxx) // Minimum code point represented by a surrogate pair is 0x10000, 17 bits, four UTF-8 // bytes final char low; if (inIx + 1 == inLength || !isSurrogatePair(c, (low = in.charAt(++inIx)))) { throw new UnpairedSurrogateException(inIx, inLength); } // TODO: Consider using putInt() to improve performance. int codePoint = toCodePoint(c, low); out.put(outIx++, (byte) ((0xF << 4) | (codePoint >>> 18))); out.put(outIx++, (byte) (0x80 | (0x3F & (codePoint >>> 12)))); out.put(outIx++, (byte) (0x80 | (0x3F & (codePoint >>> 6)))); out.put(outIx, (byte) (0x80 | (0x3F & codePoint))); } } // Successfully encoded the entire string. Java8Compatibility.position(out, outIx); } catch (IndexOutOfBoundsException e) { // TODO: Consider making the API throw IndexOutOfBoundsException instead. // If we failed in the outer ASCII loop, outIx will not have been updated. In this case, // use inIx to determine the bad write index. int badWriteIndex = out.position() + Math.max(inIx, outIx - out.position() + 1); throw new ArrayIndexOutOfBoundsException( "Failed writing " + in.charAt(inIx) + " at index " + badWriteIndex); } } } /** {@link Processor} implementation that does not use any {@code sun.misc.Unsafe} methods. */ static final class SafeProcessor extends Processor { @Override int partialIsValidUtf8(int state, byte[] bytes, int index, int limit) { if (state != COMPLETE) { // The previous decoding operation was incomplete (or malformed). // We look for a well-formed sequence consisting of bytes from // the previous decoding operation (stored in state) together // with bytes from the array slice. // // We expect such "straddler characters" to be rare. if (index >= limit) { // No bytes? No progress. return state; } int byte1 = (byte) state; // byte1 is never ASCII. if (byte1 < (byte) 0xE0) { // two-byte form // Simultaneously checks for illegal trailing-byte in // leading position and overlong 2-byte form. if (byte1 < (byte) 0xC2 // byte2 trailing-byte test || bytes[index++] > (byte) 0xBF) { return MALFORMED; } } else if (byte1 < (byte) 0xF0) { // three-byte form // Get byte2 from saved state or array int byte2 = (byte) ~(state >> 8); if (byte2 == 0) { byte2 = bytes[index++]; if (index >= limit) { return incompleteStateFor(byte1, byte2); } } if (byte2 > (byte) 0xBF // overlong? 5 most significant bits must not all be zero || (byte1 == (byte) 0xE0 && byte2 < (byte) 0xA0) // illegal surrogate codepoint? || (byte1 == (byte) 0xED && byte2 >= (byte) 0xA0) // byte3 trailing-byte test || bytes[index++] > (byte) 0xBF) { return MALFORMED; } } else { // four-byte form // Get byte2 and byte3 from saved state or array int byte2 = (byte) ~(state >> 8); int byte3 = 0; if (byte2 == 0) { byte2 = bytes[index++]; if (index >= limit) { return incompleteStateFor(byte1, byte2); } } else { byte3 = (byte) (state >> 16); } if (byte3 == 0) { byte3 = bytes[index++]; if (index >= limit) { return incompleteStateFor(byte1, byte2, byte3); } } // If we were called with state == MALFORMED, then byte1 is 0xFF, // which never occurs in well-formed UTF-8, and so we will return // MALFORMED again below. if (byte2 > (byte) 0xBF // Check that 1 <= plane <= 16. Tricky optimized form of: // if (byte1 > (byte) 0xF4 || // byte1 == (byte) 0xF0 && byte2 < (byte) 0x90 || // byte1 == (byte) 0xF4 && byte2 > (byte) 0x8F) || (((byte1 << 28) + (byte2 - (byte) 0x90)) >> 30) != 0 // byte3 trailing-byte test || byte3 > (byte) 0xBF // byte4 trailing-byte test || bytes[index++] > (byte) 0xBF) { return MALFORMED; } } } return partialIsValidUtf8(bytes, index, limit); } @Override int partialIsValidUtf8Direct(int state, ByteBuffer buffer, int index, int limit) { // For safe processing, we have to use the ByteBuffer API. return partialIsValidUtf8Default(state, buffer, index, limit); } @Override String decodeUtf8(byte[] bytes, int index, int size) throws InvalidProtocolBufferException { // Bitwise OR combines the sign bits so any negative value fails the check. if ((index | size | bytes.length - index - size) < 0) { throw new ArrayIndexOutOfBoundsException( String.format("buffer length=%d, index=%d, size=%d", bytes.length, index, size)); } int offset = index; final int limit = offset + size; // The longest possible resulting String is the same as the number of input bytes, when it is // all ASCII. For other cases, this over-allocates and we will truncate in the end. char[] resultArr = new char[size]; int resultPos = 0; // Optimize for 100% ASCII (Hotspot loves small simple top-level loops like this). // This simple loop stops when we encounter a byte >= 0x80 (i.e. non-ASCII). while (offset < limit) { byte b = bytes[offset]; if (!DecodeUtil.isOneByte(b)) { break; } offset++; DecodeUtil.handleOneByte(b, resultArr, resultPos++); } while (offset < limit) { byte byte1 = bytes[offset++]; if (DecodeUtil.isOneByte(byte1)) { DecodeUtil.handleOneByte(byte1, resultArr, resultPos++); // It's common for there to be multiple ASCII characters in a run mixed in, so add an // extra optimized loop to take care of these runs. while (offset < limit) { byte b = bytes[offset]; if (!DecodeUtil.isOneByte(b)) { break; } offset++; DecodeUtil.handleOneByte(b, resultArr, resultPos++); } } else if (DecodeUtil.isTwoBytes(byte1)) { if (offset >= limit) { throw InvalidProtocolBufferException.invalidUtf8(); } DecodeUtil.handleTwoBytes(byte1, /* byte2 */ bytes[offset++], resultArr, resultPos++); } else if (DecodeUtil.isThreeBytes(byte1)) { if (offset >= limit - 1) { throw InvalidProtocolBufferException.invalidUtf8(); } DecodeUtil.handleThreeBytes( byte1, /* byte2 */ bytes[offset++], /* byte3 */ bytes[offset++], resultArr, resultPos++); } else { if (offset >= limit - 2) { throw InvalidProtocolBufferException.invalidUtf8(); } DecodeUtil.handleFourBytes( byte1, /* byte2 */ bytes[offset++], /* byte3 */ bytes[offset++], /* byte4 */ bytes[offset++], resultArr, resultPos++); // 4-byte case requires two chars. resultPos++; } } return new String(resultArr, 0, resultPos); } @Override String decodeUtf8Direct(ByteBuffer buffer, int index, int size) throws InvalidProtocolBufferException { // For safe processing, we have to use the ByteBufferAPI. return decodeUtf8Default(buffer, index, size); } @Override int encodeUtf8(String in, byte[] out, int offset, int length) { int utf16Length = in.length(); int j = offset; int i = 0; int limit = offset + length; // Designed to take advantage of // https://wiki.openjdk.java.net/display/HotSpotInternals/RangeCheckElimination for (char c; i < utf16Length && i + j < limit && (c = in.charAt(i)) < 0x80; i++) { out[j + i] = (byte) c; } if (i == utf16Length) { return j + utf16Length; } j += i; for (char c; i < utf16Length; i++) { c = in.charAt(i); if (c < 0x80 && j < limit) { out[j++] = (byte) c; } else if (c < 0x800 && j <= limit - 2) { // 11 bits, two UTF-8 bytes out[j++] = (byte) ((0xF << 6) | (c >>> 6)); out[j++] = (byte) (0x80 | (0x3F & c)); } else if ((c < Character.MIN_SURROGATE || Character.MAX_SURROGATE < c) && j <= limit - 3) { // Maximum single-char code point is 0xFFFF, 16 bits, three UTF-8 bytes out[j++] = (byte) ((0xF << 5) | (c >>> 12)); out[j++] = (byte) (0x80 | (0x3F & (c >>> 6))); out[j++] = (byte) (0x80 | (0x3F & c)); } else if (j <= limit - 4) { // Minimum code point represented by a surrogate pair is 0x10000, 17 bits, // four UTF-8 bytes final char low; if (i + 1 == in.length() || !Character.isSurrogatePair(c, (low = in.charAt(++i)))) { throw new UnpairedSurrogateException((i - 1), utf16Length); } int codePoint = Character.toCodePoint(c, low); out[j++] = (byte) ((0xF << 4) | (codePoint >>> 18)); out[j++] = (byte) (0x80 | (0x3F & (codePoint >>> 12))); out[j++] = (byte) (0x80 | (0x3F & (codePoint >>> 6))); out[j++] = (byte) (0x80 | (0x3F & codePoint)); } else { // If we are surrogates and we're not a surrogate pair, always throw an // UnpairedSurrogateException instead of an ArrayOutOfBoundsException. if ((Character.MIN_SURROGATE <= c && c <= Character.MAX_SURROGATE) && (i + 1 == in.length() || !Character.isSurrogatePair(c, in.charAt(i + 1)))) { throw new UnpairedSurrogateException(i, utf16Length); } throw new ArrayIndexOutOfBoundsException("Failed writing " + c + " at index " + j); } } return j; } @Override void encodeUtf8Direct(String in, ByteBuffer out) { // For safe processing, we have to use the ByteBuffer API. encodeUtf8Default(in, out); } private static int partialIsValidUtf8(byte[] bytes, int index, int limit) { // Optimize for 100% ASCII (Hotspot loves small simple top-level loops like this). // This simple loop stops when we encounter a byte >= 0x80 (i.e. non-ASCII). while (index < limit && bytes[index] >= 0) { index++; } return (index >= limit) ? COMPLETE : partialIsValidUtf8NonAscii(bytes, index, limit); } private static int partialIsValidUtf8NonAscii(byte[] bytes, int index, int limit) { for (; ; ) { int byte1; int byte2; // Optimize for interior runs of ASCII bytes. do { if (index >= limit) { return COMPLETE; } } while ((byte1 = bytes[index++]) >= 0); if (byte1 < (byte) 0xE0) { // two-byte form if (index >= limit) { // Incomplete sequence return byte1; } // Simultaneously checks for illegal trailing-byte in // leading position and overlong 2-byte form. if (byte1 < (byte) 0xC2 || bytes[index++] > (byte) 0xBF) { return MALFORMED; } } else if (byte1 < (byte) 0xF0) { // three-byte form if (index >= limit - 1) { // incomplete sequence return incompleteStateFor(bytes, index, limit); } if ((byte2 = bytes[index++]) > (byte) 0xBF // overlong? 5 most significant bits must not all be zero || (byte1 == (byte) 0xE0 && byte2 < (byte) 0xA0) // check for illegal surrogate codepoints || (byte1 == (byte) 0xED && byte2 >= (byte) 0xA0) // byte3 trailing-byte test || bytes[index++] > (byte) 0xBF) { return MALFORMED; } } else { // four-byte form if (index >= limit - 2) { // incomplete sequence return incompleteStateFor(bytes, index, limit); } if ((byte2 = bytes[index++]) > (byte) 0xBF // Check that 1 <= plane <= 16. Tricky optimized form of: // if (byte1 > (byte) 0xF4 || // byte1 == (byte) 0xF0 && byte2 < (byte) 0x90 || // byte1 == (byte) 0xF4 && byte2 > (byte) 0x8F) || (((byte1 << 28) + (byte2 - (byte) 0x90)) >> 30) != 0 // byte3 trailing-byte test || bytes[index++] > (byte) 0xBF // byte4 trailing-byte test || bytes[index++] > (byte) 0xBF) { return MALFORMED; } } } } } /** {@link Processor} that uses {@code sun.misc.Unsafe} where possible to improve performance. */ static final class UnsafeProcessor extends Processor { /** Indicates whether or not all required unsafe operations are supported on this platform. */ static boolean isAvailable() { return hasUnsafeArrayOperations() && hasUnsafeByteBufferOperations(); } @Override int partialIsValidUtf8(int state, byte[] bytes, final int index, final int limit) { // Bitwise OR combines the sign bits so any negative value fails the check. if ((index | limit | bytes.length - limit) < 0) { throw new ArrayIndexOutOfBoundsException( String.format("Array length=%d, index=%d, limit=%d", bytes.length, index, limit)); } long offset = index; final long offsetLimit = limit; if (state != COMPLETE) { // The previous decoding operation was incomplete (or malformed). // We look for a well-formed sequence consisting of bytes from // the previous decoding operation (stored in state) together // with bytes from the array slice. // // We expect such "straddler characters" to be rare. if (offset >= offsetLimit) { // No bytes? No progress. return state; } int byte1 = (byte) state; // byte1 is never ASCII. if (byte1 < (byte) 0xE0) { // two-byte form // Simultaneously checks for illegal trailing-byte in // leading position and overlong 2-byte form. if (byte1 < (byte) 0xC2 // byte2 trailing-byte test || UnsafeUtil.getByte(bytes, offset++) > (byte) 0xBF) { return MALFORMED; } } else if (byte1 < (byte) 0xF0) { // three-byte form // Get byte2 from saved state or array int byte2 = (byte) ~(state >> 8); if (byte2 == 0) { byte2 = UnsafeUtil.getByte(bytes, offset++); if (offset >= offsetLimit) { return incompleteStateFor(byte1, byte2); } } if (byte2 > (byte) 0xBF // overlong? 5 most significant bits must not all be zero || (byte1 == (byte) 0xE0 && byte2 < (byte) 0xA0) // illegal surrogate codepoint? || (byte1 == (byte) 0xED && byte2 >= (byte) 0xA0) // byte3 trailing-byte test || UnsafeUtil.getByte(bytes, offset++) > (byte) 0xBF) { return MALFORMED; } } else { // four-byte form // Get byte2 and byte3 from saved state or array int byte2 = (byte) ~(state >> 8); int byte3 = 0; if (byte2 == 0) { byte2 = UnsafeUtil.getByte(bytes, offset++); if (offset >= offsetLimit) { return incompleteStateFor(byte1, byte2); } } else { byte3 = (byte) (state >> 16); } if (byte3 == 0) { byte3 = UnsafeUtil.getByte(bytes, offset++); if (offset >= offsetLimit) { return incompleteStateFor(byte1, byte2, byte3); } } // If we were called with state == MALFORMED, then byte1 is 0xFF, // which never occurs in well-formed UTF-8, and so we will return // MALFORMED again below. if (byte2 > (byte) 0xBF // Check that 1 <= plane <= 16. Tricky optimized form of: // if (byte1 > (byte) 0xF4 || // byte1 == (byte) 0xF0 && byte2 < (byte) 0x90 || // byte1 == (byte) 0xF4 && byte2 > (byte) 0x8F) || (((byte1 << 28) + (byte2 - (byte) 0x90)) >> 30) != 0 // byte3 trailing-byte test || byte3 > (byte) 0xBF // byte4 trailing-byte test || UnsafeUtil.getByte(bytes, offset++) > (byte) 0xBF) { return MALFORMED; } } } return partialIsValidUtf8(bytes, offset, (int) (offsetLimit - offset)); } @Override int partialIsValidUtf8Direct( final int state, ByteBuffer buffer, final int index, final int limit) { // Bitwise OR combines the sign bits so any negative value fails the check. if ((index | limit | buffer.limit() - limit) < 0) { throw new ArrayIndexOutOfBoundsException( String.format("buffer limit=%d, index=%d, limit=%d", buffer.limit(), index, limit)); } long address = addressOffset(buffer) + index; final long addressLimit = address + (limit - index); if (state != COMPLETE) { // The previous decoding operation was incomplete (or malformed). // We look for a well-formed sequence consisting of bytes from // the previous decoding operation (stored in state) together // with bytes from the array slice. // // We expect such "straddler characters" to be rare. if (address >= addressLimit) { // No bytes? No progress. return state; } final int byte1 = (byte) state; // byte1 is never ASCII. if (byte1 < (byte) 0xE0) { // two-byte form // Simultaneously checks for illegal trailing-byte in // leading position and overlong 2-byte form. if (byte1 < (byte) 0xC2 // byte2 trailing-byte test || UnsafeUtil.getByte(address++) > (byte) 0xBF) { return MALFORMED; } } else if (byte1 < (byte) 0xF0) { // three-byte form // Get byte2 from saved state or array int byte2 = (byte) ~(state >> 8); if (byte2 == 0) { byte2 = UnsafeUtil.getByte(address++); if (address >= addressLimit) { return incompleteStateFor(byte1, byte2); } } if (byte2 > (byte) 0xBF // overlong? 5 most significant bits must not all be zero || (byte1 == (byte) 0xE0 && byte2 < (byte) 0xA0) // illegal surrogate codepoint? || (byte1 == (byte) 0xED && byte2 >= (byte) 0xA0) // byte3 trailing-byte test || UnsafeUtil.getByte(address++) > (byte) 0xBF) { return MALFORMED; } } else { // four-byte form // Get byte2 and byte3 from saved state or array int byte2 = (byte) ~(state >> 8); int byte3 = 0; if (byte2 == 0) { byte2 = UnsafeUtil.getByte(address++); if (address >= addressLimit) { return incompleteStateFor(byte1, byte2); } } else { byte3 = (byte) (state >> 16); } if (byte3 == 0) { byte3 = UnsafeUtil.getByte(address++); if (address >= addressLimit) { return incompleteStateFor(byte1, byte2, byte3); } } // If we were called with state == MALFORMED, then byte1 is 0xFF, // which never occurs in well-formed UTF-8, and so we will return // MALFORMED again below. if (byte2 > (byte) 0xBF // Check that 1 <= plane <= 16. Tricky optimized form of: // if (byte1 > (byte) 0xF4 || // byte1 == (byte) 0xF0 && byte2 < (byte) 0x90 || // byte1 == (byte) 0xF4 && byte2 > (byte) 0x8F) || (((byte1 << 28) + (byte2 - (byte) 0x90)) >> 30) != 0 // byte3 trailing-byte test || byte3 > (byte) 0xBF // byte4 trailing-byte test || UnsafeUtil.getByte(address++) > (byte) 0xBF) { return MALFORMED; } } } return partialIsValidUtf8(address, (int) (addressLimit - address)); } @Override String decodeUtf8(byte[] bytes, int index, int size) throws InvalidProtocolBufferException { String s = new String(bytes, index, size, Internal.UTF_8); // '\uFFFD' is the UTF-8 default replacement char, which illegal byte sequences get replaced // with. if (s.indexOf('\uFFFD') < 0) { return s; } // Since s contains '\uFFFD' there are 2 options: // 1) The byte array slice is invalid UTF-8. // 2) The byte array slice is valid UTF-8 and contains encodings for "\uFFFD". // To rule out (1), we encode s and compare it to the byte array slice. // If the byte array slice was invalid UTF-8, then we would get a different sequence of bytes. if (Arrays.equals( s.getBytes(Internal.UTF_8), Arrays.copyOfRange(bytes, index, index + size))) { return s; } throw InvalidProtocolBufferException.invalidUtf8(); } @Override String decodeUtf8Direct(ByteBuffer buffer, int index, int size) throws InvalidProtocolBufferException { // Bitwise OR combines the sign bits so any negative value fails the check. if ((index | size | buffer.limit() - index - size) < 0) { throw new ArrayIndexOutOfBoundsException( String.format("buffer limit=%d, index=%d, limit=%d", buffer.limit(), index, size)); } long address = UnsafeUtil.addressOffset(buffer) + index; final long addressLimit = address + size; // The longest possible resulting String is the same as the number of input bytes, when it is // all ASCII. For other cases, this over-allocates and we will truncate in the end. char[] resultArr = new char[size]; int resultPos = 0; // Optimize for 100% ASCII (Hotspot loves small simple top-level loops like this). // This simple loop stops when we encounter a byte >= 0x80 (i.e. non-ASCII). while (address < addressLimit) { byte b = UnsafeUtil.getByte(address); if (!DecodeUtil.isOneByte(b)) { break; } address++; DecodeUtil.handleOneByte(b, resultArr, resultPos++); } while (address < addressLimit) { byte byte1 = UnsafeUtil.getByte(address++); if (DecodeUtil.isOneByte(byte1)) { DecodeUtil.handleOneByte(byte1, resultArr, resultPos++); // It's common for there to be multiple ASCII characters in a run mixed in, so add an // extra optimized loop to take care of these runs. while (address < addressLimit) { byte b = UnsafeUtil.getByte(address); if (!DecodeUtil.isOneByte(b)) { break; } address++; DecodeUtil.handleOneByte(b, resultArr, resultPos++); } } else if (DecodeUtil.isTwoBytes(byte1)) { if (address >= addressLimit) { throw InvalidProtocolBufferException.invalidUtf8(); } DecodeUtil.handleTwoBytes( byte1, /* byte2 */ UnsafeUtil.getByte(address++), resultArr, resultPos++); } else if (DecodeUtil.isThreeBytes(byte1)) { if (address >= addressLimit - 1) { throw InvalidProtocolBufferException.invalidUtf8(); } DecodeUtil.handleThreeBytes( byte1, /* byte2 */ UnsafeUtil.getByte(address++), /* byte3 */ UnsafeUtil.getByte(address++), resultArr, resultPos++); } else { if (address >= addressLimit - 2) { throw InvalidProtocolBufferException.invalidUtf8(); } DecodeUtil.handleFourBytes( byte1, /* byte2 */ UnsafeUtil.getByte(address++), /* byte3 */ UnsafeUtil.getByte(address++), /* byte4 */ UnsafeUtil.getByte(address++), resultArr, resultPos++); // 4-byte case requires two chars. resultPos++; } } return new String(resultArr, 0, resultPos); } @Override int encodeUtf8(final String in, final byte[] out, final int offset, final int length) { long outIx = offset; final long outLimit = outIx + length; final int inLimit = in.length(); if (inLimit > length || out.length - length < offset) { // Not even enough room for an ASCII-encoded string. throw new ArrayIndexOutOfBoundsException( "Failed writing " + in.charAt(inLimit - 1) + " at index " + (offset + length)); } // Designed to take advantage of // https://wiki.openjdk.java.net/display/HotSpotInternals/RangeCheckElimination int inIx = 0; for (char c; inIx < inLimit && (c = in.charAt(inIx)) < 0x80; ++inIx) { UnsafeUtil.putByte(out, outIx++, (byte) c); } if (inIx == inLimit) { // We're done, it was ASCII encoded. return (int) outIx; } for (char c; inIx < inLimit; ++inIx) { c = in.charAt(inIx); if (c < 0x80 && outIx < outLimit) { UnsafeUtil.putByte(out, outIx++, (byte) c); } else if (c < 0x800 && outIx <= outLimit - 2L) { // 11 bits, two UTF-8 bytes UnsafeUtil.putByte(out, outIx++, (byte) ((0xF << 6) | (c >>> 6))); UnsafeUtil.putByte(out, outIx++, (byte) (0x80 | (0x3F & c))); } else if ((c < MIN_SURROGATE || MAX_SURROGATE < c) && outIx <= outLimit - 3L) { // Maximum single-char code point is 0xFFFF, 16 bits, three UTF-8 bytes UnsafeUtil.putByte(out, outIx++, (byte) ((0xF << 5) | (c >>> 12))); UnsafeUtil.putByte(out, outIx++, (byte) (0x80 | (0x3F & (c >>> 6)))); UnsafeUtil.putByte(out, outIx++, (byte) (0x80 | (0x3F & c))); } else if (outIx <= outLimit - 4L) { // Minimum code point represented by a surrogate pair is 0x10000, 17 bits, four UTF-8 // bytes final char low; if (inIx + 1 == inLimit || !isSurrogatePair(c, (low = in.charAt(++inIx)))) { throw new UnpairedSurrogateException((inIx - 1), inLimit); } int codePoint = toCodePoint(c, low); UnsafeUtil.putByte(out, outIx++, (byte) ((0xF << 4) | (codePoint >>> 18))); UnsafeUtil.putByte(out, outIx++, (byte) (0x80 | (0x3F & (codePoint >>> 12)))); UnsafeUtil.putByte(out, outIx++, (byte) (0x80 | (0x3F & (codePoint >>> 6)))); UnsafeUtil.putByte(out, outIx++, (byte) (0x80 | (0x3F & codePoint))); } else { if ((MIN_SURROGATE <= c && c <= MAX_SURROGATE) && (inIx + 1 == inLimit || !isSurrogatePair(c, in.charAt(inIx + 1)))) { // We are surrogates and we're not a surrogate pair. throw new UnpairedSurrogateException(inIx, inLimit); } // Not enough space in the output buffer. throw new ArrayIndexOutOfBoundsException("Failed writing " + c + " at index " + outIx); } } // All bytes have been encoded. return (int) outIx; } @Override void encodeUtf8Direct(String in, ByteBuffer out) { final long address = addressOffset(out); long outIx = address + out.position(); final long outLimit = address + out.limit(); final int inLimit = in.length(); if (inLimit > outLimit - outIx) { // Not even enough room for an ASCII-encoded string. throw new ArrayIndexOutOfBoundsException( "Failed writing " + in.charAt(inLimit - 1) + " at index " + out.limit()); } // Designed to take advantage of // https://wiki.openjdk.java.net/display/HotSpotInternals/RangeCheckElimination int inIx = 0; for (char c; inIx < inLimit && (c = in.charAt(inIx)) < 0x80; ++inIx) { UnsafeUtil.putByte(outIx++, (byte) c); } if (inIx == inLimit) { // We're done, it was ASCII encoded. Java8Compatibility.position(out, (int) (outIx - address)); return; } for (char c; inIx < inLimit; ++inIx) { c = in.charAt(inIx); if (c < 0x80 && outIx < outLimit) { UnsafeUtil.putByte(outIx++, (byte) c); } else if (c < 0x800 && outIx <= outLimit - 2L) { // 11 bits, two UTF-8 bytes UnsafeUtil.putByte(outIx++, (byte) ((0xF << 6) | (c >>> 6))); UnsafeUtil.putByte(outIx++, (byte) (0x80 | (0x3F & c))); } else if ((c < MIN_SURROGATE || MAX_SURROGATE < c) && outIx <= outLimit - 3L) { // Maximum single-char code point is 0xFFFF, 16 bits, three UTF-8 bytes UnsafeUtil.putByte(outIx++, (byte) ((0xF << 5) | (c >>> 12))); UnsafeUtil.putByte(outIx++, (byte) (0x80 | (0x3F & (c >>> 6)))); UnsafeUtil.putByte(outIx++, (byte) (0x80 | (0x3F & c))); } else if (outIx <= outLimit - 4L) { // Minimum code point represented by a surrogate pair is 0x10000, 17 bits, four UTF-8 // bytes final char low; if (inIx + 1 == inLimit || !isSurrogatePair(c, (low = in.charAt(++inIx)))) { throw new UnpairedSurrogateException((inIx - 1), inLimit); } int codePoint = toCodePoint(c, low); UnsafeUtil.putByte(outIx++, (byte) ((0xF << 4) | (codePoint >>> 18))); UnsafeUtil.putByte(outIx++, (byte) (0x80 | (0x3F & (codePoint >>> 12)))); UnsafeUtil.putByte(outIx++, (byte) (0x80 | (0x3F & (codePoint >>> 6)))); UnsafeUtil.putByte(outIx++, (byte) (0x80 | (0x3F & codePoint))); } else { if ((MIN_SURROGATE <= c && c <= MAX_SURROGATE) && (inIx + 1 == inLimit || !isSurrogatePair(c, in.charAt(inIx + 1)))) { // We are surrogates and we're not a surrogate pair. throw new UnpairedSurrogateException(inIx, inLimit); } // Not enough space in the output buffer. throw new ArrayIndexOutOfBoundsException("Failed writing " + c + " at index " + outIx); } } // All bytes have been encoded. Java8Compatibility.position(out, (int) (outIx - address)); } /** * Counts (approximately) the number of consecutive ASCII characters starting from the given * position, using the most efficient method available to the platform. * * @param bytes the array containing the character sequence * @param offset the offset position of the index (same as index + arrayBaseOffset) * @param maxChars the maximum number of characters to count * @return the number of ASCII characters found. The stopping position will be at or before the * first non-ASCII byte. */ private static int unsafeEstimateConsecutiveAscii( byte[] bytes, long offset, final int maxChars) { if (maxChars < UNSAFE_COUNT_ASCII_THRESHOLD) { // Don't bother with small strings. return 0; } // Read bytes until 8-byte aligned so that we can read longs in the loop below. // Byte arrays are already either 8 or 16-byte aligned, so we just need to make sure that // the index (relative to the start of the array) is also 8-byte aligned. We do this by // ANDing the index with 7 to determine the number of bytes that need to be read before // we're 8-byte aligned. final int unaligned = 8 - ((int) offset & 7); int i; for (i = 0; i < unaligned; i++) { if (UnsafeUtil.getByte(bytes, offset++) < 0) { return i; } } for (; i + 8 <= maxChars; i += 8) { if ((UnsafeUtil.getLong(bytes, UnsafeUtil.BYTE_ARRAY_BASE_OFFSET + offset) & ASCII_MASK_LONG) != 0L) { break; } offset += 8; } for (; i < maxChars; i++) { if (UnsafeUtil.getByte(bytes, offset++) < 0) { return i; } } return maxChars; } /** * Same as {@link Utf8#estimateConsecutiveAscii(ByteBuffer, int, int)} except that it uses the * most efficient method available to the platform. */ private static int unsafeEstimateConsecutiveAscii(long address, final int maxChars) { int remaining = maxChars; if (remaining < UNSAFE_COUNT_ASCII_THRESHOLD) { // Don't bother with small strings. return 0; } // Read bytes until 8-byte aligned so that we can read longs in the loop below. // This is equivalent to (8-address) mod 8, the number of bytes we need to read before we're // 8-byte aligned. final int unaligned = (int) (-address & 7); for (int j = unaligned; j > 0; j--) { if (UnsafeUtil.getByte(address++) < 0) { return unaligned - j; } } // This simple loop stops when we encounter a byte >= 0x80 (i.e. non-ASCII). // To speed things up further, we're reading longs instead of bytes so we use a mask to // determine if any byte in the current long is non-ASCII. remaining -= unaligned; for (; remaining >= 8 && (UnsafeUtil.getLong(address) & ASCII_MASK_LONG) == 0; address += 8, remaining -= 8) {} return maxChars - remaining; } private static int partialIsValidUtf8(final byte[] bytes, long offset, int remaining) { // Skip past ASCII characters as quickly as possible. final int skipped = unsafeEstimateConsecutiveAscii(bytes, offset, remaining); remaining -= skipped; offset += skipped; for (; ; ) { // Optimize for interior runs of ASCII bytes. // TODO: Consider checking 8 bytes at a time after some threshold? // Maybe after seeing a few in a row that are ASCII, go back to fast mode? int byte1 = 0; for (; remaining > 0 && (byte1 = UnsafeUtil.getByte(bytes, offset++)) >= 0; --remaining) {} if (remaining == 0) { return COMPLETE; } remaining--; // If we're here byte1 is not ASCII. Only need to handle 2-4 byte forms. if (byte1 < (byte) 0xE0) { // Two-byte form (110xxxxx 10xxxxxx) if (remaining == 0) { // Incomplete sequence return byte1; } remaining--; // Simultaneously checks for illegal trailing-byte in // leading position and overlong 2-byte form. if (byte1 < (byte) 0xC2 || UnsafeUtil.getByte(bytes, offset++) > (byte) 0xBF) { return MALFORMED; } } else if (byte1 < (byte) 0xF0) { // Three-byte form (1110xxxx 10xxxxxx 10xxxxxx) if (remaining < 2) { // Incomplete sequence return unsafeIncompleteStateFor(bytes, byte1, offset, remaining); } remaining -= 2; final int byte2; if ((byte2 = UnsafeUtil.getByte(bytes, offset++)) > (byte) 0xBF // overlong? 5 most significant bits must not all be zero || (byte1 == (byte) 0xE0 && byte2 < (byte) 0xA0) // check for illegal surrogate codepoints || (byte1 == (byte) 0xED && byte2 >= (byte) 0xA0) // byte3 trailing-byte test || UnsafeUtil.getByte(bytes, offset++) > (byte) 0xBF) { return MALFORMED; } } else { // Four-byte form (1110xxxx 10xxxxxx 10xxxxxx 10xxxxxx) if (remaining < 3) { // Incomplete sequence return unsafeIncompleteStateFor(bytes, byte1, offset, remaining); } remaining -= 3; final int byte2; if ((byte2 = UnsafeUtil.getByte(bytes, offset++)) > (byte) 0xBF // Check that 1 <= plane <= 16. Tricky optimized form of: // if (byte1 > (byte) 0xF4 || // byte1 == (byte) 0xF0 && byte2 < (byte) 0x90 || // byte1 == (byte) 0xF4 && byte2 > (byte) 0x8F) || (((byte1 << 28) + (byte2 - (byte) 0x90)) >> 30) != 0 // byte3 trailing-byte test || UnsafeUtil.getByte(bytes, offset++) > (byte) 0xBF // byte4 trailing-byte test || UnsafeUtil.getByte(bytes, offset++) > (byte) 0xBF) { return MALFORMED; } } } } private static int partialIsValidUtf8(long address, int remaining) { // Skip past ASCII characters as quickly as possible. final int skipped = unsafeEstimateConsecutiveAscii(address, remaining); address += skipped; remaining -= skipped; for (; ; ) { // Optimize for interior runs of ASCII bytes. // TODO: Consider checking 8 bytes at a time after some threshold? // Maybe after seeing a few in a row that are ASCII, go back to fast mode? int byte1 = 0; for (; remaining > 0 && (byte1 = UnsafeUtil.getByte(address++)) >= 0; --remaining) {} if (remaining == 0) { return COMPLETE; } remaining--; if (byte1 < (byte) 0xE0) { // Two-byte form if (remaining == 0) { // Incomplete sequence return byte1; } remaining--; // Simultaneously checks for illegal trailing-byte in // leading position and overlong 2-byte form. if (byte1 < (byte) 0xC2 || UnsafeUtil.getByte(address++) > (byte) 0xBF) { return MALFORMED; } } else if (byte1 < (byte) 0xF0) { // Three-byte form if (remaining < 2) { // Incomplete sequence return unsafeIncompleteStateFor(address, byte1, remaining); } remaining -= 2; final byte byte2 = UnsafeUtil.getByte(address++); if (byte2 > (byte) 0xBF // overlong? 5 most significant bits must not all be zero || (byte1 == (byte) 0xE0 && byte2 < (byte) 0xA0) // check for illegal surrogate codepoints || (byte1 == (byte) 0xED && byte2 >= (byte) 0xA0) // byte3 trailing-byte test || UnsafeUtil.getByte(address++) > (byte) 0xBF) { return MALFORMED; } } else { // Four-byte form if (remaining < 3) { // Incomplete sequence return unsafeIncompleteStateFor(address, byte1, remaining); } remaining -= 3; final byte byte2 = UnsafeUtil.getByte(address++); if (byte2 > (byte) 0xBF // Check that 1 <= plane <= 16. Tricky optimized form of: // if (byte1 > (byte) 0xF4 || // byte1 == (byte) 0xF0 && byte2 < (byte) 0x90 || // byte1 == (byte) 0xF4 && byte2 > (byte) 0x8F) || (((byte1 << 28) + (byte2 - (byte) 0x90)) >> 30) != 0 // byte3 trailing-byte test || UnsafeUtil.getByte(address++) > (byte) 0xBF // byte4 trailing-byte test || UnsafeUtil.getByte(address++) > (byte) 0xBF) { return MALFORMED; } } } } private static int unsafeIncompleteStateFor( byte[] bytes, int byte1, long offset, int remaining) { switch (remaining) { case 0: return incompleteStateFor(byte1); case 1: return incompleteStateFor(byte1, UnsafeUtil.getByte(bytes, offset)); case 2: return incompleteStateFor( byte1, UnsafeUtil.getByte(bytes, offset), UnsafeUtil.getByte(bytes, offset + 1)); default: throw new AssertionError(); } } private static int unsafeIncompleteStateFor(long address, final int byte1, int remaining) { switch (remaining) { case 0: return incompleteStateFor(byte1); case 1: return incompleteStateFor(byte1, UnsafeUtil.getByte(address)); case 2: return incompleteStateFor( byte1, UnsafeUtil.getByte(address), UnsafeUtil.getByte(address + 1)); default: throw new AssertionError(); } } } /** * Utility methods for decoding bytes into {@link String}. Callers are responsible for extracting * bytes (possibly using Unsafe methods), and checking remaining bytes. All other UTF-8 validity * checks and codepoint conversion happen in this class. */ private static class DecodeUtil { /** Returns whether this is a single-byte codepoint (i.e., ASCII) with the form '0XXXXXXX'. */ private static boolean isOneByte(byte b) { return b >= 0; } /** * Returns whether this is a two-byte codepoint with the form '10XXXXXX' iff * {@link #isOneByte(byte)} is false. This private method works in the limited use in * this class where this method is only called when {@link #isOneByte(byte)} has already * returned false. It is not suitable for general or public use. */ private static boolean isTwoBytes(byte b) { return b < (byte) 0xE0; } /** * Returns whether this is a three-byte codepoint with the form '110XXXXX' iff * {@link #isOneByte(byte)} and {@link #isTwoBytes(byte)} are false. * This private method works in the limited use in * this class where this method is only called when {@link #isOneByte(byte)} an * {@link #isTwoBytes(byte)} have already returned false. It is not suitable for general * or public use. */ private static boolean isThreeBytes(byte b) { return b < (byte) 0xF0; } private static void handleOneByte(byte byte1, char[] resultArr, int resultPos) { resultArr[resultPos] = (char) byte1; } private static void handleTwoBytes(byte byte1, byte byte2, char[] resultArr, int resultPos) throws InvalidProtocolBufferException { // Simultaneously checks for illegal trailing-byte in leading position (<= '11000000') and // overlong 2-byte, '11000001'. if (byte1 < (byte) 0xC2 || isNotTrailingByte(byte2)) { throw InvalidProtocolBufferException.invalidUtf8(); } resultArr[resultPos] = (char) (((byte1 & 0x1F) << 6) | trailingByteValue(byte2)); } private static void handleThreeBytes( byte byte1, byte byte2, byte byte3, char[] resultArr, int resultPos) throws InvalidProtocolBufferException { if (isNotTrailingByte(byte2) // overlong? 5 most significant bits must not all be zero || (byte1 == (byte) 0xE0 && byte2 < (byte) 0xA0) // check for illegal surrogate codepoints || (byte1 == (byte) 0xED && byte2 >= (byte) 0xA0) || isNotTrailingByte(byte3)) { throw InvalidProtocolBufferException.invalidUtf8(); } resultArr[resultPos] = (char) (((byte1 & 0x0F) << 12) | (trailingByteValue(byte2) << 6) | trailingByteValue(byte3)); } private static void handleFourBytes( byte byte1, byte byte2, byte byte3, byte byte4, char[] resultArr, int resultPos) throws InvalidProtocolBufferException { if (isNotTrailingByte(byte2) // Check that 1 <= plane <= 16. Tricky optimized form of: // valid 4-byte leading byte? // if (byte1 > (byte) 0xF4 || // overlong? 4 most significant bits must not all be zero // byte1 == (byte) 0xF0 && byte2 < (byte) 0x90 || // codepoint larger than the highest code point (U+10FFFF)? // byte1 == (byte) 0xF4 && byte2 > (byte) 0x8F) || (((byte1 << 28) + (byte2 - (byte) 0x90)) >> 30) != 0 || isNotTrailingByte(byte3) || isNotTrailingByte(byte4)) { throw InvalidProtocolBufferException.invalidUtf8(); } int codepoint = ((byte1 & 0x07) << 18) | (trailingByteValue(byte2) << 12) | (trailingByteValue(byte3) << 6) | trailingByteValue(byte4); resultArr[resultPos] = DecodeUtil.highSurrogate(codepoint); resultArr[resultPos + 1] = DecodeUtil.lowSurrogate(codepoint); } /** Returns whether the byte is not a valid continuation of the form '10XXXXXX'. */ private static boolean isNotTrailingByte(byte b) { return b > (byte) 0xBF; } /** Returns the actual value of the trailing byte (removes the prefix '10') for composition. */ private static int trailingByteValue(byte b) { return b & 0x3F; } private static char highSurrogate(int codePoint) { return (char) ((MIN_HIGH_SURROGATE - (MIN_SUPPLEMENTARY_CODE_POINT >>> 10)) + (codePoint >>> 10)); } private static char lowSurrogate(int codePoint) { return (char) (MIN_LOW_SURROGATE + (codePoint & 0x3ff)); } } private Utf8() {} }
protocolbuffers/protobuf
java/core/src/main/java/com/google/protobuf/Utf8.java
64
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file or at // https://developers.google.com/open-source/licenses/bsd package com.google.protobuf; import static com.google.protobuf.Internal.checkNotNull; import com.google.protobuf.Internal.LongList; import java.util.Arrays; import java.util.Collection; import java.util.RandomAccess; /** * An implementation of {@link LongList} on top of a primitive array. * * @author dweis@google.com (Daniel Weis) */ final class LongArrayList extends AbstractProtobufList<Long> implements LongList, RandomAccess, PrimitiveNonBoxingCollection { private static final LongArrayList EMPTY_LIST = new LongArrayList(new long[0], 0, false); public static LongArrayList emptyList() { return EMPTY_LIST; } /** The backing store for the list. */ private long[] array; /** * The size of the list distinct from the length of the array. That is, it is the number of * elements set in the list. */ private int size; /** Constructs a new mutable {@code LongArrayList} with default capacity. */ LongArrayList() { this(new long[DEFAULT_CAPACITY], 0, true); } /** * Constructs a new mutable {@code LongArrayList} containing the same elements as {@code other}. */ private LongArrayList(long[] other, int size, boolean isMutable) { super(isMutable); this.array = other; this.size = size; } @Override protected void removeRange(int fromIndex, int toIndex) { ensureIsMutable(); if (toIndex < fromIndex) { throw new IndexOutOfBoundsException("toIndex < fromIndex"); } System.arraycopy(array, toIndex, array, fromIndex, size - toIndex); size -= (toIndex - fromIndex); modCount++; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof LongArrayList)) { return super.equals(o); } LongArrayList other = (LongArrayList) o; if (size != other.size) { return false; } final long[] arr = other.array; for (int i = 0; i < size; i++) { if (array[i] != arr[i]) { return false; } } return true; } @Override public int hashCode() { int result = 1; for (int i = 0; i < size; i++) { result = (31 * result) + Internal.hashLong(array[i]); } return result; } @Override public LongList mutableCopyWithCapacity(int capacity) { if (capacity < size) { throw new IllegalArgumentException(); } return new LongArrayList(Arrays.copyOf(array, capacity), size, true); } @Override public Long get(int index) { return getLong(index); } @Override public long getLong(int index) { ensureIndexInRange(index); return array[index]; } @Override public int indexOf(Object element) { if (!(element instanceof Long)) { return -1; } long unboxedElement = (Long) element; int numElems = size(); for (int i = 0; i < numElems; i++) { if (array[i] == unboxedElement) { return i; } } return -1; } @Override public boolean contains(Object element) { return indexOf(element) != -1; } @Override public int size() { return size; } @Override public Long set(int index, Long element) { return setLong(index, element); } @Override public long setLong(int index, long element) { ensureIsMutable(); ensureIndexInRange(index); long previousValue = array[index]; array[index] = element; return previousValue; } @Override public boolean add(Long element) { addLong(element); return true; } @Override public void add(int index, Long element) { addLong(index, element); } /** Like {@link #add(Long)} but more efficient in that it doesn't box the element. */ @Override public void addLong(long element) { ensureIsMutable(); if (size == array.length) { // Resize to 1.5x the size int length = ((size * 3) / 2) + 1; long[] newArray = new long[length]; System.arraycopy(array, 0, newArray, 0, size); array = newArray; } array[size++] = element; } /** Like {@link #add(int, Long)} but more efficient in that it doesn't box the element. */ private void addLong(int index, long element) { ensureIsMutable(); if (index < 0 || index > size) { throw new IndexOutOfBoundsException(makeOutOfBoundsExceptionMessage(index)); } if (size < array.length) { // Shift everything over to make room System.arraycopy(array, index, array, index + 1, size - index); } else { // Resize to 1.5x the size int length = ((size * 3) / 2) + 1; long[] newArray = new long[length]; // Copy the first part directly System.arraycopy(array, 0, newArray, 0, index); // Copy the rest shifted over by one to make room System.arraycopy(array, index, newArray, index + 1, size - index); array = newArray; } array[index] = element; size++; modCount++; } @Override public boolean addAll(Collection<? extends Long> collection) { ensureIsMutable(); checkNotNull(collection); // We specialize when adding another LongArrayList to avoid boxing elements. if (!(collection instanceof LongArrayList)) { return super.addAll(collection); } LongArrayList list = (LongArrayList) collection; if (list.size == 0) { return false; } int overflow = Integer.MAX_VALUE - size; if (overflow < list.size) { // We can't actually represent a list this large. throw new OutOfMemoryError(); } int newSize = size + list.size; if (newSize > array.length) { array = Arrays.copyOf(array, newSize); } System.arraycopy(list.array, 0, array, size, list.size); size = newSize; modCount++; return true; } @Override public Long remove(int index) { ensureIsMutable(); ensureIndexInRange(index); long value = array[index]; if (index < size - 1) { System.arraycopy(array, index + 1, array, index, size - index - 1); } size--; modCount++; return value; } /** * Ensures that the provided {@code index} is within the range of {@code [0, size]}. Throws an * {@link IndexOutOfBoundsException} if it is not. * * @param index the index to verify is in range */ private void ensureIndexInRange(int index) { if (index < 0 || index >= size) { throw new IndexOutOfBoundsException(makeOutOfBoundsExceptionMessage(index)); } } private String makeOutOfBoundsExceptionMessage(int index) { return "Index:" + index + ", Size:" + size; } }
protocolbuffers/protobuf
java/core/src/main/java/com/google/protobuf/LongArrayList.java
65
// Copyright 2000-2024 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.diagnostic; import org.jetbrains.annotations.ApiStatus.Internal; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; @Internal public interface Activity { @NotNull String getName(); void end(); void setDescription(@NonNls @NotNull String description); /** * Convenient method to end token and start a new sibling one. * So, start of new is always equals to this item end and yet another System.nanoTime() call is avoided. */ @NotNull Activity endAndStart(@NonNls @NotNull String name); @NotNull Activity startChild(@NonNls @NotNull String name); }
JetBrains/intellij-community
platform/diagnostic/src/Activity.java
66
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file or at // https://developers.google.com/open-source/licenses/bsd package com.google.protobuf; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * Abstract interface implemented by Protocol Message objects. * * <p>This interface is implemented by all protocol message objects. Non-lite messages additionally * implement the Message interface, which is a subclass of MessageLite. Use MessageLite instead when * you only need the subset of features which it supports -- namely, nothing that uses descriptors * or reflection. You can instruct the protocol compiler to generate classes which implement only * MessageLite, not the full Message interface, by adding the follow line to the .proto file: * * <pre> * option optimize_for = LITE_RUNTIME; * </pre> * * <p>This is particularly useful on resource-constrained systems where the full protocol buffers * runtime library is too big. * * <p>Note that on non-constrained systems (e.g. servers) when you need to link in lots of protocol * definitions, a better way to reduce total code footprint is to use {@code optimize_for = * CODE_SIZE}. This will make the generated code smaller while still supporting all the same * features (at the expense of speed). {@code optimize_for = LITE_RUNTIME} is best when you only * have a small number of message types linked into your binary, in which case the size of the * protocol buffers runtime itself is the biggest problem. * * @author kenton@google.com Kenton Varda */ @CheckReturnValue public interface MessageLite extends MessageLiteOrBuilder { /** * Serializes the message and writes it to {@code output}. This does not flush or close the * stream. */ void writeTo(CodedOutputStream output) throws IOException; /** * Get the number of bytes required to encode this message. The result is only computed on the * first call and memoized after that. * * If this message requires more than Integer.MAX_VALUE bytes to encode, the return value will * be smaller than the actual number of bytes required and might be negative. */ int getSerializedSize(); /** Gets the parser for a message of the same type as this message. */ Parser<? extends MessageLite> getParserForType(); // ----------------------------------------------------------------- // Convenience methods. /** * Serializes the message to a {@code ByteString} and returns it. This is just a trivial wrapper * around {@link #writeTo(CodedOutputStream)}. * * If this message requires more than Integer.MAX_VALUE bytes to encode, the behavior is * unpredictable. It may throw a runtime exception or truncate or slice the data. */ ByteString toByteString(); /** * Serializes the message to a {@code byte} array and returns it. This is just a trivial wrapper * around {@link #writeTo(CodedOutputStream)}. * * If this message requires more than Integer.MAX_VALUE bytes to encode, the behavior is * unpredictable. It may throw a runtime exception or truncate or slice the data. */ byte[] toByteArray(); /** * Serializes the message and writes it to {@code output}. This is just a trivial wrapper around * {@link #writeTo(CodedOutputStream)}. This does not flush or close the stream. * * <p>NOTE: Protocol Buffers are not self-delimiting. Therefore, if you write any more data to the * stream after the message, you must somehow ensure that the parser on the receiving end does not * interpret this as being part of the protocol message. This can be done, for instance, by * writing the size of the message before the data, then making sure to limit the input to that * size on the receiving end by wrapping the InputStream in one which limits the input. * Alternatively, just use {@link #writeDelimitedTo(OutputStream)}. */ void writeTo(OutputStream output) throws IOException; /** * Like {@link #writeTo(OutputStream)}, but writes the size of the message as a varint before * writing the data. This allows more data to be written to the stream after the message without * the need to delimit the message data yourself. Use {@link * Builder#mergeDelimitedFrom(InputStream)} (or the static method {@code * YourMessageType.parseDelimitedFrom(InputStream)}) to parse messages written by this method. */ void writeDelimitedTo(OutputStream output) throws IOException; // ================================================================= // Builders /** Constructs a new builder for a message of the same type as this message. */ Builder newBuilderForType(); /** * Constructs a builder initialized with the current message. Use this to derive a new message * from the current one. */ Builder toBuilder(); /** Abstract interface implemented by Protocol Message builders. */ interface Builder extends MessageLiteOrBuilder, Cloneable { /** Resets all fields to their default values. */ @CanIgnoreReturnValue Builder clear(); /** * Constructs the message based on the state of the Builder. Subsequent changes to the Builder * will not affect the returned message. * * @throws UninitializedMessageException The message is missing one or more required fields * (i.e. {@link #isInitialized()} returns false). Use {@link #buildPartial()} to bypass this * check. */ MessageLite build(); /** * Like {@link #build()}, but does not throw an exception if the message is missing required * fields. Instead, a partial message is returned. Subsequent changes to the Builder will not * affect the returned message. */ MessageLite buildPartial(); /** * Clones the Builder. * * @see Object#clone() */ Builder clone(); /** * Parses a message of this type from the input and merges it with this message. * * <p>Warning: This does not verify that all required fields are present in the input message. * If you call {@link #build()} without setting all required fields, it will throw an {@link * UninitializedMessageException}, which is a {@code RuntimeException} and thus might not be * caught. There are a few good ways to deal with this: * * <ul> * <li>Call {@link #isInitialized()} to verify that all required fields are set before * building. * <li>Use {@code buildPartial()} to build, which ignores missing required fields. * </ul> * * <p>Note: The caller should call {@link CodedInputStream#checkLastTagWas(int)} after calling * this to verify that the last tag seen was the appropriate end-group tag, or zero for EOF. * * @throws InvalidProtocolBufferException the bytes read are not syntactically correct according * to the protobuf wire format specification. The data is corrupt, incomplete, or was never * a protobuf in the first place. * @throws IOException an I/O error reading from the stream */ @CanIgnoreReturnValue Builder mergeFrom(CodedInputStream input) throws IOException; /** * Like {@link Builder#mergeFrom(CodedInputStream)}, but also parses extensions. The extensions * that you want to be able to parse must be registered in {@code extensionRegistry}. Extensions * not in the registry will be treated as unknown fields. * * @throws InvalidProtocolBufferException the bytes read are not syntactically correct according * to the protobuf wire format specification. The data is corrupt, incomplete, or was never * a protobuf in the first place. * @throws IOException an I/O error reading from the stream */ @CanIgnoreReturnValue Builder mergeFrom(CodedInputStream input, ExtensionRegistryLite extensionRegistry) throws IOException; // --------------------------------------------------------------- // Convenience methods. /** * Parse {@code data} as a message of this type and merge it with the message being built. This * is just a small wrapper around {@link #mergeFrom(CodedInputStream)}. * * @throws InvalidProtocolBufferException the bytes in data are not syntactically correct * according to the protobuf wire format specification. The data is corrupt, incomplete, or * was never a protobuf in the first place. * @return this */ @CanIgnoreReturnValue Builder mergeFrom(ByteString data) throws InvalidProtocolBufferException; /** * Parse {@code data} as a message of this type and merge it with the message being built. This * is just a small wrapper around {@link #mergeFrom(CodedInputStream,ExtensionRegistryLite)}. * * @throws InvalidProtocolBufferException the bytes in data are not syntactically correct * according to the protobuf wire format specification. The data is corrupt, incomplete, or * was never a protobuf in the first place. * @return this */ @CanIgnoreReturnValue Builder mergeFrom(ByteString data, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException; /** * Parse {@code data} as a message of this type and merge it with the message being built. This * is just a small wrapper around {@link #mergeFrom(CodedInputStream)}. * * @throws InvalidProtocolBufferException the bytes in data are not syntactically correct * according to the protobuf wire format specification. The data is corrupt, incomplete, or * was never a protobuf in the first place. * @return this */ @CanIgnoreReturnValue Builder mergeFrom(byte[] data) throws InvalidProtocolBufferException; /** * Parse {@code data} as a message of this type and merge it with the message being built. This * is just a small wrapper around {@link #mergeFrom(CodedInputStream)}. * * @throws InvalidProtocolBufferException the bytes in data are not syntactically correct * according to the protobuf wire format specification. The data is corrupt, incomplete, or * was never a protobuf in the first place. * @return this */ @CanIgnoreReturnValue Builder mergeFrom(byte[] data, int off, int len) throws InvalidProtocolBufferException; /** * Parse {@code data} as a message of this type and merge it with the message being built. This * is just a small wrapper around {@link #mergeFrom(CodedInputStream,ExtensionRegistryLite)}. * * @throws InvalidProtocolBufferException the bytes in data are not syntactically correct * according to the protobuf wire format specification. The data is corrupt, incomplete, or * was never a protobuf in the first place. * @return this */ @CanIgnoreReturnValue Builder mergeFrom(byte[] data, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException; /** * Parse {@code data} as a message of this type and merge it with the message being built. This * is just a small wrapper around {@link #mergeFrom(CodedInputStream,ExtensionRegistryLite)}. * * @throws InvalidProtocolBufferException the bytes in data are not syntactically correct * according to the protobuf wire format specification. The data is corrupt, incomplete, or * was never a protobuf in the first place. * @return this */ @CanIgnoreReturnValue Builder mergeFrom(byte[] data, int off, int len, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException; /** * Parse a message of this type from {@code input} and merge it with the message being built. * This is just a small wrapper around {@link #mergeFrom(CodedInputStream)}. Note that this * method always reads the <i>entire</i> input (unless it throws an exception). If you want it * to stop earlier, you will need to wrap your input in some wrapper stream that limits reading. * Or, use {@link MessageLite#writeDelimitedTo(OutputStream)} to write your message and {@link * #mergeDelimitedFrom(InputStream)} to read it. * * <p>Despite usually reading the entire input, this does not close the stream. * * @throws InvalidProtocolBufferException the bytes read are not syntactically correct according * to the protobuf wire format specification. The data is corrupt, incomplete, or was never * a protobuf in the first place. * @throws IOException an I/O error reading from the stream * @return this */ @CanIgnoreReturnValue Builder mergeFrom(InputStream input) throws IOException; /** * Parse a message of this type from {@code input} and merge it with the message being built. * This is just a small wrapper around {@link * #mergeFrom(CodedInputStream,ExtensionRegistryLite)}. * * @return this */ @CanIgnoreReturnValue Builder mergeFrom(InputStream input, ExtensionRegistryLite extensionRegistry) throws IOException; /** * Merge {@code other} into the message being built. {@code other} must have the exact same type * as {@code this} (i.e. {@code getClass().equals(getDefaultInstanceForType().getClass())}). * * <p>Merging occurs as follows. For each field:<br> * * For singular primitive fields, if the field is set in {@code other}, then {@code other}'s * value overwrites the value in this message.<br> * * For singular message fields, if the field is set in {@code other}, it is merged into the * corresponding sub-message of this message using the same merging rules.<br> * * For repeated fields, the elements in {@code other} are concatenated with the elements in * this message. * For oneof groups, if the other message has one of the fields set, the group * of this message is cleared and replaced by the field of the other message, so that the oneof * constraint is preserved. * * <p>This is equivalent to the {@code Message::MergeFrom} method in C++. */ @CanIgnoreReturnValue Builder mergeFrom(MessageLite other); /** * Like {@link #mergeFrom(InputStream)}, but does not read until EOF. Instead, the size of the * message (encoded as a varint) is read first, then the message data. Use {@link * MessageLite#writeDelimitedTo(OutputStream)} to write messages in this format. * * @return true if successful, or false if the stream is at EOF when the method starts. Any * other error (including reaching EOF during parsing) causes an exception to be thrown. * @throws InvalidProtocolBufferException the bytes read are not syntactically correct according * to the protobuf wire format specification. The data is corrupt, incomplete, or was never * a protobuf in the first place. * @throws IOException an I/O error reading from the stream */ boolean mergeDelimitedFrom(InputStream input) throws IOException; /** * Like {@link #mergeDelimitedFrom(InputStream)} but supporting extensions. * * @return true if successful, or false if the stream is at EOF when the method starts. Any * other error (including reaching EOF during parsing) causes an exception to be thrown. * @throws InvalidProtocolBufferException the bytes read are not syntactically correct according * to the protobuf wire format specification. The data is corrupt, incomplete, or was never * a protobuf in the first place. * @throws IOException an I/O error reading from the stream */ boolean mergeDelimitedFrom(InputStream input, ExtensionRegistryLite extensionRegistry) throws IOException; } }
protocolbuffers/protobuf
java/core/src/main/java/com/google/protobuf/MessageLite.java
67
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * Project Info: https://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * https://plantuml.com/patreon (only 1$ per month!) * https://plantuml.com/paypal * * This file is part of Smetana. * Smetana is a partial translation of Graphviz/Dot sources from C to Java. * * (C) Copyright 2009-2022, Arnaud Roques * * This translation is distributed under the same Licence as the original C program: * ************************************************************************* * Copyright (c) 2011 AT&T Intellectual Property * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: See CVS logs. Details at http://www.graphviz.org/ ************************************************************************* * * THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC * LICENSE ("AGREEMENT"). [Eclipse Public License - v 1.0] * * ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES * RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. * * You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * 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 h; import smetana.core.UnsupportedStarStruct; import smetana.core.__struct__; final public class ST_BestPos_t extends UnsupportedStarStruct { public int n; public double area; public final ST_pointf pos = new ST_pointf(); @Override public __struct__ copy() { final ST_BestPos_t result = new ST_BestPos_t(); result.n = this.n; result.area = this.area; result.pos.___((__struct__) this.pos); return result; } public void ___(__struct__ other) { ST_BestPos_t this2 = (ST_BestPos_t) other; this.n = this2.n; this.area = this2.area; this.pos.___((__struct__) this2.pos); } // typedef struct best_p_s { // int n; // double area; // pointf pos; // } BestPos_t; }
plantuml/plantuml
src/h/ST_BestPos_t.java
68
package com.thealgorithms.conversions; import java.util.Arrays; import java.util.HashSet; import java.util.InputMismatchException; import java.util.Scanner; /** * Class for converting from "any" base to "any" other base, when "any" means * from 2-36. Works by going from base 1 to decimal to base 2. Includes * auxiliary method for determining whether a number is valid for a given base. * * @author Michael Rolland * @version 2017.10.10 */ public final class AnyBaseToAnyBase { private AnyBaseToAnyBase() { } /** * Smallest and largest base you want to accept as valid input */ static final int MINIMUM_BASE = 2; static final int MAXIMUM_BASE = 36; public static void main(String[] args) { Scanner in = new Scanner(System.in); String n; int b1, b2; while (true) { try { System.out.print("Enter number: "); n = in.next(); System.out.print("Enter beginning base (between " + MINIMUM_BASE + " and " + MAXIMUM_BASE + "): "); b1 = in.nextInt(); if (b1 > MAXIMUM_BASE || b1 < MINIMUM_BASE) { System.out.println("Invalid base!"); continue; } if (!validForBase(n, b1)) { System.out.println("The number is invalid for this base!"); continue; } System.out.print("Enter end base (between " + MINIMUM_BASE + " and " + MAXIMUM_BASE + "): "); b2 = in.nextInt(); if (b2 > MAXIMUM_BASE || b2 < MINIMUM_BASE) { System.out.println("Invalid base!"); continue; } break; } catch (InputMismatchException e) { System.out.println("Invalid input."); in.next(); } } System.out.println(base2base(n, b1, b2)); in.close(); } /** * Checks if a number (as a String) is valid for a given base. */ public static boolean validForBase(String n, int base) { char[] validDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', }; // digitsForBase contains all the valid digits for the base given char[] digitsForBase = Arrays.copyOfRange(validDigits, 0, base); // Convert character array into set for convenience of contains() method HashSet<Character> digitsList = new HashSet<>(); for (int i = 0; i < digitsForBase.length; i++) { digitsList.add(digitsForBase[i]); } // Check that every digit in n is within the list of valid digits for that base. for (char c : n.toCharArray()) { if (!digitsList.contains(c)) { return false; } } return true; } /** * Method to convert any integer from base b1 to base b2. Works by * converting from b1 to decimal, then decimal to b2. * * @param n The integer to be converted. * @param b1 Beginning base. * @param b2 End base. * @return n in base b2. */ public static String base2base(String n, int b1, int b2) { // Declare variables: decimal value of n, // character of base b1, character of base b2, // and the string that will be returned. int decimalValue = 0, charB2; char charB1; String output = ""; // Go through every character of n for (int i = 0; i < n.length(); i++) { // store the character in charB1 charB1 = n.charAt(i); // if it is a non-number, convert it to a decimal value >9 and store it in charB2 if (charB1 >= 'A' && charB1 <= 'Z') { charB2 = 10 + (charB1 - 'A'); } // Else, store the integer value in charB2 else { charB2 = charB1 - '0'; } // Convert the digit to decimal and add it to the // decimalValue of n decimalValue = decimalValue * b1 + charB2; } // Converting the decimal value to base b2: // A number is converted from decimal to another base // by continuously dividing by the base and recording // the remainder until the quotient is zero. The number in the // new base is the remainders, with the last remainder // being the left-most digit. if (0 == decimalValue) { return "0"; } // While the quotient is NOT zero: while (decimalValue != 0) { // If the remainder is a digit < 10, simply add it to // the left side of the new number. if (decimalValue % b2 < 10) { output = decimalValue % b2 + output; } // If the remainder is >= 10, add a character with the // corresponding value to the new number. (A = 10, B = 11, C = 12, ...) else { output = (char) ((decimalValue % b2) + 55) + output; } // Divide by the new base again decimalValue /= b2; } return output; } }
TheAlgorithms/Java
src/main/java/com/thealgorithms/conversions/AnyBaseToAnyBase.java
69
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file or at // https://developers.google.com/open-source/licenses/bsd package com.google.protobuf; import java.io.IOException; import java.util.Arrays; /** * {@code UnknownFieldSetLite} is used to keep track of fields which were seen when parsing a * protocol message but whose field numbers or types are unrecognized. This most frequently occurs * when new fields are added to a message type and then messages containing those fields are read by * old software that was compiled before the new types were added. * * <p>For use by generated code only. * * @author dweis@google.com (Daniel Weis) */ public final class UnknownFieldSetLite { // Arbitrarily chosen. // TODO: Tune this number? private static final int MIN_CAPACITY = 8; private static final UnknownFieldSetLite DEFAULT_INSTANCE = new UnknownFieldSetLite(0, new int[0], new Object[0], /* isMutable= */ false); /** * Get an empty {@code UnknownFieldSetLite}. * * <p>For use by generated code only. */ public static UnknownFieldSetLite getDefaultInstance() { return DEFAULT_INSTANCE; } /** Returns a new mutable instance. */ static UnknownFieldSetLite newInstance() { return new UnknownFieldSetLite(); } /** * Returns a mutable {@code UnknownFieldSetLite} that is the composite of {@code first} and {@code * second}. */ static UnknownFieldSetLite mutableCopyOf(UnknownFieldSetLite first, UnknownFieldSetLite second) { int count = first.count + second.count; int[] tags = Arrays.copyOf(first.tags, count); System.arraycopy(second.tags, 0, tags, first.count, second.count); Object[] objects = Arrays.copyOf(first.objects, count); System.arraycopy(second.objects, 0, objects, first.count, second.count); return new UnknownFieldSetLite(count, tags, objects, /* isMutable= */ true); } /** The number of elements in the set. */ private int count; /** The tag numbers for the elements in the set. */ private int[] tags; /** The boxed values of the elements in the set. */ private Object[] objects; /** The lazily computed serialized size of the set. */ private int memoizedSerializedSize = -1; /** Indicates that this object is mutable. */ private boolean isMutable; /** Constructs a mutable {@code UnknownFieldSetLite}. */ private UnknownFieldSetLite() { this(0, new int[MIN_CAPACITY], new Object[MIN_CAPACITY], /* isMutable= */ true); } /** Constructs the {@code UnknownFieldSetLite}. */ private UnknownFieldSetLite(int count, int[] tags, Object[] objects, boolean isMutable) { this.count = count; this.tags = tags; this.objects = objects; this.isMutable = isMutable; } /** * Marks this object as immutable. * * <p>Future calls to methods that attempt to modify this object will throw. */ public void makeImmutable() { if (this.isMutable) { this.isMutable = false; } } /** Throws an {@link UnsupportedOperationException} if immutable. */ void checkMutable() { if (!isMutable) { throw new UnsupportedOperationException(); } } /** * Serializes the set and writes it to {@code output}. * * <p>For use by generated code only. */ public void writeTo(CodedOutputStream output) throws IOException { for (int i = 0; i < count; i++) { int tag = tags[i]; int fieldNumber = WireFormat.getTagFieldNumber(tag); switch (WireFormat.getTagWireType(tag)) { case WireFormat.WIRETYPE_VARINT: output.writeUInt64(fieldNumber, (Long) objects[i]); break; case WireFormat.WIRETYPE_FIXED32: output.writeFixed32(fieldNumber, (Integer) objects[i]); break; case WireFormat.WIRETYPE_FIXED64: output.writeFixed64(fieldNumber, (Long) objects[i]); break; case WireFormat.WIRETYPE_LENGTH_DELIMITED: output.writeBytes(fieldNumber, (ByteString) objects[i]); break; case WireFormat.WIRETYPE_START_GROUP: output.writeTag(fieldNumber, WireFormat.WIRETYPE_START_GROUP); ((UnknownFieldSetLite) objects[i]).writeTo(output); output.writeTag(fieldNumber, WireFormat.WIRETYPE_END_GROUP); break; default: throw InvalidProtocolBufferException.invalidWireType(); } } } /** * Serializes the set and writes it to {@code output} using {@code MessageSet} wire format. * * <p>For use by generated code only. */ public void writeAsMessageSetTo(CodedOutputStream output) throws IOException { for (int i = 0; i < count; i++) { int fieldNumber = WireFormat.getTagFieldNumber(tags[i]); output.writeRawMessageSetExtension(fieldNumber, (ByteString) objects[i]); } } /** Serializes the set and writes it to {@code writer} using {@code MessageSet} wire format. */ void writeAsMessageSetTo(Writer writer) throws IOException { if (writer.fieldOrder() == Writer.FieldOrder.DESCENDING) { // Write fields in descending order. for (int i = count - 1; i >= 0; i--) { int fieldNumber = WireFormat.getTagFieldNumber(tags[i]); writer.writeMessageSetItem(fieldNumber, objects[i]); } } else { // Write fields in ascending order. for (int i = 0; i < count; i++) { int fieldNumber = WireFormat.getTagFieldNumber(tags[i]); writer.writeMessageSetItem(fieldNumber, objects[i]); } } } /** Serializes the set and writes it to {@code writer}. */ public void writeTo(Writer writer) throws IOException { if (count == 0) { return; } // TODO: tags are not sorted, so there's no write order guarantees if (writer.fieldOrder() == Writer.FieldOrder.ASCENDING) { for (int i = 0; i < count; ++i) { writeField(tags[i], objects[i], writer); } } else { for (int i = count - 1; i >= 0; --i) { writeField(tags[i], objects[i], writer); } } } private static void writeField(int tag, Object object, Writer writer) throws IOException { int fieldNumber = WireFormat.getTagFieldNumber(tag); switch (WireFormat.getTagWireType(tag)) { case WireFormat.WIRETYPE_VARINT: writer.writeInt64(fieldNumber, (Long) object); break; case WireFormat.WIRETYPE_FIXED32: writer.writeFixed32(fieldNumber, (Integer) object); break; case WireFormat.WIRETYPE_FIXED64: writer.writeFixed64(fieldNumber, (Long) object); break; case WireFormat.WIRETYPE_LENGTH_DELIMITED: writer.writeBytes(fieldNumber, (ByteString) object); break; case WireFormat.WIRETYPE_START_GROUP: if (writer.fieldOrder() == Writer.FieldOrder.ASCENDING) { writer.writeStartGroup(fieldNumber); ((UnknownFieldSetLite) object).writeTo(writer); writer.writeEndGroup(fieldNumber); } else { writer.writeEndGroup(fieldNumber); ((UnknownFieldSetLite) object).writeTo(writer); writer.writeStartGroup(fieldNumber); } break; default: // TODO: Change writeTo to throw IOException? throw new RuntimeException(InvalidProtocolBufferException.invalidWireType()); } } /** * Get the number of bytes required to encode this field, including field number, using {@code * MessageSet} wire format. */ public int getSerializedSizeAsMessageSet() { int size = memoizedSerializedSize; if (size != -1) { return size; } size = 0; for (int i = 0; i < count; i++) { int tag = tags[i]; int fieldNumber = WireFormat.getTagFieldNumber(tag); size += CodedOutputStream.computeRawMessageSetExtensionSize(fieldNumber, (ByteString) objects[i]); } memoizedSerializedSize = size; return size; } /** * Get the number of bytes required to encode this set. * * <p>For use by generated code only. */ public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) { return size; } size = 0; for (int i = 0; i < count; i++) { int tag = tags[i]; int fieldNumber = WireFormat.getTagFieldNumber(tag); switch (WireFormat.getTagWireType(tag)) { case WireFormat.WIRETYPE_VARINT: size += CodedOutputStream.computeUInt64Size(fieldNumber, (Long) objects[i]); break; case WireFormat.WIRETYPE_FIXED32: size += CodedOutputStream.computeFixed32Size(fieldNumber, (Integer) objects[i]); break; case WireFormat.WIRETYPE_FIXED64: size += CodedOutputStream.computeFixed64Size(fieldNumber, (Long) objects[i]); break; case WireFormat.WIRETYPE_LENGTH_DELIMITED: size += CodedOutputStream.computeBytesSize(fieldNumber, (ByteString) objects[i]); break; case WireFormat.WIRETYPE_START_GROUP: size += CodedOutputStream.computeTagSize(fieldNumber) * 2 + ((UnknownFieldSetLite) objects[i]).getSerializedSize(); break; default: throw new IllegalStateException(InvalidProtocolBufferException.invalidWireType()); } } memoizedSerializedSize = size; return size; } private static boolean tagsEquals(int[] tags1, int[] tags2, int count) { for (int i = 0; i < count; ++i) { if (tags1[i] != tags2[i]) { return false; } } return true; } private static boolean objectsEquals(Object[] objects1, Object[] objects2, int count) { for (int i = 0; i < count; ++i) { if (!objects1[i].equals(objects2[i])) { return false; } } return true; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof UnknownFieldSetLite)) { return false; } UnknownFieldSetLite other = (UnknownFieldSetLite) obj; if (count != other.count || !tagsEquals(tags, other.tags, count) || !objectsEquals(objects, other.objects, count)) { return false; } return true; } private static int hashCode(int[] tags, int count) { int hashCode = 17; for (int i = 0; i < count; ++i) { hashCode = 31 * hashCode + tags[i]; } return hashCode; } private static int hashCode(Object[] objects, int count) { int hashCode = 17; for (int i = 0; i < count; ++i) { hashCode = 31 * hashCode + objects[i].hashCode(); } return hashCode; } @Override public int hashCode() { int hashCode = 17; hashCode = 31 * hashCode + count; hashCode = 31 * hashCode + hashCode(tags, count); hashCode = 31 * hashCode + hashCode(objects, count); return hashCode; } /** * Prints a String representation of the unknown field set. * * <p>For use by generated code only. * * @param buffer the buffer to write to * @param indent the number of spaces the fields should be indented by */ final void printWithIndent(StringBuilder buffer, int indent) { for (int i = 0; i < count; i++) { int fieldNumber = WireFormat.getTagFieldNumber(tags[i]); MessageLiteToString.printField(buffer, indent, String.valueOf(fieldNumber), objects[i]); } } // Package private for unsafe experimental runtime. void storeField(int tag, Object value) { checkMutable(); ensureCapacity(count + 1); tags[count] = tag; objects[count] = value; count++; } /** Ensures that our arrays are long enough to store more metadata. */ private void ensureCapacity(int minCapacity) { if (minCapacity > this.tags.length) { // Increase by at least 50% int newCapacity = count + count / 2; // Or new capacity if higher if (newCapacity < minCapacity) { newCapacity = minCapacity; } // And never less than MIN_CAPACITY if (newCapacity < MIN_CAPACITY) { newCapacity = MIN_CAPACITY; } this.tags = Arrays.copyOf(this.tags, newCapacity); this.objects = Arrays.copyOf(this.objects, newCapacity); } } /** * Parse a single field from {@code input} and merge it into this set. * * <p>For use by generated code only. * * @param tag The field's tag number, which was already parsed. * @return {@code false} if the tag is an end group tag. */ boolean mergeFieldFrom(final int tag, final CodedInputStream input) throws IOException { checkMutable(); final int fieldNumber = WireFormat.getTagFieldNumber(tag); switch (WireFormat.getTagWireType(tag)) { case WireFormat.WIRETYPE_VARINT: storeField(tag, input.readInt64()); return true; case WireFormat.WIRETYPE_FIXED32: storeField(tag, input.readFixed32()); return true; case WireFormat.WIRETYPE_FIXED64: storeField(tag, input.readFixed64()); return true; case WireFormat.WIRETYPE_LENGTH_DELIMITED: storeField(tag, input.readBytes()); return true; case WireFormat.WIRETYPE_START_GROUP: final UnknownFieldSetLite subFieldSet = new UnknownFieldSetLite(); subFieldSet.mergeFrom(input); input.checkLastTagWas(WireFormat.makeTag(fieldNumber, WireFormat.WIRETYPE_END_GROUP)); storeField(tag, subFieldSet); return true; case WireFormat.WIRETYPE_END_GROUP: return false; default: throw InvalidProtocolBufferException.invalidWireType(); } } /** * Convenience method for merging a new field containing a single varint value. This is used in * particular when an unknown enum value is encountered. * * <p>For use by generated code only. */ UnknownFieldSetLite mergeVarintField(int fieldNumber, int value) { checkMutable(); if (fieldNumber == 0) { throw new IllegalArgumentException("Zero is not a valid field number."); } storeField(WireFormat.makeTag(fieldNumber, WireFormat.WIRETYPE_VARINT), (long) value); return this; } /** * Convenience method for merging a length-delimited field. * * <p>For use by generated code only. */ UnknownFieldSetLite mergeLengthDelimitedField(final int fieldNumber, final ByteString value) { checkMutable(); if (fieldNumber == 0) { throw new IllegalArgumentException("Zero is not a valid field number."); } storeField(WireFormat.makeTag(fieldNumber, WireFormat.WIRETYPE_LENGTH_DELIMITED), value); return this; } /** Parse an entire message from {@code input} and merge its fields into this set. */ private UnknownFieldSetLite mergeFrom(final CodedInputStream input) throws IOException { // Ensures initialization in mergeFieldFrom. while (true) { final int tag = input.readTag(); if (tag == 0 || !mergeFieldFrom(tag, input)) { break; } } return this; } @CanIgnoreReturnValue UnknownFieldSetLite mergeFrom(UnknownFieldSetLite other) { if (other.equals(getDefaultInstance())) { return this; } checkMutable(); int newCount = this.count + other.count; ensureCapacity(newCount); System.arraycopy(other.tags, 0, tags, this.count, other.count); System.arraycopy(other.objects, 0, objects, this.count, other.count); this.count = newCount; return this; } }
protocolbuffers/protobuf
java/core/src/main/java/com/google/protobuf/UnknownFieldSetLite.java
70
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file or at // https://developers.google.com/open-source/licenses/bsd package com.google.protobuf; import static com.google.protobuf.Internal.checkNotNull; import com.google.protobuf.Internal.FloatList; import java.util.Arrays; import java.util.Collection; import java.util.RandomAccess; /** * An implementation of {@link FloatList} on top of a primitive array. * * @author dweis@google.com (Daniel Weis) */ final class FloatArrayList extends AbstractProtobufList<Float> implements FloatList, RandomAccess, PrimitiveNonBoxingCollection { private static final FloatArrayList EMPTY_LIST = new FloatArrayList(new float[0], 0, false); public static FloatArrayList emptyList() { return EMPTY_LIST; } /** The backing store for the list. */ private float[] array; /** * The size of the list distinct from the length of the array. That is, it is the number of * elements set in the list. */ private int size; /** Constructs a new mutable {@code FloatArrayList} with default capacity. */ FloatArrayList() { this(new float[DEFAULT_CAPACITY], 0, true); } /** * Constructs a new mutable {@code FloatArrayList} containing the same elements as {@code other}. */ private FloatArrayList(float[] other, int size, boolean isMutable) { super(isMutable); this.array = other; this.size = size; } @Override protected void removeRange(int fromIndex, int toIndex) { ensureIsMutable(); if (toIndex < fromIndex) { throw new IndexOutOfBoundsException("toIndex < fromIndex"); } System.arraycopy(array, toIndex, array, fromIndex, size - toIndex); size -= (toIndex - fromIndex); modCount++; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof FloatArrayList)) { return super.equals(o); } FloatArrayList other = (FloatArrayList) o; if (size != other.size) { return false; } final float[] arr = other.array; for (int i = 0; i < size; i++) { if (Float.floatToIntBits(array[i]) != Float.floatToIntBits(arr[i])) { return false; } } return true; } @Override public int hashCode() { int result = 1; for (int i = 0; i < size; i++) { result = (31 * result) + Float.floatToIntBits(array[i]); } return result; } @Override public FloatList mutableCopyWithCapacity(int capacity) { if (capacity < size) { throw new IllegalArgumentException(); } return new FloatArrayList(Arrays.copyOf(array, capacity), size, true); } @Override public Float get(int index) { return getFloat(index); } @Override public float getFloat(int index) { ensureIndexInRange(index); return array[index]; } @Override public int indexOf(Object element) { if (!(element instanceof Float)) { return -1; } float unboxedElement = (Float) element; int numElems = size(); for (int i = 0; i < numElems; i++) { if (array[i] == unboxedElement) { return i; } } return -1; } @Override public boolean contains(Object element) { return indexOf(element) != -1; } @Override public int size() { return size; } @Override public Float set(int index, Float element) { return setFloat(index, element); } @Override public float setFloat(int index, float element) { ensureIsMutable(); ensureIndexInRange(index); float previousValue = array[index]; array[index] = element; return previousValue; } @Override public boolean add(Float element) { addFloat(element); return true; } @Override public void add(int index, Float element) { addFloat(index, element); } /** Like {@link #add(Float)} but more efficient in that it doesn't box the element. */ @Override public void addFloat(float element) { ensureIsMutable(); if (size == array.length) { // Resize to 1.5x the size int length = ((size * 3) / 2) + 1; float[] newArray = new float[length]; System.arraycopy(array, 0, newArray, 0, size); array = newArray; } array[size++] = element; } /** Like {@link #add(int, Float)} but more efficient in that it doesn't box the element. */ private void addFloat(int index, float element) { ensureIsMutable(); if (index < 0 || index > size) { throw new IndexOutOfBoundsException(makeOutOfBoundsExceptionMessage(index)); } if (size < array.length) { // Shift everything over to make room System.arraycopy(array, index, array, index + 1, size - index); } else { // Resize to 1.5x the size int length = ((size * 3) / 2) + 1; float[] newArray = new float[length]; // Copy the first part directly System.arraycopy(array, 0, newArray, 0, index); // Copy the rest shifted over by one to make room System.arraycopy(array, index, newArray, index + 1, size - index); array = newArray; } array[index] = element; size++; modCount++; } @Override public boolean addAll(Collection<? extends Float> collection) { ensureIsMutable(); checkNotNull(collection); // We specialize when adding another FloatArrayList to avoid boxing elements. if (!(collection instanceof FloatArrayList)) { return super.addAll(collection); } FloatArrayList list = (FloatArrayList) collection; if (list.size == 0) { return false; } int overflow = Integer.MAX_VALUE - size; if (overflow < list.size) { // We can't actually represent a list this large. throw new OutOfMemoryError(); } int newSize = size + list.size; if (newSize > array.length) { array = Arrays.copyOf(array, newSize); } System.arraycopy(list.array, 0, array, size, list.size); size = newSize; modCount++; return true; } @Override public Float remove(int index) { ensureIsMutable(); ensureIndexInRange(index); float value = array[index]; if (index < size - 1) { System.arraycopy(array, index + 1, array, index, size - index - 1); } size--; modCount++; return value; } /** * Ensures that the provided {@code index} is within the range of {@code [0, size]}. Throws an * {@link IndexOutOfBoundsException} if it is not. * * @param index the index to verify is in range */ private void ensureIndexInRange(int index) { if (index < 0 || index >= size) { throw new IndexOutOfBoundsException(makeOutOfBoundsExceptionMessage(index)); } } private String makeOutOfBoundsExceptionMessage(int index) { return "Index:" + index + ", Size:" + size; } }
protocolbuffers/protobuf
java/core/src/main/java/com/google/protobuf/FloatArrayList.java
71
// Companion Code to the paper "Generative Forests" by R. Nock and M. Guillame-Bert. import java.io.*; import java.util.*; /************************************************************************************************************************************** * Class LocalEmpiricalMeasure (convenience) *****/ class LocalEmpiricalMeasure implements Debuggable{ // Use observations_indexes, proportions for GEOT, total_weight for EOGT public int [] observations_indexes; public double [] proportions; public double total_weight; LocalEmpiricalMeasure(int n){ if (n == 0){ observations_indexes = null; proportions = null; total_weight = 0.0; }else{ observations_indexes = new int[n]; proportions = new double[n]; int i; for (i=0;i<n;i++){ observations_indexes[i] = -1; proportions[i] = -1.0; } total_weight = 0.0; } } public static LocalEmpiricalMeasure[] SOFT_SPLIT_AT_NODE(Node node, LocalEmpiricalMeasure lem_at_n){ LocalEmpiricalMeasure[] ret; if (lem_at_n == null){ ret = new LocalEmpiricalMeasure[2]; ret[0] = ret[1] = null; return ret; } int index_feature_split = node.node_feature_split_index; Feature feature_in_node = node.node_support.feature(index_feature_split); FeatureTest f = FeatureTest.copyOf(node.node_feature_test, feature_in_node); ret = f.split_measure_soft(lem_at_n, node.myTree.myGET.myDS, feature_in_node); return ret; } public String toString(){ if (observations_indexes == null) return null; int i; String ret = "{"; for (i=0;i<observations_indexes.length;i++){ ret += "(" + observations_indexes[i] + ", " + proportions[i] + ")"; } ret += "}"; return ret; } public boolean contains_indexes(){ if ( (observations_indexes == null) || (observations_indexes.length == 0) ) return false; return true; } public void add(int iv, double pv){ // checks the index is not yet in observations_indexes if (contains_index(iv)) Dataset.perror("LocalEmpiricalMeasure.class :: cannot add index"); int [] new_indexes; double [] new_proportions; int former_size; if (observations_indexes == null){ former_size = 0; }else former_size = observations_indexes.length; new_indexes = new int[former_size + 1]; new_proportions = new double[former_size + 1]; int i; for (i=0;i<former_size;i++){ new_indexes[i] = observations_indexes[i]; new_proportions[i] = proportions[i]; } new_indexes[former_size] = iv; new_proportions[former_size] = pv; observations_indexes = new_indexes; proportions = new_proportions; total_weight += pv; } public boolean contains_index(int v){ if (observations_indexes == null) return false; int i=0; for (i=0;i<observations_indexes.length;i++) if (observations_indexes[i] == v) return true; return false; } public void init_indexes(int [] v){ observations_indexes = new int[v.length]; proportions = new double[v.length]; int i; for (i=0;i<v.length;i++){ observations_indexes[i] = v[i]; proportions[i] = -1.0; } } public void init_proportions(double v){ if (observations_indexes == null) Dataset.perror("LocalEmpiricalMeasure.class :: observations_indexes == null"); if (proportions.length != observations_indexes.length) Dataset.perror( "LocalEmpiricalMeasure.class :: proportions.length != observations_indexes.length"); int i; total_weight = 0.0; for (i=0;i<proportions.length;i++){ proportions[i] = v; total_weight += v; } } public int total_number_of_indexes(){ return observations_indexes.length; } public double total_weight(){ if (observations_indexes == null) return 0.0; double ret = 0.0; int i; for (i=0;i<proportions.length;i++) if (proportions[i] <= 0.0) Dataset.perror("LocalEmpiricalFeatures.class :: non >0 proportion"); else ret += proportions[i]; return ret; } }
google-research/google-research
generative_forests/src/LocalEmpiricalMeasure.java
72
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file or at // https://developers.google.com/open-source/licenses/bsd package com.google.protobuf; import static com.google.protobuf.Internal.checkNotNull; import com.google.protobuf.Internal.DoubleList; import java.util.Arrays; import java.util.Collection; import java.util.RandomAccess; /** * An implementation of {@link DoubleList} on top of a primitive array. * * @author dweis@google.com (Daniel Weis) */ final class DoubleArrayList extends AbstractProtobufList<Double> implements DoubleList, RandomAccess, PrimitiveNonBoxingCollection { private static final DoubleArrayList EMPTY_LIST = new DoubleArrayList(new double[0], 0, false); public static DoubleArrayList emptyList() { return EMPTY_LIST; } /** The backing store for the list. */ private double[] array; /** * The size of the list distinct from the length of the array. That is, it is the number of * elements set in the list. */ private int size; /** Constructs a new mutable {@code DoubleArrayList} with default capacity. */ DoubleArrayList() { this(new double[DEFAULT_CAPACITY], 0, true); } /** * Constructs a new mutable {@code DoubleArrayList} containing the same elements as {@code other}. */ private DoubleArrayList(double[] other, int size, boolean isMutable) { super(isMutable); this.array = other; this.size = size; } @Override protected void removeRange(int fromIndex, int toIndex) { ensureIsMutable(); if (toIndex < fromIndex) { throw new IndexOutOfBoundsException("toIndex < fromIndex"); } System.arraycopy(array, toIndex, array, fromIndex, size - toIndex); size -= (toIndex - fromIndex); modCount++; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof DoubleArrayList)) { return super.equals(o); } DoubleArrayList other = (DoubleArrayList) o; if (size != other.size) { return false; } final double[] arr = other.array; for (int i = 0; i < size; i++) { if (Double.doubleToLongBits(array[i]) != Double.doubleToLongBits(arr[i])) { return false; } } return true; } @Override public int hashCode() { int result = 1; for (int i = 0; i < size; i++) { long bits = Double.doubleToLongBits(array[i]); result = (31 * result) + Internal.hashLong(bits); } return result; } @Override public DoubleList mutableCopyWithCapacity(int capacity) { if (capacity < size) { throw new IllegalArgumentException(); } return new DoubleArrayList(Arrays.copyOf(array, capacity), size, true); } @Override public Double get(int index) { return getDouble(index); } @Override public double getDouble(int index) { ensureIndexInRange(index); return array[index]; } @Override public int indexOf(Object element) { if (!(element instanceof Double)) { return -1; } double unboxedElement = (Double) element; int numElems = size(); for (int i = 0; i < numElems; i++) { if (array[i] == unboxedElement) { return i; } } return -1; } @Override public boolean contains(Object element) { return indexOf(element) != -1; } @Override public int size() { return size; } @Override public Double set(int index, Double element) { return setDouble(index, element); } @Override public double setDouble(int index, double element) { ensureIsMutable(); ensureIndexInRange(index); double previousValue = array[index]; array[index] = element; return previousValue; } @Override public boolean add(Double element) { addDouble(element); return true; } @Override public void add(int index, Double element) { addDouble(index, element); } /** Like {@link #add(Double)} but more efficient in that it doesn't box the element. */ @Override public void addDouble(double element) { ensureIsMutable(); if (size == array.length) { // Resize to 1.5x the size int length = ((size * 3) / 2) + 1; double[] newArray = new double[length]; System.arraycopy(array, 0, newArray, 0, size); array = newArray; } array[size++] = element; } /** Like {@link #add(int, Double)} but more efficient in that it doesn't box the element. */ private void addDouble(int index, double element) { ensureIsMutable(); if (index < 0 || index > size) { throw new IndexOutOfBoundsException(makeOutOfBoundsExceptionMessage(index)); } if (size < array.length) { // Shift everything over to make room System.arraycopy(array, index, array, index + 1, size - index); } else { // Resize to 1.5x the size int length = ((size * 3) / 2) + 1; double[] newArray = new double[length]; // Copy the first part directly System.arraycopy(array, 0, newArray, 0, index); // Copy the rest shifted over by one to make room System.arraycopy(array, index, newArray, index + 1, size - index); array = newArray; } array[index] = element; size++; modCount++; } @Override public boolean addAll(Collection<? extends Double> collection) { ensureIsMutable(); checkNotNull(collection); // We specialize when adding another DoubleArrayList to avoid boxing elements. if (!(collection instanceof DoubleArrayList)) { return super.addAll(collection); } DoubleArrayList list = (DoubleArrayList) collection; if (list.size == 0) { return false; } int overflow = Integer.MAX_VALUE - size; if (overflow < list.size) { // We can't actually represent a list this large. throw new OutOfMemoryError(); } int newSize = size + list.size; if (newSize > array.length) { array = Arrays.copyOf(array, newSize); } System.arraycopy(list.array, 0, array, size, list.size); size = newSize; modCount++; return true; } @Override public Double remove(int index) { ensureIsMutable(); ensureIndexInRange(index); double value = array[index]; if (index < size - 1) { System.arraycopy(array, index + 1, array, index, size - index - 1); } size--; modCount++; return value; } /** * Ensures that the provided {@code index} is within the range of {@code [0, size]}. Throws an * {@link IndexOutOfBoundsException} if it is not. * * @param index the index to verify is in range */ private void ensureIndexInRange(int index) { if (index < 0 || index >= size) { throw new IndexOutOfBoundsException(makeOutOfBoundsExceptionMessage(index)); } } private String makeOutOfBoundsExceptionMessage(int index) { return "Index:" + index + ", Size:" + size; } }
protocolbuffers/protobuf
java/core/src/main/java/com/google/protobuf/DoubleArrayList.java
73
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * Project Info: https://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * https://plantuml.com/patreon (only 1$ per month!) * https://plantuml.com/paypal * * This file is part of Smetana. * Smetana is a partial translation of Graphviz/Dot sources from C to Java. * * (C) Copyright 2009-2022, Arnaud Roques * * This translation is distributed under the same Licence as the original C program: * ************************************************************************* * Copyright (c) 2011 AT&T Intellectual Property * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: See CVS logs. Details at http://www.graphviz.org/ ************************************************************************* * * THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC * LICENSE ("AGREEMENT"). [Eclipse Public License - v 1.0] * * ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES * RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. * * You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * 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 h; import static smetana.core.Macro.ND_order; import static smetana.core.Macro.ND_rank; import smetana.core.__ptr__; import smetana.core.__struct__; final public class ST_Agnode_s extends ST_Agobj_s { public final ST_Agobj_s base = this; public ST_Agraph_s root; public final ST_Agsubnode_s mainsub = new ST_Agsubnode_s(); public String NAME; // @Override // public String toString() { // try { // return NAME + " rank=" + ND_rank(this) + " order=" + ND_order(this); // } catch (Exception e) { // return NAME; // } // } @Override public void ___(__struct__ arg) { throw new UnsupportedOperationException(); } @Override public boolean isSameThan(__ptr__ other) { ST_Agnode_s other2 = (ST_Agnode_s) other; return this == other2; } } // struct Agnode_s { // Agobj_t base; // Agraph_t *root; // Agsubnode_t mainsub; /* embedded for main graph */ // };
plantuml/plantuml
src/h/ST_Agnode_s.java
74
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * Project Info: https://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * https://plantuml.com/patreon (only 1$ per month!) * https://plantuml.com/paypal * * This file is part of Smetana. * Smetana is a partial translation of Graphviz/Dot sources from C to Java. * * (C) Copyright 2009-2022, Arnaud Roques * * This translation is distributed under the same Licence as the original C program: * ************************************************************************* * Copyright (c) 2011 AT&T Intellectual Property * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: See CVS logs. Details at http://www.graphviz.org/ ************************************************************************* * * THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC * LICENSE ("AGREEMENT"). [Eclipse Public License - v 1.0] * * ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES * RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. * * You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * 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 h; import smetana.core.UnsupportedStarStruct; import smetana.core.__ptr__; import smetana.core.__struct__; final public class ST_pointf extends UnsupportedStarStruct { public static ST_pointf pointfof(double x, double y) { final ST_pointf result = new ST_pointf(); result.x = x; result.y = y; return result; } public static ST_pointf add_pointf(final ST_pointf p, final ST_pointf q) { final ST_pointf result = new ST_pointf(); result.x = p.x + q.x; result.y = p.y + q.y; return result; } public double x; public double y; @Override public boolean isSameThan(__ptr__ other) { return this == (ST_pointf) other; } @Override public String toString() { return "[" + x + "," + y + "]"; } @Override public ST_pointf copy() { final ST_pointf result = new ST_pointf(); result.x = this.x; result.y = this.y; return result; } @Override public void ___(__struct__ other) { final ST_pointf other2 = (ST_pointf) other; this.x = other2.x; this.y = other2.y; } } // typedef struct pointf_s { double x, y; } pointf;
plantuml/plantuml
src/h/ST_pointf.java
75
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file or at // https://developers.google.com/open-source/licenses/bsd package com.google.protobuf; import static com.google.protobuf.Internal.checkNotNull; import com.google.protobuf.Internal.BooleanList; import java.util.Arrays; import java.util.Collection; import java.util.RandomAccess; /** * An implementation of {@link BooleanList} on top of a primitive array. * * @author dweis@google.com (Daniel Weis) */ final class BooleanArrayList extends AbstractProtobufList<Boolean> implements BooleanList, RandomAccess, PrimitiveNonBoxingCollection { private static final BooleanArrayList EMPTY_LIST = new BooleanArrayList(new boolean[0], 0, false); public static BooleanArrayList emptyList() { return EMPTY_LIST; } /** The backing store for the list. */ private boolean[] array; /** * The size of the list distinct from the length of the array. That is, it is the number of * elements set in the list. */ private int size; /** Constructs a new mutable {@code BooleanArrayList} with default capacity. */ BooleanArrayList() { this(new boolean[DEFAULT_CAPACITY], 0, true); } /** * Constructs a new mutable {@code BooleanArrayList} containing the same elements as {@code * other}. */ private BooleanArrayList(boolean[] other, int size, boolean isMutable) { super(isMutable); this.array = other; this.size = size; } @Override protected void removeRange(int fromIndex, int toIndex) { ensureIsMutable(); if (toIndex < fromIndex) { throw new IndexOutOfBoundsException("toIndex < fromIndex"); } System.arraycopy(array, toIndex, array, fromIndex, size - toIndex); size -= (toIndex - fromIndex); modCount++; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof BooleanArrayList)) { return super.equals(o); } BooleanArrayList other = (BooleanArrayList) o; if (size != other.size) { return false; } final boolean[] arr = other.array; for (int i = 0; i < size; i++) { if (array[i] != arr[i]) { return false; } } return true; } @Override public int hashCode() { int result = 1; for (int i = 0; i < size; i++) { result = (31 * result) + Internal.hashBoolean(array[i]); } return result; } @Override public BooleanList mutableCopyWithCapacity(int capacity) { if (capacity < size) { throw new IllegalArgumentException(); } return new BooleanArrayList(Arrays.copyOf(array, capacity), size, true); } @Override public Boolean get(int index) { return getBoolean(index); } @Override public boolean getBoolean(int index) { ensureIndexInRange(index); return array[index]; } @Override public int indexOf(Object element) { if (!(element instanceof Boolean)) { return -1; } boolean unboxedElement = (Boolean) element; int numElems = size(); for (int i = 0; i < numElems; i++) { if (array[i] == unboxedElement) { return i; } } return -1; } @Override public boolean contains(Object element) { return indexOf(element) != -1; } @Override public int size() { return size; } @Override public Boolean set(int index, Boolean element) { return setBoolean(index, element); } @Override public boolean setBoolean(int index, boolean element) { ensureIsMutable(); ensureIndexInRange(index); boolean previousValue = array[index]; array[index] = element; return previousValue; } @Override public boolean add(Boolean element) { addBoolean(element); return true; } @Override public void add(int index, Boolean element) { addBoolean(index, element); } /** Like {@link #add(Boolean)} but more efficient in that it doesn't box the element. */ @Override public void addBoolean(boolean element) { ensureIsMutable(); if (size == array.length) { // Resize to 1.5x the size int length = ((size * 3) / 2) + 1; boolean[] newArray = new boolean[length]; System.arraycopy(array, 0, newArray, 0, size); array = newArray; } array[size++] = element; } /** Like {@link #add(int, Boolean)} but more efficient in that it doesn't box the element. */ private void addBoolean(int index, boolean element) { ensureIsMutable(); if (index < 0 || index > size) { throw new IndexOutOfBoundsException(makeOutOfBoundsExceptionMessage(index)); } if (size < array.length) { // Shift everything over to make room System.arraycopy(array, index, array, index + 1, size - index); } else { // Resize to 1.5x the size int length = ((size * 3) / 2) + 1; boolean[] newArray = new boolean[length]; // Copy the first part directly System.arraycopy(array, 0, newArray, 0, index); // Copy the rest shifted over by one to make room System.arraycopy(array, index, newArray, index + 1, size - index); array = newArray; } array[index] = element; size++; modCount++; } @Override public boolean addAll(Collection<? extends Boolean> collection) { ensureIsMutable(); checkNotNull(collection); // We specialize when adding another BooleanArrayList to avoid boxing elements. if (!(collection instanceof BooleanArrayList)) { return super.addAll(collection); } BooleanArrayList list = (BooleanArrayList) collection; if (list.size == 0) { return false; } int overflow = Integer.MAX_VALUE - size; if (overflow < list.size) { // We can't actually represent a list this large. throw new OutOfMemoryError(); } int newSize = size + list.size; if (newSize > array.length) { array = Arrays.copyOf(array, newSize); } System.arraycopy(list.array, 0, array, size, list.size); size = newSize; modCount++; return true; } @Override public Boolean remove(int index) { ensureIsMutable(); ensureIndexInRange(index); boolean value = array[index]; if (index < size - 1) { System.arraycopy(array, index + 1, array, index, size - index - 1); } size--; modCount++; return value; } /** * Ensures that the provided {@code index} is within the range of {@code [0, size]}. Throws an * {@link IndexOutOfBoundsException} if it is not. * * @param index the index to verify is in range */ private void ensureIndexInRange(int index) { if (index < 0 || index >= size) { throw new IndexOutOfBoundsException(makeOutOfBoundsExceptionMessage(index)); } } private String makeOutOfBoundsExceptionMessage(int index) { return "Index:" + index + ", Size:" + size; } }
protocolbuffers/protobuf
java/core/src/main/java/com/google/protobuf/BooleanArrayList.java
76
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * Project Info: https://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * https://plantuml.com/patreon (only 1$ per month!) * https://plantuml.com/paypal * * This file is part of Smetana. * Smetana is a partial translation of Graphviz/Dot sources from C to Java. * * (C) Copyright 2009-2022, Arnaud Roques * * This translation is distributed under the same Licence as the original C program: * ************************************************************************* * Copyright (c) 2011 AT&T Intellectual Property * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: See CVS logs. Details at http://www.graphviz.org/ ************************************************************************* * * THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC * LICENSE ("AGREEMENT"). [Eclipse Public License - v 1.0] * * ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES * RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. * * You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * 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 h; import smetana.core.CFunction; import smetana.core.UnsupportedStarStruct; import smetana.core.__ptr__; final public class ST_dt_s extends UnsupportedStarStruct { public CFunction searchf;/* search function */ public ST_dtdisc_s disc; /* method to manipulate objs */ public ST_dtdata_s data; /* sharable data */ public CFunction memoryf;/* function to alloc/free memory */ public ST_dtmethod_s meth; /* dictionary method */ public int type; /* type information */ public int nview; /* number of parent view dictionaries */ public ST_dt_s view; /* next on viewpath */ public ST_dt_s walk; /* dictionary being walked */ public __ptr__ user; /* for user's usage */ @Override public boolean isSameThan(__ptr__ other) { ST_dt_s other2 = (ST_dt_s) other; return this == other2; } } // struct _dt_s // { Dtsearch_f searchf;/* search function */ // Dtdisc_t* disc; /* method to manipulate objs */ // Dtdata_t* data; /* sharable data */ // Dtmemory_f memoryf;/* function to alloc/free memory */ // Dtmethod_t* meth; /* dictionary method */ // int type; /* type information */ // int nview; /* number of parent view dictionaries */ // Dt_t* view; /* next on viewpath */ // Dt_t* walk; /* dictionary being walked */ // void* user; /* for user's usage */ // };
plantuml/plantuml
src/h/ST_dt_s.java
77
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * Project Info: https://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * https://plantuml.com/patreon (only 1$ per month!) * https://plantuml.com/paypal * * This file is part of Smetana. * Smetana is a partial translation of Graphviz/Dot sources from C to Java. * * (C) Copyright 2009-2022, Arnaud Roques * * This translation is distributed under the same Licence as the original C program: * ************************************************************************* * Copyright (c) 2011 AT&T Intellectual Property * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: See CVS logs. Details at http://www.graphviz.org/ ************************************************************************* * * THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC * LICENSE ("AGREEMENT"). [Eclipse Public License - v 1.0] * * ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES * RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. * * You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * 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 h; import smetana.core.CString; import smetana.core.UnsupportedStarStruct; import smetana.core.__ptr__; final public class ST_layout_t extends UnsupportedStarStruct { public double quantum; public double scale; public double ratio; public double dpi; public ST_pointf margin = new ST_pointf(); public ST_pointf page = new ST_pointf(); public ST_pointf size = new ST_pointf(); public boolean filled; public boolean landscape; public boolean centered; // "ratio_t ratio_kind", public EN_ratio_t ratio_kind = EN_ratio_t.R_NONE; public __ptr__ xdots; // Always null public CString id; // Not used } // typedef struct layout_t { // double quantum; // double scale; // double ratio; /* set only if ratio_kind == R_VALUE */ // double dpi; // pointf margin; // pointf page; // pointf size; // boolean filled; // boolean landscape; // boolean centered; // ratio_t ratio_kind; // void* xdots; // char* id; // } layout_t;
plantuml/plantuml
src/h/ST_layout_t.java
78
404: Not Found
apache/dubbo
dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/TriRpcStatus.java
79
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * Project Info: https://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * https://plantuml.com/patreon (only 1$ per month!) * https://plantuml.com/paypal * * This file is part of Smetana. * Smetana is a partial translation of Graphviz/Dot sources from C to Java. * * (C) Copyright 2009-2022, Arnaud Roques * * This translation is distributed under the same Licence as the original C program: * ************************************************************************* * Copyright (c) 2011 AT&T Intellectual Property * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: See CVS logs. Details at http://www.graphviz.org/ ************************************************************************* * * THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC * LICENSE ("AGREEMENT"). [Eclipse Public License - v 1.0] * * ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES * RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. * * You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * 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 h; import smetana.core.UnsupportedStarStruct; import smetana.core.__struct__; final public class ST_Agtag_s extends UnsupportedStarStruct { public int objtype; public int mtflock; public int attrwf; public int seq; public int id; @Override public String toString() { return "id=" + id + " " + super.toString(); } @Override public ST_Agtag_s copy() { final ST_Agtag_s result = new ST_Agtag_s(); result.objtype = objtype; result.mtflock = mtflock; result.attrwf = attrwf; result.seq = seq; result.id = id; return result; } @Override public void ___(__struct__ other) { final ST_Agtag_s other2 = (ST_Agtag_s) other; objtype = other2.objtype; mtflock = other2.mtflock; attrwf = other2.attrwf; seq = other2.seq; id = other2.id; } } // struct Agtag_s { // unsigned objtype:2; /* see literal tags below */ // unsigned mtflock:1; /* move-to-front lock, see above */ // unsigned attrwf:1; /* attrs written (parity, write.c) */ // unsigned seq:(sizeof(unsigned) * 8 - 4); /* sequence no. */ // unsigned long id; /* client ID */ // };
plantuml/plantuml
src/h/ST_Agtag_s.java
80
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * Project Info: https://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * https://plantuml.com/patreon (only 1$ per month!) * https://plantuml.com/paypal * * This file is part of Smetana. * Smetana is a partial translation of Graphviz/Dot sources from C to Java. * * (C) Copyright 2009-2022, Arnaud Roques * * This translation is distributed under the same Licence as the original C program: * ************************************************************************* * Copyright (c) 2011 AT&T Intellectual Property * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: See CVS logs. Details at http://www.graphviz.org/ ************************************************************************* * * THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC * LICENSE ("AGREEMENT"). [Eclipse Public License - v 1.0] * * ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES * RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. * * You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * 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 h; import smetana.core.UnsupportedStarStruct; import smetana.core.__ptr__; final public class ST_dtdata_s extends UnsupportedStarStruct { public int type; /* type of dictionary */ public ST_dtlink_s here; /* finger to last search element */ public __ptr__ _htab; /* hash table */ public ST_dtlink_s _head = null; // Dtlink_t* _head; /* linked list */ // } hh; public int ntab; /* number of hash slots */ public int size; /* number of objects */ public int loop; /* number of nested loops */ public int minp; /* min path before splay, always even */ } // struct _dtdata_s // { int type; /* type of dictionary */ // Dtlink_t* here; /* finger to last search element */ // union // { Dtlink_t** _htab; /* hash table */ // Dtlink_t* _head; /* linked list */ // } hh; // int ntab; /* number of hash slots */ // int size; /* number of objects */ // int loop; /* number of nested loops */ // int minp; /* min path before splay, always even */ // /* for hash dt, > 0: fixed table size */ // };
plantuml/plantuml
src/h/ST_dtdata_s.java
81
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file or at // https://developers.google.com/open-source/licenses/bsd package com.google.protobuf; import com.google.protobuf.AbstractMessageLite.Builder.LimitedInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; /** * A partial implementation of the {@link Parser} interface which implements as many methods of that * interface as possible in terms of other methods. * * <p>Note: This class implements all the convenience methods in the {@link Parser} interface. See * {@link Parser} for related javadocs. Subclasses need to implement {@link * Parser#parsePartialFrom(CodedInputStream, ExtensionRegistryLite)} * * @author liujisi@google.com (Pherl Liu) */ public abstract class AbstractParser<MessageType extends MessageLite> implements Parser<MessageType> { /** Creates an UninitializedMessageException for MessageType. */ private UninitializedMessageException newUninitializedMessageException(MessageType message) { if (message instanceof AbstractMessageLite) { return ((AbstractMessageLite) message).newUninitializedMessageException(); } return new UninitializedMessageException(message); } /** * Helper method to check if message is initialized. * * @throws InvalidProtocolBufferException if it is not initialized. * @return The message to check. */ private MessageType checkMessageInitialized(MessageType message) throws InvalidProtocolBufferException { if (message != null && !message.isInitialized()) { throw newUninitializedMessageException(message) .asInvalidProtocolBufferException() .setUnfinishedMessage(message); } return message; } private static final ExtensionRegistryLite EMPTY_REGISTRY = ExtensionRegistryLite.getEmptyRegistry(); @Override public MessageType parsePartialFrom(CodedInputStream input) throws InvalidProtocolBufferException { return parsePartialFrom(input, EMPTY_REGISTRY); } @Override public MessageType parseFrom(CodedInputStream input, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException { return checkMessageInitialized(parsePartialFrom(input, extensionRegistry)); } @Override public MessageType parseFrom(CodedInputStream input) throws InvalidProtocolBufferException { return parseFrom(input, EMPTY_REGISTRY); } @Override public MessageType parsePartialFrom(ByteString data, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException { MessageType message; try { CodedInputStream input = data.newCodedInput(); message = parsePartialFrom(input, extensionRegistry); try { input.checkLastTagWas(0); } catch (InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(message); } return message; } catch (InvalidProtocolBufferException e) { throw e; } } @Override public MessageType parsePartialFrom(ByteString data) throws InvalidProtocolBufferException { return parsePartialFrom(data, EMPTY_REGISTRY); } @Override public MessageType parseFrom(ByteString data, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException { return checkMessageInitialized(parsePartialFrom(data, extensionRegistry)); } @Override public MessageType parseFrom(ByteString data) throws InvalidProtocolBufferException { return parseFrom(data, EMPTY_REGISTRY); } @Override public MessageType parseFrom(ByteBuffer data, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException { MessageType message; try { CodedInputStream input = CodedInputStream.newInstance(data); message = parsePartialFrom(input, extensionRegistry); try { input.checkLastTagWas(0); } catch (InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(message); } } catch (InvalidProtocolBufferException e) { throw e; } return checkMessageInitialized(message); } @Override public MessageType parseFrom(ByteBuffer data) throws InvalidProtocolBufferException { return parseFrom(data, EMPTY_REGISTRY); } @Override public MessageType parsePartialFrom( byte[] data, int off, int len, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException { try { CodedInputStream input = CodedInputStream.newInstance(data, off, len); MessageType message = parsePartialFrom(input, extensionRegistry); try { input.checkLastTagWas(0); } catch (InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(message); } return message; } catch (InvalidProtocolBufferException e) { throw e; } } @Override public MessageType parsePartialFrom(byte[] data, int off, int len) throws InvalidProtocolBufferException { return parsePartialFrom(data, off, len, EMPTY_REGISTRY); } @Override public MessageType parsePartialFrom(byte[] data, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException { return parsePartialFrom(data, 0, data.length, extensionRegistry); } @Override public MessageType parsePartialFrom(byte[] data) throws InvalidProtocolBufferException { return parsePartialFrom(data, 0, data.length, EMPTY_REGISTRY); } @Override public MessageType parseFrom( byte[] data, int off, int len, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException { return checkMessageInitialized(parsePartialFrom(data, off, len, extensionRegistry)); } @Override public MessageType parseFrom(byte[] data, int off, int len) throws InvalidProtocolBufferException { return parseFrom(data, off, len, EMPTY_REGISTRY); } @Override public MessageType parseFrom(byte[] data, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException { return parseFrom(data, 0, data.length, extensionRegistry); } @Override public MessageType parseFrom(byte[] data) throws InvalidProtocolBufferException { return parseFrom(data, EMPTY_REGISTRY); } @Override public MessageType parsePartialFrom(InputStream input, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException { CodedInputStream codedInput = CodedInputStream.newInstance(input); MessageType message = parsePartialFrom(codedInput, extensionRegistry); try { codedInput.checkLastTagWas(0); } catch (InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(message); } return message; } @Override public MessageType parsePartialFrom(InputStream input) throws InvalidProtocolBufferException { return parsePartialFrom(input, EMPTY_REGISTRY); } @Override public MessageType parseFrom(InputStream input, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException { return checkMessageInitialized(parsePartialFrom(input, extensionRegistry)); } @Override public MessageType parseFrom(InputStream input) throws InvalidProtocolBufferException { return parseFrom(input, EMPTY_REGISTRY); } @Override public MessageType parsePartialDelimitedFrom( InputStream input, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException { int size; try { int firstByte = input.read(); if (firstByte == -1) { return null; } size = CodedInputStream.readRawVarint32(firstByte, input); } catch (IOException e) { throw new InvalidProtocolBufferException(e); } InputStream limitedInput = new LimitedInputStream(input, size); return parsePartialFrom(limitedInput, extensionRegistry); } @Override public MessageType parsePartialDelimitedFrom(InputStream input) throws InvalidProtocolBufferException { return parsePartialDelimitedFrom(input, EMPTY_REGISTRY); } @Override public MessageType parseDelimitedFrom(InputStream input, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException { return checkMessageInitialized(parsePartialDelimitedFrom(input, extensionRegistry)); } @Override public MessageType parseDelimitedFrom(InputStream input) throws InvalidProtocolBufferException { return parseDelimitedFrom(input, EMPTY_REGISTRY); } }
protocolbuffers/protobuf
java/core/src/main/java/com/google/protobuf/AbstractParser.java
82
/* * Copyright (c) 2011-2019 Contributors to the Eclipse Foundation * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 * which is available at https://www.apache.org/licenses/LICENSE-2.0. * * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 */ package io.vertx.core; import java.util.function.Function; /** * Encapsulates the result of an asynchronous operation. * <p> * Many operations in Vert.x APIs provide results back by passing an instance of this in a {@link io.vertx.core.Handler}. * <p> * The result can either have failed or succeeded. * <p> * If it failed then the cause of the failure is available with {@link #cause}. * <p> * If it succeeded then the actual result is available with {@link #result} * * @author <a href="http://tfox.org">Tim Fox</a> */ public interface AsyncResult<T> { /** * The result of the operation. This will be null if the operation failed. * * @return the result or null if the operation failed. */ T result(); /** * A Throwable describing failure. This will be null if the operation succeeded. * * @return the cause or null if the operation succeeded. */ Throwable cause(); /** * Did it succeed? * * @return true if it succeded or false otherwise */ boolean succeeded(); /** * Did it fail? * * @return true if it failed or false otherwise */ boolean failed(); /** * Apply a {@code mapper} function on this async result.<p> * * The {@code mapper} is called with the completed value and this mapper returns a value. This value will complete the result returned by this method call.<p> * * When this async result is failed, the failure will be propagated to the returned async result and the {@code mapper} will not be called. * * @param mapper the mapper function * @return the mapped async result */ default <U> AsyncResult<U> map(Function<T, U> mapper) { if (mapper == null) { throw new NullPointerException(); } return new AsyncResult<U>() { @Override public U result() { if (succeeded()) { return mapper.apply(AsyncResult.this.result()); } else { return null; } } @Override public Throwable cause() { return AsyncResult.this.cause(); } @Override public boolean succeeded() { return AsyncResult.this.succeeded(); } @Override public boolean failed() { return AsyncResult.this.failed(); } }; } /** * Map the result of this async result to a specific {@code value}.<p> * * When this async result succeeds, this {@code value} will succeeed the async result returned by this method call.<p> * * When this async result fails, the failure will be propagated to the returned async result. * * @param value the value that eventually completes the mapped async result * @return the mapped async result */ default <V> AsyncResult<V> map(V value) { return map(t -> value); } /** * Map the result of this async result to {@code null}.<p> * * This is a convenience for {@code asyncResult.map((T) null)} or {@code asyncResult.map((Void) null)}.<p> * * When this async result succeeds, {@code null} will succeeed the async result returned by this method call.<p> * * When this async result fails, the failure will be propagated to the returned async result. * * @return the mapped async result */ default <V> AsyncResult<V> mapEmpty() { return map((V)null); } /** * Apply a {@code mapper} function on this async result.<p> * * The {@code mapper} is called with the failure and this mapper returns a value. This value will complete the result returned by this method call.<p> * * When this async result is succeeded, the value will be propagated to the returned async result and the {@code mapper} will not be called. * * @param mapper the mapper function * @return the mapped async result */ default AsyncResult<T> otherwise(Function<Throwable, T> mapper) { if (mapper == null) { throw new NullPointerException(); } return new AsyncResult<T>() { @Override public T result() { if (AsyncResult.this.succeeded()) { return AsyncResult.this.result(); } else if (AsyncResult.this.failed()) { return mapper.apply(AsyncResult.this.cause()); } else { return null; } } @Override public Throwable cause() { return null; } @Override public boolean succeeded() { return AsyncResult.this.succeeded() || AsyncResult.this.failed(); } @Override public boolean failed() { return false; } }; } /** * Map the failure of this async result to a specific {@code value}.<p> * * When this async result fails, this {@code value} will succeeed the async result returned by this method call.<p> * * When this async succeeds, the result will be propagated to the returned async result. * * @param value the value that eventually completes the mapped async result * @return the mapped async result */ default AsyncResult<T> otherwise(T value) { return otherwise(err -> value); } /** * Map the failure of this async result to {@code null}.<p> * * This is a convenience for {@code asyncResult.otherwise((T) null)}.<p> * * When this async result fails, the {@code null} will succeeed the async result returned by this method call.<p> * * When this async succeeds, the result will be propagated to the returned async result. * * @return the mapped async result */ default AsyncResult<T> otherwiseEmpty() { return otherwise(err -> null); } }
eclipse-vertx/vert.x
src/main/java/io/vertx/core/AsyncResult.java
83
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * Project Info: https://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * https://plantuml.com/patreon (only 1$ per month!) * https://plantuml.com/paypal * * This file is part of Smetana. * Smetana is a partial translation of Graphviz/Dot sources from C to Java. * * (C) Copyright 2009-2022, Arnaud Roques * * This translation is distributed under the same Licence as the original C program: * ************************************************************************* * Copyright (c) 2011 AT&T Intellectual Property * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: See CVS logs. Details at http://www.graphviz.org/ ************************************************************************* * * THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC * LICENSE ("AGREEMENT"). [Eclipse Public License - v 1.0] * * ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES * RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. * * You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * 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 h; import smetana.core.UnsupportedStarStruct; final public class ST_Agclos_s extends UnsupportedStarStruct { public final ST_Agdisc_s disc = new ST_Agdisc_s(); /* resource discipline functions */ public final ST_Agdstate_s state = new ST_Agdstate_s(); /* resource closures */ public ST_dt_s strdict; public final int[] seq = new int[3]; // "unsigned long seq[3]", public ST_Agcbstack_s cb; public boolean callbacks_enabled; /* issue user callbacks or hold them? */ // "Dict_t *lookup_by_name[3]", // "Dict_t *lookup_by_id[3]", public final ST_dt_s[] lookup_by_id = new ST_dt_s[3]; } // struct Agclos_s { // Agdisc_t disc; /* resource discipline functions */ // Agdstate_t state; /* resource closures */ // Dict_t *strdict; /* shared string dict */ // unsigned long seq[3]; /* local object sequence number counter */ // Agcbstack_t *cb; /* user and system callback function stacks */ // unsigned char callbacks_enabled; /* issue user callbacks or hold them? */ // Dict_t *lookup_by_name[3]; // Dict_t *lookup_by_id[3]; // };
plantuml/plantuml
src/h/ST_Agclos_s.java
84
package edu.stanford.nlp.util; import java.io.Serializable; import java.util.List; import java.util.Objects; import edu.stanford.nlp.util.logging.PrettyLoggable; import edu.stanford.nlp.util.logging.PrettyLogger; import edu.stanford.nlp.util.logging.Redwood.RedwoodChannels; /** * Class representing an ordered triple of objects, possibly typed. * Useful when you'd like a method to return three objects, or would like to put * triples of objects in a Collection or Map. equals() and hashcode() should * work properly. * * @author Teg Grenager (grenager@stanford.edu) */ public class Triple<T1,T2,T3> implements Comparable<Triple<T1,T2,T3>>, Serializable, PrettyLoggable { private static final long serialVersionUID = -4182871682751645440L; public T1 first; public T2 second; public T3 third; public Triple(T1 first, T2 second, T3 third) { this.first = first; this.second = second; this.third = third; } public T1 first() { return first; } public T2 second() { return second; } public T3 third() { return third; } public void setFirst(T1 o) { first = o; } public void setSecond(T2 o) { second = o; } public void setThird(T3 o) { third = o; } @SuppressWarnings("unchecked") @Override public boolean equals(Object o) { if (this == o) { return true; } if ( ! (o instanceof Triple)) { return false; } final Triple<T1,T2,T3> triple = (Triple<T1,T2,T3>) o; return Objects.equals(first, triple.first) && Objects.equals(second, triple.second) && Objects.equals(third, triple.third); } @Override public int hashCode() { int result; result = (first != null ? first.hashCode() : 0); result = 29 * result + (second != null ? second.hashCode() : 0); result = 29 * result + (third != null ? third.hashCode() : 0); return result; } @Override public String toString() { return "(" + first + "," + second + "," + third + ")"; } public List<Object> asList() { return CollectionUtils.makeList(first, second, third); } /** * Returns a Triple constructed from X, Y, and Z. Convenience method; the * compiler will disambiguate the classes used for you so that you don't have * to write out potentially long class names. */ public static <X, Y, Z> Triple<X, Y, Z> makeTriple(X x, Y y, Z z) { return new Triple<>(x, y, z); } /** * {@inheritDoc} */ public void prettyLog(RedwoodChannels channels, String description) { PrettyLogger.log(channels, description, this.asList()); } @SuppressWarnings("unchecked") @Override public int compareTo(Triple<T1, T2, T3> another) { int comp = ((Comparable<T1>) first()).compareTo(another.first()); if (comp != 0) { return comp; } else { comp = ((Comparable<T2>) second()).compareTo(another.second()); if (comp != 0) { return comp; } else { return ((Comparable<T3>) third()).compareTo(another.third()); } } } }
stanfordnlp/CoreNLP
src/edu/stanford/nlp/util/Triple.java
85
/* * Copyright (C) 2012 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 retrofit2; import static java.util.Collections.unmodifiableList; import java.lang.annotation.Annotation; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.Proxy; import java.lang.reflect.Type; import java.net.URL; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; import java.util.Deque; import java.util.List; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executor; import javax.annotation.Nullable; import okhttp3.HttpUrl; import okhttp3.OkHttpClient; import okhttp3.RequestBody; import okhttp3.ResponseBody; import retrofit2.http.GET; import retrofit2.http.HTTP; import retrofit2.http.Header; import retrofit2.http.Url; /** * Retrofit adapts a Java interface to HTTP calls by using annotations on the declared methods to * define how requests are made. Create instances using {@linkplain Builder the builder} and pass * your interface to {@link #create} to generate an implementation. * * <p>For example, * * <pre><code> * Retrofit retrofit = new Retrofit.Builder() * .baseUrl("https://api.example.com/") * .addConverterFactory(GsonConverterFactory.create()) * .build(); * * MyApi api = retrofit.create(MyApi.class); * Response&lt;User&gt; user = api.getUser().execute(); * </code></pre> * * @author Bob Lee (bob@squareup.com) * @author Jake Wharton (jw@squareup.com) */ public final class Retrofit { /** * Method associations in this map will be in one of three states, and may only progress forward * to higher-numbered states. * <ol> * <li>No value - no one has started or completed parsing annotations for the method.</li> * <li>Lock object - a thread has started parsing annotations on the method. Once the lock is * available the map will have been updated with the parsed model.</li> * <li>{@code ServiceMethod} - annotations for the method have been fully parsed.</li> * </ol> * This map should only be accessed through {@link #loadServiceMethod} which contains the state * transition logic. */ private final ConcurrentHashMap<Method, Object> serviceMethodCache = new ConcurrentHashMap<>(); final okhttp3.Call.Factory callFactory; final HttpUrl baseUrl; final List<Converter.Factory> converterFactories; final int defaultConverterFactoriesSize; final List<CallAdapter.Factory> callAdapterFactories; final int defaultCallAdapterFactoriesSize; final @Nullable Executor callbackExecutor; final boolean validateEagerly; Retrofit( okhttp3.Call.Factory callFactory, HttpUrl baseUrl, List<Converter.Factory> converterFactories, int defaultConverterFactoriesSize, List<CallAdapter.Factory> callAdapterFactories, int defaultCallAdapterFactoriesSize, @Nullable Executor callbackExecutor, boolean validateEagerly) { this.callFactory = callFactory; this.baseUrl = baseUrl; this.converterFactories = converterFactories; // Copy+unmodifiable at call site. this.defaultConverterFactoriesSize = defaultConverterFactoriesSize; this.callAdapterFactories = callAdapterFactories; // Copy+unmodifiable at call site. this.defaultCallAdapterFactoriesSize = defaultCallAdapterFactoriesSize; this.callbackExecutor = callbackExecutor; this.validateEagerly = validateEagerly; } /** * Create an implementation of the API endpoints defined by the {@code service} interface. * * <p>The relative path for a given method is obtained from an annotation on the method describing * the request type. The built-in methods are {@link retrofit2.http.GET GET}, {@link * retrofit2.http.PUT PUT}, {@link retrofit2.http.POST POST}, {@link retrofit2.http.PATCH PATCH}, * {@link retrofit2.http.HEAD HEAD}, {@link retrofit2.http.DELETE DELETE} and {@link * retrofit2.http.OPTIONS OPTIONS}. You can use a custom HTTP method with {@link HTTP @HTTP}. For * a dynamic URL, omit the path on the annotation and annotate the first parameter with {@link * Url @Url}. * * <p>Method parameters can be used to replace parts of the URL by annotating them with {@link * retrofit2.http.Path @Path}. Replacement sections are denoted by an identifier surrounded by * curly braces (e.g., "{foo}"). To add items to the query string of a URL use {@link * retrofit2.http.Query @Query}. * * <p>The body of a request is denoted by the {@link retrofit2.http.Body @Body} annotation. The * object will be converted to request representation by one of the {@link Converter.Factory} * instances. A {@link RequestBody} can also be used for a raw representation. * * <p>Alternative request body formats are supported by method annotations and corresponding * parameter annotations: * * <ul> * <li>{@link retrofit2.http.FormUrlEncoded @FormUrlEncoded} - Form-encoded data with key-value * pairs specified by the {@link retrofit2.http.Field @Field} parameter annotation. * <li>{@link retrofit2.http.Multipart @Multipart} - RFC 2388-compliant multipart data with * parts specified by the {@link retrofit2.http.Part @Part} parameter annotation. * </ul> * * <p>Additional static headers can be added for an endpoint using the {@link * retrofit2.http.Headers @Headers} method annotation. For per-request control over a header * annotate a parameter with {@link Header @Header}. * * <p>By default, methods return a {@link Call} which represents the HTTP request. The generic * parameter of the call is the response body type and will be converted by one of the {@link * Converter.Factory} instances. {@link ResponseBody} can also be used for a raw representation. * {@link Void} can be used if you do not care about the body contents. * * <p>For example: * * <pre> * public interface CategoryService { * &#64;POST("category/{cat}/") * Call&lt;List&lt;Item&gt;&gt; categoryList(@Path("cat") String a, @Query("page") int b); * } * </pre> */ @SuppressWarnings("unchecked") // Single-interface proxy creation guarded by parameter safety. public <T> T create(final Class<T> service) { validateServiceInterface(service); return (T) Proxy.newProxyInstance( service.getClassLoader(), new Class<?>[] {service}, new InvocationHandler() { private final Object[] emptyArgs = new Object[0]; @Override public @Nullable Object invoke(Object proxy, Method method, @Nullable Object[] args) throws Throwable { // If the method is a method from Object then defer to normal invocation. if (method.getDeclaringClass() == Object.class) { return method.invoke(this, args); } args = args != null ? args : emptyArgs; Reflection reflection = Platform.reflection; return reflection.isDefaultMethod(method) ? reflection.invokeDefaultMethod(method, service, proxy, args) : loadServiceMethod(service, method).invoke(proxy, args); } }); } private void validateServiceInterface(Class<?> service) { if (!service.isInterface()) { throw new IllegalArgumentException("API declarations must be interfaces."); } Deque<Class<?>> check = new ArrayDeque<>(1); check.add(service); while (!check.isEmpty()) { Class<?> candidate = check.removeFirst(); if (candidate.getTypeParameters().length != 0) { StringBuilder message = new StringBuilder("Type parameters are unsupported on ").append(candidate.getName()); if (candidate != service) { message.append(" which is an interface of ").append(service.getName()); } throw new IllegalArgumentException(message.toString()); } Collections.addAll(check, candidate.getInterfaces()); } if (validateEagerly) { Reflection reflection = Platform.reflection; for (Method method : service.getDeclaredMethods()) { if (!reflection.isDefaultMethod(method) && !Modifier.isStatic(method.getModifiers()) && !method.isSynthetic()) { loadServiceMethod(service, method); } } } } ServiceMethod<?> loadServiceMethod(Class<?> service, Method method) { while (true) { // Note: Once we are minSdk 24 this whole method can be replaced by computeIfAbsent. Object lookup = serviceMethodCache.get(method); if (lookup instanceof ServiceMethod<?>) { // Happy path: method is already parsed into the model. return (ServiceMethod<?>) lookup; } if (lookup == null) { // Map does not contain any value. Try to put in a lock for this method. We MUST synchronize // on the lock before it is visible to others via the map to signal we are doing the work. Object lock = new Object(); synchronized (lock) { lookup = serviceMethodCache.putIfAbsent(method, lock); if (lookup == null) { // On successful lock insertion, perform the work and update the map before releasing. // Other threads may be waiting on lock now and will expect the parsed model. ServiceMethod<Object> result; try { result = ServiceMethod.parseAnnotations(this, service, method); } catch (Throwable e) { // Remove the lock on failure. Any other locked threads will retry as a result. serviceMethodCache.remove(method); throw e; } serviceMethodCache.put(method, result); return result; } } } // Either the initial lookup or the attempt to put our lock in the map has returned someone // else's lock. This means they are doing the parsing, and will update the map before // releasing // the lock. Once we can take the lock, the map is guaranteed to contain the model or null. // Note: There's a chance that our effort to put a lock into the map has actually returned a // finished model instead of a lock. In that case this code will perform a pointless lock and // redundant lookup in the map of the same instance. This is rare, and ultimately harmless. synchronized (lookup) { Object result = serviceMethodCache.get(method); if (result == null) { // The other thread failed its parsing. We will retry (and probably also fail). continue; } return (ServiceMethod<?>) result; } } } /** * The factory used to create {@linkplain okhttp3.Call OkHttp calls} for sending a HTTP requests. * Typically an instance of {@link OkHttpClient}. */ public okhttp3.Call.Factory callFactory() { return callFactory; } /** The API base URL. */ public HttpUrl baseUrl() { return baseUrl; } /** * Returns a list of the factories tried when creating a {@linkplain #callAdapter(Type, * Annotation[])} call adapter}. */ public List<CallAdapter.Factory> callAdapterFactories() { return callAdapterFactories; } /** * Returns the {@link CallAdapter} for {@code returnType} from the available {@linkplain * #callAdapterFactories() factories}. * * @throws IllegalArgumentException if no call adapter available for {@code type}. */ public CallAdapter<?, ?> callAdapter(Type returnType, Annotation[] annotations) { return nextCallAdapter(null, returnType, annotations); } /** * Returns the {@link CallAdapter} for {@code returnType} from the available {@linkplain * #callAdapterFactories() factories} except {@code skipPast}. * * @throws IllegalArgumentException if no call adapter available for {@code type}. */ public CallAdapter<?, ?> nextCallAdapter( @Nullable CallAdapter.Factory skipPast, Type returnType, Annotation[] annotations) { Objects.requireNonNull(returnType, "returnType == null"); Objects.requireNonNull(annotations, "annotations == null"); int start = callAdapterFactories.indexOf(skipPast) + 1; for (int i = start, count = callAdapterFactories.size(); i < count; i++) { CallAdapter<?, ?> adapter = callAdapterFactories.get(i).get(returnType, annotations, this); if (adapter != null) { return adapter; } } StringBuilder builder = new StringBuilder("Could not locate call adapter for ").append(returnType).append(".\n"); if (skipPast != null) { builder.append(" Skipped:"); for (int i = 0; i < start; i++) { builder.append("\n * ").append(callAdapterFactories.get(i).getClass().getName()); } builder.append('\n'); } builder.append(" Tried:"); for (int i = start, count = callAdapterFactories.size(); i < count; i++) { builder.append("\n * ").append(callAdapterFactories.get(i).getClass().getName()); } throw new IllegalArgumentException(builder.toString()); } /** * Returns an unmodifiable list of the factories tried when creating a {@linkplain * #requestBodyConverter(Type, Annotation[], Annotation[]) request body converter}, a {@linkplain * #responseBodyConverter(Type, Annotation[]) response body converter}, or a {@linkplain * #stringConverter(Type, Annotation[]) string converter}. */ public List<Converter.Factory> converterFactories() { return converterFactories; } /** * Returns a {@link Converter} for {@code type} to {@link RequestBody} from the available * {@linkplain #converterFactories() factories}. * * @throws IllegalArgumentException if no converter available for {@code type}. */ public <T> Converter<T, RequestBody> requestBodyConverter( Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations) { return nextRequestBodyConverter(null, type, parameterAnnotations, methodAnnotations); } /** * Returns a {@link Converter} for {@code type} to {@link RequestBody} from the available * {@linkplain #converterFactories() factories} except {@code skipPast}. * * @throws IllegalArgumentException if no converter available for {@code type}. */ public <T> Converter<T, RequestBody> nextRequestBodyConverter( @Nullable Converter.Factory skipPast, Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations) { Objects.requireNonNull(type, "type == null"); Objects.requireNonNull(parameterAnnotations, "parameterAnnotations == null"); Objects.requireNonNull(methodAnnotations, "methodAnnotations == null"); int start = converterFactories.indexOf(skipPast) + 1; for (int i = start, count = converterFactories.size(); i < count; i++) { Converter.Factory factory = converterFactories.get(i); Converter<?, RequestBody> converter = factory.requestBodyConverter(type, parameterAnnotations, methodAnnotations, this); if (converter != null) { //noinspection unchecked return (Converter<T, RequestBody>) converter; } } StringBuilder builder = new StringBuilder("Could not locate RequestBody converter for ").append(type).append(".\n"); if (skipPast != null) { builder.append(" Skipped:"); for (int i = 0; i < start; i++) { builder.append("\n * ").append(converterFactories.get(i).getClass().getName()); } builder.append('\n'); } builder.append(" Tried:"); for (int i = start, count = converterFactories.size(); i < count; i++) { builder.append("\n * ").append(converterFactories.get(i).getClass().getName()); } throw new IllegalArgumentException(builder.toString()); } /** * Returns a {@link Converter} for {@link ResponseBody} to {@code type} from the available * {@linkplain #converterFactories() factories}. * * @throws IllegalArgumentException if no converter available for {@code type}. */ public <T> Converter<ResponseBody, T> responseBodyConverter(Type type, Annotation[] annotations) { return nextResponseBodyConverter(null, type, annotations); } /** * Returns a {@link Converter} for {@link ResponseBody} to {@code type} from the available * {@linkplain #converterFactories() factories} except {@code skipPast}. * * @throws IllegalArgumentException if no converter available for {@code type}. */ public <T> Converter<ResponseBody, T> nextResponseBodyConverter( @Nullable Converter.Factory skipPast, Type type, Annotation[] annotations) { Objects.requireNonNull(type, "type == null"); Objects.requireNonNull(annotations, "annotations == null"); int start = converterFactories.indexOf(skipPast) + 1; for (int i = start, count = converterFactories.size(); i < count; i++) { Converter<ResponseBody, ?> converter = converterFactories.get(i).responseBodyConverter(type, annotations, this); if (converter != null) { //noinspection unchecked return (Converter<ResponseBody, T>) converter; } } StringBuilder builder = new StringBuilder("Could not locate ResponseBody converter for ") .append(type) .append(".\n"); if (skipPast != null) { builder.append(" Skipped:"); for (int i = 0; i < start; i++) { builder.append("\n * ").append(converterFactories.get(i).getClass().getName()); } builder.append('\n'); } builder.append(" Tried:"); for (int i = start, count = converterFactories.size(); i < count; i++) { builder.append("\n * ").append(converterFactories.get(i).getClass().getName()); } throw new IllegalArgumentException(builder.toString()); } /** * Returns a {@link Converter} for {@code type} to {@link String} from the available {@linkplain * #converterFactories() factories}. */ public <T> Converter<T, String> stringConverter(Type type, Annotation[] annotations) { Objects.requireNonNull(type, "type == null"); Objects.requireNonNull(annotations, "annotations == null"); for (int i = 0, count = converterFactories.size(); i < count; i++) { Converter<?, String> converter = converterFactories.get(i).stringConverter(type, annotations, this); if (converter != null) { //noinspection unchecked return (Converter<T, String>) converter; } } // Nothing matched. Resort to default converter which just calls toString(). //noinspection unchecked return (Converter<T, String>) BuiltInConverters.ToStringConverter.INSTANCE; } /** * The executor used for {@link Callback} methods on a {@link Call}. This may be {@code null}, in * which case callbacks should be made synchronously on the background thread. */ public @Nullable Executor callbackExecutor() { return callbackExecutor; } public Builder newBuilder() { return new Builder(this); } /** * Build a new {@link Retrofit}. * * <p>Calling {@link #baseUrl} is required before calling {@link #build()}. All other methods are * optional. */ public static final class Builder { private @Nullable okhttp3.Call.Factory callFactory; private @Nullable HttpUrl baseUrl; private final List<Converter.Factory> converterFactories = new ArrayList<>(); private final List<CallAdapter.Factory> callAdapterFactories = new ArrayList<>(); private @Nullable Executor callbackExecutor; private boolean validateEagerly; public Builder() {} Builder(Retrofit retrofit) { callFactory = retrofit.callFactory; baseUrl = retrofit.baseUrl; // Do not add the default BuiltIntConverters and platform-aware converters added by build(). for (int i = 1, size = retrofit.converterFactories.size() - retrofit.defaultConverterFactoriesSize; i < size; i++) { converterFactories.add(retrofit.converterFactories.get(i)); } // Do not add the default, platform-aware call adapters added by build(). for (int i = 0, size = retrofit.callAdapterFactories.size() - retrofit.defaultCallAdapterFactoriesSize; i < size; i++) { callAdapterFactories.add(retrofit.callAdapterFactories.get(i)); } callbackExecutor = retrofit.callbackExecutor; validateEagerly = retrofit.validateEagerly; } /** * The HTTP client used for requests. * * <p>This is a convenience method for calling {@link #callFactory}. */ public Builder client(OkHttpClient client) { return callFactory(Objects.requireNonNull(client, "client == null")); } /** * Specify a custom call factory for creating {@link Call} instances. * * <p>Note: Calling {@link #client} automatically sets this value. */ public Builder callFactory(okhttp3.Call.Factory factory) { this.callFactory = Objects.requireNonNull(factory, "factory == null"); return this; } /** * Set the API base URL. * * @see #baseUrl(HttpUrl) */ public Builder baseUrl(URL baseUrl) { Objects.requireNonNull(baseUrl, "baseUrl == null"); return baseUrl(HttpUrl.get(baseUrl.toString())); } /** * Set the API base URL. * * @see #baseUrl(HttpUrl) */ public Builder baseUrl(String baseUrl) { Objects.requireNonNull(baseUrl, "baseUrl == null"); return baseUrl(HttpUrl.get(baseUrl)); } /** * Set the API base URL. * * <p>The specified endpoint values (such as with {@link GET @GET}) are resolved against this * value using {@link HttpUrl#resolve(String)}. The behavior of this matches that of an {@code * <a href="">} link on a website resolving on the current URL. * * <p><b>Base URLs should always end in {@code /}.</b> * * <p>A trailing {@code /} ensures that endpoints values which are relative paths will correctly * append themselves to a base which has path components. * * <p><b>Correct:</b><br> * Base URL: http://example.com/api/<br> * Endpoint: foo/bar/<br> * Result: http://example.com/api/foo/bar/ * * <p><b>Incorrect:</b><br> * Base URL: http://example.com/api<br> * Endpoint: foo/bar/<br> * Result: http://example.com/foo/bar/ * * <p>This method enforces that {@code baseUrl} has a trailing {@code /}. * * <p><b>Endpoint values which contain a leading {@code /} are absolute.</b> * * <p>Absolute values retain only the host from {@code baseUrl} and ignore any specified path * components. * * <p>Base URL: http://example.com/api/<br> * Endpoint: /foo/bar/<br> * Result: http://example.com/foo/bar/ * * <p>Base URL: http://example.com/<br> * Endpoint: /foo/bar/<br> * Result: http://example.com/foo/bar/ * * <p><b>Endpoint values may be a full URL.</b> * * <p>Values which have a host replace the host of {@code baseUrl} and values also with a scheme * replace the scheme of {@code baseUrl}. * * <p>Base URL: http://example.com/<br> * Endpoint: https://github.com/square/retrofit/<br> * Result: https://github.com/square/retrofit/ * * <p>Base URL: http://example.com<br> * Endpoint: //github.com/square/retrofit/<br> * Result: http://github.com/square/retrofit/ (note the scheme stays 'http') */ public Builder baseUrl(HttpUrl baseUrl) { Objects.requireNonNull(baseUrl, "baseUrl == null"); List<String> pathSegments = baseUrl.pathSegments(); if (!"".equals(pathSegments.get(pathSegments.size() - 1))) { throw new IllegalArgumentException("baseUrl must end in /: " + baseUrl); } this.baseUrl = baseUrl; return this; } /** Add converter factory for serialization and deserialization of objects. */ public Builder addConverterFactory(Converter.Factory factory) { converterFactories.add(Objects.requireNonNull(factory, "factory == null")); return this; } /** * Add a call adapter factory for supporting service method return types other than {@link * Call}. */ public Builder addCallAdapterFactory(CallAdapter.Factory factory) { callAdapterFactories.add(Objects.requireNonNull(factory, "factory == null")); return this; } /** * The executor on which {@link Callback} methods are invoked when returning {@link Call} from * your service method. * * <p>Note: {@code executor} is not used for {@linkplain #addCallAdapterFactory custom method * return types}. */ public Builder callbackExecutor(Executor executor) { this.callbackExecutor = Objects.requireNonNull(executor, "executor == null"); return this; } /** Returns a modifiable list of call adapter factories. */ public List<CallAdapter.Factory> callAdapterFactories() { return this.callAdapterFactories; } /** Returns a modifiable list of converter factories. */ public List<Converter.Factory> converterFactories() { return this.converterFactories; } /** * When calling {@link #create} on the resulting {@link Retrofit} instance, eagerly validate the * configuration of all methods in the supplied interface. */ public Builder validateEagerly(boolean validateEagerly) { this.validateEagerly = validateEagerly; return this; } /** * Create the {@link Retrofit} instance using the configured values. * * <p>Note: If neither {@link #client} nor {@link #callFactory} is called a default {@link * OkHttpClient} will be created and used. */ public Retrofit build() { if (baseUrl == null) { throw new IllegalStateException("Base URL required."); } okhttp3.Call.Factory callFactory = this.callFactory; if (callFactory == null) { callFactory = new OkHttpClient(); } Executor callbackExecutor = this.callbackExecutor; if (callbackExecutor == null) { callbackExecutor = Platform.callbackExecutor; } BuiltInFactories builtInFactories = Platform.builtInFactories; // Make a defensive copy of the adapters and add the default Call adapter. List<CallAdapter.Factory> callAdapterFactories = new ArrayList<>(this.callAdapterFactories); List<? extends CallAdapter.Factory> defaultCallAdapterFactories = builtInFactories.createDefaultCallAdapterFactories(callbackExecutor); callAdapterFactories.addAll(defaultCallAdapterFactories); // Make a defensive copy of the converters. List<? extends Converter.Factory> defaultConverterFactories = builtInFactories.createDefaultConverterFactories(); int defaultConverterFactoriesSize = defaultConverterFactories.size(); List<Converter.Factory> converterFactories = new ArrayList<>(1 + this.converterFactories.size() + defaultConverterFactoriesSize); // Add the built-in converter factory first. This prevents overriding its behavior but also // ensures correct behavior when using converters that consume all types. converterFactories.add(new BuiltInConverters()); converterFactories.addAll(this.converterFactories); converterFactories.addAll(defaultConverterFactories); return new Retrofit( callFactory, baseUrl, unmodifiableList(converterFactories), defaultConverterFactoriesSize, unmodifiableList(callAdapterFactories), defaultCallAdapterFactories.size(), callbackExecutor, validateEagerly); } } }
square/retrofit
retrofit/src/main/java/retrofit2/Retrofit.java
86
/* * Copyright 2008 ZXing authors * * 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.google.zxing.qrcode; import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.Writer; import com.google.zxing.WriterException; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.encoder.ByteMatrix; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; import com.google.zxing.qrcode.encoder.Encoder; import com.google.zxing.qrcode.encoder.QRCode; import java.util.Map; /** * This object renders a QR Code as a BitMatrix 2D array of greyscale values. * * @author dswitkin@google.com (Daniel Switkin) */ public final class QRCodeWriter implements Writer { private static final int QUIET_ZONE_SIZE = 4; @Override public BitMatrix encode(String contents, BarcodeFormat format, int width, int height) throws WriterException { return encode(contents, format, width, height, null); } @Override public BitMatrix encode(String contents, BarcodeFormat format, int width, int height, Map<EncodeHintType,?> hints) throws WriterException { if (contents.isEmpty()) { throw new IllegalArgumentException("Found empty contents"); } if (format != BarcodeFormat.QR_CODE) { throw new IllegalArgumentException("Can only encode QR_CODE, but got " + format); } if (width < 0 || height < 0) { throw new IllegalArgumentException("Requested dimensions are too small: " + width + 'x' + height); } ErrorCorrectionLevel errorCorrectionLevel = ErrorCorrectionLevel.L; int quietZone = QUIET_ZONE_SIZE; if (hints != null) { if (hints.containsKey(EncodeHintType.ERROR_CORRECTION)) { errorCorrectionLevel = ErrorCorrectionLevel.valueOf(hints.get(EncodeHintType.ERROR_CORRECTION).toString()); } if (hints.containsKey(EncodeHintType.MARGIN)) { quietZone = Integer.parseInt(hints.get(EncodeHintType.MARGIN).toString()); } } QRCode code = Encoder.encode(contents, errorCorrectionLevel, hints); return renderResult(code, width, height, quietZone); } /** * Renders the given {@link QRCode} as a {@link BitMatrix}, scaling the * same to be compliant with the provided dimensions. * * <p>If no scaling is required, both {@code width} and {@code height} * arguments should be non-positive numbers. * * @param code {@code QRCode} to be adapted as a {@code BitMatrix} * @param width desired width for the {@code QRCode} (in pixel units) * @param height desired height for the {@code QRCode} (in pixel units) * @param quietZone the size of the QR quiet zone (in pixel units) * @return {@code BitMatrix} instance * * @throws IllegalStateException if {@code code} does not have * a {@link QRCode#getMatrix() Matrix} * * @throws NullPointerException if {@code code} is {@code null} */ public static BitMatrix renderResult(QRCode code, int width, int height, int quietZone) { // Note that the input matrix uses 0 == white, 1 == black, while the output matrix uses // 0 == black, 255 == white (i.e. an 8 bit greyscale bitmap). ByteMatrix input = code.getMatrix(); if (input == null) { throw new IllegalStateException(); } int inputWidth = input.getWidth(); int inputHeight = input.getHeight(); int qrWidth = inputWidth + (quietZone * 2); int qrHeight = inputHeight + (quietZone * 2); int outputWidth = Math.max(width, qrWidth); int outputHeight = Math.max(height, qrHeight); int multiple = Math.min(outputWidth / qrWidth, outputHeight / qrHeight); // Padding includes both the quiet zone and the extra white pixels to accommodate the requested // dimensions. For example, if input is 25x25 the QR will be 33x33 including the quiet zone. // If the requested size is 200x160, the multiple will be 4, for a QR of 132x132. These will // handle all the padding from 100x100 (the actual QR) up to 200x160. int leftPadding = (outputWidth - (inputWidth * multiple)) / 2; int topPadding = (outputHeight - (inputHeight * multiple)) / 2; BitMatrix output = new BitMatrix(outputWidth, outputHeight); for (int inputY = 0, outputY = topPadding; inputY < inputHeight; inputY++, outputY += multiple) { // Write the contents of this row of the barcode for (int inputX = 0, outputX = leftPadding; inputX < inputWidth; inputX++, outputX += multiple) { if (input.get(inputX, inputY) == 1) { output.setRegion(outputX, outputY, multiple, multiple); } } } return output; } }
zxing/zxing
core/src/main/java/com/google/zxing/qrcode/QRCodeWriter.java
87
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * Project Info: https://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * https://plantuml.com/patreon (only 1$ per month!) * https://plantuml.com/paypal * * This file is part of Smetana. * Smetana is a partial translation of Graphviz/Dot sources from C to Java. * * (C) Copyright 2009-2022, Arnaud Roques * * This translation is distributed under the same Licence as the original C program: * ************************************************************************* * Copyright (c) 2011 AT&T Intellectual Property * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: See CVS logs. Details at http://www.graphviz.org/ ************************************************************************* * * THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC * LICENSE ("AGREEMENT"). [Eclipse Public License - v 1.0] * * ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES * RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. * * You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * 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 h; import smetana.core.UnsupportedStarStruct; final public class ST_RTree extends UnsupportedStarStruct { public ST_Node_t___ root; // "Node_t *root", public final ST_SplitQ_t split = new ST_SplitQ_t(); public int MinFill; // "long ElapsedTime", // "float UserTime, SystemTime", public int Deleting; public int StatFlag; // "int InsertCount", // "int DeleteCount", // "int ReInsertCount", // "int InSplitCount", // "int DeSplitCount", public int ElimCount; // "int EvalCount", // "int InTouchCount", // "int DeTouchCount", public int SeTouchCount; // "int CallCount", // "float SplitMeritSum", public int RectCount; public int NodeCount; public int LeafCount, NonLeafCount; public int EntryCount; } // struct RTree { // Node_t *root; // // SplitQ_t split; // // /* balance criterion for node splitting */ // int MinFill; // // /* times */ // long ElapsedTime; // float UserTime, SystemTime; // // int Deleting; // // /* variables for statistics */ // int StatFlag; /* tells if we are counting or not */ // /* counters affected only when StatFlag set */ // int InsertCount; // int DeleteCount; // int ReInsertCount; // int InSplitCount; // int DeSplitCount; // int ElimCount; // int EvalCount; // int InTouchCount; // int DeTouchCount; // int SeTouchCount; // int CallCount; // float SplitMeritSum; // // /* counters used even when StatFlag not set */ // int RectCount; // int NodeCount; // int LeafCount, NonLeafCount; // int EntryCount; // int SearchCount; // int HitCount; // // };
plantuml/plantuml
src/h/ST_RTree.java
88
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * Project Info: https://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * https://plantuml.com/patreon (only 1$ per month!) * https://plantuml.com/paypal * * This file is part of Smetana. * Smetana is a partial translation of Graphviz/Dot sources from C to Java. * * (C) Copyright 2009-2022, Arnaud Roques * * This translation is distributed under the same Licence as the original C program: * ************************************************************************* * Copyright (c) 2011 AT&T Intellectual Property * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: See CVS logs. Details at http://www.graphviz.org/ ************************************************************************* * * THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC * LICENSE ("AGREEMENT"). [Eclipse Public License - v 1.0] * * ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES * RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. * * You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * 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 h; import smetana.core.CArrayOfStar; import smetana.core.UnsupportedStarStruct; import smetana.core.__struct__; //typedef struct rank_t { //int n; /* number of nodes in this rank */ //node_t **v; /* ordered list of nodes in rank */ //int an; /* globally allocated number of nodes */ //node_t **av; /* allocated list of nodes in rank */ //double ht1, ht2; /* height below/above centerline */ //double pht1, pht2; /* as above, but only primitive nodes */ //boolean candidate; /* for transpose () */ //boolean valid; //int cache_nc; /* caches number of crossings */ //adjmatrix_t *flat; //} rank_t; final public class ST_rank_t extends UnsupportedStarStruct { public int n; public CArrayOfStar<ST_Agnode_s> v; public int an; public CArrayOfStar<ST_Agnode_s> av; public double ht1, ht2; public double pht1, pht2; public boolean candidate; public int valid; public int cache_nc; public ST_adjmatrix_t flat; @Override public String toString() { return "RANK n=" + n + " v=" + v + " an=" + an + " av=" + av; } @Override public void ___(__struct__ other) { ST_rank_t this2 = (ST_rank_t) other; this.n = this2.n; this.v = this2.v; this.an = this2.an; this.av = this2.av; this.ht1 = this2.ht1; this.ht2 = this2.ht2; this.pht1 = this2.pht1; this.pht2 = this2.pht2; this.candidate = this2.candidate; this.valid = this2.valid; this.cache_nc = this2.cache_nc; this.flat = this2.flat; } }
plantuml/plantuml
src/h/ST_rank_t.java
89
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file or at // https://developers.google.com/open-source/licenses/bsd package com.google.protobuf; import static java.lang.annotation.ElementType.CONSTRUCTOR; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PACKAGE; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * Indicates that the return value of the annotated method must be used. An error is triggered when * one of these methods is called but the result is not used. * * <p>{@code @CheckReturnValue} may be applied to a class or package to indicate that all methods in * that class (including indirectly; that is, methods of inner classes within the annotated class) * or package must have their return values used. For convenience, we provide an annotation, {@link * CanIgnoreReturnValue}, to exempt specific methods or classes from this behavior. */ @Documented @Target({METHOD, CONSTRUCTOR, TYPE, PACKAGE}) @Retention(RUNTIME) @interface CheckReturnValue {}
protocolbuffers/protobuf
java/core/src/main/java/com/google/protobuf/CheckReturnValue.java
90
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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.badlogic.gdx.utils; import com.badlogic.gdx.Application; import com.badlogic.gdx.Files; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.LifecycleListener; /** Executes tasks in the future on the main loop thread. * @author Nathan Sweet */ public class Timer { // TimerThread access is synchronized using threadLock. // Timer access is synchronized using the Timer instance. // Task access is synchronized using the Task instance. // Posted tasks are synchronized using TimerThread#postedTasks. static final Object threadLock = new Object(); static TimerThread thread; /** Timer instance singleton for general application wide usage. Static methods on {@link Timer} make convenient use of this * instance. */ static public Timer instance () { synchronized (threadLock) { TimerThread thread = thread(); if (thread.instance == null) thread.instance = new Timer(); return thread.instance; } } static private TimerThread thread () { synchronized (threadLock) { if (thread == null || thread.files != Gdx.files) { if (thread != null) thread.dispose(); thread = new TimerThread(); } return thread; } } final Array<Task> tasks = new Array(false, 8); long stopTimeMillis; public Timer () { start(); } /** Schedules a task to occur once as soon as possible, but not sooner than the start of the next frame. */ public Task postTask (Task task) { return scheduleTask(task, 0, 0, 0); } /** Schedules a task to occur once after the specified delay. */ public Task scheduleTask (Task task, float delaySeconds) { return scheduleTask(task, delaySeconds, 0, 0); } /** Schedules a task to occur once after the specified delay and then repeatedly at the specified interval until cancelled. */ public Task scheduleTask (Task task, float delaySeconds, float intervalSeconds) { return scheduleTask(task, delaySeconds, intervalSeconds, -1); } /** Schedules a task to occur once after the specified delay and then a number of additional times at the specified interval. * @param repeatCount If negative, the task will repeat forever. */ public Task scheduleTask (Task task, float delaySeconds, float intervalSeconds, int repeatCount) { synchronized (threadLock) { synchronized (this) { synchronized (task) { if (task.timer != null) throw new IllegalArgumentException("The same task may not be scheduled twice."); task.timer = this; long timeMillis = System.nanoTime() / 1000000; long executeTimeMillis = timeMillis + (long)(delaySeconds * 1000); if (thread.pauseTimeMillis > 0) executeTimeMillis -= timeMillis - thread.pauseTimeMillis; task.executeTimeMillis = executeTimeMillis; task.intervalMillis = (long)(intervalSeconds * 1000); task.repeatCount = repeatCount; tasks.add(task); } } threadLock.notifyAll(); } return task; } /** Stops the timer if it was started. Tasks will not be executed while stopped. */ public void stop () { synchronized (threadLock) { if (thread().instances.removeValue(this, true)) stopTimeMillis = System.nanoTime() / 1000000; } } /** Starts the timer if it was stopped. Tasks are delayed by the time passed while stopped. */ public void start () { synchronized (threadLock) { TimerThread thread = thread(); Array<Timer> instances = thread.instances; if (instances.contains(this, true)) return; instances.add(this); if (stopTimeMillis > 0) { delay(System.nanoTime() / 1000000 - stopTimeMillis); stopTimeMillis = 0; } threadLock.notifyAll(); } } /** Cancels all tasks. */ public void clear () { synchronized (threadLock) { TimerThread thread = thread(); synchronized (this) { synchronized (thread.postedTasks) { for (int i = 0, n = tasks.size; i < n; i++) { Task task = tasks.get(i); thread.removePostedTask(task); task.reset(); } } tasks.clear(); } } } /** Returns true if the timer has no tasks in the queue. Note that this can change at any time. Synchronize on the timer * instance to prevent tasks being added, removed, or updated. */ public synchronized boolean isEmpty () { return tasks.size == 0; } synchronized long update (TimerThread thread, long timeMillis, long waitMillis) { for (int i = 0, n = tasks.size; i < n; i++) { Task task = tasks.get(i); synchronized (task) { if (task.executeTimeMillis > timeMillis) { waitMillis = Math.min(waitMillis, task.executeTimeMillis - timeMillis); continue; } if (task.repeatCount == 0) { task.timer = null; tasks.removeIndex(i); i--; n--; } else { task.executeTimeMillis = timeMillis + task.intervalMillis; waitMillis = Math.min(waitMillis, task.intervalMillis); if (task.repeatCount > 0) task.repeatCount--; } thread.addPostedTask(task); } } return waitMillis; } /** Adds the specified delay to all tasks. */ public synchronized void delay (long delayMillis) { for (int i = 0, n = tasks.size; i < n; i++) { Task task = tasks.get(i); synchronized (task) { task.executeTimeMillis += delayMillis; } } } /** Schedules a task on {@link #instance}. * @see #postTask(Task) */ static public Task post (Task task) { return instance().postTask(task); } /** Schedules a task on {@link #instance}. * @see #scheduleTask(Task, float) */ static public Task schedule (Task task, float delaySeconds) { return instance().scheduleTask(task, delaySeconds); } /** Schedules a task on {@link #instance}. * @see #scheduleTask(Task, float, float) */ static public Task schedule (Task task, float delaySeconds, float intervalSeconds) { return instance().scheduleTask(task, delaySeconds, intervalSeconds); } /** Schedules a task on {@link #instance}. * @see #scheduleTask(Task, float, float, int) */ static public Task schedule (Task task, float delaySeconds, float intervalSeconds, int repeatCount) { return instance().scheduleTask(task, delaySeconds, intervalSeconds, repeatCount); } /** Runnable that can be scheduled on a {@link Timer}. * @author Nathan Sweet */ static abstract public class Task implements Runnable { final Application app; long executeTimeMillis, intervalMillis; int repeatCount; volatile Timer timer; public Task () { app = Gdx.app; // Store which app to postRunnable (eg for multiple LwjglAWTCanvas). if (app == null) throw new IllegalStateException("Gdx.app not available."); } /** If this is the last time the task will be ran or the task is first cancelled, it may be scheduled again in this * method. */ abstract public void run (); /** Cancels the task. It will not be executed until it is scheduled again. This method can be called at any time. */ public void cancel () { synchronized (threadLock) { thread().removePostedTask(this); Timer timer = this.timer; if (timer != null) { synchronized (timer) { timer.tasks.removeValue(this, true); reset(); } } else reset(); } } synchronized void reset () { executeTimeMillis = 0; this.timer = null; } /** Returns true if this task is scheduled to be executed in the future by a timer. The execution time may be reached at any * time after calling this method, which may change the scheduled state. To prevent the scheduled state from changing, * synchronize on this task object, eg: * * <pre> * synchronized (task) { * if (!task.isScheduled()) { ... } * } * </pre> */ public boolean isScheduled () { return timer != null; } /** Returns the time in milliseconds when this task will be executed next. */ public synchronized long getExecuteTimeMillis () { return executeTimeMillis; } } /** Manages a single thread for updating timers. Uses libgdx application events to pause, resume, and dispose the thread. * @author Nathan Sweet */ static class TimerThread implements Runnable, LifecycleListener { final Files files; final Application app; final Array<Timer> instances = new Array(1); Timer instance; long pauseTimeMillis; final Array<Task> postedTasks = new Array(2); final Array<Task> runTasks = new Array(2); private final Runnable runPostedTasks = new Runnable() { public void run () { runPostedTasks(); } }; public TimerThread () { files = Gdx.files; app = Gdx.app; app.addLifecycleListener(this); resume(); Thread thread = new Thread(this, "Timer"); thread.setDaemon(true); thread.start(); } public void run () { while (true) { synchronized (threadLock) { if (thread != this || files != Gdx.files) break; long waitMillis = 5000; if (pauseTimeMillis == 0) { long timeMillis = System.nanoTime() / 1000000; for (int i = 0, n = instances.size; i < n; i++) { try { waitMillis = instances.get(i).update(this, timeMillis, waitMillis); } catch (Throwable ex) { throw new GdxRuntimeException("Task failed: " + instances.get(i).getClass().getName(), ex); } } } if (thread != this || files != Gdx.files) break; try { if (waitMillis > 0) threadLock.wait(waitMillis); } catch (InterruptedException ignored) { } } } dispose(); } void runPostedTasks () { synchronized (postedTasks) { runTasks.addAll(postedTasks); postedTasks.clear(); } Object[] items = runTasks.items; for (int i = 0, n = runTasks.size; i < n; i++) ((Task)items[i]).run(); runTasks.clear(); } void addPostedTask (Task task) { synchronized (postedTasks) { if (postedTasks.isEmpty()) task.app.postRunnable(runPostedTasks); postedTasks.add(task); } } void removePostedTask (Task task) { synchronized (postedTasks) { Object[] items = postedTasks.items; for (int i = postedTasks.size - 1; i >= 0; i--) if (items[i] == task) postedTasks.removeIndex(i); } } public void resume () { synchronized (threadLock) { long delayMillis = System.nanoTime() / 1000000 - pauseTimeMillis; for (int i = 0, n = instances.size; i < n; i++) instances.get(i).delay(delayMillis); pauseTimeMillis = 0; threadLock.notifyAll(); } } public void pause () { synchronized (threadLock) { pauseTimeMillis = System.nanoTime() / 1000000; threadLock.notifyAll(); } } public void dispose () { // OK to call multiple times. synchronized (threadLock) { synchronized (postedTasks) { postedTasks.clear(); } if (thread == this) thread = null; instances.clear(); threadLock.notifyAll(); } app.removeLifecycleListener(this); } } }
libgdx/libgdx
gdx/src/com/badlogic/gdx/utils/Timer.java
91
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * Project Info: https://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * https://plantuml.com/patreon (only 1$ per month!) * https://plantuml.com/paypal * * This file is part of Smetana. * Smetana is a partial translation of Graphviz/Dot sources from C to Java. * * (C) Copyright 2009-2022, Arnaud Roques * * This translation is distributed under the same Licence as the original C program: * ************************************************************************* * Copyright (c) 2011 AT&T Intellectual Property * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: See CVS logs. Details at http://www.graphviz.org/ ************************************************************************* * * THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC * LICENSE ("AGREEMENT"). [Eclipse Public License - v 1.0] * * ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES * RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. * * You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * 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 h; import smetana.core.CString; import smetana.core.UnsupportedStarStruct; import smetana.core.__struct__; final public class ST_port extends UnsupportedStarStruct { public final ST_pointf p = new ST_pointf(); public double theta; public ST_boxf bp; public boolean defined; public boolean constrained; public boolean clip; public boolean dyna; public int order; public int side; public CString name; @Override public void ___(__struct__ other) { ST_port other2 = (ST_port) other; this.p.___(other2.p); this.theta = other2.theta; this.bp = other2.bp; this.defined = other2.defined; this.constrained = other2.constrained; this.clip = other2.clip; this.dyna = other2.dyna; this.order = other2.order; this.side = other2.side; this.name = other2.name; } @Override public ST_port copy() { final ST_port result = new ST_port(); result.p.___(this.p); result.theta = this.theta; result.bp = this.bp; result.defined = this.defined; result.constrained = this.constrained; result.clip = this.clip; result.dyna = this.dyna; result.order = this.order; result.side = this.side; result.name = this.name; return result; } } // typedef struct port { /* internal edge endpoint specification */ // pointf p; /* aiming point relative to node center */ // double theta; /* slope in radians */ // boxf *bp; /* if not null, points to bbox of // * rectangular area that is port target // */ // boolean defined; /* if true, edge has port info at this end */ // boolean constrained; /* if true, constraints such as theta are set */ // boolean clip; /* if true, clip end to node/port shape */ // boolean dyna; /* if true, assign compass point dynamically */ // unsigned char order; /* for mincross */ // unsigned char side; /* if port is on perimeter of node, this // * contains the bitwise OR of the sides (TOP, // * BOTTOM, etc.) it is on. // */ // char *name; /* port name, if it was explicitly given, otherwise NULL */ // } port;
plantuml/plantuml
src/h/ST_port.java
92
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.spark.util.kvstore; import java.io.Closeable; import java.util.Collection; import org.apache.spark.annotation.Private; /** * Abstraction for a local key/value store for storing app data. * * <p> * There are two main features provided by the implementations of this interface: * </p> * * <h2>Serialization</h2> * * <p> * If the underlying data store requires serialization, data will be serialized to and deserialized * using a {@link KVStoreSerializer}, which can be customized by the application. The serializer is * based on Jackson, so it supports all the Jackson annotations for controlling the serialization of * app-defined types. * </p> * * <p> * Data is also automatically compressed to save disk space. * </p> * * <h2>Automatic Key Management</h2> * * <p> * When using the built-in key management, the implementation will automatically create unique * keys for each type written to the store. Keys are based on the type name, and always start * with the "+" prefix character (so that it's easy to use both manual and automatic key * management APIs without conflicts). * </p> * * <p> * Another feature of automatic key management is indexing; by annotating fields or methods of * objects written to the store with {@link KVIndex}, indices are created to sort the data * by the values of those properties. This makes it possible to provide sorting without having * to load all instances of those types from the store. * </p> * * <p> * KVStore instances are thread-safe for both reads and writes. * </p> */ @Private public interface KVStore extends Closeable { /** * Returns app-specific metadata from the store, or null if it's not currently set. * * <p> * The metadata type is application-specific. This is a convenience method so that applications * don't need to define their own keys for this information. * </p> */ <T> T getMetadata(Class<T> klass) throws Exception; /** * Writes the given value in the store metadata key. */ void setMetadata(Object value) throws Exception; /** * Read a specific instance of an object. * * @param naturalKey The object's "natural key", which uniquely identifies it. Null keys * are not allowed. * @throws java.util.NoSuchElementException If an element with the given key does not exist. */ <T> T read(Class<T> klass, Object naturalKey) throws Exception; /** * Writes the given object to the store, including indexed fields. Indices are updated based * on the annotated fields of the object's class. * * <p> * Writes may be slower when the object already exists in the store, since it will involve * updating existing indices. * </p> * * @param value The object to write. */ void write(Object value) throws Exception; /** * Removes an object and all data related to it, like index entries, from the store. * * @param type The object's type. * @param naturalKey The object's "natural key", which uniquely identifies it. Null keys * are not allowed. * @throws java.util.NoSuchElementException If an element with the given key does not exist. */ void delete(Class<?> type, Object naturalKey) throws Exception; /** * Returns a configurable view for iterating over entities of the given type. */ <T> KVStoreView<T> view(Class<T> type) throws Exception; /** * Returns the number of items of the given type currently in the store. */ long count(Class<?> type) throws Exception; /** * Returns the number of items of the given type which match the given indexed value. */ long count(Class<?> type, String index, Object indexedValue) throws Exception; /** * A cheaper way to remove multiple items from the KVStore */ <T> boolean removeAllByIndexValues(Class<T> klass, String index, Collection<?> indexValues) throws Exception; }
apache/spark
common/kvstore/src/main/java/org/apache/spark/util/kvstore/KVStore.java
93
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * Project Info: https://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * https://plantuml.com/patreon (only 1$ per month!) * https://plantuml.com/paypal * * This file is part of Smetana. * Smetana is a partial translation of Graphviz/Dot sources from C to Java. * * (C) Copyright 2009-2022, Arnaud Roques * * This translation is distributed under the same Licence as the original C program: * ************************************************************************* * Copyright (c) 2011 AT&T Intellectual Property * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: See CVS logs. Details at http://www.graphviz.org/ ************************************************************************* * * THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC * LICENSE ("AGREEMENT"). [Eclipse Public License - v 1.0] * * ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES * RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. * * You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * 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 h; import smetana.core.FieldOffset; import smetana.core.__ptr__; import smetana.core.__struct__; final public class ST_Agedge_s extends ST_Agobj_s { public ST_Agedge_s PREV; public ST_Agedge_s NEXT; public final ST_Agobj_s base = this; public final ST_dtlink_s id_link = new ST_dtlink_s(this); public final ST_dtlink_s seq_link = new ST_dtlink_s(this); public ST_Agnode_s node; public String NAME; // @Override // public String toString() { // return NAME; // } @Override public void ___(__struct__ arg) { ST_Agedge_s this2 = (ST_Agedge_s) arg; this.tag.___(this2.tag); this.data = this2.data; this.id_link.___(this2.id_link); this.seq_link.___(this2.seq_link); this.node = this2.node; } @Override public boolean isSameThan(__ptr__ other) { ST_Agedge_s other2 = (ST_Agedge_s) other; return this == other2; } @Override public Object getTheField(FieldOffset offset) { if (offset == null || offset.getSign() == 0) { return this; } if (offset == FieldOffset.seq_link) return seq_link; if (offset == FieldOffset.id_link) return id_link; throw new UnsupportedOperationException(); } public ST_Agedge_s plus_(int pointerMove) { if (pointerMove == 1 && NEXT != null) { return NEXT; } if (pointerMove == -1 && PREV != null) { return PREV; } throw new UnsupportedOperationException(); } } // struct Agedge_s { // Agobj_t base; // Dtlink_t id_link; /* main graph only */ // Dtlink_t seq_link; // Agnode_t *node; /* the endpoint node */ // };
plantuml/plantuml
src/h/ST_Agedge_s.java
94
package me.chanjar.weixin.common.error; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import me.chanjar.weixin.common.enums.WxType; import me.chanjar.weixin.common.util.json.WxGsonBuilder; import org.apache.commons.lang3.StringUtils; import java.io.Serializable; /** * 微信错误码. * 请阅读: * 公众平台:<a href="https://developers.weixin.qq.com/doc/offiaccount/Getting_Started/Global_Return_Code.html">全局返回码说明</a> * 企业微信:<a href="https://work.weixin.qq.com/api/doc#10649">全局错误码</a> * * @author Daniel Qian & Binary Wang */ @Data @NoArgsConstructor @AllArgsConstructor @Builder public class WxError implements Serializable { private static final long serialVersionUID = 7869786563361406291L; /** * 微信错误代码. */ private int errorCode; /** * 微信错误信息. * (如果可以翻译为中文,就为中文) */ private String errorMsg; /** * 微信接口返回的错误原始信息(英文). */ private String errorMsgEn; private String json; public WxError(int errorCode, String errorMsg) { this.errorCode = errorCode; this.errorMsg = errorMsg; } public static WxError fromJson(String json) { return fromJson(json, null); } public static WxError fromJson(String json, WxType type) { final WxError wxError = WxGsonBuilder.create().fromJson(json, WxError.class); if (wxError.getErrorCode() == 0 || type == null) { return wxError; } if (StringUtils.isNotEmpty(wxError.getErrorMsg())) { wxError.setErrorMsgEn(wxError.getErrorMsg()); } switch (type) { case MP: { final String msg = WxMpErrorMsgEnum.findMsgByCode(wxError.getErrorCode()); if (msg != null) { wxError.setErrorMsg(msg); } break; } case CP: { final String msg = WxCpErrorMsgEnum.findMsgByCode(wxError.getErrorCode()); if (msg != null) { wxError.setErrorMsg(msg); } break; } case MiniApp: { final String msg = WxMaErrorMsgEnum.findMsgByCode(wxError.getErrorCode()); if (msg != null) { wxError.setErrorMsg(msg); } break; } case Open: { final String msg = WxOpenErrorMsgEnum.findMsgByCode(wxError.getErrorCode()); if (msg != null) { wxError.setErrorMsg(msg); } break; } default: return wxError; } return wxError; } @Override public String toString() { if (this.json == null) { return "错误代码:" + this.errorCode + ", 错误信息:" + this.errorMsg; } return "错误代码:" + this.errorCode + ", 错误信息:" + this.errorMsg + ",微信原始报文:" + this.json; } }
Wechat-Group/WxJava
weixin-java-common/src/main/java/me/chanjar/weixin/common/error/WxError.java
95
/* * Protocol Buffers - Google's data interchange format * Copyright 2014 Google Inc. All rights reserved. * https://developers.google.com/protocol-buffers/ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.google.protobuf.jruby; import com.google.protobuf.DescriptorProtos.FileDescriptorProto; import com.google.protobuf.Descriptors.Descriptor; import com.google.protobuf.Descriptors.DescriptorValidationException; import com.google.protobuf.Descriptors.EnumDescriptor; import com.google.protobuf.Descriptors.FieldDescriptor; import com.google.protobuf.Descriptors.FileDescriptor; import com.google.protobuf.Descriptors.ServiceDescriptor; import com.google.protobuf.Descriptors.MethodDescriptor; import com.google.protobuf.ExtensionRegistry; import com.google.protobuf.InvalidProtocolBufferException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.jruby.*; import org.jruby.anno.JRubyClass; import org.jruby.anno.JRubyMethod; import org.jruby.exceptions.RaiseException; import org.jruby.runtime.*; import org.jruby.runtime.builtin.IRubyObject; @JRubyClass(name = "DescriptorPool") public class RubyDescriptorPool extends RubyObject { public static void createRubyDescriptorPool(Ruby runtime) { RubyModule protobuf = runtime.getClassFromPath("Google::Protobuf"); RubyClass cDescriptorPool = protobuf.defineClassUnder( "DescriptorPool", runtime.getObject(), new ObjectAllocator() { @Override public IRubyObject allocate(Ruby runtime, RubyClass klazz) { return new RubyDescriptorPool(runtime, klazz); } }); cDescriptorPool.defineAnnotatedMethods(RubyDescriptorPool.class); descriptorPool = (RubyDescriptorPool) cDescriptorPool.newInstance(runtime.getCurrentContext(), Block.NULL_BLOCK); cDescriptor = (RubyClass) runtime.getClassFromPath("Google::Protobuf::Descriptor"); cEnumDescriptor = (RubyClass) runtime.getClassFromPath("Google::Protobuf::EnumDescriptor"); cFieldDescriptor = (RubyClass) runtime.getClassFromPath("Google::Protobuf::FieldDescriptor"); cServiceDescriptor = (RubyClass) runtime.getClassFromPath("Google::Protobuf::ServiceDescriptor"); cMethodDescriptor = (RubyClass) runtime.getClassFromPath("Google::Protobuf::MethodDescriptor"); } public RubyDescriptorPool(Ruby runtime, RubyClass klazz) { super(runtime, klazz); this.fileDescriptors = new ArrayList<>(); this.symtab = new HashMap<IRubyObject, IRubyObject>(); } @JRubyMethod public IRubyObject build(ThreadContext context, Block block) { RubyClass cBuilder = (RubyClass) context.runtime.getClassFromPath("Google::Protobuf::Internal::Builder"); RubyBasicObject ctx = (RubyBasicObject) cBuilder.newInstance(context, this, Block.NULL_BLOCK); ctx.instance_eval(context, block); ctx.callMethod(context, "build"); // Needs to be called to support the deprecated syntax return context.nil; } /* * call-seq: * DescriptorPool.lookup(name) => descriptor * * Finds a Descriptor, EnumDescriptor or FieldDescriptor by name and returns it, or nil if none * exists with the given name. * * This currently lazy loads the ruby descriptor objects as they are requested. * This allows us to leave the heavy lifting to the java library */ @JRubyMethod public IRubyObject lookup(ThreadContext context, IRubyObject name) { return Helpers.nullToNil(symtab.get(name), context.nil); } /* * call-seq: * DescriptorPool.generated_pool => descriptor_pool * * Class method that returns the global DescriptorPool. This is a singleton into * which generated-code message and enum types are registered. The user may also * register types in this pool for convenience so that they do not have to hold * a reference to a private pool instance. */ @JRubyMethod(meta = true, name = "generated_pool") public static IRubyObject generatedPool(ThreadContext context, IRubyObject recv) { return descriptorPool; } @JRubyMethod(required = 1) public IRubyObject add_serialized_file(ThreadContext context, IRubyObject data) { byte[] bin = data.convertToString().getBytes(); try { FileDescriptorProto.Builder builder = FileDescriptorProto.newBuilder().mergeFrom(bin, registry); registerFileDescriptor(context, builder); } catch (InvalidProtocolBufferException e) { throw RaiseException.from( context.runtime, (RubyClass) context.runtime.getClassFromPath("Google::Protobuf::ParseError"), e.getMessage()); } return context.nil; } protected void registerFileDescriptor( ThreadContext context, FileDescriptorProto.Builder builder) { final FileDescriptor fd; try { fd = FileDescriptor.buildFrom(builder.build(), existingFileDescriptors()); } catch (DescriptorValidationException e) { throw context.runtime.newRuntimeError(e.getMessage()); } String packageName = fd.getPackage(); if (!packageName.isEmpty()) { packageName = packageName + "."; } // Need to make sure enums are registered first in case anything references them for (EnumDescriptor ed : fd.getEnumTypes()) registerEnumDescriptor(context, ed, packageName); for (Descriptor message : fd.getMessageTypes()) registerDescriptor(context, message, packageName); for (FieldDescriptor fieldDescriptor : fd.getExtensions()) registerExtension(context, fieldDescriptor, packageName); for (ServiceDescriptor serviceDescriptor : fd.getServices()) registerService(context, serviceDescriptor, packageName); // Mark this as a loaded file fileDescriptors.add(fd); } private void registerDescriptor(ThreadContext context, Descriptor descriptor, String parentPath) { String fullName = parentPath + descriptor.getName(); String fullPath = fullName + "."; RubyString name = context.runtime.newString(fullName); RubyDescriptor des = (RubyDescriptor) cDescriptor.newInstance(context, Block.NULL_BLOCK); des.setName(name); des.setDescriptor(context, descriptor, this); symtab.put(name, des); // Need to make sure enums are registered first in case anything references them for (EnumDescriptor ed : descriptor.getEnumTypes()) registerEnumDescriptor(context, ed, fullPath); for (Descriptor message : descriptor.getNestedTypes()) registerDescriptor(context, message, fullPath); for (FieldDescriptor fieldDescriptor : descriptor.getExtensions()) registerExtension(context, fieldDescriptor, fullPath); } private void registerExtension( ThreadContext context, FieldDescriptor descriptor, String parentPath) { if (descriptor.getJavaType() == FieldDescriptor.JavaType.MESSAGE) { registry.add(descriptor, descriptor.toProto()); } else { registry.add(descriptor); } RubyString name = context.runtime.newString(parentPath + descriptor.getName()); RubyFieldDescriptor des = (RubyFieldDescriptor) cFieldDescriptor.newInstance(context, Block.NULL_BLOCK); des.setName(name); des.setDescriptor(context, descriptor, this); // For MessageSet extensions, there is the possibility of a name conflict. Prefer the Message. symtab.putIfAbsent(name, des); } private void registerEnumDescriptor( ThreadContext context, EnumDescriptor descriptor, String parentPath) { RubyString name = context.runtime.newString(parentPath + descriptor.getName()); RubyEnumDescriptor des = (RubyEnumDescriptor) cEnumDescriptor.newInstance(context, Block.NULL_BLOCK); des.setName(name); des.setDescriptor(context, descriptor); symtab.put(name, des); } private void registerService( ThreadContext context, ServiceDescriptor descriptor, String parentPath) { String fullName = parentPath + descriptor.getName(); RubyString name = context.runtime.newString(fullName); RubyServiceDescriptor des = (RubyServiceDescriptor) cServiceDescriptor.newInstance(context, Block.NULL_BLOCK); des.setName(name); // n.b. this will also construct the descriptors for the service's methods. des.setDescriptor(context, descriptor, this); symtab.putIfAbsent(name, des); } private FileDescriptor[] existingFileDescriptors() { return fileDescriptors.toArray(new FileDescriptor[fileDescriptors.size()]); } private static RubyClass cDescriptor; private static RubyClass cEnumDescriptor; private static RubyClass cFieldDescriptor; private static RubyClass cServiceDescriptor; private static RubyClass cMethodDescriptor; private static RubyDescriptorPool descriptorPool; private List<FileDescriptor> fileDescriptors; private Map<IRubyObject, IRubyObject> symtab; protected static final ExtensionRegistry registry = ExtensionRegistry.newInstance(); }
protocolbuffers/protobuf
ruby/src/main/java/com/google/protobuf/jruby/RubyDescriptorPool.java
96
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file or at // https://developers.google.com/open-source/licenses/bsd package com.google.protobuf; import com.google.protobuf.AbstractMessageLite.Builder.LimitedInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.TreeMap; /** * {@code UnknownFieldSet} keeps track of fields which were seen when parsing a protocol * message but whose field numbers or types are unrecognized. This most frequently occurs when new * fields are added to a message type and then messages containing those fields are read by old * software that was compiled before the new types were added. * * <p>Every {@link Message} contains an {@code UnknownFieldSet} (and every {@link Message.Builder} * contains a {@link Builder}). * * <p>Most users will never need to use this class. * * @author kenton@google.com Kenton Varda */ public final class UnknownFieldSet implements MessageLite { private final TreeMap<Integer, Field> fields; /** * Construct an {@code UnknownFieldSet} around the given map. */ private UnknownFieldSet(TreeMap<Integer, Field> fields) { this.fields = fields; } /** Create a new {@link Builder}. */ public static Builder newBuilder() { return Builder.create(); } /** Create a new {@link Builder} and initialize it to be a copy of {@code copyFrom}. */ public static Builder newBuilder(UnknownFieldSet copyFrom) { return newBuilder().mergeFrom(copyFrom); } /** Get an empty {@code UnknownFieldSet}. */ public static UnknownFieldSet getDefaultInstance() { return defaultInstance; } @Override public UnknownFieldSet getDefaultInstanceForType() { return defaultInstance; } private static final UnknownFieldSet defaultInstance = new UnknownFieldSet(new TreeMap<Integer, Field>()); @Override public boolean equals(Object other) { if (this == other) { return true; } return (other instanceof UnknownFieldSet) && fields.equals(((UnknownFieldSet) other).fields); } @Override public int hashCode() { if (fields.isEmpty()) { // avoid allocation of iterator. // This optimization may not be helpful but it is needed for the allocation tests to pass. return 0; } return fields.hashCode(); } /** Whether the field set has no fields. */ public boolean isEmpty() { return fields.isEmpty(); } /** Get a map of fields in the set by number. */ public Map<Integer, Field> asMap() { // Avoid an allocation for the common case of an empty map. if (fields.isEmpty()) { return Collections.emptyMap(); } return (Map<Integer, Field>) fields.clone(); } /** Check if the given field number is present in the set. */ public boolean hasField(int number) { return fields.containsKey(number); } /** Get a field by number. Returns an empty field if not present. Never returns {@code null}. */ public Field getField(int number) { Field result = fields.get(number); return (result == null) ? Field.getDefaultInstance() : result; } /** Serializes the set and writes it to {@code output}. */ @Override public void writeTo(CodedOutputStream output) throws IOException { if (fields.isEmpty()) { // Avoid allocating an iterator. return; } for (Map.Entry<Integer, Field> entry : fields.entrySet()) { Field field = entry.getValue(); field.writeTo(entry.getKey(), output); } } /** * Converts the set to a string in protocol buffer text format. This is just a trivial wrapper * around {@link TextFormat.Printer#printToString(UnknownFieldSet)}. */ @Override public String toString() { return TextFormat.printer().printToString(this); } /** * Serializes the message to a {@code ByteString} and returns it. This is just a trivial wrapper * around {@link #writeTo(CodedOutputStream)}. */ @Override public ByteString toByteString() { try { ByteString.CodedBuilder out = ByteString.newCodedBuilder(getSerializedSize()); writeTo(out.getCodedOutput()); return out.build(); } catch (IOException e) { throw new RuntimeException( "Serializing to a ByteString threw an IOException (should never happen).", e); } } /** * Serializes the message to a {@code byte} array and returns it. This is just a trivial wrapper * around {@link #writeTo(CodedOutputStream)}. */ @Override public byte[] toByteArray() { try { byte[] result = new byte[getSerializedSize()]; CodedOutputStream output = CodedOutputStream.newInstance(result); writeTo(output); output.checkNoSpaceLeft(); return result; } catch (IOException e) { throw new RuntimeException( "Serializing to a byte array threw an IOException (should never happen).", e); } } /** * Serializes the message and writes it to {@code output}. This is just a trivial wrapper around * {@link #writeTo(CodedOutputStream)}. */ @Override public void writeTo(OutputStream output) throws IOException { CodedOutputStream codedOutput = CodedOutputStream.newInstance(output); writeTo(codedOutput); codedOutput.flush(); } @Override public void writeDelimitedTo(OutputStream output) throws IOException { CodedOutputStream codedOutput = CodedOutputStream.newInstance(output); codedOutput.writeUInt32NoTag(getSerializedSize()); writeTo(codedOutput); codedOutput.flush(); } /** Get the number of bytes required to encode this set. */ @Override public int getSerializedSize() { int result = 0; if (fields.isEmpty()) { // Avoid allocating an iterator. return result; } for (Map.Entry<Integer, Field> entry : fields.entrySet()) { result += entry.getValue().getSerializedSize(entry.getKey()); } return result; } /** Serializes the set and writes it to {@code output} using {@code MessageSet} wire format. */ public void writeAsMessageSetTo(CodedOutputStream output) throws IOException { if (fields.isEmpty()) { // Avoid allocating an iterator. return; } for (Map.Entry<Integer, Field> entry : fields.entrySet()) { entry.getValue().writeAsMessageSetExtensionTo(entry.getKey(), output); } } /** Serializes the set and writes it to {@code writer}. */ void writeTo(Writer writer) throws IOException { if (fields.isEmpty()) { // Avoid allocating an iterator. return; } if (writer.fieldOrder() == Writer.FieldOrder.DESCENDING) { // Write fields in descending order. for (Map.Entry<Integer, Field> entry : fields.descendingMap().entrySet()) { entry.getValue().writeTo(entry.getKey(), writer); } } else { // Write fields in ascending order. for (Map.Entry<Integer, Field> entry : fields.entrySet()) { entry.getValue().writeTo(entry.getKey(), writer); } } } /** Serializes the set and writes it to {@code writer} using {@code MessageSet} wire format. */ void writeAsMessageSetTo(Writer writer) throws IOException { if (fields.isEmpty()) { // Avoid allocating an iterator. return; } if (writer.fieldOrder() == Writer.FieldOrder.DESCENDING) { // Write fields in descending order. for (Map.Entry<Integer, Field> entry : fields.descendingMap().entrySet()) { entry.getValue().writeAsMessageSetExtensionTo(entry.getKey(), writer); } } else { // Write fields in ascending order. for (Map.Entry<Integer, Field> entry : fields.entrySet()) { entry.getValue().writeAsMessageSetExtensionTo(entry.getKey(), writer); } } } /** Get the number of bytes required to encode this set using {@code MessageSet} wire format. */ public int getSerializedSizeAsMessageSet() { int result = 0; if (fields.isEmpty()) { // Avoid allocating an iterator. return result; } for (Map.Entry<Integer, Field> entry : fields.entrySet()) { result += entry.getValue().getSerializedSizeAsMessageSetExtension(entry.getKey()); } return result; } @Override public boolean isInitialized() { // UnknownFieldSets do not have required fields, so they are always // initialized. return true; } /** Parse an {@code UnknownFieldSet} from the given input stream. */ public static UnknownFieldSet parseFrom(CodedInputStream input) throws IOException { return newBuilder().mergeFrom(input).build(); } /** Parse {@code data} as an {@code UnknownFieldSet} and return it. */ public static UnknownFieldSet parseFrom(ByteString data) throws InvalidProtocolBufferException { return newBuilder().mergeFrom(data).build(); } /** Parse {@code data} as an {@code UnknownFieldSet} and return it. */ public static UnknownFieldSet parseFrom(byte[] data) throws InvalidProtocolBufferException { return newBuilder().mergeFrom(data).build(); } /** Parse an {@code UnknownFieldSet} from {@code input} and return it. */ public static UnknownFieldSet parseFrom(InputStream input) throws IOException { return newBuilder().mergeFrom(input).build(); } @Override public Builder newBuilderForType() { return newBuilder(); } @Override public Builder toBuilder() { return newBuilder().mergeFrom(this); } /** * Builder for {@link UnknownFieldSet}s. * * <p>Note that this class maintains {@link Field.Builder}s for all fields in the set. Thus, * adding one element to an existing {@link Field} does not require making a copy. This is * important for efficient parsing of unknown repeated fields. However, it implies that {@link * Field}s cannot be constructed independently, nor can two {@link UnknownFieldSet}s share the * same {@code Field} object. * * <p>Use {@link UnknownFieldSet#newBuilder()} to construct a {@code Builder}. */ public static final class Builder implements MessageLite.Builder { // This constructor should never be called directly (except from 'create'). private Builder() {} private TreeMap<Integer, Field.Builder> fieldBuilders = new TreeMap<>(); private static Builder create() { return new Builder(); } /** * Get a field builder for the given field number which includes any values that already exist. */ private Field.Builder getFieldBuilder(int number) { if (number == 0) { return null; } else { Field.Builder builder = fieldBuilders.get(number); if (builder == null) { builder = Field.newBuilder(); fieldBuilders.put(number, builder); } return builder; } } /** * Build the {@link UnknownFieldSet} and return it. */ @Override public UnknownFieldSet build() { UnknownFieldSet result; if (fieldBuilders.isEmpty()) { result = getDefaultInstance(); } else { TreeMap<Integer, Field> fields = new TreeMap<>(); for (Map.Entry<Integer, Field.Builder> entry : fieldBuilders.entrySet()) { fields.put(entry.getKey(), entry.getValue().build()); } result = new UnknownFieldSet(fields); } return result; } @Override public UnknownFieldSet buildPartial() { // No required fields, so this is the same as build(). return build(); } @Override public Builder clone() { Builder clone = UnknownFieldSet.newBuilder(); for (Map.Entry<Integer, Field.Builder> entry : fieldBuilders.entrySet()) { Integer key = entry.getKey(); Field.Builder value = entry.getValue(); clone.fieldBuilders.put(key, value.clone()); } return clone; } @Override public UnknownFieldSet getDefaultInstanceForType() { return UnknownFieldSet.getDefaultInstance(); } /** Reset the builder to an empty set. */ @Override public Builder clear() { fieldBuilders = new TreeMap<>(); return this; } /** * Clear fields from the set with a given field number. * * @throws IllegalArgumentException if number is not positive */ public Builder clearField(int number) { if (number <= 0) { throw new IllegalArgumentException(number + " is not a valid field number."); } if (fieldBuilders.containsKey(number)) { fieldBuilders.remove(number); } return this; } /** * Merge the fields from {@code other} into this set. If a field number exists in both sets, * {@code other}'s values for that field will be appended to the values in this set. */ public Builder mergeFrom(UnknownFieldSet other) { if (other != getDefaultInstance()) { for (Map.Entry<Integer, Field> entry : other.fields.entrySet()) { mergeField(entry.getKey(), entry.getValue()); } } return this; } /** * Add a field to the {@code UnknownFieldSet}. If a field with the same number already exists, * the two are merged. * * @throws IllegalArgumentException if number is not positive */ public Builder mergeField(int number, final Field field) { if (number <= 0) { throw new IllegalArgumentException(number + " is not a valid field number."); } if (hasField(number)) { getFieldBuilder(number).mergeFrom(field); } else { // Optimization: We could call getFieldBuilder(number).mergeFrom(field) // in this case, but that would create a copy of the Field object. // We'd rather reuse the one passed to us, so call addField() instead. addField(number, field); } return this; } /** * Convenience method for merging a new field containing a single varint value. This is used in * particular when an unknown enum value is encountered. * * @throws IllegalArgumentException if number is not positive */ public Builder mergeVarintField(int number, int value) { if (number <= 0) { throw new IllegalArgumentException(number + " is not a valid field number."); } getFieldBuilder(number).addVarint(value); return this; } /** * Convenience method for merging a length-delimited field. * * <p>For use by generated code only. * * @throws IllegalArgumentException if number is not positive */ public Builder mergeLengthDelimitedField(int number, ByteString value) { if (number <= 0) { throw new IllegalArgumentException(number + " is not a valid field number."); } getFieldBuilder(number).addLengthDelimited(value); return this; } /** Check if the given field number is present in the set. */ public boolean hasField(int number) { return fieldBuilders.containsKey(number); } /** * Add a field to the {@code UnknownFieldSet}. If a field with the same number already exists, * it is removed. * * @throws IllegalArgumentException if number is not positive */ public Builder addField(int number, Field field) { if (number <= 0) { throw new IllegalArgumentException(number + " is not a valid field number."); } fieldBuilders.put(number, Field.newBuilder(field)); return this; } /** * Get all present {@code Field}s as an immutable {@code Map}. If more fields are added, the * changes may or may not be reflected in this map. */ public Map<Integer, Field> asMap() { // Avoid an allocation for the common case of an empty map. if (fieldBuilders.isEmpty()) { return Collections.emptyMap(); } TreeMap<Integer, Field> fields = new TreeMap<>(); for (Map.Entry<Integer, Field.Builder> entry : fieldBuilders.entrySet()) { fields.put(entry.getKey(), entry.getValue().build()); } return Collections.unmodifiableMap(fields); } /** Parse an entire message from {@code input} and merge its fields into this set. */ @Override public Builder mergeFrom(CodedInputStream input) throws IOException { while (true) { int tag = input.readTag(); if (tag == 0 || !mergeFieldFrom(tag, input)) { break; } } return this; } /** * Parse a single field from {@code input} and merge it into this set. * * @param tag The field's tag number, which was already parsed. * @return {@code false} if the tag is an end group tag. */ public boolean mergeFieldFrom(int tag, CodedInputStream input) throws IOException { int number = WireFormat.getTagFieldNumber(tag); switch (WireFormat.getTagWireType(tag)) { case WireFormat.WIRETYPE_VARINT: getFieldBuilder(number).addVarint(input.readInt64()); return true; case WireFormat.WIRETYPE_FIXED64: getFieldBuilder(number).addFixed64(input.readFixed64()); return true; case WireFormat.WIRETYPE_LENGTH_DELIMITED: getFieldBuilder(number).addLengthDelimited(input.readBytes()); return true; case WireFormat.WIRETYPE_START_GROUP: Builder subBuilder = newBuilder(); input.readGroup(number, subBuilder, ExtensionRegistry.getEmptyRegistry()); getFieldBuilder(number).addGroup(subBuilder.build()); return true; case WireFormat.WIRETYPE_END_GROUP: return false; case WireFormat.WIRETYPE_FIXED32: getFieldBuilder(number).addFixed32(input.readFixed32()); return true; default: throw InvalidProtocolBufferException.invalidWireType(); } } /** * Parse {@code data} as an {@code UnknownFieldSet} and merge it with the set being built. This * is just a small wrapper around {@link #mergeFrom(CodedInputStream)}. */ @Override public Builder mergeFrom(ByteString data) throws InvalidProtocolBufferException { try { CodedInputStream input = data.newCodedInput(); mergeFrom(input); input.checkLastTagWas(0); return this; } catch (InvalidProtocolBufferException e) { throw e; } catch (IOException e) { throw new RuntimeException( "Reading from a ByteString threw an IOException (should never happen).", e); } } /** * Parse {@code data} as an {@code UnknownFieldSet} and merge it with the set being built. This * is just a small wrapper around {@link #mergeFrom(CodedInputStream)}. */ @Override public Builder mergeFrom(byte[] data) throws InvalidProtocolBufferException { try { CodedInputStream input = CodedInputStream.newInstance(data); mergeFrom(input); input.checkLastTagWas(0); return this; } catch (InvalidProtocolBufferException e) { throw e; } catch (IOException e) { throw new RuntimeException( "Reading from a byte array threw an IOException (should never happen).", e); } } /** * Parse an {@code UnknownFieldSet} from {@code input} and merge it with the set being built. * This is just a small wrapper around {@link #mergeFrom(CodedInputStream)}. */ @Override public Builder mergeFrom(InputStream input) throws IOException { CodedInputStream codedInput = CodedInputStream.newInstance(input); mergeFrom(codedInput); codedInput.checkLastTagWas(0); return this; } @Override public boolean mergeDelimitedFrom(InputStream input) throws IOException { int firstByte = input.read(); if (firstByte == -1) { return false; } int size = CodedInputStream.readRawVarint32(firstByte, input); InputStream limitedInput = new LimitedInputStream(input, size); mergeFrom(limitedInput); return true; } @Override public boolean mergeDelimitedFrom(InputStream input, ExtensionRegistryLite extensionRegistry) throws IOException { // UnknownFieldSet has no extensions. return mergeDelimitedFrom(input); } @Override public Builder mergeFrom(CodedInputStream input, ExtensionRegistryLite extensionRegistry) throws IOException { // UnknownFieldSet has no extensions. return mergeFrom(input); } @Override public Builder mergeFrom(ByteString data, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException { // UnknownFieldSet has no extensions. return mergeFrom(data); } @Override public Builder mergeFrom(byte[] data, int off, int len) throws InvalidProtocolBufferException { try { CodedInputStream input = CodedInputStream.newInstance(data, off, len); mergeFrom(input); input.checkLastTagWas(0); return this; } catch (InvalidProtocolBufferException e) { throw e; } catch (IOException e) { throw new RuntimeException( "Reading from a byte array threw an IOException (should never happen).", e); } } @Override public Builder mergeFrom(byte[] data, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException { // UnknownFieldSet has no extensions. return mergeFrom(data); } @Override public Builder mergeFrom(byte[] data, int off, int len, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException { // UnknownFieldSet has no extensions. return mergeFrom(data, off, len); } @Override public Builder mergeFrom(InputStream input, ExtensionRegistryLite extensionRegistry) throws IOException { // UnknownFieldSet has no extensions. return mergeFrom(input); } @Override public Builder mergeFrom(MessageLite m) { if (m instanceof UnknownFieldSet) { return mergeFrom((UnknownFieldSet) m); } throw new IllegalArgumentException( "mergeFrom(MessageLite) can only merge messages of the same type."); } @Override public boolean isInitialized() { // UnknownFieldSets do not have required fields, so they are always // initialized. return true; } } /** * Represents a single field in an {@code UnknownFieldSet}. * * <p>A {@code Field} consists of five lists of values. The lists correspond to the five "wire * types" used in the protocol buffer binary format. The wire type of each field can be determined * from the encoded form alone, without knowing the field's declared type. So, we are able to * parse unknown values at least this far and separate them. Normally, only one of the five lists * will contain any values, since it is impossible to define a valid message type that declares * two different types for the same field number. However, the code is designed to allow for the * case where the same unknown field number is encountered using multiple different wire types. * * <p>{@code Field} is an immutable class. To construct one, you must use a {@link Builder}. * * @see UnknownFieldSet */ public static final class Field { private Field() {} /** Construct a new {@link Builder}. */ public static Builder newBuilder() { return Builder.create(); } /** Construct a new {@link Builder} and initialize it to a copy of {@code copyFrom}. */ public static Builder newBuilder(Field copyFrom) { return newBuilder().mergeFrom(copyFrom); } /** Get an empty {@code Field}. */ public static Field getDefaultInstance() { return fieldDefaultInstance; } private static final Field fieldDefaultInstance = newBuilder().build(); /** Get the list of varint values for this field. */ public List<Long> getVarintList() { return varint; } /** Get the list of fixed32 values for this field. */ public List<Integer> getFixed32List() { return fixed32; } /** Get the list of fixed64 values for this field. */ public List<Long> getFixed64List() { return fixed64; } /** Get the list of length-delimited values for this field. */ public List<ByteString> getLengthDelimitedList() { return lengthDelimited; } /** * Get the list of embedded group values for this field. These are represented using {@link * UnknownFieldSet}s rather than {@link Message}s since the group's type is presumably unknown. */ public List<UnknownFieldSet> getGroupList() { return group; } @Override public boolean equals(Object other) { if (this == other) { return true; } if (!(other instanceof Field)) { return false; } return Arrays.equals(getIdentityArray(), ((Field) other).getIdentityArray()); } @Override public int hashCode() { return Arrays.hashCode(getIdentityArray()); } /** Returns the array of objects to be used to uniquely identify this {@link Field} instance. */ private Object[] getIdentityArray() { return new Object[] {varint, fixed32, fixed64, lengthDelimited, group}; } /** * Serializes the message to a {@code ByteString} and returns it. This is just a trivial wrapper * around {@link #writeTo(int, CodedOutputStream)}. */ public ByteString toByteString(int fieldNumber) { try { // TODO: consider caching serialized size in a volatile long ByteString.CodedBuilder out = ByteString.newCodedBuilder(getSerializedSize(fieldNumber)); writeTo(fieldNumber, out.getCodedOutput()); return out.build(); } catch (IOException e) { throw new RuntimeException( "Serializing to a ByteString should never fail with an IOException", e); } } /** Serializes the field, including field number, and writes it to {@code output}. */ public void writeTo(int fieldNumber, CodedOutputStream output) throws IOException { for (long value : varint) { output.writeUInt64(fieldNumber, value); } for (int value : fixed32) { output.writeFixed32(fieldNumber, value); } for (long value : fixed64) { output.writeFixed64(fieldNumber, value); } for (ByteString value : lengthDelimited) { output.writeBytes(fieldNumber, value); } for (UnknownFieldSet value : group) { output.writeGroup(fieldNumber, value); } } /** Get the number of bytes required to encode this field, including field number. */ public int getSerializedSize(int fieldNumber) { int result = 0; for (long value : varint) { result += CodedOutputStream.computeUInt64Size(fieldNumber, value); } for (int value : fixed32) { result += CodedOutputStream.computeFixed32Size(fieldNumber, value); } for (long value : fixed64) { result += CodedOutputStream.computeFixed64Size(fieldNumber, value); } for (ByteString value : lengthDelimited) { result += CodedOutputStream.computeBytesSize(fieldNumber, value); } for (UnknownFieldSet value : group) { result += CodedOutputStream.computeGroupSize(fieldNumber, value); } return result; } /** * Serializes the field, including field number, and writes it to {@code output}, using {@code * MessageSet} wire format. */ public void writeAsMessageSetExtensionTo(int fieldNumber, CodedOutputStream output) throws IOException { for (ByteString value : lengthDelimited) { output.writeRawMessageSetExtension(fieldNumber, value); } } /** Serializes the field, including field number, and writes it to {@code writer}. */ void writeTo(int fieldNumber, Writer writer) throws IOException { writer.writeInt64List(fieldNumber, varint, false); writer.writeFixed32List(fieldNumber, fixed32, false); writer.writeFixed64List(fieldNumber, fixed64, false); writer.writeBytesList(fieldNumber, lengthDelimited); if (writer.fieldOrder() == Writer.FieldOrder.ASCENDING) { for (int i = 0; i < group.size(); i++) { writer.writeStartGroup(fieldNumber); group.get(i).writeTo(writer); writer.writeEndGroup(fieldNumber); } } else { for (int i = group.size() - 1; i >= 0; i--) { writer.writeEndGroup(fieldNumber); group.get(i).writeTo(writer); writer.writeStartGroup(fieldNumber); } } } /** * Serializes the field, including field number, and writes it to {@code writer}, using {@code * MessageSet} wire format. */ private void writeAsMessageSetExtensionTo(int fieldNumber, Writer writer) throws IOException { if (writer.fieldOrder() == Writer.FieldOrder.DESCENDING) { // Write in descending field order. ListIterator<ByteString> iter = lengthDelimited.listIterator(lengthDelimited.size()); while (iter.hasPrevious()) { writer.writeMessageSetItem(fieldNumber, iter.previous()); } } else { // Write in ascending field order. for (ByteString value : lengthDelimited) { writer.writeMessageSetItem(fieldNumber, value); } } } /** * Get the number of bytes required to encode this field, including field number, using {@code * MessageSet} wire format. */ public int getSerializedSizeAsMessageSetExtension(int fieldNumber) { int result = 0; for (ByteString value : lengthDelimited) { result += CodedOutputStream.computeRawMessageSetExtensionSize(fieldNumber, value); } return result; } private List<Long> varint; private List<Integer> fixed32; private List<Long> fixed64; private List<ByteString> lengthDelimited; private List<UnknownFieldSet> group; /** * Used to build a {@link Field} within an {@link UnknownFieldSet}. * * <p>Use {@link Field#newBuilder()} to construct a {@code Builder}. */ public static final class Builder { // This constructor should only be called directly from 'create' and 'clone'. private Builder() { result = new Field(); } private static Builder create() { Builder builder = new Builder(); return builder; } private Field result; @Override public Builder clone() { Field copy = new Field(); if (result.varint == null) { copy.varint = null; } else { copy.varint = new ArrayList<>(result.varint); } if (result.fixed32 == null) { copy.fixed32 = null; } else { copy.fixed32 = new ArrayList<>(result.fixed32); } if (result.fixed64 == null) { copy.fixed64 = null; } else { copy.fixed64 = new ArrayList<>(result.fixed64); } if (result.lengthDelimited == null) { copy.lengthDelimited = null; } else { copy.lengthDelimited = new ArrayList<>(result.lengthDelimited); } if (result.group == null) { copy.group = null; } else { copy.group = new ArrayList<>(result.group); } Builder clone = new Builder(); clone.result = copy; return clone; } /** * Build the field. */ public Field build() { Field built = new Field(); if (result.varint == null) { built.varint = Collections.emptyList(); } else { built.varint = Collections.unmodifiableList(new ArrayList<>(result.varint)); } if (result.fixed32 == null) { built.fixed32 = Collections.emptyList(); } else { built.fixed32 = Collections.unmodifiableList(new ArrayList<>(result.fixed32)); } if (result.fixed64 == null) { built.fixed64 = Collections.emptyList(); } else { built.fixed64 = Collections.unmodifiableList(new ArrayList<>(result.fixed64)); } if (result.lengthDelimited == null) { built.lengthDelimited = Collections.emptyList(); } else { built.lengthDelimited = Collections.unmodifiableList( new ArrayList<>(result.lengthDelimited)); } if (result.group == null) { built.group = Collections.emptyList(); } else { built.group = Collections.unmodifiableList(new ArrayList<>(result.group)); } return built; } /** Discard the field's contents. */ public Builder clear() { result = new Field(); return this; } /** * Merge the values in {@code other} into this field. For each list of values, {@code other}'s * values are append to the ones in this field. */ public Builder mergeFrom(Field other) { if (!other.varint.isEmpty()) { if (result.varint == null) { result.varint = new ArrayList<Long>(); } result.varint.addAll(other.varint); } if (!other.fixed32.isEmpty()) { if (result.fixed32 == null) { result.fixed32 = new ArrayList<Integer>(); } result.fixed32.addAll(other.fixed32); } if (!other.fixed64.isEmpty()) { if (result.fixed64 == null) { result.fixed64 = new ArrayList<>(); } result.fixed64.addAll(other.fixed64); } if (!other.lengthDelimited.isEmpty()) { if (result.lengthDelimited == null) { result.lengthDelimited = new ArrayList<>(); } result.lengthDelimited.addAll(other.lengthDelimited); } if (!other.group.isEmpty()) { if (result.group == null) { result.group = new ArrayList<>(); } result.group.addAll(other.group); } return this; } /** Add a varint value. */ public Builder addVarint(long value) { if (result.varint == null) { result.varint = new ArrayList<>(); } result.varint.add(value); return this; } /** Add a fixed32 value. */ public Builder addFixed32(int value) { if (result.fixed32 == null) { result.fixed32 = new ArrayList<>(); } result.fixed32.add(value); return this; } /** Add a fixed64 value. */ public Builder addFixed64(long value) { if (result.fixed64 == null) { result.fixed64 = new ArrayList<>(); } result.fixed64.add(value); return this; } /** Add a length-delimited value. */ public Builder addLengthDelimited(ByteString value) { if (result.lengthDelimited == null) { result.lengthDelimited = new ArrayList<>(); } result.lengthDelimited.add(value); return this; } /** Add an embedded group. */ public Builder addGroup(UnknownFieldSet value) { if (result.group == null) { result.group = new ArrayList<>(); } result.group.add(value); return this; } } } /** Parser to implement MessageLite interface. */ public static final class Parser extends AbstractParser<UnknownFieldSet> { @Override public UnknownFieldSet parsePartialFrom( CodedInputStream input, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input); } catch (InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (IOException e) { throw new InvalidProtocolBufferException(e).setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } } private static final Parser PARSER = new Parser(); @Override public final Parser getParserForType() { return PARSER; } }
protocolbuffers/protobuf
java/core/src/main/java/com/google/protobuf/UnknownFieldSet.java
97
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * Project Info: https://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * https://plantuml.com/patreon (only 1$ per month!) * https://plantuml.com/paypal * * This file is part of Smetana. * Smetana is a partial translation of Graphviz/Dot sources from C to Java. * * (C) Copyright 2009-2022, Arnaud Roques * * This translation is distributed under the same Licence as the original C program: * ************************************************************************* * Copyright (c) 2011 AT&T Intellectual Property * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: See CVS logs. Details at http://www.graphviz.org/ ************************************************************************* * * THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC * LICENSE ("AGREEMENT"). [Eclipse Public License - v 1.0] * * ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES * RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. * * You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * 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 h; import smetana.core.UnsupportedStarStruct; final public class ST_Node_t___ extends UnsupportedStarStruct implements ST_Node_t___or_object_t { public int count; public int level; // Sorry guys :-) public final ST_Branch_t branch[] = new ST_Branch_t[] { new ST_Branch_t(), new ST_Branch_t(), new ST_Branch_t(), new ST_Branch_t(), new ST_Branch_t(), new ST_Branch_t(), new ST_Branch_t(), new ST_Branch_t(), new ST_Branch_t(), new ST_Branch_t(), new ST_Branch_t(), new ST_Branch_t(), new ST_Branch_t(), new ST_Branch_t(), new ST_Branch_t(), new ST_Branch_t(), new ST_Branch_t(), new ST_Branch_t(), new ST_Branch_t(), new ST_Branch_t(), new ST_Branch_t(), new ST_Branch_t(), new ST_Branch_t(), new ST_Branch_t(), new ST_Branch_t(), new ST_Branch_t(), new ST_Branch_t(), new ST_Branch_t(), new ST_Branch_t(), new ST_Branch_t(), new ST_Branch_t(), new ST_Branch_t(), new ST_Branch_t(), new ST_Branch_t(), new ST_Branch_t(), new ST_Branch_t(), new ST_Branch_t(), new ST_Branch_t(), new ST_Branch_t(), new ST_Branch_t(), new ST_Branch_t(), new ST_Branch_t(), new ST_Branch_t(), new ST_Branch_t(), new ST_Branch_t(), new ST_Branch_t(), new ST_Branch_t(), new ST_Branch_t(), new ST_Branch_t(), new ST_Branch_t(), new ST_Branch_t(), new ST_Branch_t(), new ST_Branch_t(), new ST_Branch_t(), new ST_Branch_t(), new ST_Branch_t(), new ST_Branch_t(), new ST_Branch_t(), new ST_Branch_t(), new ST_Branch_t(), new ST_Branch_t(), new ST_Branch_t(), new ST_Branch_t(), new ST_Branch_t() }; } // typedef struct Node { // int count; // int level; /* 0 is leaf, others positive */ // struct Branch branch[64]; // } Node_t;
plantuml/plantuml
src/h/ST_Node_t___.java
98
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * Project Info: https://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * https://plantuml.com/patreon (only 1$ per month!) * https://plantuml.com/paypal * * This file is part of Smetana. * Smetana is a partial translation of Graphviz/Dot sources from C to Java. * * (C) Copyright 2009-2022, Arnaud Roques * * This translation is distributed under the same Licence as the original C program: * ************************************************************************* * Copyright (c) 2011 AT&T Intellectual Property * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: See CVS logs. Details at http://www.graphviz.org/ ************************************************************************* * * THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC * LICENSE ("AGREEMENT"). [Eclipse Public License - v 1.0] * * ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES * RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. * * You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * 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 h; import smetana.core.FieldOffset; import smetana.core.__ptr__; import smetana.core.__struct__; import smetana.core.debug.SmetanaDebug; final public class ST_Agraph_s extends ST_Agobj_s { public final ST_Agobj_s base = this; public final ST_Agdesc_s desc = new ST_Agdesc_s(); public final ST_dtlink_s link = new ST_dtlink_s(this); public ST_dt_s n_seq; /* the node set in sequence */ public ST_dt_s n_id; /* the node set indexed by ID */ public ST_dt_s e_seq; /* holders for edge sets */ public ST_dt_s e_id; /* holders for edge sets */ public ST_dt_s g_dict; /* subgraphs - descendants */ public ST_Agraph_s parent; /* subgraphs - ancestors */ public ST_Agraph_s root; /* subgraphs - ancestors */ public ST_Agclos_s clos; /* shared resources */ public String NAME; private static int CPT = 0; // @Override // public String toString() { // return super.toString() + " " + NAME; // } public ST_Agraph_s() { this.NAME = "G" + CPT; CPT++; SmetanaDebug.LOG("creation " + this); } @Override public Object getTheField(FieldOffset offset) { if (offset == null || offset.getSign() == 0) return this; if (offset == FieldOffset.link) return link; throw new UnsupportedOperationException(); } @Override public void ___(__struct__ arg) { throw new UnsupportedOperationException(); } @Override public boolean isSameThan(__ptr__ other) { ST_Agraph_s other2 = (ST_Agraph_s) other; return this == other2; } } // struct Agraph_s { // Agobj_t base; // Agdesc_t desc; // Dtlink_t link; // Dict_t *n_seq; /* the node set in sequence */ // Dict_t *n_id; /* the node set indexed by ID */ // Dict_t *e_seq, *e_id; /* holders for edge sets */ // Dict_t *g_dict; /* subgraphs - descendants */ // Agraph_t *parent, *root; /* subgraphs - ancestors */ // Agclos_t *clos; /* shared resources */ // };
plantuml/plantuml
src/h/ST_Agraph_s.java
99
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file or at // https://developers.google.com/open-source/licenses/bsd package com.google.protobuf; import static com.google.protobuf.Internal.checkNotNull; import com.google.protobuf.DescriptorProtos.DescriptorProto; import com.google.protobuf.DescriptorProtos.Edition; import com.google.protobuf.DescriptorProtos.EnumDescriptorProto; import com.google.protobuf.DescriptorProtos.EnumOptions; import com.google.protobuf.DescriptorProtos.EnumValueDescriptorProto; import com.google.protobuf.DescriptorProtos.EnumValueOptions; import com.google.protobuf.DescriptorProtos.FeatureSet; import com.google.protobuf.DescriptorProtos.FeatureSetDefaults; import com.google.protobuf.DescriptorProtos.FeatureSetDefaults.FeatureSetEditionDefault; import com.google.protobuf.DescriptorProtos.FieldDescriptorProto; import com.google.protobuf.DescriptorProtos.FieldOptions; import com.google.protobuf.DescriptorProtos.FileDescriptorProto; import com.google.protobuf.DescriptorProtos.FileOptions; import com.google.protobuf.DescriptorProtos.MessageOptions; import com.google.protobuf.DescriptorProtos.MethodDescriptorProto; import com.google.protobuf.DescriptorProtos.MethodOptions; import com.google.protobuf.DescriptorProtos.OneofDescriptorProto; import com.google.protobuf.DescriptorProtos.OneofOptions; import com.google.protobuf.DescriptorProtos.ServiceDescriptorProto; import com.google.protobuf.DescriptorProtos.ServiceOptions; import com.google.protobuf.Descriptors.DescriptorValidationException; import com.google.protobuf.JavaFeaturesProto.JavaFeatures; import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Logger; /** * Contains a collection of classes which describe protocol message types. * * <p>Every message type has a {@link Descriptor}, which lists all its fields and other information * about a type. You can get a message type's descriptor by calling {@code * MessageType.getDescriptor()}, or (given a message object of the type) {@code * message.getDescriptorForType()}. Furthermore, each message is associated with a {@link * FileDescriptor} for a relevant {@code .proto} file. You can obtain it by calling {@code * Descriptor.getFile()}. A {@link FileDescriptor} contains descriptors for all the messages defined * in that file, and file descriptors for all the imported {@code .proto} files. * * <p>Descriptors are built from DescriptorProtos, as defined in {@code * google/protobuf/descriptor.proto}. * * @author kenton@google.com Kenton Varda */ @CheckReturnValue public final class Descriptors { private static final Logger logger = Logger.getLogger(Descriptors.class.getName()); private static final int[] EMPTY_INT_ARRAY = new int[0]; private static final Descriptor[] EMPTY_DESCRIPTORS = new Descriptor[0]; private static final FieldDescriptor[] EMPTY_FIELD_DESCRIPTORS = new FieldDescriptor[0]; private static final EnumDescriptor[] EMPTY_ENUM_DESCRIPTORS = new EnumDescriptor[0]; private static final ServiceDescriptor[] EMPTY_SERVICE_DESCRIPTORS = new ServiceDescriptor[0]; private static final OneofDescriptor[] EMPTY_ONEOF_DESCRIPTORS = new OneofDescriptor[0]; private static final ConcurrentHashMap<Integer, FeatureSet> FEATURE_CACHE = new ConcurrentHashMap<>(); @SuppressWarnings("NonFinalStaticField") private static volatile FeatureSetDefaults javaEditionDefaults = null; /** Sets the default feature mappings used during the build. Exposed for tests. */ static void setTestJavaEditionDefaults(FeatureSetDefaults defaults) { javaEditionDefaults = defaults; } /** Gets the default feature mappings used during the build. */ static FeatureSetDefaults getJavaEditionDefaults() { // Force explicit initialization before synchronized block which can trigger initialization in // `JavaFeaturesProto.registerAllExtensions()` and `FeatureSetdefaults.parseFrom()` calls. // Otherwise, this can result in deadlock if another threads holds the static init block's // implicit lock. This operation should be cheap if initialization has already occurred. Descriptor unused1 = FeatureSetDefaults.getDescriptor(); FileDescriptor unused2 = JavaFeaturesProto.getDescriptor(); if (javaEditionDefaults == null) { synchronized (Descriptors.class) { if (javaEditionDefaults == null) { try { ExtensionRegistry registry = ExtensionRegistry.newInstance(); registry.add(JavaFeaturesProto.java_); setTestJavaEditionDefaults( FeatureSetDefaults.parseFrom( JavaEditionDefaults.PROTOBUF_INTERNAL_JAVA_EDITION_DEFAULTS.getBytes( Internal.ISO_8859_1), registry)); } catch (Exception e) { throw new AssertionError(e); } } } } return javaEditionDefaults; } static FeatureSet getEditionDefaults(Edition edition) { FeatureSetDefaults javaEditionDefaults = getJavaEditionDefaults(); if (edition.getNumber() < javaEditionDefaults.getMinimumEdition().getNumber()) { throw new IllegalArgumentException( "Edition " + edition + " is lower than the minimum supported edition " + javaEditionDefaults.getMinimumEdition() + "!"); } if (edition.getNumber() > javaEditionDefaults.getMaximumEdition().getNumber()) { throw new IllegalArgumentException( "Edition " + edition + " is greater than the maximum supported edition " + javaEditionDefaults.getMaximumEdition() + "!"); } FeatureSetEditionDefault found = null; for (FeatureSetEditionDefault editionDefault : javaEditionDefaults.getDefaultsList()) { if (editionDefault.getEdition().getNumber() > edition.getNumber()) { break; } found = editionDefault; } if (found == null) { throw new IllegalArgumentException( "Edition " + edition + " does not have a valid default FeatureSet!"); } return found.getFixedFeatures().toBuilder().mergeFrom(found.getOverridableFeatures()).build(); } private static FeatureSet internFeatures(FeatureSet features) { FeatureSet cached = FEATURE_CACHE.putIfAbsent(features.hashCode(), features); if (cached == null) { return features; } return cached; } /** * Describes a {@code .proto} file, including everything defined within. That includes, in * particular, descriptors for all the messages and file descriptors for all other imported {@code * .proto} files (dependencies). */ public static final class FileDescriptor extends GenericDescriptor { /** Convert the descriptor to its protocol message representation. */ @Override public FileDescriptorProto toProto() { return proto; } /** Get the file name. */ @Override public String getName() { return proto.getName(); } /** Returns this object. */ @Override public FileDescriptor getFile() { return this; } /** Returns the same as getName(). */ @Override public String getFullName() { return proto.getName(); } /** * Get the proto package name. This is the package name given by the {@code package} statement * in the {@code .proto} file, which differs from the Java package. */ public String getPackage() { return proto.getPackage(); } /** Get the {@code FileOptions}, defined in {@code descriptor.proto}. */ public FileOptions getOptions() { if (this.options == null) { FileOptions strippedOptions = this.proto.getOptions(); if (strippedOptions.hasFeatures()) { // Clients should be using feature accessor methods, not accessing features on the // options // proto. strippedOptions = strippedOptions.toBuilder().clearFeatures().build(); } synchronized (this) { if (this.options == null) { this.options = strippedOptions; } } } return this.options; } /** Get a list of top-level message types declared in this file. */ public List<Descriptor> getMessageTypes() { return Collections.unmodifiableList(Arrays.asList(messageTypes)); } /** Get a list of top-level enum types declared in this file. */ public List<EnumDescriptor> getEnumTypes() { return Collections.unmodifiableList(Arrays.asList(enumTypes)); } /** Get a list of top-level services declared in this file. */ public List<ServiceDescriptor> getServices() { return Collections.unmodifiableList(Arrays.asList(services)); } /** Get a list of top-level extensions declared in this file. */ public List<FieldDescriptor> getExtensions() { return Collections.unmodifiableList(Arrays.asList(extensions)); } /** Get a list of this file's dependencies (imports). */ public List<FileDescriptor> getDependencies() { return Collections.unmodifiableList(Arrays.asList(dependencies)); } /** Get a list of this file's public dependencies (public imports). */ public List<FileDescriptor> getPublicDependencies() { return Collections.unmodifiableList(Arrays.asList(publicDependencies)); } /** Get the edition of the .proto file. */ Edition getEdition() { switch (proto.getSyntax()) { case "editions": return proto.getEdition(); case "proto3": return Edition.EDITION_PROTO3; default: return Edition.EDITION_PROTO2; } } public void copyHeadingTo(FileDescriptorProto.Builder protoBuilder) { protoBuilder.setName(getName()).setSyntax(proto.getSyntax()); if (!getPackage().isEmpty()) { protoBuilder.setPackage(getPackage()); } if (proto.getSyntax().equals("editions")) { protoBuilder.setEdition(proto.getEdition()); } if (proto.hasOptions() && !proto.getOptions().equals(FileOptions.getDefaultInstance())) { protoBuilder.setOptions(proto.getOptions()); } } /** * Find a message type in the file by name. Does not find nested types. * * @param name The unqualified type name to look for. * @return The message type's descriptor, or {@code null} if not found. */ public Descriptor findMessageTypeByName(String name) { // Don't allow looking up nested types. This will make optimization // easier later. if (name.indexOf('.') != -1) { return null; } final String packageName = getPackage(); if (!packageName.isEmpty()) { name = packageName + '.' + name; } final GenericDescriptor result = pool.findSymbol(name); if (result instanceof Descriptor && result.getFile() == this) { return (Descriptor) result; } else { return null; } } /** * Find an enum type in the file by name. Does not find nested types. * * @param name The unqualified type name to look for. * @return The enum type's descriptor, or {@code null} if not found. */ public EnumDescriptor findEnumTypeByName(String name) { // Don't allow looking up nested types. This will make optimization // easier later. if (name.indexOf('.') != -1) { return null; } final String packageName = getPackage(); if (!packageName.isEmpty()) { name = packageName + '.' + name; } final GenericDescriptor result = pool.findSymbol(name); if (result instanceof EnumDescriptor && result.getFile() == this) { return (EnumDescriptor) result; } else { return null; } } /** * Find a service type in the file by name. * * @param name The unqualified type name to look for. * @return The service type's descriptor, or {@code null} if not found. */ public ServiceDescriptor findServiceByName(String name) { // Don't allow looking up nested types. This will make optimization // easier later. if (name.indexOf('.') != -1) { return null; } final String packageName = getPackage(); if (!packageName.isEmpty()) { name = packageName + '.' + name; } final GenericDescriptor result = pool.findSymbol(name); if (result instanceof ServiceDescriptor && result.getFile() == this) { return (ServiceDescriptor) result; } else { return null; } } /** * Find an extension in the file by name. Does not find extensions nested inside message types. * * @param name The unqualified extension name to look for. * @return The extension's descriptor, or {@code null} if not found. */ public FieldDescriptor findExtensionByName(String name) { if (name.indexOf('.') != -1) { return null; } final String packageName = getPackage(); if (!packageName.isEmpty()) { name = packageName + '.' + name; } final GenericDescriptor result = pool.findSymbol(name); if (result instanceof FieldDescriptor && result.getFile() == this) { return (FieldDescriptor) result; } else { return null; } } /** * Construct a {@code FileDescriptor}. * * @param proto the protocol message form of the FileDescriptort * @param dependencies {@code FileDescriptor}s corresponding to all of the file's dependencies. * @throws DescriptorValidationException {@code proto} is not a valid descriptor. This can occur * for a number of reasons; for instance, because a field has an undefined type or because * two messages were defined with the same name. */ public static FileDescriptor buildFrom(FileDescriptorProto proto, FileDescriptor[] dependencies) throws DescriptorValidationException { return buildFrom(proto, dependencies, false); } /** * Construct a {@code FileDescriptor}. * * @param proto the protocol message form of the FileDescriptor * @param dependencies {@code FileDescriptor}s corresponding to all of the file's dependencies * @param allowUnknownDependencies if true, non-existing dependencies will be ignored and * undefined message types will be replaced with a placeholder type. Undefined enum types * still cause a DescriptorValidationException. * @throws DescriptorValidationException {@code proto} is not a valid descriptor. This can occur * for a number of reasons; for instance, because a field has an undefined type or because * two messages were defined with the same name. */ public static FileDescriptor buildFrom( FileDescriptorProto proto, FileDescriptor[] dependencies, boolean allowUnknownDependencies) throws DescriptorValidationException { return buildFrom(proto, dependencies, allowUnknownDependencies, false); } private static FileDescriptor buildFrom( FileDescriptorProto proto, FileDescriptor[] dependencies, boolean allowUnknownDependencies, boolean allowUnresolvedFeatures) throws DescriptorValidationException { // Building descriptors involves two steps: translating and linking. // In the translation step (implemented by FileDescriptor's // constructor), we build an object tree mirroring the // FileDescriptorProto's tree and put all of the descriptors into the // DescriptorPool's lookup tables. In the linking step, we look up all // type references in the DescriptorPool, so that, for example, a // FieldDescriptor for an embedded message contains a pointer directly // to the Descriptor for that message's type. We also detect undefined // types in the linking step. DescriptorPool pool = new DescriptorPool(dependencies, allowUnknownDependencies); FileDescriptor result = new FileDescriptor(proto, dependencies, pool, allowUnknownDependencies); result.crossLink(); // Skip feature resolution until later for calls from gencode. if (!allowUnresolvedFeatures) { // We do not need to force feature resolution for proto1 dependencies // since dependencies from non-gencode should already be fully feature resolved. result.resolveAllFeaturesInternal(); } return result; } private static byte[] latin1Cat(final String[] strings) { // Hack: We can't embed a raw byte array inside generated Java code // (at least, not efficiently), but we can embed Strings. So, the // protocol compiler embeds the FileDescriptorProto as a giant // string literal which is passed to this function to construct the // file's FileDescriptor. The string literal contains only 8-bit // characters, each one representing a byte of the FileDescriptorProto's // serialized form. So, if we convert it to bytes in ISO-8859-1, we // should get the original bytes that we want. // Literal strings are limited to 64k, so it may be split into multiple strings. if (strings.length == 1) { return strings[0].getBytes(Internal.ISO_8859_1); } StringBuilder descriptorData = new StringBuilder(); for (String part : strings) { descriptorData.append(part); } return descriptorData.toString().getBytes(Internal.ISO_8859_1); } private static FileDescriptor[] findDescriptors( final Class<?> descriptorOuterClass, final String[] dependencyClassNames, final String[] dependencyFileNames) { List<FileDescriptor> descriptors = new ArrayList<>(); for (int i = 0; i < dependencyClassNames.length; i++) { try { Class<?> clazz = descriptorOuterClass.getClassLoader().loadClass(dependencyClassNames[i]); descriptors.add((FileDescriptor) clazz.getField("descriptor").get(null)); } catch (Exception e) { // We allow unknown dependencies by default. If a dependency cannot // be found we only generate a warning. logger.warning("Descriptors for \"" + dependencyFileNames[i] + "\" can not be found."); } } return descriptors.toArray(new FileDescriptor[0]); } /** * This method is to be called by generated code only. It is equivalent to {@code buildFrom} * except that the {@code FileDescriptorProto} is encoded in protocol buffer wire format. */ public static FileDescriptor internalBuildGeneratedFileFrom( final String[] descriptorDataParts, final FileDescriptor[] dependencies) { final byte[] descriptorBytes = latin1Cat(descriptorDataParts); FileDescriptorProto proto; try { proto = FileDescriptorProto.parseFrom(descriptorBytes); } catch (InvalidProtocolBufferException e) { throw new IllegalArgumentException( "Failed to parse protocol buffer descriptor for generated code.", e); } try { // When building descriptors for generated code, we allow unknown // dependencies by default and delay feature resolution until later. return buildFrom(proto, dependencies, true, true); } catch (DescriptorValidationException e) { throw new IllegalArgumentException( "Invalid embedded descriptor for \"" + proto.getName() + "\".", e); } } /** * This method is to be called by generated code only. It uses Java reflection to load the * dependencies' descriptors. */ public static FileDescriptor internalBuildGeneratedFileFrom( final String[] descriptorDataParts, final Class<?> descriptorOuterClass, final String[] dependencyClassNames, final String[] dependencyFileNames) { FileDescriptor[] dependencies = findDescriptors(descriptorOuterClass, dependencyClassNames, dependencyFileNames); return internalBuildGeneratedFileFrom(descriptorDataParts, dependencies); } /** * This method is to be called by generated code only. It updates the FileDescriptorProto * associated with the descriptor by parsing it again with the given ExtensionRegistry. This is * needed to recognize custom options. */ public static void internalUpdateFileDescriptor( FileDescriptor descriptor, ExtensionRegistry registry) { ByteString bytes = descriptor.proto.toByteString(); try { FileDescriptorProto proto = FileDescriptorProto.parseFrom(bytes, registry); descriptor.setProto(proto); } catch (InvalidProtocolBufferException e) { throw new IllegalArgumentException( "Failed to parse protocol buffer descriptor for generated code.", e); } } /** * This class should be used by generated code only. When calling {@link * FileDescriptor#internalBuildGeneratedFileFrom}, the caller provides a callback implementing * this interface. The callback is called after the FileDescriptor has been constructed, in * order to assign all the global variables defined in the generated code which point at parts * of the FileDescriptor. The callback returns an ExtensionRegistry which contains any * extensions which might be used in the descriptor -- that is, extensions of the various * "Options" messages defined in descriptor.proto. The callback may also return null to indicate * that no extensions are used in the descriptor. * * <p>This interface is deprecated. Use the return value of internalBuildGeneratedFrom() * instead. */ @Deprecated public interface InternalDescriptorAssigner { ExtensionRegistry assignDescriptors(FileDescriptor root); } private FileDescriptorProto proto; private volatile FileOptions options; private final Descriptor[] messageTypes; private final EnumDescriptor[] enumTypes; private final ServiceDescriptor[] services; private final FieldDescriptor[] extensions; private final FileDescriptor[] dependencies; private final FileDescriptor[] publicDependencies; private final DescriptorPool pool; private FileDescriptor( final FileDescriptorProto proto, final FileDescriptor[] dependencies, final DescriptorPool pool, boolean allowUnknownDependencies) throws DescriptorValidationException { this.pool = pool; this.proto = proto; this.dependencies = dependencies.clone(); HashMap<String, FileDescriptor> nameToFileMap = new HashMap<>(); for (FileDescriptor file : dependencies) { nameToFileMap.put(file.getName(), file); } List<FileDescriptor> publicDependencies = new ArrayList<>(); for (int i = 0; i < proto.getPublicDependencyCount(); i++) { int index = proto.getPublicDependency(i); if (index < 0 || index >= proto.getDependencyCount()) { throw new DescriptorValidationException(this, "Invalid public dependency index."); } String name = proto.getDependency(index); FileDescriptor file = nameToFileMap.get(name); if (file == null) { if (!allowUnknownDependencies) { throw new DescriptorValidationException(this, "Invalid public dependency: " + name); } // Ignore unknown dependencies. } else { publicDependencies.add(file); } } this.publicDependencies = new FileDescriptor[publicDependencies.size()]; publicDependencies.toArray(this.publicDependencies); pool.addPackage(getPackage(), this); messageTypes = (proto.getMessageTypeCount() > 0) ? new Descriptor[proto.getMessageTypeCount()] : EMPTY_DESCRIPTORS; for (int i = 0; i < proto.getMessageTypeCount(); i++) { messageTypes[i] = new Descriptor(proto.getMessageType(i), this, null, i); } enumTypes = (proto.getEnumTypeCount() > 0) ? new EnumDescriptor[proto.getEnumTypeCount()] : EMPTY_ENUM_DESCRIPTORS; for (int i = 0; i < proto.getEnumTypeCount(); i++) { enumTypes[i] = new EnumDescriptor(proto.getEnumType(i), this, null, i); } services = (proto.getServiceCount() > 0) ? new ServiceDescriptor[proto.getServiceCount()] : EMPTY_SERVICE_DESCRIPTORS; for (int i = 0; i < proto.getServiceCount(); i++) { services[i] = new ServiceDescriptor(proto.getService(i), this, i); } extensions = (proto.getExtensionCount() > 0) ? new FieldDescriptor[proto.getExtensionCount()] : EMPTY_FIELD_DESCRIPTORS; for (int i = 0; i < proto.getExtensionCount(); i++) { extensions[i] = new FieldDescriptor(proto.getExtension(i), this, null, i, true); } } /** Create a placeholder FileDescriptor for a message Descriptor. */ FileDescriptor(String packageName, Descriptor message) throws DescriptorValidationException { this.parent = null; this.pool = new DescriptorPool(new FileDescriptor[0], true); this.proto = FileDescriptorProto.newBuilder() .setName(message.getFullName() + ".placeholder.proto") .setPackage(packageName) .addMessageType(message.toProto()) .build(); this.dependencies = new FileDescriptor[0]; this.publicDependencies = new FileDescriptor[0]; messageTypes = new Descriptor[] {message}; enumTypes = EMPTY_ENUM_DESCRIPTORS; services = EMPTY_SERVICE_DESCRIPTORS; extensions = EMPTY_FIELD_DESCRIPTORS; pool.addPackage(packageName, this); pool.addSymbol(message); } public void resolveAllFeaturesImmutable() { try { resolveAllFeaturesInternal(); } catch (DescriptorValidationException e) { throw new IllegalArgumentException("Invalid features for \"" + proto.getName() + "\".", e); } } /** * This method is to be called by generated code only. It resolves features for the descriptor * and all of its children. */ private void resolveAllFeaturesInternal() throws DescriptorValidationException { if (this.features != null) { return; } synchronized (this) { if (this.features != null) { return; } resolveFeatures(proto.getOptions().getFeatures()); for (Descriptor messageType : messageTypes) { messageType.resolveAllFeatures(); } for (EnumDescriptor enumType : enumTypes) { enumType.resolveAllFeatures(); } for (ServiceDescriptor service : services) { service.resolveAllFeatures(); } for (FieldDescriptor extension : extensions) { extension.resolveAllFeatures(); } } } @Override FeatureSet inferLegacyProtoFeatures() { FeatureSet.Builder features = FeatureSet.newBuilder(); if (getEdition().getNumber() >= Edition.EDITION_2023.getNumber()) { return features.build(); } if (getEdition() == Edition.EDITION_PROTO2) { if (proto.getOptions().getJavaStringCheckUtf8()) { features.setExtension( JavaFeaturesProto.java_, JavaFeatures.newBuilder() .setUtf8Validation(JavaFeatures.Utf8Validation.VERIFY) .build()); } } return features.build(); } @Override boolean hasInferredLegacyProtoFeatures() { if (getEdition().getNumber() >= Edition.EDITION_2023.getNumber()) { return false; } if (getEdition() == Edition.EDITION_PROTO2) { if (proto.getOptions().getJavaStringCheckUtf8()) { return true; } } return false; } /** Look up and cross-link all field types, etc. */ private void crossLink() throws DescriptorValidationException { for (final Descriptor messageType : messageTypes) { messageType.crossLink(); } for (final ServiceDescriptor service : services) { service.crossLink(); } for (final FieldDescriptor extension : extensions) { extension.crossLink(); } } /** * Replace our {@link FileDescriptorProto} with the given one, which is identical except that it * might contain extensions that weren't present in the original. This method is needed for * bootstrapping when a file defines custom options. The options may be defined in the file * itself, so we can't actually parse them until we've constructed the descriptors, but to * construct the descriptors we have to have parsed the descriptor protos. So, we have to parse * the descriptor protos a second time after constructing the descriptors. */ private synchronized void setProto(final FileDescriptorProto proto) { this.proto = proto; this.options = null; try { resolveFeatures(proto.getOptions().getFeatures()); for (int i = 0; i < messageTypes.length; i++) { messageTypes[i].setProto(proto.getMessageType(i)); } for (int i = 0; i < enumTypes.length; i++) { enumTypes[i].setProto(proto.getEnumType(i)); } for (int i = 0; i < services.length; i++) { services[i].setProto(proto.getService(i)); } for (int i = 0; i < extensions.length; i++) { extensions[i].setProto(proto.getExtension(i)); } } catch (DescriptorValidationException e) { throw new IllegalArgumentException("Invalid features for \"" + proto.getName() + "\".", e); } } } // ================================================================= /** Describes a message type. */ public static final class Descriptor extends GenericDescriptor { /** * Get the index of this descriptor within its parent. In other words, given a {@link * FileDescriptor} {@code file}, the following is true: * * <pre> * for all i in [0, file.getMessageTypeCount()): * file.getMessageType(i).getIndex() == i * </pre> * * Similarly, for a {@link Descriptor} {@code messageType}: * * <pre> * for all i in [0, messageType.getNestedTypeCount()): * messageType.getNestedType(i).getIndex() == i * </pre> */ public int getIndex() { return index; } /** Convert the descriptor to its protocol message representation. */ @Override public DescriptorProto toProto() { return proto; } /** Get the type's unqualified name. */ @Override public String getName() { return proto.getName(); } /** * Get the type's fully-qualified name, within the proto language's namespace. This differs from * the Java name. For example, given this {@code .proto}: * * <pre> * package foo.bar; * option java_package = "com.example.protos" * message Baz {} * </pre> * * {@code Baz}'s full name is "foo.bar.Baz". */ @Override public String getFullName() { return fullName; } /** Get the {@link FileDescriptor} containing this descriptor. */ @Override public FileDescriptor getFile() { return file; } /** If this is a nested type, get the outer descriptor, otherwise null. */ public Descriptor getContainingType() { return containingType; } /** Get the {@code MessageOptions}, defined in {@code descriptor.proto}. */ public MessageOptions getOptions() { if (this.options == null) { MessageOptions strippedOptions = this.proto.getOptions(); if (strippedOptions.hasFeatures()) { // Clients should be using feature accessor methods, not accessing features on the // options // proto. strippedOptions = strippedOptions.toBuilder().clearFeatures().build(); } synchronized (this) { if (this.options == null) { this.options = strippedOptions; } } } return this.options; } /** Get a list of this message type's fields. */ public List<FieldDescriptor> getFields() { return Collections.unmodifiableList(Arrays.asList(fields)); } /** Get a list of this message type's oneofs. */ public List<OneofDescriptor> getOneofs() { return Collections.unmodifiableList(Arrays.asList(oneofs)); } /** Get a list of this message type's real oneofs. */ public List<OneofDescriptor> getRealOneofs() { return Collections.unmodifiableList(Arrays.asList(oneofs).subList(0, realOneofCount)); } /** Get a list of this message type's extensions. */ public List<FieldDescriptor> getExtensions() { return Collections.unmodifiableList(Arrays.asList(extensions)); } /** Get a list of message types nested within this one. */ public List<Descriptor> getNestedTypes() { return Collections.unmodifiableList(Arrays.asList(nestedTypes)); } /** Get a list of enum types nested within this one. */ public List<EnumDescriptor> getEnumTypes() { return Collections.unmodifiableList(Arrays.asList(enumTypes)); } /** Determines if the given field number is an extension. */ public boolean isExtensionNumber(final int number) { int index = Arrays.binarySearch(extensionRangeLowerBounds, number); if (index < 0) { index = ~index - 1; } // extensionRangeLowerBounds[index] is the biggest value <= number return index >= 0 && number < extensionRangeUpperBounds[index]; } /** Determines if the given field number is reserved. */ public boolean isReservedNumber(final int number) { for (final DescriptorProto.ReservedRange range : proto.getReservedRangeList()) { if (range.getStart() <= number && number < range.getEnd()) { return true; } } return false; } /** Determines if the given field name is reserved. */ public boolean isReservedName(final String name) { checkNotNull(name); for (final String reservedName : proto.getReservedNameList()) { if (reservedName.equals(name)) { return true; } } return false; } /** * Indicates whether the message can be extended. That is, whether it has any "extensions x to * y" ranges declared on it. */ public boolean isExtendable() { return !proto.getExtensionRangeList().isEmpty(); } /** * Finds a field by name. * * @param name The unqualified name of the field (e.g. "foo"). For protocol buffer messages that * follow <a * href=https://developers.google.com/protocol-buffers/docs/style#message_and_field_names>Google's * guidance on naming</a> this will be a snake case string, such as * <pre>song_name</pre> * . * @return The field's descriptor, or {@code null} if not found. */ public FieldDescriptor findFieldByName(final String name) { final GenericDescriptor result = file.pool.findSymbol(fullName + '.' + name); if (result instanceof FieldDescriptor) { return (FieldDescriptor) result; } else { return null; } } /** * Finds a field by field number. * * @param number The field number within this message type. * @return The field's descriptor, or {@code null} if not found. */ public FieldDescriptor findFieldByNumber(final int number) { return binarySearch( fieldsSortedByNumber, fieldsSortedByNumber.length, FieldDescriptor.NUMBER_GETTER, number); } /** * Finds a nested message type by name. * * @param name The unqualified name of the nested type such as "Foo" * @return The types's descriptor, or {@code null} if not found. */ public Descriptor findNestedTypeByName(final String name) { final GenericDescriptor result = file.pool.findSymbol(fullName + '.' + name); if (result instanceof Descriptor) { return (Descriptor) result; } else { return null; } } /** * Finds a nested enum type by name. * * @param name The unqualified name of the nested type such as "Foo" * @return The types's descriptor, or {@code null} if not found. */ public EnumDescriptor findEnumTypeByName(final String name) { final GenericDescriptor result = file.pool.findSymbol(fullName + '.' + name); if (result instanceof EnumDescriptor) { return (EnumDescriptor) result; } else { return null; } } private final int index; private DescriptorProto proto; private volatile MessageOptions options; private final String fullName; private final FileDescriptor file; private final Descriptor containingType; private final Descriptor[] nestedTypes; private final EnumDescriptor[] enumTypes; private final FieldDescriptor[] fields; private final FieldDescriptor[] fieldsSortedByNumber; private final FieldDescriptor[] extensions; private final OneofDescriptor[] oneofs; private final int realOneofCount; private final int[] extensionRangeLowerBounds; private final int[] extensionRangeUpperBounds; // Used to create a placeholder when the type cannot be found. Descriptor(final String fullname) throws DescriptorValidationException { String name = fullname; String packageName = ""; int pos = fullname.lastIndexOf('.'); if (pos != -1) { name = fullname.substring(pos + 1); packageName = fullname.substring(0, pos); } this.index = 0; this.proto = DescriptorProto.newBuilder() .setName(name) .addExtensionRange( DescriptorProto.ExtensionRange.newBuilder().setStart(1).setEnd(536870912).build()) .build(); this.fullName = fullname; this.containingType = null; this.nestedTypes = EMPTY_DESCRIPTORS; this.enumTypes = EMPTY_ENUM_DESCRIPTORS; this.fields = EMPTY_FIELD_DESCRIPTORS; this.fieldsSortedByNumber = EMPTY_FIELD_DESCRIPTORS; this.extensions = EMPTY_FIELD_DESCRIPTORS; this.oneofs = EMPTY_ONEOF_DESCRIPTORS; this.realOneofCount = 0; // Create a placeholder FileDescriptor to hold this message. this.file = new FileDescriptor(packageName, this); this.parent = this.file; extensionRangeLowerBounds = new int[] {1}; extensionRangeUpperBounds = new int[] {536870912}; } private Descriptor( final DescriptorProto proto, final FileDescriptor file, final Descriptor parent, final int index) throws DescriptorValidationException { if (parent == null) { this.parent = file; } else { this.parent = parent; } this.index = index; this.proto = proto; fullName = computeFullName(file, parent, proto.getName()); this.file = file; containingType = parent; oneofs = (proto.getOneofDeclCount() > 0) ? new OneofDescriptor[proto.getOneofDeclCount()] : EMPTY_ONEOF_DESCRIPTORS; for (int i = 0; i < proto.getOneofDeclCount(); i++) { oneofs[i] = new OneofDescriptor(proto.getOneofDecl(i), file, this, i); } nestedTypes = (proto.getNestedTypeCount() > 0) ? new Descriptor[proto.getNestedTypeCount()] : EMPTY_DESCRIPTORS; for (int i = 0; i < proto.getNestedTypeCount(); i++) { nestedTypes[i] = new Descriptor(proto.getNestedType(i), file, this, i); } enumTypes = (proto.getEnumTypeCount() > 0) ? new EnumDescriptor[proto.getEnumTypeCount()] : EMPTY_ENUM_DESCRIPTORS; for (int i = 0; i < proto.getEnumTypeCount(); i++) { enumTypes[i] = new EnumDescriptor(proto.getEnumType(i), file, this, i); } fields = (proto.getFieldCount() > 0) ? new FieldDescriptor[proto.getFieldCount()] : EMPTY_FIELD_DESCRIPTORS; for (int i = 0; i < proto.getFieldCount(); i++) { fields[i] = new FieldDescriptor(proto.getField(i), file, this, i, false); } this.fieldsSortedByNumber = (proto.getFieldCount() > 0) ? fields.clone() : EMPTY_FIELD_DESCRIPTORS; extensions = (proto.getExtensionCount() > 0) ? new FieldDescriptor[proto.getExtensionCount()] : EMPTY_FIELD_DESCRIPTORS; for (int i = 0; i < proto.getExtensionCount(); i++) { extensions[i] = new FieldDescriptor(proto.getExtension(i), file, this, i, true); } for (int i = 0; i < proto.getOneofDeclCount(); i++) { oneofs[i].fields = new FieldDescriptor[oneofs[i].getFieldCount()]; oneofs[i].fieldCount = 0; } for (int i = 0; i < proto.getFieldCount(); i++) { OneofDescriptor oneofDescriptor = fields[i].getContainingOneof(); if (oneofDescriptor != null) { oneofDescriptor.fields[oneofDescriptor.fieldCount++] = fields[i]; } } int syntheticOneofCount = 0; for (OneofDescriptor oneof : this.oneofs) { if (oneof.isSynthetic()) { syntheticOneofCount++; } else { if (syntheticOneofCount > 0) { throw new DescriptorValidationException(this, "Synthetic oneofs must come last."); } } } this.realOneofCount = this.oneofs.length - syntheticOneofCount; file.pool.addSymbol(this); // NOTE: The defined extension ranges are guaranteed to be disjoint. if (proto.getExtensionRangeCount() > 0) { extensionRangeLowerBounds = new int[proto.getExtensionRangeCount()]; extensionRangeUpperBounds = new int[proto.getExtensionRangeCount()]; int i = 0; for (final DescriptorProto.ExtensionRange range : proto.getExtensionRangeList()) { extensionRangeLowerBounds[i] = range.getStart(); extensionRangeUpperBounds[i] = range.getEnd(); i++; } // Since the ranges are disjoint, sorting these independently must still produce the correct // order. Arrays.sort(extensionRangeLowerBounds); Arrays.sort(extensionRangeUpperBounds); } else { extensionRangeLowerBounds = EMPTY_INT_ARRAY; extensionRangeUpperBounds = EMPTY_INT_ARRAY; } } /** See {@link FileDescriptor#resolveAllFeatures}. */ private void resolveAllFeatures() throws DescriptorValidationException { resolveFeatures(proto.getOptions().getFeatures()); for (Descriptor nestedType : nestedTypes) { nestedType.resolveAllFeatures(); } for (EnumDescriptor enumType : enumTypes) { enumType.resolveAllFeatures(); } // Oneofs must be resolved before any children oneof fields. for (OneofDescriptor oneof : oneofs) { oneof.resolveAllFeatures(); } for (FieldDescriptor field : fields) { field.resolveAllFeatures(); } for (FieldDescriptor extension : extensions) { extension.resolveAllFeatures(); } } /** Look up and cross-link all field types, etc. */ private void crossLink() throws DescriptorValidationException { for (final Descriptor nestedType : nestedTypes) { nestedType.crossLink(); } for (final FieldDescriptor field : fields) { field.crossLink(); } Arrays.sort(fieldsSortedByNumber); validateNoDuplicateFieldNumbers(); for (final FieldDescriptor extension : extensions) { extension.crossLink(); } } private void validateNoDuplicateFieldNumbers() throws DescriptorValidationException { for (int i = 0; i + 1 < fieldsSortedByNumber.length; i++) { FieldDescriptor old = fieldsSortedByNumber[i]; FieldDescriptor field = fieldsSortedByNumber[i + 1]; if (old.getNumber() == field.getNumber()) { throw new DescriptorValidationException( field, "Field number " + field.getNumber() + " has already been used in \"" + field.getContainingType().getFullName() + "\" by field \"" + old.getName() + "\"."); } } } /** See {@link FileDescriptor#setProto}. */ private void setProto(final DescriptorProto proto) throws DescriptorValidationException { this.proto = proto; this.options = null; resolveFeatures(proto.getOptions().getFeatures()); for (int i = 0; i < nestedTypes.length; i++) { nestedTypes[i].setProto(proto.getNestedType(i)); } for (int i = 0; i < oneofs.length; i++) { oneofs[i].setProto(proto.getOneofDecl(i)); } for (int i = 0; i < enumTypes.length; i++) { enumTypes[i].setProto(proto.getEnumType(i)); } for (int i = 0; i < fields.length; i++) { fields[i].setProto(proto.getField(i)); } for (int i = 0; i < extensions.length; i++) { extensions[i].setProto(proto.getExtension(i)); } } } // ================================================================= /** Describes a field of a message type. */ public static final class FieldDescriptor extends GenericDescriptor implements Comparable<FieldDescriptor>, FieldSet.FieldDescriptorLite<FieldDescriptor> { private static final NumberGetter<FieldDescriptor> NUMBER_GETTER = new NumberGetter<FieldDescriptor>() { @Override public int getNumber(FieldDescriptor fieldDescriptor) { return fieldDescriptor.getNumber(); } }; /** * Get the index of this descriptor within its parent. * * @see Descriptors.Descriptor#getIndex() */ public int getIndex() { return index; } /** Convert the descriptor to its protocol message representation. */ @Override public FieldDescriptorProto toProto() { return proto; } /** Get the field's unqualified name. */ @Override public String getName() { return proto.getName(); } /** Get the field's number. */ @Override public int getNumber() { return proto.getNumber(); } /** * Get the field's fully-qualified name. * * @see Descriptors.Descriptor#getFullName() */ @Override public String getFullName() { return fullName; } /** Get the JSON name of this field. */ public String getJsonName() { String result = jsonName; if (result != null) { return result; } else if (proto.hasJsonName()) { return jsonName = proto.getJsonName(); } else { return jsonName = fieldNameToJsonName(proto.getName()); } } /** * Get the field's java type. This is just for convenience. Every {@code * FieldDescriptorProto.Type} maps to exactly one Java type. */ public JavaType getJavaType() { return getType().getJavaType(); } /** For internal use only. */ @Override public WireFormat.JavaType getLiteJavaType() { return getLiteType().getJavaType(); } /** Get the {@code FileDescriptor} containing this descriptor. */ @Override public FileDescriptor getFile() { return file; } /** Get the field's declared type. */ public Type getType() { // Override delimited messages as legacy group type. Leaves unresolved messages as-is // since these are used before feature resolution when parsing java feature set defaults // (custom options) into unknown fields. if (type == Type.MESSAGE && this.features != null && getFeatures().getMessageEncoding() == FeatureSet.MessageEncoding.DELIMITED) { return Type.GROUP; } return type; } /** For internal use only. */ @Override public WireFormat.FieldType getLiteType() { return table[getType().ordinal()]; } /** For internal use only. */ public boolean needsUtf8Check() { if (getType() != Type.STRING) { return false; } if (getContainingType().toProto().getOptions().getMapEntry()) { // Always enforce strict UTF-8 checking for map fields. return true; } if (getFeatures() .getExtension(JavaFeaturesProto.java_) .getUtf8Validation() .equals(JavaFeatures.Utf8Validation.VERIFY)) { return true; } return getFeatures().getUtf8Validation().equals(FeatureSet.Utf8Validation.VERIFY); } public boolean isMapField() { return getType() == Type.MESSAGE && isRepeated() && getMessageType().toProto().getOptions().getMapEntry(); } // I'm pretty sure values() constructs a new array every time, since there // is nothing stopping the caller from mutating the array. Therefore we // make a static copy here. private static final WireFormat.FieldType[] table = WireFormat.FieldType.values(); /** Is this field declared required? */ public boolean isRequired() { return getFeatures().getFieldPresence() == DescriptorProtos.FeatureSet.FieldPresence.LEGACY_REQUIRED; } /** Is this field declared optional? */ public boolean isOptional() { return proto.getLabel() == FieldDescriptorProto.Label.LABEL_OPTIONAL && getFeatures().getFieldPresence() != DescriptorProtos.FeatureSet.FieldPresence.LEGACY_REQUIRED; } /** Is this field declared repeated? */ @Override public boolean isRepeated() { return proto.getLabel() == FieldDescriptorProto.Label.LABEL_REPEATED; } /** * Does this field have the {@code [packed = true]} option or is this field packable in proto3 * and not explicitly set to unpacked? */ @Override public boolean isPacked() { if (!isPackable()) { return false; } return getFeatures() .getRepeatedFieldEncoding() .equals(FeatureSet.RepeatedFieldEncoding.PACKED); } /** Can this field be packed? That is, is it a repeated primitive field? */ public boolean isPackable() { return isRepeated() && getLiteType().isPackable(); } /** Returns true if the field had an explicitly-defined default value. */ public boolean hasDefaultValue() { return proto.hasDefaultValue(); } /** * Returns the field's default value. Valid for all types except for messages and groups. For * all other types, the object returned is of the same class that would returned by * Message.getField(this). */ public Object getDefaultValue() { if (getJavaType() == JavaType.MESSAGE) { throw new UnsupportedOperationException( "FieldDescriptor.getDefaultValue() called on an embedded message field."); } return defaultValue; } /** Get the {@code FieldOptions}, defined in {@code descriptor.proto}. */ public FieldOptions getOptions() { if (this.options == null) { FieldOptions strippedOptions = this.proto.getOptions(); if (strippedOptions.hasFeatures()) { // Clients should be using feature accessor methods, not accessing features on the // options // proto. strippedOptions = strippedOptions.toBuilder().clearFeatures().build(); } synchronized (this) { if (this.options == null) { this.options = strippedOptions; } } } return this.options; } /** Is this field an extension? */ public boolean isExtension() { return proto.hasExtendee(); } /** * Get the field's containing type. For extensions, this is the type being extended, not the * location where the extension was defined. See {@link #getExtensionScope()}. */ public Descriptor getContainingType() { return containingType; } /** Get the field's containing oneof. */ public OneofDescriptor getContainingOneof() { return containingOneof; } /** Get the field's containing oneof, only if non-synthetic. */ public OneofDescriptor getRealContainingOneof() { return containingOneof != null && !containingOneof.isSynthetic() ? containingOneof : null; } /** * Returns true if this field was syntactically written with "optional" in the .proto file. * Excludes singular proto3 fields that do not have a label. */ boolean hasOptionalKeyword() { return isProto3Optional || (file.getEdition() == Edition.EDITION_PROTO2 && isOptional() && getContainingOneof() == null); } /** * Returns true if this field tracks presence, ie. does the field distinguish between "unset" * and "present with default value." * * <p>This includes required, optional, and oneof fields. It excludes maps, repeated fields, and * singular proto3 fields without "optional". * * <p>For fields where hasPresence() == true, the return value of msg.hasField() is semantically * meaningful. */ public boolean hasPresence() { if (isRepeated()) { return false; } return isProto3Optional || getType() == Type.MESSAGE || getType() == Type.GROUP || isExtension() || getContainingOneof() != null || getFeatures().getFieldPresence() != DescriptorProtos.FeatureSet.FieldPresence.IMPLICIT; } /** * Returns true if this field is structured like the synthetic field of a proto2 group. This * allows us to expand our treatment of delimited fields without breaking proto2 files that have * been upgraded to editions. */ boolean isGroupLike() { if (getFeatures().getMessageEncoding() != DescriptorProtos.FeatureSet.MessageEncoding.DELIMITED) { // Groups are always tag-delimited. return false; } if (!getMessageType().getName().toLowerCase().equals(getName())) { // Group fields always are always the lowercase type name. return false; } if (getMessageType().getFile() != getFile()) { // Groups could only be defined in the same file they're used. return false; } // Group messages are always defined in the same scope as the field. File level extensions // will compare NULL == NULL here, which is why the file comparison above is necessary to // ensure both come from the same file. return isExtension() ? getMessageType().getContainingType() == getExtensionScope() : getMessageType().getContainingType() == getContainingType(); } /** * For extensions defined nested within message types, gets the outer type. Not valid for * non-extension fields. For example, consider this {@code .proto} file: * * <pre> * message Foo { * extensions 1000 to max; * } * extend Foo { * optional int32 baz = 1234; * } * message Bar { * extend Foo { * optional int32 moo = 4321; * } * } * </pre> * * Both {@code baz}'s and {@code moo}'s containing type is {@code Foo}. However, {@code baz}'s * extension scope is {@code null} while {@code moo}'s extension scope is {@code Bar}. */ public Descriptor getExtensionScope() { if (!isExtension()) { throw new UnsupportedOperationException( String.format("This field is not an extension. (%s)", fullName)); } return extensionScope; } /** For embedded message and group fields, gets the field's type. */ public Descriptor getMessageType() { if (getJavaType() != JavaType.MESSAGE) { throw new UnsupportedOperationException( String.format("This field is not of message type. (%s)", fullName)); } return messageType; } /** For enum fields, gets the field's type. */ @Override public EnumDescriptor getEnumType() { if (getJavaType() != JavaType.ENUM) { throw new UnsupportedOperationException( String.format("This field is not of enum type. (%s)", fullName)); } return enumType; } /** * Determines if the given enum field is treated as closed based on legacy non-conformant * behavior. * * <p>Conformant behavior determines closedness based on the enum and can be queried using * {@code EnumDescriptor.isClosed()}. * * <p>Some runtimes currently have a quirk where non-closed enums are treated as closed when * used as the type of fields defined in a `syntax = proto2;` file. This quirk is not present in * all runtimes; as of writing, we know that: * * <ul> * <li>C++, Java, and C++-based Python share this quirk. * <li>UPB and UPB-based Python do not. * <li>PHP and Ruby treat all enums as open regardless of declaration. * </ul> * * <p>Care should be taken when using this function to respect the target runtime's enum * handling quirks. */ public boolean legacyEnumFieldTreatedAsClosed() { // Don't check JavaFeaturesProto extension for files without dependencies. // This is especially important for descriptor.proto since getting the JavaFeaturesProto // extension itself involves calling legacyEnumFieldTreatedAsClosed() which would otherwise // infinite loop. if (getFile().getDependencies().isEmpty()) { return getType() == Type.ENUM && enumType.isClosed(); } return getType() == Type.ENUM && (getFeatures().getExtension(JavaFeaturesProto.java_).getLegacyClosedEnum() || enumType.isClosed()); } /** * Compare with another {@code FieldDescriptor}. This orders fields in "canonical" order, which * simply means ascending order by field number. {@code other} must be a field of the same type. * That is, {@code getContainingType()} must return the same {@code Descriptor} for both fields. * * @return negative, zero, or positive if {@code this} is less than, equal to, or greater than * {@code other}, respectively */ @Override public int compareTo(final FieldDescriptor other) { if (other.containingType != containingType) { throw new IllegalArgumentException( "FieldDescriptors can only be compared to other FieldDescriptors " + "for fields of the same message type."); } return getNumber() - other.getNumber(); } @Override public String toString() { return getFullName(); } private final int index; private FieldDescriptorProto proto; private volatile FieldOptions options; private final String fullName; private String jsonName; private final FileDescriptor file; private final Descriptor extensionScope; private final boolean isProto3Optional; // Possibly initialized during cross-linking. private Type type; private Descriptor containingType; private Descriptor messageType; private OneofDescriptor containingOneof; private EnumDescriptor enumType; private Object defaultValue; public enum Type { DOUBLE(JavaType.DOUBLE), FLOAT(JavaType.FLOAT), INT64(JavaType.LONG), UINT64(JavaType.LONG), INT32(JavaType.INT), FIXED64(JavaType.LONG), FIXED32(JavaType.INT), BOOL(JavaType.BOOLEAN), STRING(JavaType.STRING), GROUP(JavaType.MESSAGE), MESSAGE(JavaType.MESSAGE), BYTES(JavaType.BYTE_STRING), UINT32(JavaType.INT), ENUM(JavaType.ENUM), SFIXED32(JavaType.INT), SFIXED64(JavaType.LONG), SINT32(JavaType.INT), SINT64(JavaType.LONG); // Private copy to avoid repeated allocations from calls to values() in valueOf(). private static final Type[] types = values(); Type(JavaType javaType) { this.javaType = javaType; } private final JavaType javaType; public FieldDescriptorProto.Type toProto() { return FieldDescriptorProto.Type.forNumber(ordinal() + 1); } public JavaType getJavaType() { return javaType; } public static Type valueOf(final FieldDescriptorProto.Type type) { return types[type.getNumber() - 1]; } } static { // Refuse to init if someone added a new declared type. if (Type.types.length != FieldDescriptorProto.Type.values().length) { throw new RuntimeException( "descriptor.proto has a new declared type but Descriptors.java wasn't updated."); } } public enum JavaType { INT(0), LONG(0L), FLOAT(0F), DOUBLE(0D), BOOLEAN(false), STRING(""), BYTE_STRING(ByteString.EMPTY), ENUM(null), MESSAGE(null); JavaType(final Object defaultDefault) { this.defaultDefault = defaultDefault; } /** * The default default value for fields of this type, if it's a primitive type. This is meant * for use inside this file only, hence is private. */ private final Object defaultDefault; } // This method should match exactly with the ToJsonName() function in C++ // descriptor.cc. private static String fieldNameToJsonName(String name) { final int length = name.length(); StringBuilder result = new StringBuilder(length); boolean isNextUpperCase = false; for (int i = 0; i < length; i++) { char ch = name.charAt(i); if (ch == '_') { isNextUpperCase = true; } else if (isNextUpperCase) { // This closely matches the logic for ASCII characters in: // http://google3/google/protobuf/descriptor.cc?l=249-251&rcl=228891689 if ('a' <= ch && ch <= 'z') { ch = (char) (ch - 'a' + 'A'); } result.append(ch); isNextUpperCase = false; } else { result.append(ch); } } return result.toString(); } private FieldDescriptor( final FieldDescriptorProto proto, final FileDescriptor file, final Descriptor parent, final int index, final boolean isExtension) throws DescriptorValidationException { this.parent = parent; this.index = index; this.proto = proto; fullName = computeFullName(file, parent, proto.getName()); this.file = file; if (proto.hasType()) { type = Type.valueOf(proto.getType()); } isProto3Optional = proto.getProto3Optional(); if (getNumber() <= 0) { throw new DescriptorValidationException(this, "Field numbers must be positive integers."); } if (isExtension) { if (!proto.hasExtendee()) { throw new DescriptorValidationException( this, "FieldDescriptorProto.extendee not set for extension field."); } containingType = null; // Will be filled in when cross-linking if (parent != null) { extensionScope = parent; } else { extensionScope = null; this.parent = file; } if (proto.hasOneofIndex()) { throw new DescriptorValidationException( this, "FieldDescriptorProto.oneof_index set for extension field."); } containingOneof = null; } else { if (proto.hasExtendee()) { throw new DescriptorValidationException( this, "FieldDescriptorProto.extendee set for non-extension field."); } containingType = parent; if (proto.hasOneofIndex()) { if (proto.getOneofIndex() < 0 || proto.getOneofIndex() >= parent.toProto().getOneofDeclCount()) { throw new DescriptorValidationException( this, "FieldDescriptorProto.oneof_index is out of range for type " + parent.getName()); } containingOneof = parent.getOneofs().get(proto.getOneofIndex()); containingOneof.fieldCount++; this.parent = containingOneof; } else { containingOneof = null; } extensionScope = null; } file.pool.addSymbol(this); } /** See {@link FileDescriptor#resolveAllFeatures}. */ private void resolveAllFeatures() throws DescriptorValidationException { resolveFeatures(proto.getOptions().getFeatures()); } @Override FeatureSet inferLegacyProtoFeatures() { FeatureSet.Builder features = FeatureSet.newBuilder(); if (getFile().getEdition().getNumber() >= Edition.EDITION_2023.getNumber()) { return features.build(); } if (proto.getLabel() == FieldDescriptorProto.Label.LABEL_REQUIRED) { features.setFieldPresence(FeatureSet.FieldPresence.LEGACY_REQUIRED); } if (proto.getType() == FieldDescriptorProto.Type.TYPE_GROUP) { features.setMessageEncoding(FeatureSet.MessageEncoding.DELIMITED); } if (getFile().getEdition() == Edition.EDITION_PROTO2 && proto.getOptions().getPacked()) { features.setRepeatedFieldEncoding(FeatureSet.RepeatedFieldEncoding.PACKED); } if (getFile().getEdition() == Edition.EDITION_PROTO3) { if (proto.getOptions().hasPacked() && !proto.getOptions().getPacked()) { features.setRepeatedFieldEncoding(FeatureSet.RepeatedFieldEncoding.EXPANDED); } } return features.build(); } @Override boolean hasInferredLegacyProtoFeatures() { if (getFile().getEdition().getNumber() >= Edition.EDITION_2023.getNumber()) { return false; } if (proto.getLabel() == FieldDescriptorProto.Label.LABEL_REQUIRED) { return true; } if (proto.getType() == FieldDescriptorProto.Type.TYPE_GROUP) { return true; } if (proto.getOptions().getPacked()) { return true; } if (getFile().getEdition() == Edition.EDITION_PROTO3) { if (proto.getOptions().hasPacked() && !proto.getOptions().getPacked()) { return true; } } return false; } @Override void validateFeatures() throws DescriptorValidationException { if (containingType != null && containingType.toProto().getOptions().getMessageSetWireFormat()) { if (isExtension()) { if (!isOptional() || getType() != Type.MESSAGE) { throw new DescriptorValidationException( this, "Extensions of MessageSets must be optional messages."); } } } } /** Look up and cross-link all field types, etc. */ private void crossLink() throws DescriptorValidationException { if (proto.hasExtendee()) { final GenericDescriptor extendee = file.pool.lookupSymbol( proto.getExtendee(), this, DescriptorPool.SearchFilter.TYPES_ONLY); if (!(extendee instanceof Descriptor)) { throw new DescriptorValidationException( this, '\"' + proto.getExtendee() + "\" is not a message type."); } containingType = (Descriptor) extendee; if (!getContainingType().isExtensionNumber(getNumber())) { throw new DescriptorValidationException( this, '\"' + getContainingType().getFullName() + "\" does not declare " + getNumber() + " as an extension number."); } } if (proto.hasTypeName()) { final GenericDescriptor typeDescriptor = file.pool.lookupSymbol( proto.getTypeName(), this, DescriptorPool.SearchFilter.TYPES_ONLY); if (!proto.hasType()) { // Choose field type based on symbol. if (typeDescriptor instanceof Descriptor) { type = Type.MESSAGE; } else if (typeDescriptor instanceof EnumDescriptor) { type = Type.ENUM; } else { throw new DescriptorValidationException( this, '\"' + proto.getTypeName() + "\" is not a type."); } } if (getJavaType() == JavaType.MESSAGE) { if (!(typeDescriptor instanceof Descriptor)) { throw new DescriptorValidationException( this, '\"' + proto.getTypeName() + "\" is not a message type."); } messageType = (Descriptor) typeDescriptor; if (proto.hasDefaultValue()) { throw new DescriptorValidationException(this, "Messages can't have default values."); } } else if (getJavaType() == JavaType.ENUM) { if (!(typeDescriptor instanceof EnumDescriptor)) { throw new DescriptorValidationException( this, '\"' + proto.getTypeName() + "\" is not an enum type."); } enumType = (EnumDescriptor) typeDescriptor; } else { throw new DescriptorValidationException(this, "Field with primitive type has type_name."); } } else { if (getJavaType() == JavaType.MESSAGE || getJavaType() == JavaType.ENUM) { throw new DescriptorValidationException( this, "Field with message or enum type missing type_name."); } } // Only repeated primitive fields may be packed. if (proto.getOptions().getPacked() && !isPackable()) { throw new DescriptorValidationException( this, "[packed = true] can only be specified for repeated primitive fields."); } // We don't attempt to parse the default value until here because for // enums we need the enum type's descriptor. if (proto.hasDefaultValue()) { if (isRepeated()) { throw new DescriptorValidationException( this, "Repeated fields cannot have default values."); } try { switch (getType()) { case INT32: case SINT32: case SFIXED32: defaultValue = TextFormat.parseInt32(proto.getDefaultValue()); break; case UINT32: case FIXED32: defaultValue = TextFormat.parseUInt32(proto.getDefaultValue()); break; case INT64: case SINT64: case SFIXED64: defaultValue = TextFormat.parseInt64(proto.getDefaultValue()); break; case UINT64: case FIXED64: defaultValue = TextFormat.parseUInt64(proto.getDefaultValue()); break; case FLOAT: if (proto.getDefaultValue().equals("inf")) { defaultValue = Float.POSITIVE_INFINITY; } else if (proto.getDefaultValue().equals("-inf")) { defaultValue = Float.NEGATIVE_INFINITY; } else if (proto.getDefaultValue().equals("nan")) { defaultValue = Float.NaN; } else { defaultValue = Float.valueOf(proto.getDefaultValue()); } break; case DOUBLE: if (proto.getDefaultValue().equals("inf")) { defaultValue = Double.POSITIVE_INFINITY; } else if (proto.getDefaultValue().equals("-inf")) { defaultValue = Double.NEGATIVE_INFINITY; } else if (proto.getDefaultValue().equals("nan")) { defaultValue = Double.NaN; } else { defaultValue = Double.valueOf(proto.getDefaultValue()); } break; case BOOL: defaultValue = Boolean.valueOf(proto.getDefaultValue()); break; case STRING: defaultValue = proto.getDefaultValue(); break; case BYTES: try { defaultValue = TextFormat.unescapeBytes(proto.getDefaultValue()); } catch (TextFormat.InvalidEscapeSequenceException e) { throw new DescriptorValidationException( this, "Couldn't parse default value: " + e.getMessage(), e); } break; case ENUM: defaultValue = enumType.findValueByName(proto.getDefaultValue()); if (defaultValue == null) { throw new DescriptorValidationException( this, "Unknown enum default value: \"" + proto.getDefaultValue() + '\"'); } break; case MESSAGE: case GROUP: throw new DescriptorValidationException(this, "Message type had default value."); } } catch (NumberFormatException e) { throw new DescriptorValidationException( this, "Could not parse default value: \"" + proto.getDefaultValue() + '\"', e); } } else { // Determine the default default for this field. if (isRepeated()) { defaultValue = Collections.emptyList(); } else { switch (getJavaType()) { case ENUM: // We guarantee elsewhere that an enum type always has at least // one possible value. defaultValue = enumType.getValues().get(0); break; case MESSAGE: defaultValue = null; break; default: defaultValue = getJavaType().defaultDefault; break; } } } } /** See {@link FileDescriptor#setProto}. */ private void setProto(final FieldDescriptorProto proto) throws DescriptorValidationException { this.proto = proto; this.options = null; resolveFeatures(proto.getOptions().getFeatures()); } /** For internal use only. This is to satisfy the FieldDescriptorLite interface. */ @Override public MessageLite.Builder internalMergeFrom(MessageLite.Builder to, MessageLite from) { // FieldDescriptors are only used with non-lite messages so we can just // down-cast and call mergeFrom directly. return ((Message.Builder) to).mergeFrom((Message) from); } } // ================================================================= /** Describes an enum type. */ public static final class EnumDescriptor extends GenericDescriptor implements Internal.EnumLiteMap<EnumValueDescriptor> { /** * Get the index of this descriptor within its parent. * * @see Descriptors.Descriptor#getIndex() */ public int getIndex() { return index; } /** Convert the descriptor to its protocol message representation. */ @Override public EnumDescriptorProto toProto() { return proto; } /** Get the type's unqualified name. */ @Override public String getName() { return proto.getName(); } /** * Get the type's fully-qualified name. * * @see Descriptors.Descriptor#getFullName() */ @Override public String getFullName() { return fullName; } /** Get the {@link FileDescriptor} containing this descriptor. */ @Override public FileDescriptor getFile() { return file; } /** * Determines if the given enum is closed. * * <p>Closed enum means that it: * * <ul> * <li>Has a fixed set of values, rather than being equivalent to an int32. * <li>Encountering values not in this set causes them to be treated as unknown fields. * <li>The first value (i.e., the default) may be nonzero. * </ul> * * <p>WARNING: Some runtimes currently have a quirk where non-closed enums are treated as closed * when used as the type of fields defined in a `syntax = proto2;` file. This quirk is not * present in all runtimes; as of writing, we know that: * * <ul> * <li> C++, Java, and C++-based Python share this quirk. * <li> UPB and UPB-based Python do not. * <li> PHP and Ruby treat all enums as open regardless of declaration. * </ul> * * <p>Care should be taken when using this function to respect the target runtime's enum * handling quirks. */ public boolean isClosed() { return getFeatures().getEnumType() == DescriptorProtos.FeatureSet.EnumType.CLOSED; } /** If this is a nested type, get the outer descriptor, otherwise null. */ public Descriptor getContainingType() { return containingType; } /** Get the {@code EnumOptions}, defined in {@code descriptor.proto}. */ public EnumOptions getOptions() { if (this.options == null) { EnumOptions strippedOptions = this.proto.getOptions(); if (strippedOptions.hasFeatures()) { // Clients should be using feature accessor methods, not accessing features on the // options // proto. strippedOptions = strippedOptions.toBuilder().clearFeatures().build(); } synchronized (this) { if (this.options == null) { this.options = strippedOptions; } } } return this.options; } /** Get a list of defined values for this enum. */ public List<EnumValueDescriptor> getValues() { return Collections.unmodifiableList(Arrays.asList(values)); } /** Determines if the given field number is reserved. */ public boolean isReservedNumber(final int number) { for (final EnumDescriptorProto.EnumReservedRange range : proto.getReservedRangeList()) { if (range.getStart() <= number && number <= range.getEnd()) { return true; } } return false; } /** Determines if the given field name is reserved. */ public boolean isReservedName(final String name) { checkNotNull(name); for (final String reservedName : proto.getReservedNameList()) { if (reservedName.equals(name)) { return true; } } return false; } /** * Find an enum value by name. * * @param name the unqualified name of the value such as "FOO" * @return the value's descriptor, or {@code null} if not found */ public EnumValueDescriptor findValueByName(final String name) { final GenericDescriptor result = file.pool.findSymbol(fullName + '.' + name); if (result instanceof EnumValueDescriptor) { return (EnumValueDescriptor) result; } else { return null; } } /** * Find an enum value by number. If multiple enum values have the same number, this returns the * first defined value with that number. * * @param number The value's number. * @return the value's descriptor, or {@code null} if not found. */ @Override public EnumValueDescriptor findValueByNumber(final int number) { return binarySearch( valuesSortedByNumber, distinctNumbers, EnumValueDescriptor.NUMBER_GETTER, number); } private static class UnknownEnumValueReference extends WeakReference<EnumValueDescriptor> { private final int number; private UnknownEnumValueReference(int number, EnumValueDescriptor descriptor) { super(descriptor); this.number = number; } } /** * Get the enum value for a number. If no enum value has this number, construct an * EnumValueDescriptor for it. */ public EnumValueDescriptor findValueByNumberCreatingIfUnknown(final int number) { EnumValueDescriptor result = findValueByNumber(number); if (result != null) { return result; } // The number represents an unknown enum value. synchronized (this) { if (cleanupQueue == null) { cleanupQueue = new ReferenceQueue<>(); unknownValues = new HashMap<>(); } else { while (true) { UnknownEnumValueReference toClean = (UnknownEnumValueReference) cleanupQueue.poll(); if (toClean == null) { break; } unknownValues.remove(toClean.number); } } // There are two ways we can be missing a value: it wasn't in the map, or the reference // has been GC'd. (It may even have been GC'd since we cleaned up the references a few // lines of code ago.) So get out the reference, if it's still present... WeakReference<EnumValueDescriptor> reference = unknownValues.get(number); result = (reference == null) ? null : reference.get(); if (result == null) { result = new EnumValueDescriptor(this, number); unknownValues.put(number, new UnknownEnumValueReference(number, result)); } } return result; } // Used in tests only. int getUnknownEnumValueDescriptorCount() { return unknownValues.size(); } private final int index; private EnumDescriptorProto proto; private volatile EnumOptions options; private final String fullName; private final FileDescriptor file; private final Descriptor containingType; private final EnumValueDescriptor[] values; private final EnumValueDescriptor[] valuesSortedByNumber; private final int distinctNumbers; private Map<Integer, WeakReference<EnumValueDescriptor>> unknownValues = null; private ReferenceQueue<EnumValueDescriptor> cleanupQueue = null; private EnumDescriptor( final EnumDescriptorProto proto, final FileDescriptor file, final Descriptor parent, final int index) throws DescriptorValidationException { if (parent == null) { this.parent = file; } else { this.parent = parent; } this.index = index; this.proto = proto; fullName = computeFullName(file, parent, proto.getName()); this.file = file; containingType = parent; if (proto.getValueCount() == 0) { // We cannot allow enums with no values because this would mean there // would be no valid default value for fields of this type. throw new DescriptorValidationException(this, "Enums must contain at least one value."); } values = new EnumValueDescriptor[proto.getValueCount()]; for (int i = 0; i < proto.getValueCount(); i++) { values[i] = new EnumValueDescriptor(proto.getValue(i), file, this, i); } valuesSortedByNumber = values.clone(); Arrays.sort(valuesSortedByNumber, EnumValueDescriptor.BY_NUMBER); // deduplicate int j = 0; for (int i = 1; i < proto.getValueCount(); i++) { EnumValueDescriptor oldValue = valuesSortedByNumber[j]; EnumValueDescriptor newValue = valuesSortedByNumber[i]; if (oldValue.getNumber() != newValue.getNumber()) { valuesSortedByNumber[++j] = newValue; } } this.distinctNumbers = j + 1; Arrays.fill(valuesSortedByNumber, distinctNumbers, proto.getValueCount(), null); file.pool.addSymbol(this); } /** See {@link FileDescriptor#resolveAllFeatures}. */ private void resolveAllFeatures() throws DescriptorValidationException { resolveFeatures(proto.getOptions().getFeatures()); for (EnumValueDescriptor value : values) { value.resolveAllFeatures(); } } /** See {@link FileDescriptor#setProto}. */ private void setProto(final EnumDescriptorProto proto) throws DescriptorValidationException { this.proto = proto; this.options = null; resolveFeatures(proto.getOptions().getFeatures()); for (int i = 0; i < values.length; i++) { values[i].setProto(proto.getValue(i)); } } } // ================================================================= /** * Describes one value within an enum type. Note that multiple defined values may have the same * number. In generated Java code, all values with the same number after the first become aliases * of the first. However, they still have independent EnumValueDescriptors. */ @SuppressWarnings("ShouldNotSubclass") public static final class EnumValueDescriptor extends GenericDescriptor implements Internal.EnumLite { static final Comparator<EnumValueDescriptor> BY_NUMBER = new Comparator<EnumValueDescriptor>() { @Override public int compare(EnumValueDescriptor o1, EnumValueDescriptor o2) { return Integer.valueOf(o1.getNumber()).compareTo(o2.getNumber()); } }; static final NumberGetter<EnumValueDescriptor> NUMBER_GETTER = new NumberGetter<EnumValueDescriptor>() { @Override public int getNumber(EnumValueDescriptor enumValueDescriptor) { return enumValueDescriptor.getNumber(); } }; /** * Get the index of this descriptor within its parent. * * @see Descriptors.Descriptor#getIndex() */ public int getIndex() { return index; } /** Convert the descriptor to its protocol message representation. */ @Override public EnumValueDescriptorProto toProto() { return proto; } /** Get the value's unqualified name. */ @Override public String getName() { return proto.getName(); } /** Get the value's number. */ @Override public int getNumber() { return proto.getNumber(); } @Override public String toString() { return proto.getName(); } /** * Get the value's fully-qualified name. * * @see Descriptors.Descriptor#getFullName() */ @Override public String getFullName() { return fullName; } /** Get the {@link FileDescriptor} containing this descriptor. */ @Override public FileDescriptor getFile() { return type.file; } /** Get the value's enum type. */ public EnumDescriptor getType() { return type; } /** Get the {@code EnumValueOptions}, defined in {@code descriptor.proto}. */ public EnumValueOptions getOptions() { if (this.options == null) { EnumValueOptions strippedOptions = this.proto.getOptions(); if (strippedOptions.hasFeatures()) { // Clients should be using feature accessor methods, not accessing features on the // options // proto. strippedOptions = strippedOptions.toBuilder().clearFeatures().build(); } synchronized (this) { if (this.options == null) { this.options = strippedOptions; } } } return this.options; } private final int index; private EnumValueDescriptorProto proto; private volatile EnumValueOptions options; private final String fullName; private final EnumDescriptor type; private EnumValueDescriptor( final EnumValueDescriptorProto proto, final FileDescriptor file, final EnumDescriptor parent, final int index) throws DescriptorValidationException { this.parent = parent; this.index = index; this.proto = proto; this.type = parent; this.fullName = parent.getFullName() + '.' + proto.getName(); file.pool.addSymbol(this); } // Create an unknown enum value. private EnumValueDescriptor(final EnumDescriptor parent, final Integer number) { String name = "UNKNOWN_ENUM_VALUE_" + parent.getName() + "_" + number; EnumValueDescriptorProto proto = EnumValueDescriptorProto.newBuilder().setName(name).setNumber(number).build(); this.parent = parent; this.index = -1; this.proto = proto; this.type = parent; this.fullName = parent.getFullName() + '.' + proto.getName(); // Don't add this descriptor into pool. } /** See {@link FileDescriptor#resolveAllFeatures}. */ private void resolveAllFeatures() throws DescriptorValidationException { resolveFeatures(proto.getOptions().getFeatures()); } /** See {@link FileDescriptor#setProto}. */ private void setProto(final EnumValueDescriptorProto proto) throws DescriptorValidationException { this.proto = proto; this.options = null; resolveFeatures(proto.getOptions().getFeatures()); } } // ================================================================= /** Describes a service type. */ public static final class ServiceDescriptor extends GenericDescriptor { /** * Get the index of this descriptor within its parent. * @see Descriptors.Descriptor#getIndex() */ public int getIndex() { return index; } /** Convert the descriptor to its protocol message representation. */ @Override public ServiceDescriptorProto toProto() { return proto; } /** Get the type's unqualified name. */ @Override public String getName() { return proto.getName(); } /** * Get the type's fully-qualified name. * * @see Descriptors.Descriptor#getFullName() */ @Override public String getFullName() { return fullName; } /** Get the {@link FileDescriptor} containing this descriptor. */ @Override public FileDescriptor getFile() { return file; } /** Get the {@code ServiceOptions}, defined in {@code descriptor.proto}. */ public ServiceOptions getOptions() { if (this.options == null) { ServiceOptions strippedOptions = this.proto.getOptions(); if (strippedOptions.hasFeatures()) { // Clients should be using feature accessor methods, not accessing features on the // options // proto. strippedOptions = strippedOptions.toBuilder().clearFeatures().build(); } synchronized (this) { if (this.options == null) { this.options = strippedOptions; } } } return this.options; } /** Get a list of methods for this service. */ public List<MethodDescriptor> getMethods() { return Collections.unmodifiableList(Arrays.asList(methods)); } /** * Find a method by name. * * @param name the unqualified name of the method such as "Foo" * @return the method's descriptor, or {@code null} if not found */ public MethodDescriptor findMethodByName(final String name) { final GenericDescriptor result = file.pool.findSymbol(fullName + '.' + name); if (result instanceof MethodDescriptor) { return (MethodDescriptor) result; } else { return null; } } private final int index; private ServiceDescriptorProto proto; private volatile ServiceOptions options; private final String fullName; private final FileDescriptor file; private MethodDescriptor[] methods; private ServiceDescriptor( final ServiceDescriptorProto proto, final FileDescriptor file, final int index) throws DescriptorValidationException { this.parent = file; this.index = index; this.proto = proto; fullName = computeFullName(file, null, proto.getName()); this.file = file; methods = new MethodDescriptor[proto.getMethodCount()]; for (int i = 0; i < proto.getMethodCount(); i++) { methods[i] = new MethodDescriptor(proto.getMethod(i), file, this, i); } file.pool.addSymbol(this); } /** See {@link FileDescriptor#resolveAllFeatures}. */ private void resolveAllFeatures() throws DescriptorValidationException { resolveFeatures(proto.getOptions().getFeatures()); for (MethodDescriptor method : methods) { method.resolveAllFeatures(); } } private void crossLink() throws DescriptorValidationException { for (final MethodDescriptor method : methods) { method.crossLink(); } } /** See {@link FileDescriptor#setProto}. */ private void setProto(final ServiceDescriptorProto proto) throws DescriptorValidationException { this.proto = proto; this.options = null; resolveFeatures(proto.getOptions().getFeatures()); for (int i = 0; i < methods.length; i++) { methods[i].setProto(proto.getMethod(i)); } } } // ================================================================= /** Describes one method within a service type. */ public static final class MethodDescriptor extends GenericDescriptor { /** * Get the index of this descriptor within its parent. * @see Descriptors.Descriptor#getIndex() */ public int getIndex() { return index; } /** Convert the descriptor to its protocol message representation. */ @Override public MethodDescriptorProto toProto() { return proto; } /** Get the method's unqualified name. */ @Override public String getName() { return proto.getName(); } /** * Get the method's fully-qualified name. * * @see Descriptors.Descriptor#getFullName() */ @Override public String getFullName() { return fullName; } /** Get the {@link FileDescriptor} containing this descriptor. */ @Override public FileDescriptor getFile() { return file; } /** Get the method's service type. */ public ServiceDescriptor getService() { return service; } /** Get the method's input type. */ public Descriptor getInputType() { return inputType; } /** Get the method's output type. */ public Descriptor getOutputType() { return outputType; } /** Get whether or not the inputs are streaming. */ public boolean isClientStreaming() { return proto.getClientStreaming(); } /** Get whether or not the outputs are streaming. */ public boolean isServerStreaming() { return proto.getServerStreaming(); } /** Get the {@code MethodOptions}, defined in {@code descriptor.proto}. */ public MethodOptions getOptions() { if (this.options == null) { MethodOptions strippedOptions = this.proto.getOptions(); if (strippedOptions.hasFeatures()) { // Clients should be using feature accessor methods, not accessing features on the // options // proto. strippedOptions = strippedOptions.toBuilder().clearFeatures().build(); } synchronized (this) { if (this.options == null) { this.options = strippedOptions; } } } return this.options; } private final int index; private MethodDescriptorProto proto; private volatile MethodOptions options; private final String fullName; private final FileDescriptor file; private final ServiceDescriptor service; // Initialized during cross-linking. private Descriptor inputType; private Descriptor outputType; private MethodDescriptor( final MethodDescriptorProto proto, final FileDescriptor file, final ServiceDescriptor parent, final int index) throws DescriptorValidationException { this.parent = parent; this.index = index; this.proto = proto; this.file = file; service = parent; fullName = parent.getFullName() + '.' + proto.getName(); file.pool.addSymbol(this); } /** See {@link FileDescriptor#resolveAllFeatures}. */ private void resolveAllFeatures() throws DescriptorValidationException { resolveFeatures(proto.getOptions().getFeatures()); } private void crossLink() throws DescriptorValidationException { final GenericDescriptor input = getFile() .pool .lookupSymbol(proto.getInputType(), this, DescriptorPool.SearchFilter.TYPES_ONLY); if (!(input instanceof Descriptor)) { throw new DescriptorValidationException( this, '\"' + proto.getInputType() + "\" is not a message type."); } inputType = (Descriptor) input; final GenericDescriptor output = getFile() .pool .lookupSymbol(proto.getOutputType(), this, DescriptorPool.SearchFilter.TYPES_ONLY); if (!(output instanceof Descriptor)) { throw new DescriptorValidationException( this, '\"' + proto.getOutputType() + "\" is not a message type."); } outputType = (Descriptor) output; } /** See {@link FileDescriptor#setProto}. */ private void setProto(final MethodDescriptorProto proto) throws DescriptorValidationException { this.proto = proto; this.options = null; resolveFeatures(proto.getOptions().getFeatures()); } } // ================================================================= private static String computeFullName( final FileDescriptor file, final Descriptor parent, final String name) { if (parent != null) { return parent.getFullName() + '.' + name; } final String packageName = file.getPackage(); if (!packageName.isEmpty()) { return packageName + '.' + name; } return name; } // ================================================================= /** * All descriptors implement this to make it easier to implement tools like {@code * DescriptorPool}. */ public abstract static class GenericDescriptor { // Private constructor to prevent subclasses outside of com.google.protobuf.Descriptors private GenericDescriptor() {} public abstract Message toProto(); public abstract String getName(); public abstract String getFullName(); public abstract FileDescriptor getFile(); void resolveFeatures(FeatureSet unresolvedFeatures) throws DescriptorValidationException { if (this.parent != null && unresolvedFeatures.equals(FeatureSet.getDefaultInstance()) && !hasInferredLegacyProtoFeatures()) { this.features = this.parent.features; validateFeatures(); return; } FeatureSet.Builder features; if (this.parent == null) { Edition edition = getFile().getEdition(); features = getEditionDefaults(edition).toBuilder(); } else { features = this.parent.features.toBuilder(); } features.mergeFrom(inferLegacyProtoFeatures()); features.mergeFrom(unresolvedFeatures); this.features = internFeatures(features.build()); validateFeatures(); } FeatureSet inferLegacyProtoFeatures() { return FeatureSet.getDefaultInstance(); } boolean hasInferredLegacyProtoFeatures() { return false; } void validateFeatures() throws DescriptorValidationException {} FeatureSet getFeatures() { // TODO: Remove lazy resolution of unresolved features for legacy syntax for // compatibility with older <4.26.x gencode in the next breaking release. if (this.features == null && (getFile().getEdition() == Edition.EDITION_PROTO2 || getFile().getEdition() == Edition.EDITION_PROTO3)) { getFile().resolveAllFeaturesImmutable(); } return this.features; } GenericDescriptor parent; volatile FeatureSet features; } /** Thrown when building descriptors fails because the source DescriptorProtos are not valid. */ public static class DescriptorValidationException extends Exception { private static final long serialVersionUID = 5750205775490483148L; /** Gets the full name of the descriptor where the error occurred. */ public String getProblemSymbolName() { return name; } /** Gets the protocol message representation of the invalid descriptor. */ public Message getProblemProto() { return proto; } /** Gets a human-readable description of the error. */ public String getDescription() { return description; } private final String name; private final Message proto; private final String description; private DescriptorValidationException( final GenericDescriptor problemDescriptor, final String description) { super(problemDescriptor.getFullName() + ": " + description); // Note that problemDescriptor may be partially uninitialized, so we // don't want to expose it directly to the user. So, we only provide // the name and the original proto. name = problemDescriptor.getFullName(); proto = problemDescriptor.toProto(); this.description = description; } private DescriptorValidationException( final GenericDescriptor problemDescriptor, final String description, final Throwable cause) { this(problemDescriptor, description); initCause(cause); } private DescriptorValidationException( final FileDescriptor problemDescriptor, final String description) { super(problemDescriptor.getName() + ": " + description); // Note that problemDescriptor may be partially uninitialized, so we // don't want to expose it directly to the user. So, we only provide // the name and the original proto. name = problemDescriptor.getName(); proto = problemDescriptor.toProto(); this.description = description; } } // ================================================================= /** * A private helper class which contains lookup tables containing all the descriptors defined in a * particular file. */ private static final class DescriptorPool { /** Defines what subclass of descriptors to search in the descriptor pool. */ enum SearchFilter { TYPES_ONLY, AGGREGATES_ONLY, ALL_SYMBOLS } DescriptorPool(final FileDescriptor[] dependencies, boolean allowUnknownDependencies) { this.dependencies = Collections.newSetFromMap( new IdentityHashMap<FileDescriptor, Boolean>(dependencies.length)); this.allowUnknownDependencies = allowUnknownDependencies; for (Descriptors.FileDescriptor dependency : dependencies) { this.dependencies.add(dependency); importPublicDependencies(dependency); } for (final FileDescriptor dependency : this.dependencies) { try { addPackage(dependency.getPackage(), dependency); } catch (DescriptorValidationException e) { // Can't happen, because addPackage() only fails when the name // conflicts with a non-package, but we have not yet added any // non-packages at this point. throw new AssertionError(e); } } } /** Find and put public dependencies of the file into dependencies set. */ private void importPublicDependencies(final FileDescriptor file) { for (FileDescriptor dependency : file.getPublicDependencies()) { if (dependencies.add(dependency)) { importPublicDependencies(dependency); } } } private final Set<FileDescriptor> dependencies; private final boolean allowUnknownDependencies; private final Map<String, GenericDescriptor> descriptorsByName = new HashMap<>(); /** Find a generic descriptor by fully-qualified name. */ GenericDescriptor findSymbol(final String fullName) { return findSymbol(fullName, SearchFilter.ALL_SYMBOLS); } /** * Find a descriptor by fully-qualified name and given option to only search valid field type * descriptors. */ GenericDescriptor findSymbol(final String fullName, final SearchFilter filter) { GenericDescriptor result = descriptorsByName.get(fullName); if (result != null) { if ((filter == SearchFilter.ALL_SYMBOLS) || ((filter == SearchFilter.TYPES_ONLY) && isType(result)) || ((filter == SearchFilter.AGGREGATES_ONLY) && isAggregate(result))) { return result; } } for (final FileDescriptor dependency : dependencies) { result = dependency.pool.descriptorsByName.get(fullName); if (result != null) { if ((filter == SearchFilter.ALL_SYMBOLS) || ((filter == SearchFilter.TYPES_ONLY) && isType(result)) || ((filter == SearchFilter.AGGREGATES_ONLY) && isAggregate(result))) { return result; } } } return null; } /** Checks if the descriptor is a valid type for a message field. */ boolean isType(GenericDescriptor descriptor) { return (descriptor instanceof Descriptor) || (descriptor instanceof EnumDescriptor); } /** Checks if the descriptor is a valid namespace type. */ boolean isAggregate(GenericDescriptor descriptor) { return (descriptor instanceof Descriptor) || (descriptor instanceof EnumDescriptor) || (descriptor instanceof PackageDescriptor) || (descriptor instanceof ServiceDescriptor); } /** * Look up a type descriptor by name, relative to some other descriptor. The name may be * fully-qualified (with a leading '.'), partially-qualified, or unqualified. C++-like name * lookup semantics are used to search for the matching descriptor. */ GenericDescriptor lookupSymbol( final String name, final GenericDescriptor relativeTo, final DescriptorPool.SearchFilter filter) throws DescriptorValidationException { GenericDescriptor result; String fullname; if (name.startsWith(".")) { // Fully-qualified name. fullname = name.substring(1); result = findSymbol(fullname, filter); } else { // If "name" is a compound identifier, we want to search for the // first component of it, then search within it for the rest. // If name is something like "Foo.Bar.baz", and symbols named "Foo" are // defined in multiple parent scopes, we only want to find "Bar.baz" in // the innermost one. E.g., the following should produce an error: // message Bar { message Baz {} } // message Foo { // message Bar { // } // optional Bar.Baz baz = 1; // } // So, we look for just "Foo" first, then look for "Bar.baz" within it // if found. final int firstPartLength = name.indexOf('.'); final String firstPart; if (firstPartLength == -1) { firstPart = name; } else { firstPart = name.substring(0, firstPartLength); } // We will search each parent scope of "relativeTo" looking for the // symbol. final StringBuilder scopeToTry = new StringBuilder(relativeTo.getFullName()); while (true) { // Chop off the last component of the scope. final int dotpos = scopeToTry.lastIndexOf("."); if (dotpos == -1) { fullname = name; result = findSymbol(name, filter); break; } else { scopeToTry.setLength(dotpos + 1); // Append firstPart and try to find scopeToTry.append(firstPart); result = findSymbol(scopeToTry.toString(), DescriptorPool.SearchFilter.AGGREGATES_ONLY); if (result != null) { if (firstPartLength != -1) { // We only found the first part of the symbol. Now look for // the whole thing. If this fails, we *don't* want to keep // searching parent scopes. scopeToTry.setLength(dotpos + 1); scopeToTry.append(name); result = findSymbol(scopeToTry.toString(), filter); } fullname = scopeToTry.toString(); break; } // Not found. Remove the name so we can try again. scopeToTry.setLength(dotpos); } } } if (result == null) { if (allowUnknownDependencies && filter == SearchFilter.TYPES_ONLY) { logger.warning( "The descriptor for message type \"" + name + "\" cannot be found and a placeholder is created for it"); // We create a dummy message descriptor here regardless of the // expected type. If the type should be message, this dummy // descriptor will work well and if the type should be enum, a // DescriptorValidationException will be thrown later. In either // case, the code works as expected: we allow unknown message types // but not unknown enum types. result = new Descriptor(fullname); // Add the placeholder file as a dependency so we can find the // placeholder symbol when resolving other references. this.dependencies.add(result.getFile()); return result; } else { throw new DescriptorValidationException(relativeTo, '\"' + name + "\" is not defined."); } } else { return result; } } /** * Adds a symbol to the symbol table. If a symbol with the same name already exists, throws an * error. */ void addSymbol(final GenericDescriptor descriptor) throws DescriptorValidationException { validateSymbolName(descriptor); final String fullName = descriptor.getFullName(); final GenericDescriptor old = descriptorsByName.put(fullName, descriptor); if (old != null) { descriptorsByName.put(fullName, old); if (descriptor.getFile() == old.getFile()) { final int dotpos = fullName.lastIndexOf('.'); if (dotpos == -1) { throw new DescriptorValidationException( descriptor, '\"' + fullName + "\" is already defined."); } else { throw new DescriptorValidationException( descriptor, '\"' + fullName.substring(dotpos + 1) + "\" is already defined in \"" + fullName.substring(0, dotpos) + "\"."); } } else { throw new DescriptorValidationException( descriptor, '\"' + fullName + "\" is already defined in file \"" + old.getFile().getName() + "\"."); } } } /** * Represents a package in the symbol table. We use PackageDescriptors just as placeholders so * that someone cannot define, say, a message type that has the same name as an existing * package. */ private static final class PackageDescriptor extends GenericDescriptor { @Override public Message toProto() { return file.toProto(); } @Override public String getName() { return name; } @Override public String getFullName() { return fullName; } @Override public FileDescriptor getFile() { return file; } PackageDescriptor(final String name, final String fullName, final FileDescriptor file) { this.file = file; this.fullName = fullName; this.name = name; } private final String name; private final String fullName; private final FileDescriptor file; } /** * Adds a package to the symbol tables. If a package by the same name already exists, that is * fine, but if some other kind of symbol exists under the same name, an exception is thrown. If * the package has multiple components, this also adds the parent package(s). */ void addPackage(final String fullName, final FileDescriptor file) throws DescriptorValidationException { final int dotpos = fullName.lastIndexOf('.'); final String name; if (dotpos == -1) { name = fullName; } else { addPackage(fullName.substring(0, dotpos), file); name = fullName.substring(dotpos + 1); } final GenericDescriptor old = descriptorsByName.put(fullName, new PackageDescriptor(name, fullName, file)); if (old != null) { descriptorsByName.put(fullName, old); if (!(old instanceof PackageDescriptor)) { throw new DescriptorValidationException( file, '\"' + name + "\" is already defined (as something other than a " + "package) in file \"" + old.getFile().getName() + "\"."); } } } /** * Verifies that the descriptor's name is valid. That is, it contains only letters, digits, and * underscores, and does not start with a digit. */ static void validateSymbolName(final GenericDescriptor descriptor) throws DescriptorValidationException { final String name = descriptor.getName(); if (name.length() == 0) { throw new DescriptorValidationException(descriptor, "Missing name."); } // Non-ASCII characters are not valid in protobuf identifiers, even // if they are letters or digits. // The first character must be a letter or '_'. // Subsequent characters may be letters, numbers, or digits. for (int i = 0; i < name.length(); i++) { final char c = name.charAt(i); if (('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || (c == '_') || ('0' <= c && c <= '9' && i > 0)) { // Valid continue; } throw new DescriptorValidationException( descriptor, '\"' + name + "\" is not a valid identifier."); } } } /** Describes a oneof of a message type. */ public static final class OneofDescriptor extends GenericDescriptor { /** Get the index of this descriptor within its parent. */ public int getIndex() { return index; } @Override public String getName() { return proto.getName(); } @Override public FileDescriptor getFile() { return file; } @Override public String getFullName() { return fullName; } public Descriptor getContainingType() { return containingType; } public int getFieldCount() { return fieldCount; } public OneofOptions getOptions() { if (this.options == null) { OneofOptions strippedOptions = this.proto.getOptions(); if (strippedOptions.hasFeatures()) { // Clients should be using feature accessor methods, not accessing features on the // options // proto. strippedOptions = strippedOptions.toBuilder().clearFeatures().build(); } synchronized (this) { if (this.options == null) { this.options = strippedOptions; } } } return this.options; } /** Get a list of this message type's fields. */ public List<FieldDescriptor> getFields() { return Collections.unmodifiableList(Arrays.asList(fields)); } public FieldDescriptor getField(int index) { return fields[index]; } @Override public OneofDescriptorProto toProto() { return proto; } boolean isSynthetic() { return fields.length == 1 && fields[0].isProto3Optional; } /** See {@link FileDescriptor#resolveAllFeatures}. */ private void resolveAllFeatures() throws DescriptorValidationException { resolveFeatures(proto.getOptions().getFeatures()); } private void setProto(final OneofDescriptorProto proto) throws DescriptorValidationException { this.proto = proto; this.options = null; resolveFeatures(proto.getOptions().getFeatures()); } private OneofDescriptor( final OneofDescriptorProto proto, final FileDescriptor file, final Descriptor parent, final int index) { this.parent = parent; this.proto = proto; fullName = computeFullName(file, parent, proto.getName()); this.file = file; this.index = index; containingType = parent; fieldCount = 0; } private final int index; private OneofDescriptorProto proto; private volatile OneofOptions options; private final String fullName; private final FileDescriptor file; private Descriptor containingType; private int fieldCount; private FieldDescriptor[] fields; } private static <T> T binarySearch(T[] array, int size, NumberGetter<T> getter, int number) { int left = 0; int right = size - 1; while (left <= right) { int mid = (left + right) / 2; T midValue = array[mid]; int midValueNumber = getter.getNumber(midValue); if (number < midValueNumber) { right = mid - 1; } else if (number > midValueNumber) { left = mid + 1; } else { return midValue; } } return null; } private interface NumberGetter<T> { int getNumber(T t); } }
protocolbuffers/protobuf
java/core/src/main/java/com/google/protobuf/Descriptors.java
100
package mindustry.core; import arc.*; import arc.Graphics.*; import arc.Input.*; import arc.assets.*; import arc.func.*; import arc.graphics.*; import arc.graphics.g2d.*; import arc.input.*; import arc.math.*; import arc.math.geom.*; import arc.scene.*; import arc.scene.actions.*; import arc.scene.event.*; import arc.scene.style.*; import arc.scene.ui.*; import arc.scene.ui.TextField.*; import arc.scene.ui.Tooltip.*; import arc.scene.ui.layout.*; import arc.struct.*; import arc.util.*; import mindustry.editor.*; import mindustry.game.EventType.*; import mindustry.gen.*; import mindustry.graphics.*; import mindustry.logic.*; import mindustry.ui.*; import mindustry.ui.dialogs.*; import mindustry.ui.fragments.*; import static arc.scene.actions.Actions.*; import static mindustry.Vars.*; public class UI implements ApplicationListener, Loadable{ public static String billions, millions, thousands; public static PixmapPacker packer; public MenuFragment menufrag; public HudFragment hudfrag; public ChatFragment chatfrag; public ConsoleFragment consolefrag; public MinimapFragment minimapfrag; public PlayerListFragment listfrag; public LoadingFragment loadfrag; public HintsFragment hints; public WidgetGroup menuGroup, hudGroup; public AboutDialog about; public GameOverDialog restart; public CustomGameDialog custom; public EditorMapsDialog maps; public LoadDialog load; public DiscordDialog discord; public JoinDialog join; public HostDialog host; public PausedDialog paused; public SettingsMenuDialog settings; public KeybindDialog controls; public MapEditorDialog editor; public LanguageDialog language; public BansDialog bans; public AdminsDialog admins; public TraceDialog traces; public DatabaseDialog database; public ContentInfoDialog content; public PlanetDialog planet; public ResearchDialog research; public SchematicsDialog schematics; public ModsDialog mods; public ColorPicker picker; public EffectsDialog effects; public LogicDialog logic; public FullTextDialog fullText; public CampaignCompleteDialog campaignComplete; public IntMap<Dialog> followUpMenus; public Cursor drillCursor, unloadCursor, targetCursor, repairCursor; private @Nullable Element lastAnnouncement; public UI(){ Fonts.loadFonts(); } public static void loadColors(){ Colors.put("accent", Pal.accent); Colors.put("unlaunched", Color.valueOf("8982ed")); Colors.put("highlight", Pal.accent.cpy().lerp(Color.white, 0.3f)); Colors.put("stat", Pal.stat); Colors.put("negstat", Pal.negativeStat); } @Override public void loadAsync(){ } @Override public void loadSync(){ Fonts.outline.getData().markupEnabled = true; Fonts.def.getData().markupEnabled = true; Fonts.def.setOwnsTexture(false); Core.assets.getAll(Font.class, new Seq<>()).each(font -> font.setUseIntegerPositions(true)); Core.scene = new Scene(); Core.input.addProcessor(Core.scene); int[] insets = Core.graphics.getSafeInsets(); Core.scene.marginLeft = insets[0]; Core.scene.marginRight = insets[1]; Core.scene.marginTop = insets[2]; Core.scene.marginBottom = insets[3]; Tex.load(); Icon.load(); Styles.load(); Tex.loadStyles(); Fonts.loadContentIcons(); Dialog.setShowAction(() -> sequence(alpha(0f), fadeIn(0.1f))); Dialog.setHideAction(() -> sequence(fadeOut(0.1f))); Tooltips.getInstance().animations = false; Tooltips.getInstance().textProvider = text -> new Tooltip(t -> t.background(Styles.black6).margin(4f).add(text)); if(mobile){ Tooltips.getInstance().offsetY += Scl.scl(60f); } Core.settings.setErrorHandler(e -> { Log.err(e); Core.app.post(() -> showErrorMessage("Failed to access local storage.\nSettings will not be saved.")); }); ClickListener.clicked = () -> Sounds.press.play(); drillCursor = Core.graphics.newCursor("drill", Fonts.cursorScale()); unloadCursor = Core.graphics.newCursor("unload", Fonts.cursorScale()); targetCursor = Core.graphics.newCursor("target", Fonts.cursorScale()); repairCursor = Core.graphics.newCursor("repair", Fonts.cursorScale()); } @Override public Seq<AssetDescriptor> getDependencies(){ return Seq.with(new AssetDescriptor<>(Control.class), new AssetDescriptor<>("outline", Font.class), new AssetDescriptor<>("default", Font.class)); } @Override public void update(){ if(disableUI || Core.scene == null) return; Events.fire(Trigger.uiDrawBegin); Core.scene.act(); Core.scene.draw(); if(Core.input.keyTap(KeyCode.mouseLeft) && Core.scene.hasField()){ Element e = Core.scene.hit(Core.input.mouseX(), Core.input.mouseY(), true); if(!(e instanceof TextField)){ Core.scene.setKeyboardFocus(null); } } Events.fire(Trigger.uiDrawEnd); } @Override public void init(){ billions = Core.bundle.get("unit.billions"); millions = Core.bundle.get("unit.millions"); thousands = Core.bundle.get("unit.thousands"); menuGroup = new WidgetGroup(); hudGroup = new WidgetGroup(); menufrag = new MenuFragment(); hudfrag = new HudFragment(); hints = new HintsFragment(); chatfrag = new ChatFragment(); minimapfrag = new MinimapFragment(); listfrag = new PlayerListFragment(); loadfrag = new LoadingFragment(); consolefrag = new ConsoleFragment(); picker = new ColorPicker(); effects = new EffectsDialog(); editor = new MapEditorDialog(); controls = new KeybindDialog(); restart = new GameOverDialog(); join = new JoinDialog(); discord = new DiscordDialog(); load = new LoadDialog(); custom = new CustomGameDialog(); language = new LanguageDialog(); database = new DatabaseDialog(); settings = new SettingsMenuDialog(); host = new HostDialog(); paused = new PausedDialog(); about = new AboutDialog(); bans = new BansDialog(); admins = new AdminsDialog(); traces = new TraceDialog(); maps = new EditorMapsDialog(); content = new ContentInfoDialog(); planet = new PlanetDialog(); research = new ResearchDialog(); mods = new ModsDialog(); schematics = new SchematicsDialog(); logic = new LogicDialog(); fullText = new FullTextDialog(); campaignComplete = new CampaignCompleteDialog(); followUpMenus = new IntMap<>(); Group group = Core.scene.root; menuGroup.setFillParent(true); menuGroup.touchable = Touchable.childrenOnly; menuGroup.visible(() -> state.isMenu()); hudGroup.setFillParent(true); hudGroup.touchable = Touchable.childrenOnly; hudGroup.visible(() -> state.isGame()); Core.scene.add(menuGroup); Core.scene.add(hudGroup); hudfrag.build(hudGroup); menufrag.build(menuGroup); chatfrag.build(hudGroup); minimapfrag.build(hudGroup); listfrag.build(hudGroup); consolefrag.build(hudGroup); loadfrag.build(group); new FadeInFragment().build(group); } @Override public void resize(int width, int height){ if(Core.scene == null) return; int[] insets = Core.graphics.getSafeInsets(); Core.scene.marginLeft = insets[0]; Core.scene.marginRight = insets[1]; Core.scene.marginTop = insets[2]; Core.scene.marginBottom = insets[3]; Core.scene.resize(width, height); Events.fire(new ResizeEvent()); } public TextureRegionDrawable getIcon(String name){ if(Icon.icons.containsKey(name)) return Icon.icons.get(name); return Core.atlas.getDrawable("error"); } public TextureRegionDrawable getIcon(String name, String def){ if(Icon.icons.containsKey(name)) return Icon.icons.get(name); return getIcon(def); } public void loadAnd(Runnable call){ loadAnd("@loading", call); } public void loadAnd(String text, Runnable call){ loadfrag.show(text); Time.runTask(7f, () -> { call.run(); loadfrag.hide(); }); } public void showTextInput(String titleText, String text, int textLength, String def, boolean numbers, Cons<String> confirmed, Runnable closed) { showTextInput(titleText, text, textLength, def, numbers, false, confirmed, closed); } public void showTextInput(String titleText, String text, int textLength, String def, boolean numbers, boolean allowEmpty, Cons<String> confirmed, Runnable closed){ if(mobile){ var description = (text.startsWith("@") ? Core.bundle.get(text.substring(1)) : text); var empty = allowEmpty; Core.input.getTextInput(new TextInput(){{ this.title = (titleText.startsWith("@") ? Core.bundle.get(titleText.substring(1)) : titleText); this.text = def; this.numeric = numbers; this.maxLength = textLength; this.accepted = confirmed; this.canceled = closed; this.allowEmpty = empty; this.message = description; }}); }else{ new Dialog(titleText){{ cont.margin(30).add(text).padRight(6f); TextFieldFilter filter = numbers ? TextFieldFilter.digitsOnly : (f, c) -> true; TextField field = cont.field(def, t -> {}).size(330f, 50f).get(); field.setMaxLength(textLength); field.setFilter(filter); buttons.defaults().size(120, 54).pad(4); buttons.button("@cancel", () -> { closed.run(); hide(); }); buttons.button("@ok", () -> { confirmed.get(field.getText()); hide(); }).disabled(b -> !allowEmpty && field.getText().isEmpty()); keyDown(KeyCode.enter, () -> { String text = field.getText(); if(allowEmpty || !text.isEmpty()){ confirmed.get(text); hide(); } }); closeOnBack(closed); show(); Core.scene.setKeyboardFocus(field); field.setCursorPosition(def.length()); }}; } } public void showTextInput(String title, String text, String def, Cons<String> confirmed){ showTextInput(title, text, 32, def, confirmed); } public void showTextInput(String title, String text, int textLength, String def, Cons<String> confirmed){ showTextInput(title, text, textLength, def, false, confirmed); } public void showTextInput(String title, String text, int textLength, String def, boolean numeric, Cons<String> confirmed){ showTextInput(title, text, textLength, def, numeric, confirmed, () -> {}); } public void showInfoFade(String info){ showInfoFade(info, 7f); } public void showInfoFade(String info, float duration){ var cinfo = Core.scene.find("coreinfo"); Table table = new Table(); table.touchable = Touchable.disabled; table.setFillParent(true); if(cinfo.visible && !state.isMenu()) table.marginTop(cinfo.getPrefHeight() / Scl.scl() / 2); table.actions(Actions.fadeOut(duration, Interp.fade), Actions.remove()); table.top().add(info).style(Styles.outlineLabel).padTop(10); Core.scene.add(table); } public void addDescTooltip(Element elem, String description){ if(description == null) return; elem.addListener(new Tooltip(t -> t.background(Styles.black8).margin(4f).add(description).color(Color.lightGray)){ { allowMobile = true; } @Override protected void setContainerPosition(Element element, float x, float y){ this.targetActor = element; Vec2 pos = element.localToStageCoordinates(Tmp.v1.set(0, 0)); container.pack(); container.setPosition(pos.x, pos.y, Align.topLeft); container.setOrigin(0, element.getHeight()); } }); } /** Shows a fading label at the top of the screen. */ public void showInfoToast(String info, float duration){ var cinfo = Core.scene.find("coreinfo"); Table table = new Table(); table.touchable = Touchable.disabled; table.setFillParent(true); if(cinfo.visible && !state.isMenu()) table.marginTop(cinfo.getPrefHeight() / Scl.scl() / 2); table.update(() -> { if(state.isMenu()) table.remove(); }); table.actions(Actions.delay(duration * 0.9f), Actions.fadeOut(duration * 0.1f, Interp.fade), Actions.remove()); table.top().table(Styles.black3, t -> t.margin(4).add(info).style(Styles.outlineLabel)).padTop(10); Core.scene.add(table); lastAnnouncement = table; } /** Shows a label at some position on the screen. Does not fade. */ public void showInfoPopup(String info, float duration, int align, int top, int left, int bottom, int right){ Table table = new Table(); table.setFillParent(true); table.touchable = Touchable.disabled; table.update(() -> { if(state.isMenu()) table.remove(); }); table.actions(Actions.delay(duration), Actions.remove()); table.align(align).table(Styles.black3, t -> t.margin(4).add(info).style(Styles.outlineLabel)).pad(top, left, bottom, right); Core.scene.add(table); } /** Shows a label in the world. This label is behind everything. Does not fade. */ public void showLabel(String info, float duration, float worldx, float worldy){ var table = new Table(Styles.black3).margin(4); table.touchable = Touchable.disabled; table.update(() -> { if(state.isMenu()) table.remove(); Vec2 v = Core.camera.project(worldx, worldy); table.setPosition(v.x, v.y, Align.center); }); table.actions(Actions.delay(duration), Actions.remove()); table.add(info).style(Styles.outlineLabel); table.pack(); table.act(0f); //make sure it's at the back Core.scene.root.addChildAt(0, table); table.getChildren().first().act(0f); } public void showInfo(String info){ new Dialog(""){{ getCell(cont).growX(); cont.margin(15).add(info).width(400f).wrap().get().setAlignment(Align.center, Align.center); buttons.button("@ok", this::hide).size(110, 50).pad(4); keyDown(KeyCode.enter, this::hide); closeOnBack(); }}.show(); } public void showInfoOnHidden(String info, Runnable listener){ new Dialog(""){{ getCell(cont).growX(); cont.margin(15).add(info).width(400f).wrap().get().setAlignment(Align.center, Align.center); buttons.button("@ok", this::hide).size(110, 50).pad(4); hidden(listener); closeOnBack(); }}.show(); } public void showStartupInfo(String info){ new Dialog(""){{ getCell(cont).growX(); cont.margin(15).add(info).width(400f).wrap().get().setAlignment(Align.left); buttons.button("@ok", this::hide).size(110, 50).pad(4); closeOnBack(); }}.show(); } public void showErrorMessage(String text){ new Dialog(""){{ setFillParent(true); cont.margin(15f); cont.add("@error.title"); cont.row(); cont.image().width(300f).pad(2).height(4f).color(Color.scarlet); cont.row(); cont.add(text).pad(2f).growX().wrap().get().setAlignment(Align.center); cont.row(); cont.button("@ok", this::hide).size(120, 50).pad(4); closeOnBack(); }}.show(); } public void showException(Throwable t){ showException("", t); } public void showException(String text, Throwable exc){ if(loadfrag == null) return; loadfrag.hide(); new Dialog(""){{ String message = Strings.getFinalMessage(exc); setFillParent(true); cont.margin(15); cont.add("@error.title").colspan(2); cont.row(); cont.image().width(300f).pad(2).colspan(2).height(4f).color(Color.scarlet); cont.row(); cont.add((text.startsWith("@") ? Core.bundle.get(text.substring(1)) : text) + (message == null ? "" : "\n[lightgray](" + message + ")")).colspan(2).wrap().growX().center().get().setAlignment(Align.center); cont.row(); Collapser col = new Collapser(base -> base.pane(t -> t.margin(14f).add(Strings.neatError(exc)).color(Color.lightGray).left()), true); cont.button("@details", Styles.togglet, col::toggle).size(180f, 50f).checked(b -> !col.isCollapsed()).fillX().right(); cont.button("@ok", this::hide).size(110, 50).fillX().left(); cont.row(); cont.add(col).colspan(2).pad(2); closeOnBack(); }}.show(); } public void showText(String titleText, String text){ showText(titleText, text, Align.center); } public void showText(String titleText, String text, int align){ new Dialog(titleText){{ cont.row(); cont.image().width(400f).pad(2).colspan(2).height(4f).color(Pal.accent); cont.row(); cont.add(text).width(400f).wrap().get().setAlignment(align, align); cont.row(); buttons.button("@ok", this::hide).size(110, 50).pad(4); closeOnBack(); }}.show(); } public void showInfoText(String titleText, String text){ new Dialog(titleText){{ cont.margin(15).add(text).width(400f).wrap().left().get().setAlignment(Align.left, Align.left); buttons.button("@ok", this::hide).size(110, 50).pad(4); closeOnBack(); }}.show(); } public void showSmall(String titleText, String text){ new Dialog(titleText){{ cont.margin(10).add(text); titleTable.row(); titleTable.image().color(Pal.accent).height(3f).growX().pad(2f); buttons.button("@ok", this::hide).size(110, 50).pad(4); closeOnBack(); }}.show(); } public void showConfirm(String text, Runnable confirmed){ showConfirm("@confirm", text, null, confirmed); } public void showConfirm(String title, String text, Runnable confirmed){ showConfirm(title, text, null, confirmed); } public void showConfirm(String title, String text, Boolp hide, Runnable confirmed){ BaseDialog dialog = new BaseDialog(title); dialog.cont.add(text).width(mobile ? 400f : 500f).wrap().pad(4f).get().setAlignment(Align.center, Align.center); dialog.buttons.defaults().size(200f, 54f).pad(2f); dialog.setFillParent(false); dialog.buttons.button("@cancel", Icon.cancel, dialog::hide); dialog.buttons.button("@ok", Icon.ok, () -> { dialog.hide(); confirmed.run(); }); if(hide != null){ dialog.update(() -> { if(hide.get()){ dialog.hide(); } }); } dialog.keyDown(KeyCode.enter, () -> { dialog.hide(); confirmed.run(); }); dialog.keyDown(KeyCode.escape, dialog::hide); dialog.keyDown(KeyCode.back, dialog::hide); dialog.show(); } public void showCustomConfirm(String title, String text, String yes, String no, Runnable confirmed, Runnable denied){ BaseDialog dialog = new BaseDialog(title); dialog.cont.add(text).width(mobile ? 400f : 500f).wrap().pad(4f).get().setAlignment(Align.center, Align.center); dialog.buttons.defaults().size(200f, 54f).pad(2f); dialog.setFillParent(false); dialog.buttons.button(no, () -> { dialog.hide(); denied.run(); }); dialog.buttons.button(yes, () -> { dialog.hide(); confirmed.run(); }); dialog.keyDown(KeyCode.escape, dialog::hide); dialog.keyDown(KeyCode.back, dialog::hide); dialog.show(); } public boolean hasAnnouncement(){ return lastAnnouncement != null && lastAnnouncement.parent != null; } /** Display text in the middle of the screen, then fade out. */ public void announce(String text){ announce(text, 3); } /** Display text in the middle of the screen, then fade out. */ public void announce(String text, float duration){ Table t = new Table(Styles.black3); t.touchable = Touchable.disabled; t.margin(8f).add(text).style(Styles.outlineLabel).labelAlign(Align.center); t.update(() -> t.setPosition(Core.graphics.getWidth()/2f, Core.graphics.getHeight()/2f, Align.center)); t.actions(Actions.fadeOut(duration, Interp.pow4In), Actions.remove()); t.pack(); t.act(0.1f); Core.scene.add(t); lastAnnouncement = t; } public void showOkText(String title, String text, Runnable confirmed){ BaseDialog dialog = new BaseDialog(title); dialog.cont.add(text).width(500f).wrap().pad(4f).get().setAlignment(Align.center, Align.center); dialog.buttons.defaults().size(200f, 54f).pad(2f); dialog.setFillParent(false); dialog.buttons.button("@ok", () -> { dialog.hide(); confirmed.run(); }); dialog.show(); } // TODO REPLACE INTEGER WITH arc.fun.IntCons(int, T) or something like that. public Dialog newMenuDialog(String title, String message, String[][] options, Cons2<Integer, Dialog> buttonListener){ return new Dialog(title){{ setFillParent(true); removeChild(titleTable); cont.add(titleTable).width(400f); cont.row(); cont.image().width(400f).pad(2).colspan(2).height(4f).color(Pal.accent).bottom(); cont.row(); cont.pane(table -> { table.add(message).width(400f).wrap().get().setAlignment(Align.center); table.row(); int option = 0; for(var optionsRow : options){ Table buttonRow = table.row().table().get().row(); int fullWidth = 400 - (optionsRow.length - 1) * 8; // adjust to count padding as well int width = fullWidth / optionsRow.length; int lastWidth = fullWidth - width * (optionsRow.length - 1); // take the rest of space for uneven table for(int i = 0; i < optionsRow.length; i++){ if(optionsRow[i] == null) continue; String optionName = optionsRow[i]; int finalOption = option; buttonRow.button(optionName, () -> buttonListener.get(finalOption, this)) .size(i == optionsRow.length - 1 ? lastWidth : width, 50).pad(4); option++; } } }).growX(); }}; } /** Shows a menu that fires a callback when an option is selected. If nothing is selected, -1 is returned. */ public void showMenu(String title, String message, String[][] options, Intc callback){ Dialog dialog = newMenuDialog(title, message, options, (option, myself) -> { callback.get(option); myself.hide(); }); dialog.closeOnBack(() -> callback.get(-1)); dialog.show(); } /** Shows a menu that hides when another followUp-menu is shown or when nothing is selected. * @see UI#showMenu(String, String, String[][], Intc) */ public void showFollowUpMenu(int menuId, String title, String message, String[][] options, Intc callback) { Dialog dialog = newMenuDialog(title, message, options, (option, myself) -> callback.get(option)); dialog.closeOnBack(() -> { followUpMenus.remove(menuId); callback.get(-1); }); Dialog oldDialog = followUpMenus.remove(menuId); if(oldDialog != null){ dialog.show(Core.scene, null); oldDialog.hide(null); }else{ dialog.show(); } followUpMenus.put(menuId, dialog); } public void hideFollowUpMenu(int menuId) { if(!followUpMenus.containsKey(menuId)) return; followUpMenus.remove(menuId).hide(); } /** Formats time with hours:minutes:seconds. */ public static String formatTime(float ticks){ int seconds = (int)(ticks / 60); if(seconds < 60) return "0:" + (seconds < 10 ? "0" : "") + seconds; int minutes = seconds / 60; int modSec = seconds % 60; if(minutes < 60) return minutes + ":" + (modSec < 10 ? "0" : "") + modSec; int hours = minutes / 60; int modMinute = minutes % 60; return hours + ":" + (modMinute < 10 ? "0" : "") + modMinute + ":" + (modSec < 10 ? "0" : "") + modSec; } public static String formatAmount(long number){ //prevent things like bars displaying erroneous representations of casted infinities if(number == Long.MAX_VALUE) return "∞"; if(number == Long.MIN_VALUE) return "-∞"; long mag = Math.abs(number); String sign = number < 0 ? "-" : ""; if(mag >= 1_000_000_000){ return sign + Strings.fixed(mag / 1_000_000_000f, 1) + "[gray]" + billions + "[]"; }else if(mag >= 1_000_000){ return sign + Strings.fixed(mag / 1_000_000f, 1) + "[gray]" + millions + "[]"; }else if(mag >= 10_000){ return number / 1000 + "[gray]" + thousands + "[]"; }else if(mag >= 1000){ return sign + Strings.fixed(mag / 1000f, 1) + "[gray]" + thousands + "[]"; }else{ return number + ""; } } public static int roundAmount(int number){ if(number >= 1_000_000_000){ return Mathf.round(number, 100_000_000); }else if(number >= 1_000_000){ return Mathf.round(number, 100_000); }else if(number >= 10_000){ return Mathf.round(number, 1000); }else if(number >= 1000){ return Mathf.round(number, 100); }else if(number >= 100){ return Mathf.round(number, 100); }else if(number >= 10){ return Mathf.round(number, 10); }else{ return number; } } }
Anuken/Mindustry
core/src/mindustry/core/UI.java