com.sun.jersey.core.header.FormDataContentDisposition Java Examples

The following examples show how to use com.sun.jersey.core.header.FormDataContentDisposition. 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: StaashDataResourceImpl.java    From staash with Apache License 2.0 6 votes vote down vote up
@POST
@Path("/kvstore")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
   @ResourceFilters(StaashAuditFilter.class)
public String storeFile(
		@FormDataParam("value") InputStream uploadedInputStream,
		@FormDataParam("value") FormDataContentDisposition fileDetail) {
	try {
		writeToChunkedKVStore(uploadedInputStream, fileDetail.getFileName());
	} catch (IOException e) {
		e.printStackTrace();
		return "{\"msg\":\"file could not be uploaded\"}";
	}
	return "{\"msg\":\"file successfully uploaded\"}";
}
 
Example #2
Source File: FakeApi.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@POST
@Path("/{petId}/uploadImageWithRequiredFile")
@Consumes({ "multipart/form-data" })
@Produces({ "application/json" })
@io.swagger.annotations.ApiOperation(value = "uploads an image (required)", notes = "", response = ModelApiResponse.class, authorizations = {
    @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = {
        @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"),
        @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets")
    })
}, tags={ "pet" })
@io.swagger.annotations.ApiResponses(value = { 
    @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = ModelApiResponse.class) })
public Response uploadFileWithRequiredFile(
    @ApiParam(value = "ID of pet to update", required = true) @PathParam("petId") @NotNull  Long petId,
    @FormDataParam("requiredFile") InputStream inputStream,
    @FormDataParam("requiredFile") FormDataContentDisposition fileDetail,
    @FormDataParam("additionalMetadata")  String additionalMetadata,
    @Context SecurityContext securityContext)
throws NotFoundException {
    return delegate.uploadFileWithRequiredFile(petId,inputStream, fileDetail,additionalMetadata,securityContext);
}
 
Example #3
Source File: PetApi.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@POST
@Path("/pet/{petId}/uploadImage")
@Consumes({ "multipart/form-data" })
@Produces({ "application/json" })
@io.swagger.annotations.ApiOperation(value = "uploads an image", notes = "", response = ModelApiResponse.class, authorizations = {
    @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = {
        @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"),
        @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets")
    })
}, tags={ "pet",  })
@io.swagger.annotations.ApiResponses(value = { 
    @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = ModelApiResponse.class) })
public Response uploadFile(
    @ApiParam(value = "ID of pet to update", required = true) @PathParam("petId") @NotNull  Long petId,
    @FormDataParam("additionalMetadata")  String additionalMetadata,
    @FormDataParam("file") InputStream inputStream,
    @FormDataParam("file") FormDataContentDisposition fileDetail,
    @Context SecurityContext securityContext)
throws NotFoundException {
    return delegate.uploadFile(petId,additionalMetadata,inputStream, fileDetail,securityContext);
}
 
Example #4
Source File: PetApi.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@POST
@Path("/fake/{petId}/uploadImageWithRequiredFile")
@Consumes({ "multipart/form-data" })
@Produces({ "application/json" })
@io.swagger.annotations.ApiOperation(value = "uploads an image (required)", notes = "", response = ModelApiResponse.class, authorizations = {
    @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = {
        @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"),
        @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets")
    })
}, tags={ "pet" })
@io.swagger.annotations.ApiResponses(value = { 
    @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = ModelApiResponse.class) })
public Response uploadFileWithRequiredFile(
    @ApiParam(value = "ID of pet to update", required = true) @PathParam("petId") @NotNull  Long petId,
    @FormDataParam("requiredFile") InputStream inputStream,
    @FormDataParam("requiredFile") FormDataContentDisposition fileDetail,
    @FormDataParam("additionalMetadata")  String additionalMetadata,
    @Context SecurityContext securityContext)
throws NotFoundException {
    return delegate.uploadFileWithRequiredFile(petId,inputStream, fileDetail,additionalMetadata,securityContext);
}
 
Example #5
Source File: PetApi.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@POST
@Path("/{petId}/uploadImage")
@Consumes({ "multipart/form-data" })
@Produces({ "application/json" })
@io.swagger.annotations.ApiOperation(value = "uploads an image", notes = "", response = ModelApiResponse.class, authorizations = {
    @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = {
        @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"),
        @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets")
    })
}, tags={ "pet" })
@io.swagger.annotations.ApiResponses(value = { 
    @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = ModelApiResponse.class) })
public Response uploadFile(
    @ApiParam(value = "ID of pet to update", required = true) @PathParam("petId") @NotNull  Long petId,
    @FormDataParam("additionalMetadata")  String additionalMetadata,
    @FormDataParam("file") InputStream inputStream,
    @FormDataParam("file") FormDataContentDisposition fileDetail,
    @Context SecurityContext securityContext)
throws NotFoundException {
    return delegate.uploadFile(petId,additionalMetadata,inputStream, fileDetail,securityContext);
}
 
