org.apache.cxf.jaxrs.ext.multipart.Attachment Java Examples

The following examples show how to use org.apache.cxf.jaxrs.ext.multipart.Attachment. 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: ApisApi.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@POST
@Path("/validate-wsdl")
@Consumes({ "multipart/form-data" })
@Produces({ "application/json" })
@ApiOperation(value = "Validate a WSDL Definition", notes = "This operation can be used to validate a WSDL definition and retrieve a summary. Provide either `url` or `file` to specify the definition. ", response = WSDLValidationResponseDTO.class, authorizations = {
    @Authorization(value = "OAuth2Security", scopes = {
        @AuthorizationScope(scope = "apim:api_create", description = "Create API")
    })
}, tags={ "Validation" })
@ApiResponses(value = { 
    @ApiResponse(code = 200, message = "OK. API definition validation information is returned ", response = WSDLValidationResponseDTO.class),
    @ApiResponse(code = 400, message = "Bad Request. Invalid request or validation error. ", response = ErrorDTO.class),
    @ApiResponse(code = 404, message = "Not Found. Workflow for the given reference in not found. ", response = ErrorDTO.class) })
public Response validateWSDLDefinition(@Multipart(value = "url", required = false)  String url,  @Multipart(value = "file", required = false) InputStream fileInputStream, @Multipart(value = "file" , required = false) Attachment fileDetail) throws APIManagementException{
    return delegate.validateWSDLDefinition(url, fileInputStream, fileDetail, securityContext);
}
 
Example #2
Source File: MediaServiceRestImplTest.java    From jwala with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateMedia() throws IOException {
    List<Attachment> attachments = new ArrayList<>();
    InputStream inputStream = mock(InputStream.class);
    Attachment attachment = mock(Attachment.class);
    DataHandler dataHandler = mock(DataHandler.class);
    when(attachment.getDataHandler()).thenReturn(dataHandler);
    when(dataHandler.getName()).thenReturn("mockString");
    when(dataHandler.getInputStream()).thenReturn(inputStream);
    MultivaluedMap<String, String> multimap = mock(MultivaluedMap.class);
    when(multimap.size()).thenReturn(2);
    when(attachment.getHeaders()).thenReturn(multimap);

    attachments.add(attachment);
    Response response = mediaServiceRest.createMedia(attachments);
    assertEquals(Response.Status.CREATED.getStatusCode(), response.getStatus());

}
 
Example #3
Source File: ScriptLibrariesApi.java    From identity-api-server with Apache License 2.0 6 votes vote down vote up
@Valid
@PUT
@Path("/{script-library-name}")
@Consumes({"multipart/form-data"})
@Produces({"application/json"})
@ApiOperation(value = "Update a script library. ", notes = "This API provides the capability to Update a script library of an script library by using name. ", response = Void.class, tags = {
        "Script Libraries"})
@ApiResponses(value = {
        @ApiResponse(code = 200, message = "Successfully Updated", response = Void.class),
        @ApiResponse(code = 400, message = "Bad Request", response = Error.class),
        @ApiResponse(code = 401, message = "Unauthorized", response = Error.class),
        @ApiResponse(code = 403, message = "Forbidden", response = Error.class),
        @ApiResponse(code = 404, message = "Not Found", response = Error.class),
        @ApiResponse(code = 500, message = "Server Error", response = Error.class)
})
public Response updateScriptLibrary(
        @ApiParam(value = "Name of the script library", required = true) @PathParam("script-library-name") String scriptLibraryName,
        @Multipart(value = "content") InputStream contentInputStream,
        @Multipart(value = "content") Attachment contentDetail,
        @Multipart(value = "description", required = false) String description) {

    return delegate.updateScriptLibrary(scriptLibraryName, contentInputStream, contentDetail, description);
}
 
