Java Code Examples for javax.ws.rs.core.MediaType#APPLICATION_OCTET_STREAM

The following examples show how to use javax.ws.rs.core.MediaType#APPLICATION_OCTET_STREAM . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: QueueResource.java    From usergrid with Apache License 2.0 6 votes vote down vote up
/**
 * 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 ) );
}
 
Example 2
Source File: UserManagement.java    From opencps-v2 with GNU Affero General Public License v3.0 6 votes vote down vote up
@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);
 
Example 3
Source File: FileAction.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
@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));
}
 
Example 4
Source File: CourseResourceFolderWebService.java    From olat with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 5
Source File: KeyAsSegment.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@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));
}
 
Example 6
Source File: ClientAttributeCertificateResource.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 7
Source File: BinaryStreamResource.java    From cukes with Apache License 2.0 5 votes vote down vote up
@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));
}
 
Example 8
Source File: AssociatedResource.java    From lumongo with Apache License 2.0 5 votes vote down vote up
@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();

}
 
Example 9
Source File: Catalog.java    From cxf with Apache License 2.0 5 votes vote down vote up
@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);
            }
        }
    };
}
 
Example 10
Source File: TikaResource.java    From camel-quarkus with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example 11
Source File: EmployeeManagement.java    From opencps-v2 with GNU Affero General Public License v3.0 5 votes vote down vote up
@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);
 
Example 12
Source File: TestResource.java    From ribbon with Apache License 2.0 5 votes vote down vote up
@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();
    }
}
 
Example 13
Source File: BridgeResource.java    From pxf with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example 14
Source File: Tests.java    From proteus with Apache License 2.0 5 votes vote down vote up
@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();
	 

}
 
Example 15
Source File: IntegrationSupportHandler.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 16
Source File: OctetStreamMediaTypeTest.java    From openwebbeans-meecrowave with Apache License 2.0 4 votes vote down vote up
@GET
@Path("responseBytes")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response getResponseBytes() {
    return Response.ok("resp".getBytes()).build();
}
 
Example 17
Source File: RestDataspaceImpl.java    From scheduling with GNU Affero General Public License v3.0 4 votes vote down vote up
private String mediaType(FileObject fo) throws FileSystemException {
    String contentType = fo.getContent().getContentInfo().getContentType();
    return Strings.isNullOrEmpty(contentType) ? MediaType.APPLICATION_OCTET_STREAM : contentType;
}
 
Example 18
Source File: GtfsRealtimeApi.java    From core with GNU General Public License v3.0 4 votes vote down vote up
/**
 * 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();
}
 
Example 19
Source File: Tests.java    From proteus with Apache License 2.0 3 votes vote down vote up
@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();
	 

}
 
Example 20
Source File: Tests.java    From proteus with Apache License 2.0 3 votes vote down vote up
@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();
	 

}