Example #6
Source File: FileResource.java    From ctsms with GNU Lesser General Public License v2.1 6 votes vote down vote up
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces({ MediaType.APPLICATION_JSON })
public FileOutVO addFile(@FormDataParam("json") FormDataBodyPart json,
		@FormDataParam("data") FormDataBodyPart content,
		@FormDataParam("data") FormDataContentDisposition contentDisposition,
		@FormDataParam("data") final InputStream input) throws AuthenticationException, AuthorisationException, ServiceException {
	// https://stackoverflow.com/questions/27609569/file-upload-along-with-other-object-in-jersey-restful-web-service
	json.setMediaType(MediaType.APPLICATION_JSON_TYPE);
	FileInVO in = json.getValueAs(FileInVO.class);
	FileStreamInVO stream = new FileStreamInVO();
	stream.setStream(input);
	stream.setMimeType(content.getMediaType().toString());
	stream.setSize(contentDisposition.getSize());
	stream.setFileName(contentDisposition.getFileName());
	return WebUtil.getServiceLocator().getFileService().addFile(auth, in, stream);
}
 
Example #7
Source File: FileResource.java    From ctsms with GNU Lesser General Public License v2.1 6 votes vote down vote up
@PUT
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces({ MediaType.APPLICATION_JSON })
public FileOutVO updateFile(@FormDataParam("json") FormDataBodyPart json,
		@FormDataParam("data") FormDataBodyPart content,
		@FormDataParam("data") FormDataContentDisposition contentDisposition,
		@FormDataParam("data") final InputStream input) throws AuthenticationException, AuthorisationException, ServiceException {
	json.setMediaType(MediaType.APPLICATION_JSON_TYPE);
	FileInVO in = json.getValueAs(FileInVO.class);
	FileStreamInVO stream = new FileStreamInVO();
	stream.setStream(input);
	stream.setMimeType(content.getMediaType().toString());
	stream.setSize(contentDisposition.getSize());
	stream.setFileName(contentDisposition.getFileName());
	return WebUtil.getServiceLocator().getFileService().updateFile(auth, in, stream);
}
 
Example #8
Source File: ProbandResource.java    From ctsms with GNU Lesser General Public License v2.1 5 votes vote down vote up
@PUT
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces({ MediaType.APPLICATION_JSON })
public ProbandImageOutVO setProbandImage(@FormDataParam("json") FormDataBodyPart json,
		@FormDataParam("data") FormDataBodyPart content,
		@FormDataParam("data") FormDataContentDisposition contentDisposition,
		@FormDataParam("data") final InputStream input) throws Exception {
	json.setMediaType(MediaType.APPLICATION_JSON_TYPE);
	ProbandImageInVO in = json.getValueAs(ProbandImageInVO.class);
	in.setDatas(CommonUtil.inputStreamToByteArray(input));
	in.setMimeType(content.getMediaType().toString());
	in.setFileName(contentDisposition.getFileName());
	return WebUtil.getServiceLocator().getProbandService().setProbandImage(auth, in);
}
 
Example #9
Source File: InputFieldResource.java    From ctsms with GNU Lesser General Public License v2.1 5 votes vote down vote up
@PUT
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces({ MediaType.APPLICATION_JSON })
public InputFieldOutVO updateInputField(@FormDataParam("json") FormDataBodyPart json,
		@FormDataParam("data") FormDataBodyPart content,
		@FormDataParam("data") FormDataContentDisposition contentDisposition,
		@FormDataParam("data") final InputStream input) throws Exception {
	json.setMediaType(MediaType.APPLICATION_JSON_TYPE);
	InputFieldInVO in = json.getValueAs(InputFieldInVO.class);
	in.setDatas(CommonUtil.inputStreamToByteArray(input));
	in.setMimeType(content.getMediaType().toString());
	in.setFileName(contentDisposition.getFileName());
	return WebUtil.getServiceLocator().getInputFieldService().updateInputField(auth, in);
}
 
Example #10
Source File: FileUploadService.java    From Tutorials with Apache License 2.0 5 votes vote down vote up
/**
    * Returns text response to caller containing current time-stamp
    * @return error response in case of missing parameters an internal exception or
    * success response if file has been stored successfully 
    */
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
   public Response uploadFile(
       @FormDataParam("file") InputStream uploadedInputStream,
       @FormDataParam("file") FormDataContentDisposition fileDetail) {
	
	// check if all form parameters are provided
	if (uploadedInputStream == null || fileDetail == null)
		return Response.status(400).entity("Invalid form data").build();
	
	// create our destination folder, if it not exists
	try {
		createFolderIfNotExists(UPLOAD_FOLDER);
	} catch (SecurityException se) {
		return Response.status(500).entity("Can not create destination folder on server").build();
	}

       String uploadedFileLocation = UPLOAD_FOLDER + fileDetail.getFileName();
       try {
		saveToFile(uploadedInputStream, uploadedFileLocation);
	} catch (IOException e) {
		return Response.status(500).entity("Can not save file").build();
	}

       return Response.status(200).entity("File saved to " + uploadedFileLocation).build();
   }
 