Example #4
Source File: ApplicationsApi.java    From identity-api-server with Apache License 2.0 6 votes vote down vote up
@Valid
@POST
@Path("/import")
@Consumes({ "multipart/form-data" })
@Produces({ "application/json" })
@ApiOperation(value = "Create application from an exported XML file ", notes = "This API provides the capability to store the application information, provided as a file.<br>   <b>Permission required:</b> <br>       * /permission/admin/manage/identity/applicationmgt/create <br>   <b>Scope required:</b> <br>       * internal_application_mgt_create ", response = Void.class, authorizations = {
    @Authorization(value = "BasicAuth"),
    @Authorization(value = "OAuth2", scopes = {
        
    })
}, tags={ "Applications", })
@ApiResponses(value = { 
    @ApiResponse(code = 201, message = "Successfully created.", response = Void.class),
    @ApiResponse(code = 400, message = "Bad Request", response = Error.class),
    @ApiResponse(code = 401, message = "Unauthorized", response = Void.class),
    @ApiResponse(code = 403, message = "Forbidden", response = Void.class),
    @ApiResponse(code = 409, message = "Conflict", response = Error.class),
    @ApiResponse(code = 500, message = "Server Error", response = Error.class)
})
public Response importApplication( @Multipart(value = "file", required = false) InputStream fileInputStream, @Multipart(value = "file" , required = false) Attachment fileDetail) {

    return delegate.importApplication(fileInputStream, fileDetail );
}
 
Example #5
Source File: TenantThemeApi.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@POST
@Path("/import")
@Consumes({ "multipart/form-data" })
@Produces({ "application/json" })
@ApiOperation(value = "Import a DevPortal Tenant Theme", notes = "This operation can be used to import a DevPortal tenant theme. ", response = Void.class, authorizations = {
    @Authorization(value = "OAuth2Security", scopes = {
        @AuthorizationScope(scope = "apim:tenant_theme_manage", description = "Manage tenant themes"),
        @AuthorizationScope(scope = "apim:admin", description = "Manage all admin operations")
    })
}, tags={  })
@ApiResponses(value = { 
    @ApiResponse(code = 200, message = "Ok. Theme Imported Successfully. ", response = Void.class),
    @ApiResponse(code = 403, message = "Forbidden. Not Authorized to import. ", response = ErrorDTO.class),
    @ApiResponse(code = 500, message = "Internal Server Error. Error in importing Theme. ", response = ErrorDTO.class) })
public Response tenantThemeImportPost( @Multipart(value = "file") InputStream fileInputStream, @Multipart(value = "file" ) Attachment fileDetail) throws APIManagementException{
    return delegate.tenantThemeImportPost(fileInputStream, fileDetail, securityContext);
}
 
Example #6
Source File: UploadArtifactsTest.java    From archiva with Apache License 2.0 6 votes vote down vote up
@Test
public void saveFile() throws IOException, ArchivaRestServiceException {
    log.debug("Starting saveFile()");

    Path path = Paths.get("target/appserver-base/repositories/internal/org/apache/archiva/archiva-model/1.2/archiva-model-1.2.jar");
    log.debug("Jar exists: {}",Files.exists(path));
    Files.deleteIfExists(path);
    path = Paths.get("target/appserver-base/repositories/internal/org/apache/archiva/archiva-model/1.2/archiva-model-1.2.pom");
    Files.deleteIfExists(path);
    FileUploadService service = getUploadService();
    service.clearUploadedFiles();
    Path file = getProjectDirectory().resolve("src/test/repositories/snapshot-repo/org/apache/archiva/archiva-model/1.4-M4-SNAPSHOT/archiva-model-1.4-M4-20130425.081822-1.jar");
    log.debug("Upload file exists: {}", Files.exists(file));
    final Attachment fileAttachment = new AttachmentBuilder().object(Files.newInputStream(file)).contentDisposition(new ContentDisposition("form-data; filename=\"archiva-model.jar\"; name=\"files[]\"")).build();
    MultipartBody body = new MultipartBody(fileAttachment);
    service.post(body);
    service.save("internal", "org.apache.archiva", "archiva-model", "1.2", "jar", true);
}
 
Example #7
Source File: ResourceServiceRestImplTest.java    From jwala with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateExternalPropertiesResource() throws IOException {

    Attachment extPropMockAttachment = mock(Attachment.class);
    DataHandler extPropMockDataHandler = mock(DataHandler.class);
    when(extPropMockAttachment.getDataHandler()).thenReturn(extPropMockDataHandler);
    when(extPropMockAttachment.getHeader(eq("Content-Type"))).thenReturn("application/octet-stream");
    when(extPropMockDataHandler.getName()).thenReturn("ext.properties.tpl");
    when(extPropMockDataHandler.getInputStream()).thenReturn(new ByteArrayInputStream("key=value".getBytes()));

    CreateResourceParam createExtPropertiesParam = new CreateResourceParam();
    Response response = cut.createResource("ext.properties", createExtPropertiesParam, Arrays.asList(extPropMockAttachment));

    assertNotNull(response);
    assertEquals("0", ((ApplicationResponse) response.getEntity()).getMsgCode());
}
 
