下面列出了怎么用org.springframework.util.unit.DataSize的API类实例代码及写法,或者点击链接到github查看源代码。
public void initialize() {
// 首次启动加载数据字典到 ServletContext 内存
dictionaryService.addDictionaryToServletContext();
mailService.initialize();
// 将待发送的邮件重新加入到发送队列
mailService.retry(false);
String maxFileSize = (String) dictionaryService.get("FILE", "MAX_FILE_SIZE");
String maxRequestSize = (String) dictionaryService.get("FILE", "MAX_REQUEST_SIZE");
updatableMultipartConfigElement.setMaxFileSize(DataSize.parse(maxFileSize).toBytes());
updatableMultipartConfigElement.setMaxRequestSize(DataSize.parse(maxRequestSize).toBytes());
String timeZoneId = (String) dictionaryService.get("SYSTEM", "TIME_ZONE_ID");
TimeZone.setDefault(TimeZone.getTimeZone(timeZoneId));
// Calendar.getInstance(TimeZone.getTimeZone());
// DateFormat.getDateTimeInstance().setTimeZone(TimeZone.getTimeZone(timeZoneId));
}
@Test
void shouldReturnCompressedResponse() {
final ArmeriaReactiveWebServerFactory factory = factory();
final Compression compression = new Compression();
compression.setEnabled(true);
compression.setMinResponseSize(DataSize.ofBytes(1));
compression.setMimeTypes(new String[] { "text/plain" });
compression.setExcludedUserAgents(new String[] { "unknown-agent/[0-9]+\\.[0-9]+\\.[0-9]+$" });
factory.setCompression(compression);
runEchoServer(factory, server -> {
final AggregatedHttpResponse res = sendPostRequest(httpClient(server));
assertThat(res.status()).isEqualTo(com.linecorp.armeria.common.HttpStatus.OK);
assertThat(res.headers().get(HttpHeaderNames.CONTENT_ENCODING)).isEqualTo("gzip");
assertThat(res.contentUtf8()).isNotEqualTo("hello");
});
}
@Bean
public MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
// 单个文件最大
factory.setMaxFileSize(DataSize.of(100, DataUnit.MEGABYTES)); // 100MB
// / 设置总上传数据总大小
factory.setMaxRequestSize(DataSize.of(100, DataUnit.MEGABYTES));// 100MB
return factory.createMultipartConfig();
}
@ExceptionHandler(MultipartException.class)
public ResponseEntity<FailureEntity> sizeLimitExceededExceptionHandler(HttpServletRequest httpServletRequest, Throwable throwable) {
HttpStatus httpStatus = getStatus(httpServletRequest);
FailureEntity fm = failureEntity.i18n("file.upload_fail");
if (throwable instanceof MaxUploadSizeExceededException) {
String maxFileSize = DataSizeUtil.pretty(DataSize.parse((String) dictionaryService.get("FILE", "MAX_FILE_SIZE")).toBytes());
String maxRequestSize = DataSizeUtil.pretty(DataSize.parse((String) dictionaryService.get("FILE", "MAX_REQUEST_SIZE")).toBytes());
fm = failureEntity.i18n("file.upload_fail_max_upload_size_exceeded", maxFileSize, maxRequestSize);
}
throwable.printStackTrace();
return new ResponseEntity<>(fm, httpStatus);
}
@Bean
public MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
//文件最大KB,MB
factory.setMaxFileSize(DataSize.ofBytes(10485760));
//设置总上传数据总大小
factory.setMaxRequestSize(DataSize.ofBytes(10485760));
return factory.createMultipartConfig();
}
/**
* Configures limits such as max message sizes that should be used by the server.
*
* @param builder The server builder to configure.
*/
protected void configureLimits(final T builder) {
final DataSize maxInboundMessageSize = this.properties.getMaxInboundMessageSize();
if (maxInboundMessageSize != null) {
builder.maxInboundMessageSize((int) maxInboundMessageSize.toBytes());
}
}
/**
* Configures limits such as max message sizes that should be used by the channel.
*
* @param builder The channel builder to configure.
* @param name The name of the client to configure.
*/
protected void configureLimits(final T builder, final String name) {
final GrpcChannelProperties properties = getPropertiesFor(name);
final DataSize maxInboundMessageSize = properties.getMaxInboundMessageSize();
if (maxInboundMessageSize != null) {
builder.maxInboundMessageSize((int) maxInboundMessageSize.toBytes());
}
}
@Test
void propertiesAreLoaded() {
assertThat(mailModuleProperties).isNotNull();
assertThat(mailModuleProperties.getDefaultSubject()).isEqualTo("hello");
assertThat(mailModuleProperties.getEnabled()).isTrue();
assertThat(mailModuleProperties.getPauseBetweenMails()).isEqualByComparingTo(Duration.ofSeconds(5));
assertThat(mailModuleProperties.getMaxAttachmentSize()).isEqualByComparingTo(DataSize.ofMegabytes(1));
assertThat(mailModuleProperties.getSmtpServers()).hasSize(2);
assertThat(mailModuleProperties.getMaxAttachmentWeight().getGrams()).isEqualTo(5000L);
}
/**
* Configures limits such as max message sizes that should be used by the server.
*
* @param builder The server builder to configure.
*/
protected void configureLimits(final T builder) {
final DataSize maxInboundMessageSize = this.properties.getMaxInboundMessageSize();
if (maxInboundMessageSize != null) {
builder.maxInboundMessageSize((int) maxInboundMessageSize.toBytes());
}
}
/**
* Configures limits such as max message sizes that should be used by the channel.
*
* @param builder The channel builder to configure.
* @param name The name of the client to configure.
*/
protected void configureLimits(final T builder, final String name) {
final GrpcChannelProperties properties = getPropertiesFor(name);
final DataSize maxInboundMessageSize = properties.getMaxInboundMessageSize();
if (maxInboundMessageSize != null) {
builder.maxInboundMessageSize((int) maxInboundMessageSize.toBytes());
}
}
@Override
public boolean isValid(DataSize value, ConstraintValidatorContext context) {
// null values are valid
if (value == null) {
return true;
}
return value.toBytes() <= maxValue;
}
@Test
public void toStringFormat() {
RequestSizeConfig config = new RequestSizeConfig();
config.setMaxSize(DataSize.ofBytes(1000L));
GatewayFilter filter = new RequestSizeGatewayFilterFactory().apply(config);
assertThat(filter.toString()).contains("max").contains("1000");
}
@Test
public void toStringFormat() {
Config config = new Config();
config.setMaxSize(DataSize.ofBytes(1000L));
GatewayFilter filter = new RequestHeaderSizeGatewayFilterFactory().apply(config);
assertThat(filter.toString()).contains("max").contains("1000B");
}
@Bean
public RouteLocator testRouteLocator(RouteLocatorBuilder builder) {
return builder.routes().route("test_request_header_size",
r -> r.order(-1).host("**.test.org").filters(
f -> f.setRequestHeaderSize(DataSize.of(46L, DataUnit.BYTES)))
.uri(uri))
.build();
}
@Test
void shouldReturnNonCompressedResponse_dueToContentType() {
final ArmeriaReactiveWebServerFactory factory = factory();
final Compression compression = new Compression();
compression.setEnabled(true);
compression.setMinResponseSize(DataSize.ofBytes(1));
compression.setMimeTypes(new String[] { "text/html" });
factory.setCompression(compression);
runEchoServer(factory, server -> {
final AggregatedHttpResponse res = sendPostRequest(httpClient(server));
validateEchoResponse(res);
assertThat(res.headers().get(HttpHeaderNames.CONTENT_ENCODING)).isNull();
});
}
@Test
void shouldReturnNonCompressedResponse_dueToUserAgent() {
final ArmeriaReactiveWebServerFactory factory = factory();
final Compression compression = new Compression();
compression.setEnabled(true);
compression.setMinResponseSize(DataSize.ofBytes(1));
compression.setExcludedUserAgents(new String[] { "test-agent/[0-9]+\\.[0-9]+\\.[0-9]+$" });
factory.setCompression(compression);
runEchoServer(factory, server -> {
final AggregatedHttpResponse res = sendPostRequest(httpClient(server));
validateEchoResponse(res);
assertThat(res.headers().get(HttpHeaderNames.CONTENT_ENCODING)).isNull();
});
}
@Test
void test() {
assertEquals(Duration.ofMinutes(42), this.grpcServerProperties.getKeepAliveTime());
assertEquals(DataSize.ofMegabytes(5), this.grpcServerProperties.getMaxInboundMessageSize());
}
@Test
void test() {
assertEquals(Duration.ofSeconds(42), this.grpcServerProperties.getKeepAliveTime());
assertEquals(DataSize.ofMegabytes(5), this.grpcServerProperties.getMaxInboundMessageSize());
}
@Test
void test() {
final GrpcChannelProperties properties = this.grpcChannelsProperties.getChannel("test");
assertEquals(Duration.ofSeconds(42), properties.getKeepAliveTime());
assertEquals(DataSize.ofMegabytes(5), properties.getMaxInboundMessageSize());
}
@Test
void test() {
final GrpcChannelProperties properties = this.grpcChannelsProperties.getChannel("test");
assertEquals(Duration.ofMinutes(42), properties.getKeepAliveTime());
assertEquals(DataSize.ofMegabytes(5), properties.getMaxInboundMessageSize());
}
public DataSize getMaxAttachmentSize() {
return maxAttachmentSize;
}
public void setMaxAttachmentSize(DataSize maxAttachmentSize) {
this.maxAttachmentSize = maxAttachmentSize;
}
@Test
void test() {
assertEquals(Duration.ofMinutes(42), this.grpcServerProperties.getKeepAliveTime());
assertEquals(DataSize.ofMegabytes(5), this.grpcServerProperties.getMaxInboundMessageSize());
}
@Test
void test() {
assertEquals(Duration.ofSeconds(42), this.grpcServerProperties.getKeepAliveTime());
assertEquals(DataSize.ofMegabytes(5), this.grpcServerProperties.getMaxInboundMessageSize());
}
@Test
void test() {
final GrpcChannelProperties properties = this.grpcChannelsProperties.getChannel("test");
assertEquals(Duration.ofSeconds(42), properties.getKeepAliveTime());
assertEquals(DataSize.ofMegabytes(5), properties.getMaxInboundMessageSize());
}
@Test
void test() {
final GrpcChannelProperties properties = this.grpcChannelsProperties.getChannel("test");
assertEquals(Duration.ofMinutes(42), properties.getKeepAliveTime());
assertEquals(DataSize.ofMegabytes(5), properties.getMaxInboundMessageSize());
}
private boolean checkType(String type, String text, ClassLoader cl) throws IllegalArgumentException {
Class<?> clazz = ClassUtils.resolveClassName(type, cl);
if (clazz != null) {
try {
parser.parseType(text, clazz);
} catch (Exception e1) {
if (clazz.isEnum()) {
// generate and try relaxed variants of value
for (String relaxedName : new RelaxedNames(text)) {
try {
parser.parseType(relaxedName, clazz);
return true;
} catch (Exception e2) {
// try another variant
}
if (canceled) {
break;
}
}
return false;
} else {
try {
// handle a few specific cases where no direct constructor from string or converter exist
switch (type) {
case "java.nio.file.Path":
Paths.get(text);
return true;
case "java.util.Locale":
LocaleUtils.toLocale(text);
return true;
case "java.time.Duration":
DurationStyle.detectAndParse(text);
return true;
case "org.springframework.util.unit.DataSize":
DataSize.parse(text);
return true;
case "java.lang.Class":
cl.loadClass(text);
return true;
default:
return false;
}
} catch (Exception e3) {
return false;
}
}
}
}
// unresolvable/unknown class, assume user knows what is doing
return true;
}
@Max(Integer.MAX_VALUE)
public DataSize getMaxHeaderSize() {
return maxHeaderSize;
}
public void setMaxHeaderSize(DataSize maxHeaderSize) {
this.maxHeaderSize = maxHeaderSize;
}
@Max(Integer.MAX_VALUE)
public DataSize getMaxInitialLineLength() {
return maxInitialLineLength;
}