Example #11
Source File: FakeApi.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@POST

@Consumes({ "application/x-www-form-urlencoded" })

@io.swagger.annotations.ApiOperation(value = "Fake endpoint for testing various parameters  假端點  偽のエンドポイント  가짜 엔드 포인트", notes = "Fake endpoint for testing various parameters  假端點  偽のエンドポイント  가짜 엔드 포인트", response = Void.class, authorizations = {
    @io.swagger.annotations.Authorization(value = "http_basic_test")
}, tags={ "fake",  })
@io.swagger.annotations.ApiResponses(value = { 
    @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid username supplied", response = Void.class),
    @io.swagger.annotations.ApiResponse(code = 404, message = "User not found", response = Void.class) })
public Response testEndpointParameters(
    @ApiParam(value = "None", required=true)  @FormParam("number")  BigDecimal number,
    @ApiParam(value = "None", required=true)  @FormParam("double")  Double _double,
    @ApiParam(value = "None", required=true)  @FormParam("pattern_without_delimiter")  String patternWithoutDelimiter,
    @ApiParam(value = "None", required=true)  @FormParam("byte")  byte[] _byte,
    @ApiParam(value = "None")  @FormParam("integer")  Integer integer,
    @ApiParam(value = "None")  @FormParam("int32")  Integer int32,
    @ApiParam(value = "None")  @FormParam("int64")  Long int64,
    @ApiParam(value = "None")  @FormParam("float")  Float _float,
    @ApiParam(value = "None")  @FormParam("string")  String string,
    @FormDataParam("binary") InputStream inputStream,
    @FormDataParam("binary") FormDataContentDisposition fileDetail,
    @ApiParam(value = "None")  @FormParam("date")  Date date,
    @ApiParam(value = "None")  @FormParam("dateTime")  Date dateTime,
    @ApiParam(value = "None")  @FormParam("password")  String password,
    @ApiParam(value = "None")  @FormParam("callback")  String paramCallback,
    @Context SecurityContext securityContext)
throws NotFoundException {
    return delegate.testEndpointParameters(number,_double,patternWithoutDelimiter,_byte,integer,int32,int64,_float,string,inputStream, fileDetail,date,dateTime,password,paramCallback,securityContext);
}
 
Example #12
Source File: JobResource.java    From ctsms with GNU Lesser General Public License v2.1 5 votes vote down vote up
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces({ MediaType.APPLICATION_JSON })
public JobOutVO addJob(@FormDataParam("json") FormDataBodyPart json,
		@FormDataParam("data") FormDataBodyPart content,
		@FormDataParam("data") FormDataContentDisposition contentDisposition,
		@FormDataParam("data") final InputStream input) throws Exception {
	json.setMediaType(MediaType.APPLICATION_JSON_TYPE);
	JobAddVO in = json.getValueAs(JobAddVO.class);
	in.setDatas(CommonUtil.inputStreamToByteArray(input));
	in.setMimeType(content.getMediaType().toString());
	in.setFileName(contentDisposition.getFileName());
	return WebUtil.getServiceLocator().getJobService().addJob(auth, in);
}
 
Example #13
Source File: JobResource.java    From ctsms with GNU Lesser General Public License v2.1 5 votes vote down vote up
@PUT
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces({ MediaType.APPLICATION_JSON })
public JobOutVO updateJob(@FormDataParam("json") FormDataBodyPart json,
		@FormDataParam("data") FormDataBodyPart content,
		@FormDataParam("data") FormDataContentDisposition contentDisposition,
		@FormDataParam("data") final InputStream input) throws Exception {
	//https://stackoverflow.com/questions/27609569/file-upload-along-with-other-object-in-jersey-restful-web-service/27614403
	json.setMediaType(MediaType.APPLICATION_JSON_TYPE);
	JobUpdateVO in = json.getValueAs(JobUpdateVO.class);
	in.setDatas(CommonUtil.inputStreamToByteArray(input));
	in.setMimeType(content.getMediaType().toString());
	in.setFileName(contentDisposition.getFileName());
	return WebUtil.getServiceLocator().getJobService().updateJob(auth, in);
}
 
Example #14
Source File: StaffResource.java    From ctsms with GNU Lesser General Public License v2.1 5 votes vote down vote up
@PUT
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces({ MediaType.APPLICATION_JSON })
public StaffImageOutVO setStaffImage(@FormDataParam("json") FormDataBodyPart json,
		@FormDataParam("data") FormDataBodyPart content,
		@FormDataParam("data") FormDataContentDisposition contentDisposition,
		@FormDataParam("data") final InputStream input) throws Exception {
	json.setMediaType(MediaType.APPLICATION_JSON_TYPE);
	StaffImageInVO in = json.getValueAs(StaffImageInVO.class);
	in.setDatas(CommonUtil.inputStreamToByteArray(input));
	in.setMimeType(content.getMediaType().toString());
	in.setFileName(contentDisposition.getFileName());
	return WebUtil.getServiceLocator().getStaffService().setStaffImage(auth, in);
}
 