Example #8
Source File: ImportApi.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@POST
@Path("/api")
@Consumes({ "multipart/form-data" })
@Produces({ "application/json" })
@ApiOperation(value = "Import an API", notes = "This operation can be used to import an API. ", response = Void.class, authorizations = {
    @Authorization(value = "OAuth2Security", scopes = {
        @AuthorizationScope(scope = "apim:admin", description = "Manage all admin operations"),
        @AuthorizationScope(scope = "apim:api_import_export", description = "Import and export APIs related operations")
    })
}, tags={ "API (Individual)",  })
@ApiResponses(value = { 
    @ApiResponse(code = 200, message = "Created. API Imported Successfully. ", response = Void.class),
    @ApiResponse(code = 403, message = "Forbidden Not Authorized to import. ", response = ErrorDTO.class),
    @ApiResponse(code = 404, message = "Not Found. Requested API to update not found. ", response = ErrorDTO.class),
    @ApiResponse(code = 409, message = "Conflict. API to import already exists. ", response = ErrorDTO.class),
    @ApiResponse(code = 500, message = "Internal Server Error. Error in importing API. ", response = ErrorDTO.class) })
public Response importApiPost( @Multipart(value = "file") InputStream fileInputStream, @Multipart(value = "file" ) Attachment fileDetail,  @ApiParam(value = "Preserve Original Provider of the API. This is the user choice to keep or replace the API provider. ")  @QueryParam("preserveProvider") Boolean preserveProvider,  @ApiParam(value = "Whether to update the API or not. This is used when updating already existing APIs. ")  @QueryParam("overwrite") Boolean overwrite) throws APIManagementException{
    return delegate.importApiPost(fileInputStream, fileDetail, preserveProvider, overwrite, securityContext);
}
 
Example #9
Source File: ResourceServiceRestImplTest.java    From jwala with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateTemplate() throws IOException {
    List<Attachment> attachmentList = new ArrayList<>();
    Attachment json = mock(Attachment.class);
    Attachment tpl = mock(Attachment.class);
    attachmentList.add(json);
    attachmentList.add(tpl);
    DataHandler jsonDataHandler = mock(DataHandler.class);
    DataHandler tplDataHandler = mock(DataHandler.class);
    when(json.getDataHandler()).thenReturn(jsonDataHandler);
    when(tpl.getDataHandler()).thenReturn(tplDataHandler);
    when(jsonDataHandler.getName()).thenReturn("test-target.json");
    when(tplDataHandler.getName()).thenReturn("test-target.tpl");
    String jsonContent = "{}";
    when(jsonDataHandler.getInputStream()).thenReturn(new ByteArrayInputStream(jsonContent.getBytes()));
    String tplContent = "template content";
    when(tplDataHandler.getInputStream()).thenReturn(new ByteArrayInputStream(tplContent.getBytes()));

    when(impl.createTemplate(any(InputStream.class), any(InputStream.class), anyString(), any(User.class))).thenReturn(new CreateResourceResponseWrapper(new ConfigTemplate()));
    Response response = cut.createTemplate(attachmentList, "test-target-name", authenticatedUser);

    assertEquals(Response.Status.CREATED.getStatusCode(), response.getStatus());
}
 
Example #10
Source File: PropertyGroupService.java    From document-management-system with GNU General Public License v2.0 6 votes vote down vote up
@POST
@Path("/registerDefinition")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public void registerDefinition(List<Attachment> atts) throws GenericException {
	log.debug("registerDefinition({})", atts);
	InputStream is = null;

	try {
		for (Attachment att : atts) {
			if ("pgDef".equals(att.getContentDisposition().getParameter("name"))) {
				is = att.getDataHandler().getInputStream();
			}
		}

		String pgDef = IOUtils.toString(is);
		PropertyGroupModule cm = ModuleManager.getPropertyGroupModule();
		cm.registerDefinition(null, pgDef);
		log.debug("registerDefinition: void");
	} catch (Exception e) {
		throw new GenericException(e);
	} finally {
		IOUtils.closeQuietly(is);
	}
}
 
