本文整理了Java中akka.util.ByteString
类的一些代码示例,展示了ByteString
类的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。ByteString
类的具体详情如下:
包路径:akka.util.ByteString
类名称:ByteString
暂无
代码示例来源:origin: com.typesafe.play/play_2.11
/**
* Create an entity from the given String.
*
* @param content The content.
* @param charset The charset.
* @return the HTTP entity.
*/
public static final HttpEntity fromString(String content, String charset) {
return new Strict(ByteString.fromString(content, charset), Optional.of("text/plain; charset=" + charset));
}
代码示例来源:origin: com.typesafe.play/play-test_2.12
/**
* Extracts the content as a String.
*
* @param result The result to extract the content from.
* @param mat The materializer to use to extract the body from the result stream.
* @return The content of the result as a String.
*/
public static String contentAsString(Result result, Materializer mat) {
return contentAsBytes(result, mat, DEFAULT_TIMEOUT)
.decodeString(result.charset().orElse("utf-8"));
}
代码示例来源:origin: com.typesafe.play/play_2.12
/**
* Set a Binary Data to this request.
* The <tt>Content-Type</tt> header of the request is set to <tt>application/octet-stream</tt>.
*
* @param data the Binary Data
* @param tempFileCreator the temporary file creator for binary data.
* @return the modified builder
*/
public RequestBuilder bodyRaw(byte[] data, Files.TemporaryFileCreator tempFileCreator) {
return bodyRaw(ByteString.fromArray(data), tempFileCreator);
}
代码示例来源:origin: com.typesafe.play/play
@Override
protected String parse(Http.RequestHeader request, ByteString bytes) throws Exception {
// Per RFC 7231:
// The default charset of ISO-8859-1 for text media types has been removed; the default is now
// whatever the media type definition says.
// Per RFC 6657:
// The default "charset" parameter value for "text/plain" is unchanged from [RFC2046] and remains as "US-ASCII".
// https://tools.ietf.org/html/rfc6657#section-4
Charset charset = request.charset().map(Charset::forName).orElse(US_ASCII);
try {
CharsetDecoder decoder = charset.newDecoder().onMalformedInput(CodingErrorAction.REPORT);
return decoder.decode(bytes.toByteBuffer()).toString();
} catch (CharacterCodingException e) {
String msg = String.format("Parser tried to parse request %s as text body with charset %s, but it contains invalid characters!", request.id(), charset);
logger.warn(msg);
return bytes.decodeString(charset); // parse and return with unmappable characters.
} catch (Exception e) {
String msg = "Unexpected exception while parsing text/plain body";
logger.error(msg, e);
return bytes.decodeString(charset);
}
}
}
代码示例来源:origin: com.typesafe.play/play-ahc-ws-standalone_2.12
builder.setQueryParams(queryParameters);
getBody().ifPresent(bodyWritable -> {
builder.setBody(byteString.toArray());
} else {
String stringBody = byteString.decodeString(charset);
long contentLength = Optional.ofNullable(possiblyModifiedHeaders.get(CONTENT_LENGTH))
.map(Long::valueOf).orElse(-1L);
possiblyModifiedHeaders.remove(CONTENT_LENGTH);
Publisher<ByteBuf> publisher = sourceBody.map(bs -> Unpooled.wrappedBuffer(bs.toByteBuffer()))
.runWith(Sink.asPublisher(AsPublisher.WITHOUT_FANOUT), materializer);
builder.setBody(publisher, contentLength);
代码示例来源:origin: com.github.rmannibucau/playx-servlet
@Override
public Accumulator<ByteString, Result> apply(final Http.RequestHeader requestHeader) {
return state.getServletContext().findMatchingServlet(requestHeader).map(servlet -> {
final long length = requestHeader.getHeaders().get("Content-Length").map(Long::parseLong)
.orElse(Long.MAX_VALUE);
final BodyParser.Bytes slurper = new BodyParser.Bytes(length, state.getHttpErrorHandler());
return slurper.apply(requestHeader).mapFuture(
resultOrBytes -> resultOrBytes.left.map(CompletableFuture::completedFuture).orElseGet(() -> {
return state.getServletContext()
.executeInvoke(servlet, requestHeader,
resultOrBytes.right.get().iterator().asInputStream(), servlet.getServletPath())
.toCompletableFuture();
}), state.getServletContext().getDefaultExecutor());
}).orElseGet(() -> next.apply(requestHeader));
}
};
代码示例来源:origin: org.eclipse.ditto/ditto-services-connectivity-messaging
private MqttMessage mapExternalMessageToMqttMessage(
final MqttPublishTarget mqttTarget,
final MqttQoS qos,
final ExternalMessage externalMessage) {
final ByteString payload;
if (externalMessage.isTextMessage()) {
final Charset charset = externalMessage.findContentType()
.map(MessageMappers::determineCharset)
.orElse(StandardCharsets.UTF_8);
payload = externalMessage
.getTextPayload()
.map(text -> ByteString.fromString(text, charset))
.orElse(ByteString.empty());
} else if (externalMessage.isBytesMessage()) {
payload = externalMessage.getBytePayload()
.map(ByteString::fromByteBuffer)
.orElse(ByteString.empty());
} else {
payload = ByteString.empty();
}
return MqttMessage.create(mqttTarget.getTopic(), payload, qos);
}
代码示例来源:origin: com.typesafe.play/play
@Override
protected Document parse(Http.RequestHeader request, ByteString bytes) throws Exception {
return XML.fromInputStream(bytes.iterator().asInputStream(), request.charset().orElse(null));
}
}
代码示例来源:origin: com.typesafe.play/play_2.11
@Override
protected final Accumulator<ByteString, F.Either<Result, A>> apply1(Http.RequestHeader request) {
Accumulator<ByteString, ByteString> byteStringByteStringAccumulator = Accumulator.strict(
maybeStrictBytes -> CompletableFuture.completedFuture(maybeStrictBytes.orElse(ByteString.empty())),
Sink.fold(ByteString.empty(), ByteString::concat)
);
Accumulator<ByteString, F.Either<Result, A>> byteStringEitherAccumulator = byteStringByteStringAccumulator.mapFuture(bytes -> {
try {
return CompletableFuture.completedFuture(F.Either.Right(parse(request, bytes)));
} catch (Exception e) {
return errorHandler.onClientError(request, Status$.MODULE$.BAD_REQUEST(), errorMessage + ": " + e.getMessage())
.thenApply(F.Either::<Result, A>Left);
}
}, JavaParsers.trampoline());
return byteStringEitherAccumulator;
}
代码示例来源:origin: com.typesafe.play/play
return ByteString.empty();
} else if (body instanceof Optional) {
if (!((Optional<?>) body).isPresent()) {
return ByteString.empty();
return ByteString.fromArray((byte[]) body);
} else if (body instanceof String) {
return ByteString.fromString((String) body);
} else if (body instanceof RawBuffer) {
return ((RawBuffer) body).asBytes();
} else if (body instanceof JsonNode) {
return ByteString.fromString(Json.stringify((JsonNode) body));
} else if (body instanceof Document) {
return XML.toBytes((Document) body);
} else {
Map<String, String[]> form = asFormUrlEncoded();
if (form != null) {
return ByteString.fromString(
form.entrySet()
.stream()
.flatMap(entry -> {
String key = encode(entry.getKey());
return Arrays.stream(entry.getValue()).map(
value -> key + "=" + encode(value)
);
})
代码示例来源:origin: com.typesafe.play/play_2.11
/**
* Generates a simple result with byte-array content.
*
* @param status the HTTP status for this result e.g. 200 (OK), 404 (NOT_FOUND)
* @param content the result's body content, as a byte array
* @return the result
*/
public static Result status(int status, byte[] content) {
if (content == null) {
throw new NullPointerException("Null content");
}
return new Result(status, new HttpEntity.Strict(ByteString.fromArray(content), Optional.empty()));
}
代码示例来源:origin: eclipse/ditto
log.debug("Received MQTT message on topic {}: {}", message.topic(), message.payload().utf8String());
.withBytes(message.payload().toByteBuffer())
.withAuthorizationContext(sourceAuthorizationContext)
.withEnforcement(getEnforcementFilter(message.topic()))
final AddressMetric theAddressMetric = ConnectivityModelFactory.newAddressMetric(
this.addressMetric != null ? this.addressMetric.getStatus() : ConnectionStatus.UNKNOWN,
this.addressMetric != null ? this.addressMetric.getStatusDetails().orElse(null) : null,
consumedMessages, lastMessageConsumedAt);
log.debug("theAddressMetric: {}", theAddressMetric);
代码示例来源:origin: eclipse/ditto
private CompletableFuture<JsonArray> mapResponseToJsonArray(final HttpResponse response) {
final CompletionStage<JsonObject> body =
response.entity().getDataBytes().fold(ByteString.empty(), ByteString::concat)
.map(ByteString::utf8String)
.map(JsonFactory::readFrom)
.map(JsonValue::asObject)
.runWith(Sink.head(), httpClient.getActorMaterializer());
final JsonPointer keysPointer = JsonPointer.of("keys");
return body.toCompletableFuture()
.thenApply(jsonObject -> jsonObject.getValue(keysPointer).map(JsonValue::asArray)
.orElseThrow(() -> new JsonMissingFieldException(keysPointer)))
.exceptionally(t -> {
throw new IllegalStateException("Failed to extract public keys from JSON response: " + body, t);
});
}
代码示例来源:origin: com.typesafe.play/play-test_2.11
/**
* Extracts the content as bytes.
*
* @param content the content to be turned into bytes.
* @return the body of the content as a byte string.
*/
public static ByteString contentAsBytes(Content content) {
return ByteString.fromString(content.body());
}
代码示例来源:origin: com.typesafe.play/play-ahc-ws_2.11
/**
* @deprecated Use {@code response.getBodyAsBytes().toArray()}
*/
@Override
@Deprecated
public byte[] asByteArray() {
return underlying.getBodyAsBytes().toArray();
}
代码示例来源:origin: eclipse/ditto
private Route handleSudoCountThingsPerRequest(final RequestContext ctx, final SudoCountThings command) {
final CompletableFuture<HttpResponse> httpResponseFuture = new CompletableFuture<>();
Source.single(command)
.to(Sink.actorRef(createHttpPerRequestActor(ctx, httpResponseFuture),
HttpRequestActor.COMPLETE_MESSAGE))
.run(materializer);
final CompletionStage<HttpResponse> allThingsCountHttpResponse = Source.fromCompletionStage(httpResponseFuture)
.flatMapConcat(httpResponse -> httpResponse.entity().getDataBytes())
.fold(ByteString.empty(), ByteString::concat)
.map(ByteString::utf8String)
.map(Integer::valueOf)
.map(count -> JsonObject.newBuilder().set("allThingsCount", count).build())
.map(jsonObject -> HttpResponse.create()
.withEntity(ContentTypes.APPLICATION_JSON, ByteString.fromString(jsonObject.toString()))
.withStatus(HttpStatusCode.OK.toInt()))
.runWith(Sink.head(), materializer);
return completeWithFuture(allThingsCountHttpResponse);
}
代码示例来源:origin: com.typesafe.play/play_2.11
@Override
protected JsonNode parse(Http.RequestHeader request, ByteString bytes) throws Exception {
return play.libs.Json.parse(bytes.iterator().asInputStream());
}
}
代码示例来源:origin: elder-oss/sourcerer
@SuppressWarnings("unchecked")
private ImmutableMap<String, String> fromEsMetadata(final Content metadata) {
if (metadata == null
|| metadata.contentType() != ContentType.json()
|| metadata.value().size() == 0) {
return ImmutableMap.of();
}
try {
return ImmutableMap.copyOf((Map) objectMapper
.readerFor(new TypeReference<Map<String, String>>() {
})
.readValue(metadata.value().iterator().asInputStream()));
} catch (IOException ex) {
throw new RetriableEventReadException("Internal error reading events", ex);
}
}
代码示例来源:origin: com.typesafe.play/play
/**
* Set a Binary Data to this request.
* The <tt>Content-Type</tt> header of the request is set to <tt>application/octet-stream</tt>.
*
* @param data the Binary Data
* @param tempFileCreator the temporary file creator for binary data.
* @return the modified builder
*/
public RequestBuilder bodyRaw(ByteString data, Files.TemporaryFileCreator tempFileCreator) {
play.api.mvc.RawBuffer buffer = new play.api.mvc.RawBuffer(data.size(), tempFileCreator.asScala(), data);
return body(new RequestBody(JavaParsers.toJavaRaw(buffer)), "application/octet-stream");
}
代码示例来源:origin: com.lightbend.lagom/lagom-javadsl-jackson
@Override
public Throwable deserialize(RawExceptionMessage message) {
ExceptionMessage exceptionMessage;
try {
exceptionMessage = objectMapper.readValue(message.message().iterator().asInputStream(), ExceptionMessage.class);
} catch (Exception e) {
exceptionMessage = new ExceptionMessage("UndeserializableException", message.message().utf8String());
}
return TransportException.fromCodeAndMessage(message.errorCode(), exceptionMessage);
}
}
内容来源于网络,如有侵权,请联系作者删除!