Example #15
Source File: FakeApi.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@POST

@Consumes({ "application/x-www-form-urlencoded" })

@io.swagger.annotations.ApiOperation(value = "Fake endpoint for testing various parameters  假端點  偽のエンドポイント  가짜 엔드 포인트", notes = "Fake endpoint for testing various parameters  假端點  偽のエンドポイント  가짜 엔드 포인트", response = Void.class, authorizations = {
    @io.swagger.annotations.Authorization(value = "http_basic_test")
}, tags={ "fake",  })
@io.swagger.annotations.ApiResponses(value = { 
    @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid username supplied", response = Void.class),
    @io.swagger.annotations.ApiResponse(code = 404, message = "User not found", response = Void.class) })
public Response testEndpointParameters(
    @ApiParam(value = "None", required=true)  @FormParam("number")  BigDecimal number,
    @ApiParam(value = "None", required=true)  @FormParam("double")  Double _double,
    @ApiParam(value = "None", required=true)  @FormParam("pattern_without_delimiter")  String patternWithoutDelimiter,
    @ApiParam(value = "None", required=true)  @FormParam("byte")  byte[] _byte,
    @ApiParam(value = "None")  @FormParam("integer")  Integer integer,
    @ApiParam(value = "None")  @FormParam("int32")  Integer int32,
    @ApiParam(value = "None")  @FormParam("int64")  Long int64,
    @ApiParam(value = "None")  @FormParam("float")  Float _float,
    @ApiParam(value = "None")  @FormParam("string")  String string,
    @FormDataParam("binary") InputStream inputStream,
    @FormDataParam("binary") FormDataContentDisposition fileDetail,
    @ApiParam(value = "None")  @FormParam("date")  Date date,
    @ApiParam(value = "None")  @FormParam("dateTime")  Date dateTime,
    @ApiParam(value = "None")  @FormParam("password")  String password,
    @ApiParam(value = "None")  @FormParam("callback")  String paramCallback,
    @Context SecurityContext securityContext)
throws NotFoundException {
    return delegate.testEndpointParameters(number,_double,patternWithoutDelimiter,_byte,integer,int32,int64,_float,string,inputStream, fileDetail,date,dateTime,password,paramCallback,securityContext);
}
 
Example #16
Source File: ManagementResource.java    From roboconf-platform with Apache License 2.0 5 votes vote down vote up
@Override
public Response loadUploadedZippedApplicationTemplate( InputStream uploadedInputStream, FormDataContentDisposition fileDetail ) {

	this.logger.fine( "Request: load application from an uploaded ZIP file (" + fileDetail.getFileName() + ")." );
	File tempZipFile = new File( System.getProperty( "java.io.tmpdir" ), fileDetail.getFileName());
	Response response;
	try {
		// Copy the uploaded ZIP file on the disk
		Utils.copyStream( uploadedInputStream, tempZipFile );

		// Load the application
		response = loadZippedApplicationTemplate( tempZipFile.toURI().toURL().toString());

	} catch( IOException e ) {
		response = handleError(
				Status.NOT_ACCEPTABLE,
				new RestError( REST_MNGMT_ZIP_ERROR, e ),
				lang( this.manager )).build();

	} finally {
		Utils.closeQuietly( uploadedInputStream );

		// We do not need the uploaded file anymore.
		// In case of success, it was copied in the DM's configuration.
		Utils.deleteFilesRecursivelyAndQuietly( tempZipFile );
	}

	return response;
}
 
Example #17
Source File: ManagementResourceImageTest.java    From roboconf-platform with Apache License 2.0 5 votes vote down vote up
private Response setImage( final String name, final String qualifier, final File image ) throws IOException {

		try (final InputStream stream = new FileInputStream(image)) {
			return this.resource.setImage(
					name, qualifier, stream,
					FormDataContentDisposition
							.name(image.getName())
							.fileName(image.getName())
							.size(image.length())
							.build());
		}
	}
 
Example #18
Source File: JCRSolutionDirectFileModel.java    From pentaho-reporting with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void setData( final FileName fullName, final byte[] data ) throws FileSystemException {
  /*
  /api/repo/files/import
  public Response doPostImport(
    @FormDataParam("importDir") String uploadDir,
    @FormDataParam("fileUpload") InputStream fileIS,
    @FormDataParam("overwriteFile") String overwriteFile,
    @FormDataParam("overwriteAclPermissions") String overwriteAclPermissions,
    @FormDataParam("applyAclPermissions") String applyAclPermission,
    @FormDataParam("retainOwnership") String retainOwnership,
    @FormDataParam("charSet") String charSet,
    @FormDataParam("logLevel") String logLevel,
    @FormDataParam("fileUpload") FormDataContentDisposition fileInfo,
    @FormDataParam("fileNameOverried) String fileNameOveride )
  */
  logger.debug( "setData: " + fullName );

  final String name = fullName.getBaseName();
  final String parent = fullName.getParent().getPath();
  final ByteArrayInputStream stream = new ByteArrayInputStream( data );
  final FormDataContentDisposition fd = FormDataContentDisposition
    .name( name )
    .fileName( name )
    .build();
  Response response =
    this.importRes.doPostImport( parent, stream, "true", null, "true", "true", null, "WARN", fd, null );
  throwExceptionOnBadResponse( response );
}
 