Example #11
Source File: FakeApiTest.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
/**
 * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 
 *
 * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 
 *
 * @throws ApiException if the API call fails
 */
@Test
@Ignore
public void testEndpointParametersTest() throws Exception {
    BigDecimal number = cache.getBigDecimal("/testEndpointParameters/number");
    Double _double = cache.getDouble("/testEndpointParameters/_double");
    String patternWithoutDelimiter = cache.getString("/testEndpointParameters/patternWithoutDelimiter");
    byte[] _byte = cache.getBinary("/testEndpointParameters/_byte");
    Integer integer = cache.getInt("/testEndpointParameters/integer");
    Integer int32 = cache.getInt("/testEndpointParameters/int32");
    Long int64 = cache.getLong("/testEndpointParameters/int64");
    Float _float = cache.getFloat("/testEndpointParameters/_float");
    String string = cache.getString("/testEndpointParameters/string");
    Attachment binary = new Attachment("binary", MediaType.TEXT_PLAIN, "Dummy attachment content");
    LocalDate date = cache.getObject("/testEndpointParameters/date", LocalDate.class);
    Date dateTime = cache.getObject("/testEndpointParameters/dateTime", Date.class);
    String password = cache.getString("/testEndpointParameters/password");
    String paramCallback = cache.getString("/testEndpointParameters/paramCallback");
    api.testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback);
}
 
Example #12
Source File: StreamingService.java    From cxf with Apache License 2.0 6 votes vote down vote up
@POST
@Path("/multipart")
@Consumes("multipart/form-data")
@Produces("text/plain")
public void processMultipartStream(@Suspended AsyncResponse async,
                                   @Multipart("file") Attachment att) {
    MediaType mediaType = att.getContentType();
    if (mediaType == null) {
        String fileName = att.getContentDisposition().getFilename();
        if (fileName != null) {
            int extDot = fileName.lastIndexOf('.');
            if (extDot > 0) {
                mediaType = MEDIA_TYPE_TABLE.get(fileName.substring(extDot + 1));
            }
        }
    }

    TikaContentExtractor tika = new TikaContentExtractor();
    TikaContent tikaContent = tika.extract(att.getObject(InputStream.class),
                                           mediaType);
    processStream(async, SparkUtils.getStringsFromString(tikaContent.getContent()));
}
 
Example #13
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 #14
Source File: DossierFileManagement.java    From opencps-v2 with GNU Affero General Public License v3.0 6 votes vote down vote up
@POST
@Path("/{id}/files/{referenceUid}")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces({
	MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON
})
@ApiOperation(value = "update DossierFile", response = String.class)
@ApiResponses(value = {
	@ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns the DossierFileModel was updated", response = DossierFileResultsModel.class),
	@ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized", response = ExceptionModel.class),
	@ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found", response = ExceptionModel.class),
	@ApiResponse(code = HttpURLConnection.HTTP_FORBIDDEN, message = "Access denied", response = ExceptionModel.class)
})
public Response updateDossierFile(
	@Context HttpServletRequest request, @Context HttpHeaders header,
	@Context Company company, @Context Locale locale, @Context User user,
	@Context ServiceContext serviceContext,
	@ApiParam(value = "id of dossier", required = true) @PathParam("id") long id,
	@ApiParam(value = "reference of dossierfile", required = true) @PathParam("referenceUid") String referenceUid,
	@ApiParam(value = "Attachment files", required = true) @Multipart("file") Attachment file);
 
Example #15
Source File: UploadArtifactsTest.java    From archiva with Apache License 2.0 6 votes vote down vote up
@Test
public void saveFileWithOtherExtension() throws IOException, ArchivaRestServiceException {
    log.debug("Starting saveFileWithOtherExtension()");

    Path path = Paths.get("target/appserver-base/repositories/internal/org/apache/archiva/archiva-model/1.2/archiva-model-1.2.bin");
    log.debug("Jar exists: {}",Files.exists(path));
    Files.deleteIfExists(path);
    Path pomPath = Paths.get("target/appserver-base/repositories/internal/org/apache/archiva/archiva-model/1.2/archiva-model-1.2.pom");
    Files.deleteIfExists(pomPath);
    FileUploadService service = getUploadService();
    service.clearUploadedFiles();
    Path file = getProjectDirectory().resolve("src/test/repositories/snapshot-repo/org/apache/archiva/archiva-model/1.4-M4-SNAPSHOT/archiva-model-1.4-M4-20130425.081822-1.jar");
    log.debug("Upload file exists: {}", Files.exists(file));
    final Attachment fileAttachment = new AttachmentBuilder().object(Files.newInputStream(file)).contentDisposition(new ContentDisposition("form-data; filename=\"archiva-model.bin\"; name=\"files[]\"")).build();
    MultipartBody body = new MultipartBody(fileAttachment);
    service.post(body);
    assertTrue(service.save("internal", "org.apache.archiva", "archiva-model", "1.2", "bin", false));
    assertTrue(Files.exists(path));
}
 
