下面列出了java.util.Locale#ROOT 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static URI createDeltaLink(final String rawRequestUri, String deltaToken)
throws ODataApplicationException {
// Remove a maybe existing skiptoken, making sure that the query part is not empty.
String deltalink = rawRequestUri.contains("?") ?
rawRequestUri.replaceAll("(\\$|%24)deltatoken=.+&?", "").replaceAll("(\\?|&)$", "") :
rawRequestUri;
// Add a question mark or an ampersand, depending on the current query part.
deltalink += deltalink.contains("?") ? '&' : '?';
deltaToken = deltaToken.substring(0, 4);
// Append the new skiptoken.
deltalink += SystemQueryOptionKind.DELTATOKEN.toString().replace("$", "%24") // poor man's percent encoding
+ '='
+ "%2A" +deltaToken ; // "%2A" is a percent-encoded asterisk
try {
return new URI(deltalink);
} catch (final URISyntaxException e) {
throw new ODataApplicationException("Exception while constructing delta link",
HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), Locale.ROOT, e);
}
}
@Override
public TypedOperand asTypedOperand(final EdmPrimitiveType... types) throws ODataApplicationException {
final String literal = (String) value;
Object newValue;
// First try the null literal
if ((newValue = tryCast(literal, ODataConstants.primitiveNull)) != null) {
return new TypedOperand(newValue, ODataConstants.primitiveNull);
}
// Than try the given types
for (EdmPrimitiveType type : types) {
newValue = tryCast(literal, type);
if (newValue != null) {
return new TypedOperand(newValue, type);
}
}
throw new ODataApplicationException("Cast failed", HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(),
Locale.ROOT);
}
@Override
public TypedOperand asTypedOperand(final EdmPrimitiveType type) throws ODataApplicationException {
final String literal = (String) value;
Object newValue = null;
// First try the null literal.
if ((newValue = tryCast(literal, primNull)) != null) {
return new TypedOperand(newValue, primNull);
}
// Then try the given type.
if ((newValue = tryCast(literal, type)) != null) {
return new TypedOperand(newValue, type);
}
throw new ODataApplicationException("Cast failed", HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(),
Locale.ROOT);
}
@SuppressWarnings( "unchecked")
@Override
public TypedOperand asTypedOperandForCollection(EdmPrimitiveType type) throws ODataApplicationException {
List<Object> newValue = new ArrayList<Object>();
List<Object> list = (List<Object>) value;
for (Object val : list) {
final String literal = (String) val;
// First try the null literal.
if (null != tryCast(literal, primNull)) {
newValue.add(tryCast(literal, primNull));
type = primNull;
}
// Then try the given type.
if (null != tryCast(literal, type)) {
newValue.add(tryCast(literal, type));
}
}
if (!newValue.isEmpty()) {
return new TypedOperand(newValue, type);
}
throw new ODataApplicationException("Cast failed", HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(),
Locale.ROOT);
}
private static String array(String name, Collection<List<Integer>> codePoints) {
try (Formatter fmt = new Formatter(new StringBuilder(), Locale.ROOT)) {
fmt.format("static final int[][] %s = {%n/* @formatter:off */%n", name);
boolean isNewLine = true;
int index = 0;
for (List<Integer> codePoint : codePoints) {
if (isNewLine) {
isNewLine = false;
}
fmt.format("{");
String prefix = "";
for (int cp : codePoint) {
fmt.format("%s0x%x", prefix, cp);
prefix = ", ";
}
fmt.format("},");
if (++index % 6 == 0) {
isNewLine = true;
fmt.format("%n");
} else {
fmt.format(" ");
}
}
if (!isNewLine) {
fmt.format("%n");
}
fmt.format("/* @formatter:on */%n};%n");
return fmt.toString();
}
}
private void readFunctionImportInternal(final ODataRequest request, final ODataResponse response,
final UriInfo uriInfo, final ContentType responseFormat) throws ODataApplicationException, SerializerException {
// 1st step: Analyze the URI and fetch the entity returned by the function import
// Function Imports are always the first segment of the resource path
final UriResource firstSegment = uriInfo.getUriResourceParts().get(0);
if (!(firstSegment instanceof UriResourceFunction)) {
throw new ODataApplicationException("Not implemented", HttpStatusCode.NOT_IMPLEMENTED.getStatusCode(),
Locale.ENGLISH);
}
final UriResourceFunction uriResourceFunction = (UriResourceFunction) firstSegment;
final Entity entity = storage.readFunctionImportEntity(uriResourceFunction, serviceMetadata);
if (entity == null) {
throw new ODataApplicationException("Nothing found.", HttpStatusCode.NOT_FOUND.getStatusCode(), Locale.ROOT);
}
// 2nd step: Serialize the response entity
final EdmEntityType edmEntityType = (EdmEntityType) uriResourceFunction.getFunction().getReturnType().getType();
final ContextURL contextURL = ContextURL.with().type(edmEntityType).build();
final EntitySerializerOptions opts = EntitySerializerOptions.with().contextURL(contextURL).build();
final ODataSerializer serializer = odata.createSerializer(responseFormat);
final SerializerResult serializerResult = serializer.entity(serviceMetadata, edmEntityType, entity, opts);
// 3rd configure the response object
response.setContent(serializerResult.getContent());
response.setStatusCode(HttpStatusCode.OK.getStatusCode());
response.setHeader(HttpHeader.CONTENT_TYPE, responseFormat.toContentTypeString());
}
@Nonnull
public static Locale getDisplayLocaleOfSubtypeLocale(@Nonnull final String localeString) {
if (NO_LANGUAGE.equals(localeString)) {
return sResources.getConfiguration().locale;
}
if (sExceptionalLocaleDisplayedInRootLocale.containsKey(localeString)) {
return Locale.ROOT;
}
return LocaleUtils.constructLocaleFromString(localeString);
}
public VisitorOperand ceiling() throws ODataApplicationException {
final TypedOperand operand = parameters.get(0).asTypedOperand();
if (operand.isNull()) {
return operand;
} else if (operand.isDecimalType()) {
return new TypedOperand(operand.getTypedValue(BigDecimal.class).round(new MathContext(1, RoundingMode.CEILING)),
operand.getType());
} else {
throw new ODataApplicationException("Invalid type", HttpStatusCode.BAD_REQUEST.getStatusCode(), Locale.ROOT);
}
}
public EntityCollection readFunctionImportCollection(final UriResourceFunction uriResourceFunction,
final ServiceMetadata serviceMetadata) throws ODataApplicationException {
if (DemoEdmProvider.FUNCTION_COUNT_CATEGORIES.equals(uriResourceFunction.getFunctionImport().getName())) {
// Get the parameter of the function
final UriParameter parameterAmount = uriResourceFunction.getParameters().get(0);
// Try to convert the parameter to an Integer.
// We have to take care, that the type of parameter fits to its EDM declaration
int amount;
try {
amount = Integer.parseInt(parameterAmount.getText());
} catch (NumberFormatException e) {
throw new ODataApplicationException("Type of parameter Amount must be Edm.Int32", HttpStatusCode.BAD_REQUEST
.getStatusCode(), Locale.ENGLISH);
}
final List<Entity> resultEntityList = new ArrayList<Entity>();
// Loop over all categories and check how many products are linked
for (final Entity category : manager.getEntityCollection(DemoEdmProvider.ES_CATEGORIES_NAME)) {
final EntityCollection products = getRelatedEntityCollection(category, DemoEdmProvider.NAV_TO_PRODUCTS);
if (products.getEntities().size() == amount) {
resultEntityList.add(category);
}
}
final EntityCollection resultCollection = new EntityCollection();
resultCollection.getEntities().addAll(resultEntityList);
return resultCollection;
} else {
throw new ODataApplicationException("Function not implemented", HttpStatusCode.NOT_IMPLEMENTED.getStatusCode(),
Locale.ROOT);
}
}
@Override
public void setLocale(Locale locale) {
if (locale == null || locale.getLanguage().equals(Locale.ENGLISH.getLanguage())) {
this.currentLocale = Locale.ROOT;
} else {
this.currentLocale = locale;
}
}
private void validatePath(final UriInfoResource uriInfo) throws ODataApplicationException {
final List<UriResource> resourcePaths = uriInfo.getUriResourceParts();
for (final UriResource segment : resourcePaths.subList(1, resourcePaths.size())) {
final UriResourceKind kind = segment.getKind();
if (kind != UriResourceKind.navigationProperty
&& kind != UriResourceKind.primitiveProperty
&& kind != UriResourceKind.complexProperty
&& kind != UriResourceKind.count
&& kind != UriResourceKind.value
&& kind != UriResourceKind.function) {
throw new ODataApplicationException("Invalid resource type.",
HttpStatusCode.NOT_IMPLEMENTED.getStatusCode(), Locale.ROOT);
}
}
}
@Override
public void processActionComplex(final ODataRequest request, ODataResponse response, final UriInfo uriInfo,
final ContentType requestFormat, final ContentType responseFormat)
throws ODataApplicationException, ODataLibraryException {
EdmAction action = null;
Map<String, Parameter> parameters = null;
Property property = null;
final List<UriResource> resourcePaths = uriInfo.asUriInfoResource().getUriResourceParts();
if (resourcePaths.size() > 1) {
if (resourcePaths.get(0) instanceof UriResourceEntitySet) {
UriResourceEntitySet uriResourceEntitySet = (UriResourceEntitySet) resourcePaths.get(0);
EdmEntitySet entitySet = uriResourceEntitySet.getEntitySet();
action = ((UriResourceAction) resourcePaths.get(resourcePaths.size() - 1))
.getAction();
parameters = readParameters(action, request.getBody(), requestFormat);
property =
dataProvider.processBoundActionComplex(action.getName(), parameters, entitySet,
uriResourceEntitySet.getKeyPredicates());
}
} else {
action = ((UriResourceAction) resourcePaths.get(0))
.getAction();
parameters = readParameters(action, request.getBody(), requestFormat);
property = dataProvider.processActionComplex(action.getName(), parameters);
}
EdmComplexType type = (EdmComplexType) action.getReturnType().getType();
if (property == null || property.isNull()) {
if (action.getReturnType().isNullable()) {
response.setStatusCode(HttpStatusCode.NO_CONTENT.getStatusCode());
} else {
// Not nullable return type so we have to give back an Internal Server Error
throw new ODataApplicationException("The action could not be executed.",
HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), Locale.ROOT);
}
} else {
final Return returnPreference = odata.createPreferences(request.getHeaders(HttpHeader.PREFER)).getReturn();
if (returnPreference == null || returnPreference == Return.REPRESENTATION) {
final ContextURL contextURL = ContextURL.with().type(type).build();
final ComplexSerializerOptions options = ComplexSerializerOptions.with().contextURL(contextURL).build();
final SerializerResult result =
odata.createSerializer(responseFormat).complex(serviceMetadata, type, property, options);
response.setContent(result.getContent());
response.setHeader(HttpHeader.CONTENT_TYPE, responseFormat.toContentTypeString());
response.setStatusCode(HttpStatusCode.OK.getStatusCode());
} else {
response.setStatusCode(HttpStatusCode.NO_CONTENT.getStatusCode());
}
if (returnPreference != null) {
response.setHeader(HttpHeader.PREFERENCE_APPLIED,
PreferencesApplied.with().returnRepresentation(returnPreference).build().toValueString());
}
}
}
private VisitorOperand throwNotImplemented() throws ODataApplicationException {
throw new ODataApplicationException("Not implemented", HttpStatusCode.NOT_IMPLEMENTED.getStatusCode(),
Locale.ROOT);
}
public void createEntity(ODataRequest request, ODataResponse response, UriInfo uriInfo,
ContentType requestFormat, ContentType responseFormat)
throws ODataApplicationException, DeserializerException, SerializerException {
throw new ODataApplicationException("Not supported.", HttpStatusCode.NOT_IMPLEMENTED.getStatusCode(), Locale.ROOT);
}
/**
* Reads the default serializable fields, provides default values for objects
* in older serial versions, and initializes non-serializable fields.
* If {@code serialVersionOnStream}
* is less than 1, initializes {@code monetarySeparator} to be
* the same as {@code decimalSeparator} and {@code exponential}
* to be 'E'.
* If {@code serialVersionOnStream} is less than 2,
* initializes {@code locale}to the root locale, and initializes
* If {@code serialVersionOnStream} is less than 3, it initializes
* {@code exponentialSeparator} using {@code exponential}.
* If {@code serialVersionOnStream} is less than 4, it initializes
* {@code perMillText}, {@code percentText}, and
* {@code minusSignText} using {@code perMill}, {@code percent}, and
* {@code minusSign} respectively.
* Sets {@code serialVersionOnStream} back to the maximum allowed value so that
* default serialization will work properly if this object is streamed out again.
* Initializes the currency from the intlCurrencySymbol field.
*
* @throws InvalidObjectException if {@code char} and {@code String}
* representations of either percent, per mille, and/or minus sign disagree.
* @since 1.1.6
*/
@java.io.Serial
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
if (serialVersionOnStream < 1) {
// Didn't have monetarySeparator or exponential field;
// use defaults.
monetarySeparator = decimalSeparator;
exponential = 'E';
}
if (serialVersionOnStream < 2) {
// didn't have locale; use root locale
locale = Locale.ROOT;
}
if (serialVersionOnStream < 3) {
// didn't have exponentialSeparator. Create one using exponential
exponentialSeparator = Character.toString(exponential);
}
if (serialVersionOnStream < 4) {
// didn't have perMillText, percentText, and minusSignText.
// Create one using corresponding char variations.
perMillText = Character.toString(perMill);
percentText = Character.toString(percent);
minusSignText = Character.toString(minusSign);
} else {
// Check whether char and text fields agree
if (findNonFormatChar(perMillText, '\uFFFF') != perMill ||
findNonFormatChar(percentText, '\uFFFF') != percent ||
findNonFormatChar(minusSignText, '\uFFFF') != minusSign) {
throw new InvalidObjectException(
"'char' and 'String' representations of either percent, " +
"per mille, and/or minus sign disagree.");
}
}
serialVersionOnStream = currentSerialVersion;
if (intlCurrencySymbol != null) {
try {
currency = Currency.getInstance(intlCurrencySymbol);
} catch (IllegalArgumentException e) {
}
currencyInitialized = true;
}
}
public void testGetDisplayName() {
final Locale[] testLocales = {
Locale.ROOT,
new Locale("en"),
new Locale("en", "US"),
new Locale("", "US"),
new Locale("no", "NO", "NY"),
new Locale("", "", "NY"),
Locale.forLanguageTag("zh-Hans"),
Locale.forLanguageTag("zh-Hant"),
Locale.forLanguageTag("zh-Hans-CN"),
Locale.forLanguageTag("und-Hans"),
};
final String[] displayNameEnglish = {
"",
"English",
"English (United States)",
"United States",
"Norwegian (Norway,Nynorsk)",
"Nynorsk",
"Chinese (Simplified Han)",
"Chinese (Traditional Han)",
"Chinese (Simplified Han,China)",
"Simplified Han",
};
final String[] displayNameSimplifiedChinese = {
"",
"\u82f1\u6587",
"\u82f1\u6587 (\u7f8e\u56fd)",
"\u7f8e\u56fd",
"\u632a\u5a01\u6587 (\u632a\u5a01,Nynorsk)",
"Nynorsk",
"\u4e2d\u6587 (\u7b80\u4f53\u4e2d\u6587)",
"\u4e2d\u6587 (\u7e41\u4f53\u4e2d\u6587)",
"\u4e2d\u6587 (\u7b80\u4f53\u4e2d\u6587,\u4e2d\u56fd)",
"\u7b80\u4f53\u4e2d\u6587",
};
for (int i = 0; i < testLocales.length; i++) {
Locale loc = testLocales[i];
assertEquals("English display name for " + loc.toLanguageTag(),
displayNameEnglish[i], loc.getDisplayName(Locale.ENGLISH));
assertEquals("Simplified Chinese display name for " + loc.toLanguageTag(),
displayNameSimplifiedChinese[i], loc.getDisplayName(Locale.CHINA));
}
}
private static String getFormattedDateTime(final String pattern) {
final SimpleDateFormat sdf = new SimpleDateFormat(pattern, Locale.ROOT);
return sdf.format(new Date());
}
/**
* Returns {@code true} if the formatter should use scientific notation for the given value.
* We use scientific notation if the number magnitude is too high or too low. The threshold values used here
* may be different than the threshold values used in the standard {@link StringBuilder#append(double)} method.
* In particular, we use a higher threshold for large numbers because ellipsoid axis lengths are above the JDK
* threshold when the axis length is given in feet (about 2.1E+7) while we still want to format them as usual numbers.
*
* Note that we perform this special formatting only if the 'NumberFormat' is not localized (which is the usual case).
*
* @param abs the absolute value of the number to format.
*/
final boolean useScientificNotation(final double abs) {
return SCIENTIFIC_NOTATION && (abs < 1E-3 || abs >= 1E+9) && locale == Locale.ROOT;
}
/**
* <p>By substituting Locale.ROOT for any locale that includes English, we're counting on the fact that the locale is in the end
* used in a call to {@link java.util.ResourceBundle#getBundle(java.lang.String, java.util.Locale, java.lang.ClassLoader) }.</p>
*
* <p>Note that Locale.ROOT bypasses the default locale (which could be French or German). It relies on the convention we used for
* naming bundles files in Wildfly (LocalDescriptions.properties, not LocalDescriptions_en.properties).</p>
*/
static Locale replaceByRootLocaleIfLanguageIsEnglish(Locale locale) {
return (locale.getLanguage().equals(ENGLISH) ? Locale.ROOT : locale);
}
/**
* Creates a new date formatter with Farrago specific options. Farrago
* parsing is strict and does not allow values such as day 0, month 13, etc.
*
* @param format {@link SimpleDateFormat} pattern
*/
public static SimpleDateFormat newDateFormat(String format) {
SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.ROOT);
sdf.setLenient(false);
return sdf;
}