Example #19
Source File: InputFieldResource.java    From ctsms with GNU Lesser General Public License v2.1 5 votes vote down vote up
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces({ MediaType.APPLICATION_JSON })
public InputFieldOutVO addInputField(@FormDataParam("json") FormDataBodyPart json,
		@FormDataParam("data") FormDataBodyPart content,
		@FormDataParam("data") FormDataContentDisposition contentDisposition,
		@FormDataParam("data") final InputStream input) throws Exception {
	json.setMediaType(MediaType.APPLICATION_JSON_TYPE);
	InputFieldInVO in = json.getValueAs(InputFieldInVO.class);
	in.setDatas(CommonUtil.inputStreamToByteArray(input));
	in.setMimeType(content.getMediaType().toString());
	in.setFileName(contentDisposition.getFileName());
	return WebUtil.getServiceLocator().getInputFieldService().addInputField(auth, in);
}
 
Example #20
Source File: GenericEntityServiceResource.java    From Eagle with Apache License 2.0 4 votes vote down vote up
@PUT
@Consumes({MediaType.MULTIPART_FORM_DATA})
@Produces(MediaType.APPLICATION_JSON)
public GenericServiceAPIResponseEntity update(@FormDataParam("file") InputStream fileInputStream,
                                              @FormDataParam("file") FormDataContentDisposition cdh,
                                              @QueryParam("serviceName") String serviceName){
    GenericServiceAPIResponseEntity<String> response = new GenericServiceAPIResponseEntity<String>();
    DataStorage dataStorage;
    Map<String,Object> meta = new HashMap<>();
    StopWatch stopWatch = new StopWatch();
    try {
        stopWatch.start();
        EntityDefinition entityDefinition = EntityDefinitionManager.getEntityByServiceName(serviceName);

        if(entityDefinition == null){
            throw new IllegalArgumentException("entity definition of service "+serviceName+" not found");
        }

        List<? extends TaggedLogAPIEntity> entities = unmarshalEntitiesByServie(fileInputStream, entityDefinition);
        dataStorage = DataStorageManager.getDataStorageByEagleConfig();

        UpdateStatement updateStatement = new UpdateStatement(entities,entityDefinition);
        ModifyResult<String> result = updateStatement.execute(dataStorage);
        if(result.isSuccess()) {
            List<String> keys =result.getIdentifiers();
            if(keys != null) {
                response.setObj(keys, String.class);
                meta.put(TOTAL_RESULTS,keys.size());
            }else{
                meta.put(TOTAL_RESULTS,0);
            }
            meta.put(ELAPSEDMS,stopWatch.getTime());
            response.setMeta(meta);
            response.setSuccess(true);
        }
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
        response.setException(e);
    } finally {
        stopWatch.stop();
    }
    return response;
}
 
Example #21
Source File: GenericEntityServiceResource.java    From Eagle with Apache License 2.0 4 votes vote down vote up
@POST
@Consumes({MediaType.MULTIPART_FORM_DATA})
@Produces(MediaType.APPLICATION_JSON)
public GenericServiceAPIResponseEntity create(@FormDataParam("file") InputStream fileInputStream,
                                              @FormDataParam("file") FormDataContentDisposition cdh,
                                              @QueryParam("serviceName") String serviceName) {
    GenericServiceAPIResponseEntity<String> response = new GenericServiceAPIResponseEntity<String>();
    Map<String,Object> meta = new HashMap<>();
    StopWatch stopWatch = new StopWatch();
    try {
        stopWatch.start();
        EntityDefinition entityDefinition = EntityDefinitionManager.getEntityByServiceName(serviceName);

        if(entityDefinition == null){
            throw new IllegalArgumentException("entity definition of service "+serviceName+" not found");
        }

        List<? extends TaggedLogAPIEntity> entities = unmarshalEntitiesByServie(fileInputStream, entityDefinition);
        DataStorage dataStorage = DataStorageManager.getDataStorageByEagleConfig();
        CreateStatement createStatement = new CreateStatement(entities,entityDefinition);
        ModifyResult<String> result = createStatement.execute(dataStorage);
        if(result.isSuccess()) {
            List<String> keys =result.getIdentifiers();
            if(keys != null) {
                response.setObj(keys, String.class);
                response.setObj(keys, String.class);
                meta.put(TOTAL_RESULTS,keys.size());
            }else{
                meta.put(TOTAL_RESULTS,0);
            }
            meta.put(ELAPSEDMS,stopWatch.getTime());
            response.setMeta(meta);
            response.setSuccess(true);
        }
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
        response.setException(e);
    }finally {
        stopWatch.stop();
    }
    return response;
}
 
Example #22
Source File: BeanParamInjectParamExtension.java    From swagger-maven-plugin with Apache License 2.0 4 votes vote down vote up
@Override
public boolean shouldIgnoreClass(Class<?> cls) {
    return FormDataContentDisposition.class.equals(cls);
}
 