Example #16
Source File: ApisApi.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@POST
@Path("/validate-graphql-schema")
@Consumes({ "multipart/form-data" })
@Produces({ "application/json" })
@ApiOperation(value = "Validate GraphQL API definition and retrieve a summary", notes = "This operation can be used to validate a graphQL definition and retrieve a summary. ", response = GraphQLValidationResponseDTO.class, authorizations = {
    @Authorization(value = "OAuth2Security", scopes = {
        @AuthorizationScope(scope = "apim:api_create", description = "Create API")
    })
}, tags={ "Validation",  })
@ApiResponses(value = { 
    @ApiResponse(code = 200, message = "OK. API definition validation information is returned ", response = GraphQLValidationResponseDTO.class),
    @ApiResponse(code = 400, message = "Bad Request. Invalid request or validation error. ", response = ErrorDTO.class),
    @ApiResponse(code = 404, message = "Not Found. Workflow for the given reference in not found. ", response = ErrorDTO.class) })
public Response apisValidateGraphqlSchemaPost( @Multipart(value = "file") InputStream fileInputStream, @Multipart(value = "file" ) Attachment fileDetail) throws APIManagementException{
    return delegate.apisValidateGraphqlSchemaPost(fileInputStream, fileDetail, securityContext);
}
 
Example #17
Source File: PaymentFileManagement.java    From opencps-v2 with GNU Affero General Public License v3.0 6 votes vote down vote up
@PUT
@Path("/{id}/payments/{referenceUid}/confirmfile")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@ApiOperation(value = "upload PaymentFile")
@ApiResponses(value = {
		@ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns"),
		@ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized", response = ExceptionModel.class),
		@ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found", response = ExceptionModel.class),
		@ApiResponse(code = HttpURLConnection.HTTP_FORBIDDEN, message = "Access denied", response = ExceptionModel.class) })
public Response updatePaymentFileConfirm(@Context HttpServletRequest request, @Context HttpHeaders header,
		@Context Company company, @Context Locale locale, @Context User user,
		@Context ServiceContext serviceContext, 
		@ApiParam(value = "id of payments", required = true) @PathParam("id") String id,
		@ApiParam(value = "reference of paymentFile", required = true) @PathParam("referenceUid") String referenceUid,
		@ApiParam(value = "Attachment files") @Multipart("file") Attachment file/*,
		@ApiParam(value = "Metadata of PaymentFile") @Multipart("confirmNote") String confirmNote,
		@ApiParam(value = "Metadata of PaymentFile") @Multipart("paymentMethod") String paymentMethod,
		@ApiParam(value = "Metadata of PaymentFile") @Multipart("confirmPayload") String confirmPayload*/);
 
Example #18
Source File: AttachmentUtils.java    From cxf with Apache License 2.0 6 votes vote down vote up
private static Map<String, Attachment> fromListToMap(List<Attachment> atts,
                                                     boolean preferContentDisposition) {
    Map<String, Attachment> map = new LinkedHashMap<>();
    for (Attachment a : atts) {
        String contentId = null;
        if (preferContentDisposition) {
            ContentDisposition cd = a.getContentDisposition();
            if (cd != null) {
                contentId = cd.getParameter("name");
            }
        }
        if (contentId == null) {
            contentId = a.getContentId();
        }
        map.put(contentId, a);
    }
    return map;
}
 
