下面列出了javax.ws.rs.core.MediaType#APPLICATION_OCTET_STREAM 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Send a queue message with a binary data payload.
*
* @param queueName Name of queue to target (queue must exist)
* @param regionsParam Comma-separated list of regions to send to
* @param delayParam Delay (ms) before sending message (not yet supported)
* @param expirationParam Time (ms) after which message will expire (not yet supported)
* @param actualContentType Content type of messageBody data (if not application/octet-stream)
* @param messageBody Binary data that is the payload of the queue message
*/
@POST
@Path( "{queueName}/messages" )
@Consumes(MediaType.APPLICATION_OCTET_STREAM)
@Produces(MediaType.APPLICATION_JSON)
public Response sendMessageBinary(
@PathParam("queueName") String queueName,
@QueryParam("regions" ) @DefaultValue("") String regionsParam,
@QueryParam("delay") @DefaultValue("") String delayParam,
@QueryParam("expiration") @DefaultValue("") String expirationParam,
@QueryParam("contentType") String actualContentType,
byte[] messageBody) throws Exception {
String contentType = actualContentType != null ? actualContentType : MediaType.APPLICATION_OCTET_STREAM;
return sendMessage( queueName, regionsParam, delayParam, expirationParam,
contentType, ByteBuffer.wrap( messageBody ) );
}
@JaxrsMethodDescribe(value = "上传文件,并进行压缩,如果文件大小小于指定宽度或者宽度<0,则不进行压缩.", action = ActionUpload.class)
@PUT
@Path("upload/referencetype/{referenceType}/reference/{reference}/scale/{scale}")
@Consumes({ MediaType.MULTIPART_FORM_DATA, MediaType.APPLICATION_OCTET_STREAM })
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
public void upload(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
@JaxrsParameterDescribe("文件类型") @PathParam("referenceType") String referenceType,
@JaxrsParameterDescribe("关联id") @PathParam("reference") String reference,
@JaxrsParameterDescribe("缩放") @PathParam("scale") Integer scale,
@FormDataParam(FILE_FIELD) final byte[] bytes,
@JaxrsParameterDescribe("上传文件") @FormDataParam(FILE_FIELD) final FormDataContentDisposition disposition) {
ActionResult<ActionUpload.Wo> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionUpload().execute(effectivePerson, referenceType, reference, scale, bytes, disposition);
} catch (Exception e) {
logger.error(e, effectivePerson, request, null);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@POST
@Path("/generate/pom.xml")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public byte[] projectPom(Integration integration) throws IOException {
return projectGenerator.generatePom(integration);
}
@GET
@Path("sharedfolder/{path:.*}")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_HTML, MediaType.APPLICATION_OCTET_STREAM })
public Response getSharedFiles(@PathParam("courseId") final Long courseId, @PathParam("path") final List<PathSegment> path, @Context final UriInfo uriInfo,
@Context final HttpServletRequest httpRequest, @Context final Request request) {
return getFiles(courseId, path, FolderType.COURSE_FOLDER, uriInfo, httpRequest, request);
}
@POST
@Path("response/bytebuffer")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@Consumes("*/*")
public ServerResponse<ByteBuffer> responseUploadByteBuffer(ServerRequest request, @FormParam("file") ByteBuffer file ) throws Exception
{
return response(file).applicationOctetStream();
}
@PUT
@Path("/{id}/esign")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response uploadEsign(@Context HttpServletRequest request, @Context HttpHeaders header,
@Context Company company, @Context Locale locale, @Context User user,
@Context ServiceContext serviceContext, @PathParam("id") long id, @Multipart("file") Attachment attachment,
@Multipart("fileName") String fileName, @Multipart("fileType") String fileType,
@Multipart("fileSize") long fileSize);
/**
* Handles read data request. Parses the request, creates a bridge instance and iterates over its
* records, printing it out to the outgoing stream. Outputs GPDBWritable or Text formats.
*
* Parameters come via HTTP headers.
*
* @param servletContext Servlet context contains attributes required by SecuredHDFS
* @param headers Holds HTTP headers from request
* @return response object containing stream that will output records
*/
@GET
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response read(@Context final ServletContext servletContext,
@Context HttpHeaders headers) {
RequestContext context = parseRequest(headers);
Bridge bridge = bridgeFactory.getReadBridge(context);
// THREAD-SAFE parameter has precedence
boolean isThreadSafe = context.isThreadSafe() && bridge.isThreadSafe();
LOG.debug("Request for {} will be handled {} synchronization", context.getDataSource(), (isThreadSafe ? "without" : "with"));
return readResponse(bridge, context, isThreadSafe);
}
@POST
@Path("/postStream")
@Consumes( { MediaType.APPLICATION_OCTET_STREAM, MediaType.APPLICATION_XML})
public Response handlePost(final InputStream in, @HeaderParam("Transfer-Encoding") String transferEncoding) {
try {
byte[] bytes = IOUtils.toByteArray(in);
String entity = new String(bytes, "UTF-8");
return Response.ok(entity).build();
} catch (Exception e) {
return Response.serverError().build();
}
}
@PUT
@Path("/{id}/photo")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response uploadEmployeePhoto(@Context HttpServletRequest request, @Context HttpHeaders header,
@Context Company company, @Context Locale locale, @Context User user,
@Context ServiceContext serviceContext, @PathParam("id") long id, @Multipart("file") Attachment attachment,
@Multipart("fileName") String fileName, @Multipart("fileType") String fileType,
@Multipart("fileSize") long fileSize);
@Path("/parseAsText")
@POST
@Consumes(MediaType.APPLICATION_OCTET_STREAM)
@Produces(MediaType.TEXT_PLAIN)
public Response parseAsTxt(byte[] message) throws Exception {
final String response = producerTemplate.requestBody("tika:parse?tikaParseOutputFormat=text", message,
String.class);
return Response
.created(new URI("https://camel.apache.org/"))
.entity(response)
.build();
}
@GET
@Path("/{source}")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public StreamingOutput getBook(@PathParam("source") final String source) throws IOException {
return new StreamingOutput() {
@Override
public void write(final OutputStream out) throws IOException, WebApplicationException {
try (InputStream in = storage.getDocument(source)) {
out.write(IOUtils.readBytesFromStream(in));
} catch (final FileNotFoundException ex) {
throw new NotFoundException("Document does not exist: " + source);
}
}
};
}
@GET
@Produces({ MediaType.APPLICATION_OCTET_STREAM })
public Response get(@Context Response response, @QueryParam(LumongoConstants.ID) final String uniqueId,
@QueryParam(LumongoConstants.FILE_NAME) final String fileName, @QueryParam(LumongoConstants.INDEX) final String indexName) {
StreamingOutput stream = new StreamingOutput() {
@Override
public void write(OutputStream output) throws IOException, WebApplicationException {
if (uniqueId != null && fileName != null && indexName != null) {
InputStream is = indexManager.getAssociatedDocumentStream(indexName, uniqueId, fileName);
if (is != null) {
StreamHelper.copyStream(is, output);
}
else {
throw new WebApplicationException("Cannot find associated document with uniqueId <" + uniqueId + "> with fileName <" + fileName + ">",
LumongoConstants.NOT_FOUND);
}
}
else {
throw new WebApplicationException(LumongoConstants.ID + " and " + LumongoConstants.FILE_NAME + " are required",
LumongoConstants.BAD_REQUEST);
}
}
};
return Response.ok(stream).header("content-disposition", "attachment; filename = " + fileName).build();
}
@POST
@Consumes(MediaType.APPLICATION_OCTET_STREAM)
public Response upload(InputStream is) throws IOException {
byte[] bytes = IOUtils.toByteArray(is);
System.out.println("Read " + bytes.length + " byte(s)");
return rest.ok(String.valueOf(bytes.length));
}
/**
* Generate a new keypair and certificate, and get the private key file
*
* Generates a keypair and certificate and serves the private key in a specified keystore format.
* Only generated public certificate is saved in Keycloak DB - the private key is not.
*
* @param config Keystore configuration as JSON
* @return
*/
@POST
@NoCache
@Path("/generate-and-download")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@Consumes(MediaType.APPLICATION_JSON)
public byte[] generateAndGetKeystore(final KeyStoreConfig config) {
auth.clients().requireConfigure(client);
if (config.getFormat() != null && !config.getFormat().equals("JKS") && !config.getFormat().equals("PKCS12")) {
throw new NotAcceptableException("Only support jks or pkcs12 format.");
}
if (config.getKeyPassword() == null) {
throw new ErrorResponseException("password-missing", "Need to specify a key password for jks generation and download", Response.Status.BAD_REQUEST);
}
if (config.getStorePassword() == null) {
throw new ErrorResponseException("password-missing", "Need to specify a store password for jks generation and download", Response.Status.BAD_REQUEST);
}
CertificateRepresentation info = KeycloakModelUtils.generateKeyPairCertificate(client.getClientId());
byte[] rtn = getKeystore(config, info.getPrivateKey(), info.getCertificate());
info.setPrivateKey(null);
CertificateInfoHelper.updateClientModelCertificateInfo(client, info, attributePrefix);
adminEvent.operation(OperationType.ACTION).resourcePath(session.getContext().getUri()).representation(info).success();
return rtn;
}
@POST
@Path("/{entitySetName}")
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_ATOM_XML, MediaType.APPLICATION_JSON })
@Consumes({ MediaType.APPLICATION_ATOM_XML, MediaType.APPLICATION_JSON, MediaType.APPLICATION_OCTET_STREAM })
@Override
public Response postNewEntity(
@Context final UriInfo uriInfo,
@HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept,
@HeaderParam("Content-Type") @DefaultValue(StringUtils.EMPTY) final String contentType,
@HeaderParam("Prefer") @DefaultValue(StringUtils.EMPTY) final String prefer,
@PathParam("entitySetName") final String entitySetName,
final String entity) {
return replaceServiceName(super.postNewEntity(uriInfo, accept, contentType, prefer, entitySetName, entity));
}
@GET
@Path("responseBytes")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response getResponseBytes() {
return Response.ok("resp".getBytes()).build();
}
private String mediaType(FileObject fo) throws FileSystemException {
String contentType = fo.getContent().getContentInfo().getContentType();
return Strings.isNullOrEmpty(contentType) ? MediaType.APPLICATION_OCTET_STREAM : contentType;
}
/**
* For getting GTFS-realtime Vehicle Positions data for all vehicles.
*
* @param stdParameters
* @param format
* if set to "human" then will output GTFS-rt data in human
* readable format. Otherwise will output data in binary format.
* @return
* @throws WebApplicationException
*/
@Path("/command/gtfs-rt/tripUpdates")
@GET
@Produces({ MediaType.TEXT_PLAIN, MediaType.APPLICATION_OCTET_STREAM })
public Response getGtfsRealtimeTripFeed(
final @BeanParam StandardParameters stdParameters,
@QueryParam(value = "format") String format)
throws WebApplicationException {
// Make sure request is valid
stdParameters.validate();
// Determine if output should be in human readable format or in
// standard binary GTFS-realtime format.
final boolean humanFormatOutput = "human".equals(format);
// Determine the appropriate output format. For plain text best to use
// MediaType.TEXT_PLAIN so that output is formatted properly in web
// browser instead of newlines being removed. For binary output should
// use MediaType.APPLICATION_OCTET_STREAM.
String mediaType =
humanFormatOutput ? MediaType.TEXT_PLAIN
: MediaType.APPLICATION_OCTET_STREAM;
// Prepare a StreamingOutput object so can write using it
StreamingOutput stream = new StreamingOutput() {
public void write(OutputStream outputStream) throws IOException,
WebApplicationException {
try {
FeedMessage message =
GtfsRtTripFeed.getPossiblyCachedMessage(
stdParameters.getAgencyId(),
MAX_GTFS_RT_CACHE_SECS);
// Output in human readable format or in standard binary
// format
if (humanFormatOutput) {
// Output data in human readable format. First, convert
// the octal escaped message to regular UTF encoding.
String decodedMessage =
OctalDecoder.convertOctalEscapedString(message
.toString());
outputStream.write(decodedMessage.getBytes());
} else {
// Standard binary output
message.writeTo(outputStream);
}
} catch (Exception e) {
throw new WebApplicationException(e);
}
}
};
// Write out the data using the output stream
return Response.ok(stream).type(mediaType).build();
}
@POST
@Path("response/file")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@Consumes("*/*")
@ApiOperation(value = "Upload file path endpoint")
public ServerResponse<ByteBuffer> responseUploadFile(ServerRequest request, @FormParam("file") File file ) throws Exception
{
ByteBuffer response = ByteBuffer.wrap(Files.asByteSource(file).read());
return response(response).applicationOctetStream();
}
@POST
@Path("response/file")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@Consumes("*/*")
public ServerResponse<ByteBuffer> responseUploadFile(ServerRequest request, @FormParam("file") File file ) throws Exception
{
ByteBuffer response = ByteBuffer.wrap(Files.asByteSource(file).read());
return response(response).applicationOctetStream();
}