Example #23
Source File: GenericEntityServiceResource.java    From eagle with Apache License 2.0 4 votes vote down vote up
@POST
@Consumes({MediaType.MULTIPART_FORM_DATA})
@Produces(MediaType.APPLICATION_JSON)
public GenericServiceAPIResponseEntity create(@FormDataParam("file") InputStream fileInputStream,
                                              @FormDataParam("file") FormDataContentDisposition cdh,
                                              @QueryParam("serviceName") String serviceName) {
    GenericServiceAPIResponseEntity<String> response = new GenericServiceAPIResponseEntity<String>();
    Map<String,Object> meta = new HashMap<>();
    StopWatch stopWatch = new StopWatch();
    try {
        stopWatch.start();
        EntityDefinition entityDefinition = EntityDefinitionManager.getEntityByServiceName(serviceName);

        if(entityDefinition == null){
            throw new IllegalArgumentException("entity definition of service "+serviceName+" not found");
        }

        List<? extends TaggedLogAPIEntity> entities = unmarshalEntitiesByServie(fileInputStream, entityDefinition);
        DataStorage dataStorage = DataStorageManager.getDataStorageByEagleConfig();
        CreateStatement createStatement = new CreateStatement(entities,entityDefinition);
        ModifyResult<String> result = createStatement.execute(dataStorage);
        if(result.isSuccess()) {
            List<String> keys =result.getIdentifiers();
            if(keys != null) {
                response.setObj(keys, String.class);
                response.setObj(keys, String.class);
                meta.put(TOTAL_RESULTS,keys.size());
            }else{
                meta.put(TOTAL_RESULTS,0);
            }
            meta.put(ELAPSEDMS,stopWatch.getTime());
            response.setMeta(meta);
            response.setSuccess(true);
        }
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
        response.setException(e);
    }finally {
        stopWatch.stop();
    }
    return response;
}
 
Example #24
Source File: GenericEntityServiceResource.java    From eagle with Apache License 2.0 4 votes vote down vote up
@PUT
@Consumes({MediaType.MULTIPART_FORM_DATA})
@Produces(MediaType.APPLICATION_JSON)
public GenericServiceAPIResponseEntity update(@FormDataParam("file") InputStream fileInputStream,
                                              @FormDataParam("file") FormDataContentDisposition cdh,
                                              @QueryParam("serviceName") String serviceName){
    GenericServiceAPIResponseEntity<String> response = new GenericServiceAPIResponseEntity<String>();
    DataStorage dataStorage;
    Map<String,Object> meta = new HashMap<>();
    StopWatch stopWatch = new StopWatch();
    try {
        stopWatch.start();
        EntityDefinition entityDefinition = EntityDefinitionManager.getEntityByServiceName(serviceName);

        if(entityDefinition == null){
            throw new IllegalArgumentException("entity definition of service "+serviceName+" not found");
        }

        List<? extends TaggedLogAPIEntity> entities = unmarshalEntitiesByServie(fileInputStream, entityDefinition);
        dataStorage = DataStorageManager.getDataStorageByEagleConfig();

        UpdateStatement updateStatement = new UpdateStatement(entities,entityDefinition);
        ModifyResult<String> result = updateStatement.execute(dataStorage);
        if(result.isSuccess()) {
            List<String> keys =result.getIdentifiers();
            if(keys != null) {
                response.setObj(keys, String.class);
                meta.put(TOTAL_RESULTS,keys.size());
            }else{
                meta.put(TOTAL_RESULTS,0);
            }
            meta.put(ELAPSEDMS,stopWatch.getTime());
            response.setMeta(meta);
            response.setSuccess(true);
        }
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
        response.setException(e);
    } finally {
        stopWatch.stop();
    }
    return response;
}
 