Example #19
Source File: ImportApi.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@POST
@Path("/applications")
@Consumes({ "multipart/form-data" })
@Produces({ "application/json" })
@io.swagger.annotations.ApiOperation(value = "Import an Application", notes = "This operation can be used to import an Application.\n", response = ApplicationInfoDTO.class)
@io.swagger.annotations.ApiResponses(value = { 
    @io.swagger.annotations.ApiResponse(code = 200, message = "OK.\nSuccessful response with the updated object information as entity in the body.\n"),
    
    @io.swagger.annotations.ApiResponse(code = 207, message = "Multi Status.\nPartially successful response with skipped APIs information object as entity in the body.\n"),
    
    @io.swagger.annotations.ApiResponse(code = 400, message = "Bad Request.\nInvalid request or validation error\n"),
    
    @io.swagger.annotations.ApiResponse(code = 406, message = "Not Acceptable.\nThe requested media type is not supported\n") })

public Response importApplicationsPost(@ApiParam(value = "Zip archive consisting of exported Application Configuration.\n") @Multipart(value = "file") InputStream fileInputStream,
@ApiParam(value = "Zip archive consisting of exported Application Configuration.\n : details") @Multipart(value = "file" ) Attachment fileDetail,
@ApiParam(value = "Preserve Original Creator of the Application\n") @QueryParam("preserveOwner")  Boolean preserveOwner,
@ApiParam(value = "Skip importing Subscriptions of the Application\n") @QueryParam("skipSubscriptions")  Boolean skipSubscriptions,
@ApiParam(value = "Expected Owner of the Application in the Import Environment\n") @QueryParam("appOwner")  String appOwner,
@ApiParam(value = "Skip importing Keys of the Application\n") @QueryParam("skipApplicationKeys")  Boolean skipApplicationKeys,
@ApiParam(value = "Update if application exists\n") @QueryParam("update")  Boolean update)
{
return delegate.importApplicationsPost(fileInputStream,fileDetail,preserveOwner,skipSubscriptions,appOwner,skipApplicationKeys,update);
}
 
Example #20
Source File: DossierFileManagementImpl.java    From opencps-v2 with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public Response addDossierFileByDossierId(HttpServletRequest request, HttpHeaders header, Company company,
		Locale locale, User user, ServiceContext serviceContext, Attachment file, String id, String referenceUid,
		String dossierTemplateNo, String dossierPartNo, String fileTemplateNo, String displayName, String fileType,
		String isSync, String formData, String removed, String eForm, Long modifiedDate) {

	long groupId = GetterUtil.getLong(header.getHeaderString("groupId"));
	_log.debug("In dossier file create");
	try {
		DossierFile dossierFile = CPSDossierBusinessLocalServiceUtil.addDossierFileByDossierId(groupId, company, user, serviceContext, file, id, referenceUid, dossierTemplateNo, dossierPartNo, fileTemplateNo, displayName, fileType, isSync, formData, removed, eForm, modifiedDate);
		DossierFileModel result = DossierFileUtils.mappingToDossierFileModel(dossierFile);

		_log.debug("__End bind to dossierFile" + new Date());

		return Response.status(200).entity(result).build();
	} catch (Exception e) {
		return BusinessExceptionImpl.processException(e);
	}
}
 
Example #21
Source File: ProxyServletTest.java    From openwebbeans-meecrowave with Apache License 2.0 6 votes vote down vote up
@Test
public void upload() {
    withClient(target -> {
        final Response response = target.path("/upload1").request()
                .post(entity(new MultipartBody(asList(
                        new Attachment("metadata", APPLICATION_JSON, "{\"content\":\"text\"}"),
                        new Attachment(
                                "file",
                                Thread.currentThread().getContextClassLoader().getResourceAsStream("ProxyServletTest/upload/file.txt"),
                                new ContentDisposition("uploadded.txt"))
                )), MULTIPART_FORM_DATA));
        assertEquals(HttpURLConnection.HTTP_OK, response.getStatus());
        final String actual = response.readEntity(String.class);
        assertTrue(actual, actual.contains("uuid:"));
        assertTrue(actual, actual.contains("Content-Type: application/json"));
        assertTrue(actual, actual.contains("{\"content\":\"text\"}"));
        assertTrue(actual, actual.contains("Content-Type: application/octet-stream"));
        assertTrue(actual, actual.contains("test\nfile\nwith\nmultiple\nlines"));
    });
}
 