Example #25
Source File: TestServiceREST.java    From ranger with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void test49importPoliciesFromFileAllowingOverride() throws Exception {
	HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
	RangerPolicyValidator policyValidator = Mockito.mock(RangerPolicyValidator.class) ;
	Map<String, RangerPolicy> policiesMap = new LinkedHashMap<String, RangerPolicy>();
	RangerPolicy rangerPolicy = rangerPolicy();
	RangerService service = rangerService();
	XXService xService = xService();
	policiesMap.put("Name", rangerPolicy);
	XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class);
	XXServiceDef xServiceDef = serviceDef();
	XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class);
	XXSecurityZoneRefServiceDao xSecZoneRefServiceDao = Mockito.mock(XXSecurityZoneRefServiceDao.class);
	XXSecurityZoneRefTagServiceDao xSecZoneRefTagServiceDao = Mockito.mock(XXSecurityZoneRefTagServiceDao.class);
	XXSecurityZoneRefService xSecZoneRefService = Mockito.mock(XXSecurityZoneRefService.class);
	XXSecurityZoneRefTagService xSecZoneRefTagService = Mockito.mock(XXSecurityZoneRefTagService.class);
	XXSecurityZoneDao xSecZoneDao = Mockito.mock(XXSecurityZoneDao.class);
	XXSecurityZone xSecZone = Mockito.mock(XXSecurityZone.class);
	List<XXSecurityZoneRefService> zoneServiceList = new ArrayList<>();
	List<XXSecurityZoneRefTagService> zoneTagServiceList = new ArrayList<>();
	zoneServiceList.add(xSecZoneRefService);
	zoneTagServiceList.add(xSecZoneRefTagService);
	Map<String, String> zoneMappingMap = new LinkedHashMap<String, String>();
	zoneMappingMap.put("ZoneSource", "ZoneDestination");

	String PARAM_SERVICE_TYPE = "serviceType";
	String serviceTypeList = "hdfs,hbase,hive,yarn,knox,storm,solr,kafka,nifi,atlas,sqoop";
	request.setAttribute("serviceType", "hdfs,hbase,hive,yarn,knox,storm,solr,kafka,nifi,atlas,sqoop");
	SearchFilter filter = new SearchFilter();
	filter.setParam("serviceType", "value");

	File jsonPolicyFile = new File(importPoliceTestFilePath);
	InputStream uploadedInputStream = new FileInputStream(jsonPolicyFile);
	FormDataContentDisposition fileDetail = FormDataContentDisposition.name("file")
			.fileName(jsonPolicyFile.getName()).size(uploadedInputStream.toString().length()).build();
	boolean isOverride = true;

	InputStream zoneInputStream =IOUtils.toInputStream("ZoneSource=ZoneDestination", "UTF-8");

	Mockito.when(searchUtil.getSearchFilter(request, policyService.sortFields)).thenReturn(filter);
	Mockito.when(request.getParameter(PARAM_SERVICE_TYPE)).thenReturn(serviceTypeList);
	Mockito.when(svcStore.createPolicyMap(Mockito.any(Map.class), Mockito.any(List.class),Mockito.anyString(),Mockito.any(Map.class), Mockito.any(List.class), Mockito.any(List.class),
			Mockito.any(RangerPolicy.class), Mockito.any(Map.class))).thenReturn(policiesMap);
	Mockito.when(validatorFactory.getPolicyValidator(svcStore)).thenReturn(policyValidator);
	Mockito.when(bizUtil.isAdmin()).thenReturn(true);
	Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao);

	Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao);

	Mockito.when(daoManager.getXXService().findByName("HDFS_1-1-20150316062453")).thenReturn(xService);
	Mockito.when(daoManager.getXXServiceDef().getById(xService.getType())).thenReturn(xServiceDef);
	Mockito.when(validatorFactory.getPolicyValidator(svcStore)).thenReturn(policyValidator);
	Mockito.when(svcStore.getMapFromInputStream(zoneInputStream)).thenReturn(zoneMappingMap);
	Mockito.when(daoManager.getXXSecurityZoneDao()).thenReturn(xSecZoneDao);
	Mockito.when(xSecZoneDao.findByZoneName(Mockito.anyString())).thenReturn(xSecZone);
	Mockito.when(daoManager.getXXSecurityZoneRefService()).thenReturn(xSecZoneRefServiceDao);
	Mockito.when(xSecZoneRefServiceDao.findByServiceNameAndZoneId(Mockito.anyString(),Mockito.anyLong())).thenReturn(zoneServiceList);
	Mockito.when(daoManager.getXXSecurityZoneRefTagService()).thenReturn(xSecZoneRefTagServiceDao);
	Mockito.when(xSecZoneRefTagServiceDao.findByTagServiceNameAndZoneId(Mockito.anyString(),Mockito.anyLong())).thenReturn(zoneTagServiceList);
	Mockito.when(svcStore.getServiceByName(Mockito.anyString())).thenReturn(service);
	serviceREST.importPoliciesFromFile(request, null, zoneInputStream, uploadedInputStream, fileDetail, isOverride , "unzoneToZone");

	Mockito.verify(svcStore).createPolicy(rangerPolicy);

}
 
Example #26
Source File: TestServiceREST.java    From ranger with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void test50importPoliciesFromFileNotAllowingOverride() throws Exception {
	HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
	Map<String, RangerPolicy> policiesMap = new LinkedHashMap<String, RangerPolicy>();
	RangerPolicy rangerPolicy = rangerPolicy();
	XXService xService = xService();
	policiesMap.put("Name", rangerPolicy);
	XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class);
	XXServiceDef xServiceDef = serviceDef();
	XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class);
	XXSecurityZoneRefServiceDao xSecZoneRefServiceDao = Mockito.mock(XXSecurityZoneRefServiceDao.class);
	XXSecurityZoneRefTagServiceDao xSecZoneRefTagServiceDao = Mockito.mock(XXSecurityZoneRefTagServiceDao.class);
	XXSecurityZoneRefService xSecZoneRefService = Mockito.mock(XXSecurityZoneRefService.class);
	XXSecurityZoneRefTagService xSecZoneRefTagService = Mockito.mock(XXSecurityZoneRefTagService.class);
	XXSecurityZoneDao xSecZoneDao = Mockito.mock(XXSecurityZoneDao.class);
	XXSecurityZone xSecZone = Mockito.mock(XXSecurityZone.class);
	List<XXSecurityZoneRefService> zoneServiceList = new ArrayList<>();
	List<XXSecurityZoneRefTagService> zoneTagServiceList = new ArrayList<>();
	zoneServiceList.add(xSecZoneRefService);
	zoneTagServiceList.add(xSecZoneRefTagService);
	Map<String, String> zoneMappingMap = new LinkedHashMap<String, String>();
	zoneMappingMap.put("ZoneSource", "ZoneDestination");

	String PARAM_SERVICE_TYPE = "serviceType";
	String serviceTypeList = "hdfs,hbase,hive,yarn,knox,storm,solr,kafka,nifi,atlas,sqoop";
	request.setAttribute("serviceType", "hdfs,hbase,hive,yarn,knox,storm,solr,kafka,nifi,atlas,sqoop");
	SearchFilter filter = new SearchFilter();
	filter.setParam("serviceType", "value");

	File jsonPolicyFile = new File(importPoliceTestFilePath);
	InputStream uploadedInputStream = new FileInputStream(jsonPolicyFile);
	FormDataContentDisposition fileDetail = FormDataContentDisposition.name("file")
			.fileName(jsonPolicyFile.getName()).size(uploadedInputStream.toString().length()).build();
	boolean isOverride = false;

	InputStream zoneInputStream = IOUtils.toInputStream("ZoneSource=ZoneDestination", "UTF-8");

	Mockito.when(searchUtil.getSearchFilter(request, policyService.sortFields)).thenReturn(filter);
	Mockito.when(request.getParameter(PARAM_SERVICE_TYPE)).thenReturn(serviceTypeList);
	Mockito.when(svcStore.createPolicyMap(Mockito.any(Map.class), Mockito.any(List.class),Mockito.anyString(),Mockito.any(Map.class), Mockito.any(List.class), Mockito.any(List.class),
			Mockito.any(RangerPolicy.class), Mockito.any(Map.class))).thenReturn(policiesMap);
	Mockito.when(validatorFactory.getPolicyValidator(svcStore)).thenReturn(policyValidator);
	Mockito.when(bizUtil.isAdmin()).thenReturn(true);
	Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao);

	Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao);

	Mockito.when(daoManager.getXXService().findByName("HDFS_1-1-20150316062453")).thenReturn(xService);
	Mockito.when(daoManager.getXXServiceDef().getById(xService.getType())).thenReturn(xServiceDef);

	Mockito.when(svcStore.getMapFromInputStream(zoneInputStream)).thenReturn(zoneMappingMap);
	Mockito.when(daoManager.getXXSecurityZoneDao()).thenReturn(xSecZoneDao);
	Mockito.when(xSecZoneDao.findByZoneName(Mockito.anyString())).thenReturn(xSecZone);
	Mockito.when(daoManager.getXXSecurityZoneRefService()).thenReturn(xSecZoneRefServiceDao);
	Mockito.when(xSecZoneRefServiceDao.findByServiceNameAndZoneId(Mockito.anyString(),Mockito.anyLong())).thenReturn(zoneServiceList);
	Mockito.when(daoManager.getXXSecurityZoneRefTagService()).thenReturn(xSecZoneRefTagServiceDao);
	Mockito.when(xSecZoneRefTagServiceDao.findByTagServiceNameAndZoneId(Mockito.anyString(),Mockito.anyLong())).thenReturn(zoneTagServiceList);
	serviceREST.importPoliciesFromFile(request, null, zoneInputStream, uploadedInputStream, fileDetail, isOverride, "unzoneToUnZone");
	Mockito.verify(svcStore).createPolicy(rangerPolicy);

}
 
Example #27
Source File: PetApiServiceImpl.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
@Override
public Response uploadFile(Long petId, String additionalMetadata, InputStream fileInputStream, FormDataContentDisposition fileDetail, SecurityContext securityContext)
throws NotFoundException {
    // do some magic!
    return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build();
}
 
Example #28
Source File: PetApiService.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
public abstract Response uploadFile(Long petId,String additionalMetadata,InputStream fileInputStream, FormDataContentDisposition fileDetail,SecurityContext securityContext)
throws NotFoundException;
 
Example #29
Source File: FakeApiService.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
public abstract Response uploadFileWithRequiredFile(Long petId,InputStream requiredFileInputStream, FormDataContentDisposition requiredFileDetail,String additionalMetadata,SecurityContext securityContext)
throws NotFoundException;
 
Example #30
Source File: FakeApiService.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
public abstract Response testEndpointParameters(BigDecimal number,Double _double,String patternWithoutDelimiter,byte[] _byte,Integer integer,Integer int32,Long int64,Float _float,String string,InputStream binaryInputStream, FormDataContentDisposition binaryDetail,Date date,Date dateTime,String password,String paramCallback,SecurityContext securityContext)
throws NotFoundException;