Example #22
Source File: ApisApi.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@PUT
@Path("/{apiId}/mediation-policies/{mediationPolicyId}/content")
@Consumes({ "multipart/form-data" })
@Produces({ "application/json" })
@ApiOperation(value = "Update an API specific mediation policy", notes = "This operation can be used to update an existing mediation policy of an API. ", response = MediationDTO.class, authorizations = {
    @Authorization(value = "OAuth2Security", scopes = {
        @AuthorizationScope(scope = "apim:api_create", description = "Create API"),
        @AuthorizationScope(scope = "apim:mediation_policy_manage", description = "Update and delete mediation policies")
    })
}, tags={ "API Mediation Policy",  })
@ApiResponses(value = { 
    @ApiResponse(code = 200, message = "OK. Successful response with updated API object ", response = MediationDTO.class),
    @ApiResponse(code = 400, message = "Bad Request. Invalid request or validation error ", response = ErrorDTO.class),
    @ApiResponse(code = 403, message = "Forbidden. The request must be conditional but no condition has been specified. ", response = ErrorDTO.class),
    @ApiResponse(code = 404, message = "Not Found. The resource to be updated does not exist. ", response = ErrorDTO.class),
    @ApiResponse(code = 412, message = "Precondition Failed. The request has not been performed because one of the preconditions is not met. ", response = ErrorDTO.class) })
public Response apisApiIdMediationPoliciesMediationPolicyIdContentPut(@Multipart(value = "type")  String type, @ApiParam(value = "**API ID** consisting of the **UUID** of the API. ",required=true) @PathParam("apiId") String apiId, @ApiParam(value = "Mediation policy Id ",required=true) @PathParam("mediationPolicyId") String mediationPolicyId,  @Multipart(value = "file", required = false) InputStream fileInputStream, @Multipart(value = "file" , required = false) Attachment fileDetail, @Multipart(value = "inlineContent", required = false)  String inlineContent, @ApiParam(value = "Validator for conditional requests; based on ETag. " )@HeaderParam("If-Match") String ifMatch) throws APIManagementException{
    return delegate.apisApiIdMediationPoliciesMediationPolicyIdContentPut(type, apiId, mediationPolicyId, fileInputStream, fileDetail, inlineContent, ifMatch, securityContext);
}
 
Example #23
Source File: ClientProxyImpl.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected List<Attachment> handleMultipart(MultivaluedMap<ParameterType, Parameter> map,
                                         OperationResourceInfo ori,
                                         Object[] params) {
    List<Parameter> fm = getParameters(map, ParameterType.REQUEST_BODY);
    List<Attachment> atts = new ArrayList<>(fm.size());
    fm.forEach(p -> {
        Multipart part = getMultipart(ori, p.getIndex());
        if (part != null) {
            Object partObject = params[p.getIndex()];
            if (partObject != null) {
                atts.add(new Attachment(part.value(), part.type(), partObject));
            }
        }
    });
    return atts;
}
 
Example #24
Source File: MailService.java    From document-management-system with GNU General Public License v2.0 5 votes vote down vote up
@POST
@Path("/importMsg")
@Consumes(MediaType.MULTIPART_FORM_DATA)
// The "dstId" and "content" parameters comes in the POST request body.
public Mail importMsg(List<Attachment> atts) throws RepositoryException, AccessDeniedException, PathNotFoundException,
		DatabaseException, IOException, AutomationException, UserQuotaExceededException, FileSizeExceededException,
		ExtensionException, UnsupportedMimeTypeException, ItemExistsException, VirusDetectedException, MessagingException {
	log.debug("importMsg({})", atts);
	InputStream is = null;
	String dstPath = null;

	try {
		for (Attachment att : atts) {
			if ("dstId".equals(att.getContentDisposition().getParameter("name"))) {
				String dstId = att.getObject(String.class);

				if (PathUtils.isPath(dstId)) {
					dstPath = dstId;
				} else {
					dstPath = ModuleManager.getRepositoryModule().getNodePath(null, dstId);
				}
			} else if ("content".equals(att.getContentDisposition().getParameter("name"))) {
				is = att.getDataHandler().getInputStream();
			}
		}

		Mail newMail = OKMMail.getInstance().importMsg(dstPath, is);
		log.debug("importMsg: {}", newMail);
		return newMail;
	} finally {
		IOUtils.closeQuietly(is);
	}
}
 
Example #25
Source File: MultipartModificationFilter.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(List<Attachment> atts) {
    Attachment dataPart = atts.remove(0);
    Attachment newDataPart = new Attachment(new ByteArrayInputStream("Hi".getBytes()), 
                                            dataPart.getHeaders());
    atts.add(0, newDataPart);
}
 
Example #26
Source File: PathApi.java    From swagger-aem with Apache License 2.0 5 votes vote down vote up
@POST
@Path("/{name}")
@Consumes({ "multipart/form-data" })

@ApiOperation(value = "", notes = "", response = Void.class, authorizations = {
    @Authorization(value = "aemAuth")
}, tags={ "sling",  })
@ApiResponses(value = { 
    @ApiResponse(code = 200, message = "Default response", response = Void.class) })
public Response postNode(@ApiParam(value = "",required=true) @PathParam("path") String path, @ApiParam(value = "",required=true) @PathParam("name") String name,  @ApiParam(value = "")  @QueryParam(":operation") String colonOperation,  @ApiParam(value = "")  @QueryParam("deleteAuthorizable") String deleteAuthorizable,  @Multipart(value = "file", required = false) InputStream fileInputStream, @Multipart(value = "file" , required = false) Attachment fileDetail) {
    return delegate.postNode(path, name, colonOperation, deleteAuthorizable, fileInputStream, fileDetail, securityContext);
}
 
Example #27
Source File: MultipartStore.java    From cxf with Apache License 2.0 5 votes vote down vote up
@POST
@Path("/books/filesform2")
@Produces("text/xml")
@Consumes("multipart/form-data")
public Response addBookFilesFormNoOwnerParam(@Multipart("files") List<Book> books)
    throws Exception {
    Attachment attOwner = AttachmentUtils.getFirstMatchingPart(context, "owner");
    return addBookFilesForm(attOwner.getObject(String.class), books);
}
 
Example #28
Source File: DocumentService.java    From document-management-system with GNU General Public License v2.0 5 votes vote down vote up
@POST
@Path("/checkin")
@Consumes(MediaType.MULTIPART_FORM_DATA)
// The "docId" and "content" parameters comes in the POST request body (encoded as XML or JSON).
public Version checkin(List<Attachment> atts) throws GenericException {
	try {
		log.debug("checkin({})", atts);
		String docId = null;
		String comment = null;
		InputStream is = null;

		for (Attachment att : atts) {
			if ("docId".equals(att.getContentDisposition().getParameter("name"))) {
				docId = att.getObject(String.class);
			} else if ("comment".equals(att.getContentDisposition().getParameter("name"))) {
				comment = att.getObject(String.class);
			} else if ("content".equals(att.getContentDisposition().getParameter("name"))) {
				is = att.getDataHandler().getInputStream();
			}
		}

		DocumentModule dm = ModuleManager.getDocumentModule();
		Version version = dm.checkin(null, docId, is, comment);
		IOUtils.closeQuietly(is);
		log.debug("checkin: {}", version);
		return version;
	} catch (Exception e) {
		throw new GenericException(e);
	}
}
 
Example #29
Source File: ScriptLibrariesApiServiceImpl.java    From identity-api-server with Apache License 2.0 5 votes vote down vote up
@Override
public Response updateScriptLibrary(String scriptLibraryName, InputStream contentInputStream,
                                    Attachment contentDetail, String description) {

    serverScriptLibrariesService.updateScriptLibrary(scriptLibraryName, contentInputStream, description);
    return Response.ok().build();
}
 
Example #30
Source File: UploadArtifactsTest.java    From archiva with Apache License 2.0 5 votes vote down vote up
@Test
public void uploadAndDeleteFile() throws IOException, ArchivaRestServiceException {
    FileUploadService service = getUploadService();
    try {
        Path file = getProjectDirectory().resolve("src/test/repositories/snapshot-repo/org/apache/archiva/archiva-model/1.4-M4-SNAPSHOT/archiva-model-1.4-M4-20130425.081822-1.jar");
        final Attachment fileAttachment = new AttachmentBuilder().object(Files.newInputStream(file)).contentDisposition(new ContentDisposition("form-data; filename=\"" + file.getFileName().toString() + "\"; name=\"files[]\"")).build();
        MultipartBody body = new MultipartBody(fileAttachment);
        service.post(body);
        service.deleteFile(file.getFileName().toString());
    } finally {
        service.clearUploadedFiles();
    }
}