Search in sources :

Example 51 with Attachment

use of org.wso2.carbon.attachment.mgt.api.attachment.Attachment in project carbon-business-process by wso2.

the class ProcessInstanceService method setBinaryVariable.

protected RestVariable setBinaryVariable(MultipartBody multipartBody, Execution execution, int responseVariableType, boolean isNew) throws IOException, ServletException {
    boolean debugEnabled = log.isDebugEnabled();
    List<org.apache.cxf.jaxrs.ext.multipart.Attachment> attachments = multipartBody.getAllAttachments();
    int attachmentSize = attachments.size();
    if (attachmentSize <= 0) {
        throw new ActivitiIllegalArgumentException("No Attachments found with the request body");
    }
    AttachmentDataHolder attachmentDataHolder = new AttachmentDataHolder();
    for (int i = 0; i < attachmentSize; i++) {
        org.apache.cxf.jaxrs.ext.multipart.Attachment attachment = attachments.get(i);
        String contentDispositionHeaderValue = attachment.getHeader("Content-Disposition");
        String contentType = attachment.getHeader("Content-Type");
        if (debugEnabled) {
            log.debug("Going to iterate:" + i);
            log.debug("contentDisposition:" + contentDispositionHeaderValue);
        }
        if (contentDispositionHeaderValue != null) {
            contentDispositionHeaderValue = contentDispositionHeaderValue.trim();
            Map<String, String> contentDispositionHeaderValueMap = Utils.processContentDispositionHeader(contentDispositionHeaderValue);
            String dispositionName = contentDispositionHeaderValueMap.get("name");
            DataHandler dataHandler = attachment.getDataHandler();
            OutputStream outputStream;
            if ("name".equals(dispositionName)) {
                try {
                    outputStream = Utils.getAttachmentStream(dataHandler.getInputStream());
                } catch (IOException e) {
                    throw new ActivitiIllegalArgumentException("Attachment Name Reading error occured", e);
                }
                if (outputStream != null) {
                    String fileName = outputStream.toString();
                    attachmentDataHolder.setName(fileName);
                }
            } else if ("type".equals(dispositionName)) {
                try {
                    outputStream = Utils.getAttachmentStream(dataHandler.getInputStream());
                } catch (IOException e) {
                    throw new ActivitiIllegalArgumentException("Attachment Type Reading error occured", e);
                }
                if (outputStream != null) {
                    String typeName = outputStream.toString();
                    attachmentDataHolder.setType(typeName);
                }
            } else if ("scope".equals(dispositionName)) {
                try {
                    outputStream = Utils.getAttachmentStream(dataHandler.getInputStream());
                } catch (IOException e) {
                    throw new ActivitiIllegalArgumentException("Attachment Description Reading error occured", e);
                }
                if (outputStream != null) {
                    String scope = outputStream.toString();
                    attachmentDataHolder.setScope(scope);
                }
            }
            if (contentType != null) {
                if ("file".equals(dispositionName)) {
                    InputStream inputStream;
                    try {
                        inputStream = dataHandler.getInputStream();
                    } catch (IOException e) {
                        throw new ActivitiIllegalArgumentException("Error Occured During processing empty body.", e);
                    }
                    if (inputStream != null) {
                        attachmentDataHolder.setContentType(contentType);
                        byte[] attachmentArray = new byte[0];
                        try {
                            attachmentArray = IOUtils.toByteArray(inputStream);
                        } catch (IOException e) {
                            throw new ActivitiIllegalArgumentException("Processing Attachment Body Failed.", e);
                        }
                        attachmentDataHolder.setAttachmentArray(attachmentArray);
                    }
                }
            }
        }
    }
    attachmentDataHolder.printDebug();
    String variableScope = attachmentDataHolder.getScope();
    String variableName = attachmentDataHolder.getName();
    String variableType = attachmentDataHolder.getType();
    if (attachmentDataHolder.getName() == null) {
        throw new ActivitiIllegalArgumentException("Attachment name is required.");
    }
    if (attachmentDataHolder.getAttachmentArray() == null) {
        throw new ActivitiIllegalArgumentException("Empty attachment body was found in request body after " + "decoding the request" + ".");
    }
    if (debugEnabled) {
        log.debug("variableScope:" + variableScope + " variableName:" + variableName + " variableType:" + variableType);
    }
    try {
        // Validate input and set defaults
        if (variableName == null) {
            throw new ActivitiIllegalArgumentException("No variable name was found in request body.");
        }
        if (variableType != null) {
            if (!RestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE.equals(variableType) && !RestResponseFactory.SERIALIZABLE_VARIABLE_TYPE.equals(variableType)) {
                throw new ActivitiIllegalArgumentException("Only 'binary' and 'serializable' are supported as variable type.");
            }
        } else {
            variableType = RestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE;
        }
        RestVariable.RestVariableScope scope = RestVariable.RestVariableScope.LOCAL;
        if (variableScope != null) {
            scope = RestVariable.getScopeFromString(variableScope);
        }
        if (variableType.equals(RestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE)) {
            // Use raw bytes as variable value
            setVariable(execution, variableName, attachmentDataHolder.getAttachmentArray(), scope, isNew);
        } else {
            // Try deserializing the object
            try (InputStream inputStream = new ByteArrayInputStream(attachmentDataHolder.getAttachmentArray());
                ObjectInputStream stream = new ObjectInputStream(inputStream)) {
                Object value = stream.readObject();
                setVariable(execution, variableName, value, scope, isNew);
            }
        }
        RestResponseFactory restResponseFactory = new RestResponseFactory();
        if (responseVariableType == RestResponseFactory.VARIABLE_PROCESS) {
            return new RestResponseFactory().createBinaryRestVariable(variableName, scope, variableType, null, null, execution.getId(), uriInfo.getBaseUri().toString());
        } else {
            return restResponseFactory.createBinaryRestVariable(variableName, scope, variableType, null, execution.getId(), null, uriInfo.getBaseUri().toString());
        }
    } catch (IOException ioe) {
        throw new ActivitiIllegalArgumentException("Could not process multipart content", ioe);
    } catch (ClassNotFoundException ioe) {
        throw new BPMNContentNotSupportedException("The provided body contains a serialized object for which the " + "class is not found: " + ioe.getMessage());
    }
}
Also used : ByteArrayOutputStream(java.io.ByteArrayOutputStream) ObjectOutputStream(java.io.ObjectOutputStream) OutputStream(java.io.OutputStream) DataHandler(javax.activation.DataHandler) BPMNContentNotSupportedException(org.wso2.carbon.bpmn.rest.common.exception.BPMNContentNotSupportedException) RestVariable(org.wso2.carbon.bpmn.rest.engine.variable.RestVariable) ActivitiIllegalArgumentException(org.activiti.engine.ActivitiIllegalArgumentException) AttachmentDataHolder(org.wso2.carbon.bpmn.rest.model.runtime.AttachmentDataHolder) Context(javax.ws.rs.core.Context) CommandContext(org.activiti.engine.impl.interceptor.CommandContext) PrivilegedCarbonContext(org.wso2.carbon.context.PrivilegedCarbonContext) JAXBContext(javax.xml.bind.JAXBContext) RestResponseFactory(org.wso2.carbon.bpmn.rest.common.RestResponseFactory) ObjectInputStream(java.io.ObjectInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) ByteArrayInputStream(java.io.ByteArrayInputStream) ObjectInputStream(java.io.ObjectInputStream)

Example 52 with Attachment

use of org.wso2.carbon.attachment.mgt.api.attachment.Attachment in project carbon-business-process by wso2.

the class WorkflowTaskService method deleteAttachment.

@DELETE
@Path("/{taskId}/attachments/{attachmentId}")
public Response deleteAttachment(@PathParam("taskId") String taskId, @PathParam("attachmentId") String attachmentId) {
    Task task = getTaskFromRequest(taskId);
    TaskService taskService = BPMNOSGIService.getTaskService();
    Attachment attachment = taskService.getAttachment(attachmentId);
    if (attachment == null) {
        throw new ActivitiObjectNotFoundException("Task '" + task.getId() + "' doesn't have an attachment with id '" + attachmentId + "'.", Comment.class);
    }
    taskService.deleteAttachment(attachmentId);
    return Response.ok().status(Response.Status.NO_CONTENT).build();
}
Also used : BaseTaskService(org.wso2.carbon.bpmn.rest.service.base.BaseTaskService)

Example 53 with Attachment

use of org.wso2.carbon.attachment.mgt.api.attachment.Attachment in project carbon-business-process by wso2.

the class WorkflowTaskService method getIdentityLink.

/*    protected AttachmentResponse createBinaryAttachment(HttpServletRequest httpServletRequest, Task task, Response.ResponseBuilder responseBuilder) throws
            IOException {

        String name = uriInfo.getQueryParameters().getFirst("name");
        String description = uriInfo.getQueryParameters().getFirst("description");
        String type = uriInfo.getQueryParameters().getFirst("type");


        byte[] byteArray = Utils.processMultiPartFile(httpServletRequest, "Attachment content");
        if (byteArray == null) {
            throw new ActivitiIllegalArgumentException("Empty attachment body was found in request body after " +
                    "decoding the request" +
                    ".");
        }

        if (name == null) {
            throw new ActivitiIllegalArgumentException("Attachment name is required.");
        }


        TaskService taskService = BPMNOSGIService.getTaskService();

        try {
            InputStream inputStream = new ByteArrayInputStream(byteArray);
            Attachment createdAttachment = taskService.createAttachment(type, task.getId(), task.getProcessInstanceId(), name,
                    description, inputStream);

            responseBuilder.status(Response.Status.CREATED);
            return new RestResponseFactory().createAttachmentResponse(createdAttachment, uriInfo.getBaseUri().toString());

        } catch (Exception e) {
            throw new ActivitiException("Error creating attachment response", e);
        }
    }*/
protected IdentityLink getIdentityLink(String family, String identityId, String type, String taskId) {
    boolean isUser = family.equals(RestUrls.SEGMENT_IDENTITYLINKS_FAMILY_USERS);
    TaskService taskService = BPMNOSGIService.getTaskService();
    // Perhaps it would be better to offer getting a single identitylink from the API
    List<IdentityLink> allLinks = taskService.getIdentityLinksForTask(taskId);
    for (IdentityLink link : allLinks) {
        boolean rightIdentity = false;
        if (isUser) {
            rightIdentity = identityId.equals(link.getUserId());
        } else {
            rightIdentity = identityId.equals(link.getGroupId());
        }
        if (rightIdentity && link.getType().equals(type)) {
            return link;
        }
    }
    throw new ActivitiObjectNotFoundException("Could not find the requested identity link.", IdentityLink.class);
}
Also used : BaseTaskService(org.wso2.carbon.bpmn.rest.service.base.BaseTaskService) RestIdentityLink(org.wso2.carbon.bpmn.rest.model.common.RestIdentityLink)

Example 54 with Attachment

use of org.wso2.carbon.attachment.mgt.api.attachment.Attachment in project carbon-business-process by wso2.

the class WorkflowTaskService method createAttachmentForBinary.

@POST
@Path("/{taskId}/attachments")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response createAttachmentForBinary(@PathParam("taskId") String taskId, MultipartBody multipartBody, @Context HttpServletRequest httpServletRequest) {
    boolean debugEnabled = log.isDebugEnabled();
    List<org.apache.cxf.jaxrs.ext.multipart.Attachment> attachments = multipartBody.getAllAttachments();
    int attachmentSize = attachments.size();
    if (attachmentSize <= 0) {
        throw new ActivitiIllegalArgumentException("No Attachments found with the request body");
    }
    AttachmentDataHolder attachmentDataHolder = new AttachmentDataHolder();
    for (int i = 0; i < attachmentSize; i++) {
        org.apache.cxf.jaxrs.ext.multipart.Attachment attachment = attachments.get(i);
        String contentDispositionHeaderValue = attachment.getHeader("Content-Disposition");
        String contentType = attachment.getHeader("Content-Type");
        if (debugEnabled) {
            log.debug("Going to iterate:" + i);
            log.debug("contentDisposition:" + contentDispositionHeaderValue);
        }
        if (contentDispositionHeaderValue != null) {
            contentDispositionHeaderValue = contentDispositionHeaderValue.trim();
            Map<String, String> contentDispositionHeaderValueMap = Utils.processContentDispositionHeader(contentDispositionHeaderValue);
            String dispositionName = contentDispositionHeaderValueMap.get("name");
            DataHandler dataHandler = attachment.getDataHandler();
            OutputStream outputStream = null;
            if ("name".equals(dispositionName)) {
                try {
                    outputStream = Utils.getAttachmentStream(dataHandler.getInputStream());
                } catch (IOException e) {
                    throw new ActivitiIllegalArgumentException("Attachment Name Reading error occured", e);
                }
                if (outputStream != null) {
                    String fileName = outputStream.toString();
                    attachmentDataHolder.setName(fileName);
                }
            } else if ("type".equals(dispositionName)) {
                try {
                    outputStream = Utils.getAttachmentStream(dataHandler.getInputStream());
                } catch (IOException e) {
                    throw new ActivitiIllegalArgumentException("Attachment Type Reading error occured", e);
                }
                if (outputStream != null) {
                    String typeName = outputStream.toString();
                    attachmentDataHolder.setType(typeName);
                }
            } else if ("description".equals(dispositionName)) {
                try {
                    outputStream = Utils.getAttachmentStream(dataHandler.getInputStream());
                } catch (IOException e) {
                    throw new ActivitiIllegalArgumentException("Attachment Description Reading error occured", e);
                }
                if (outputStream != null) {
                    String description = outputStream.toString();
                    attachmentDataHolder.setDescription(description);
                }
            }
            if (contentType != null) {
                if ("file".equals(dispositionName)) {
                    InputStream inputStream = null;
                    try {
                        inputStream = dataHandler.getInputStream();
                    } catch (IOException e) {
                        throw new ActivitiIllegalArgumentException("Error Occured During processing empty body.", e);
                    }
                    if (inputStream != null) {
                        attachmentDataHolder.setContentType(contentType);
                        byte[] attachmentArray = new byte[0];
                        try {
                            attachmentArray = IOUtils.toByteArray(inputStream);
                        } catch (IOException e) {
                            throw new ActivitiIllegalArgumentException("Processing Attachment Body Failed.", e);
                        }
                        attachmentDataHolder.setAttachmentArray(attachmentArray);
                    }
                }
            }
        }
    }
    attachmentDataHolder.printDebug();
    if (attachmentDataHolder.getName() == null) {
        throw new ActivitiIllegalArgumentException("Attachment name is required.");
    }
    if (attachmentDataHolder.getAttachmentArray() == null) {
        throw new ActivitiIllegalArgumentException("Empty attachment body was found in request body after " + "decoding the request" + ".");
    }
    TaskService taskService = BPMNOSGIService.getTaskService();
    Task task = getTaskFromRequest(taskId);
    Response.ResponseBuilder responseBuilder = Response.ok();
    AttachmentResponse result = null;
    try {
        InputStream inputStream = new ByteArrayInputStream(attachmentDataHolder.getAttachmentArray());
        Attachment createdAttachment = taskService.createAttachment(attachmentDataHolder.getContentType(), task.getId(), task.getProcessInstanceId(), attachmentDataHolder.getName(), attachmentDataHolder.getDescription(), inputStream);
        responseBuilder.status(Response.Status.CREATED);
        result = new RestResponseFactory().createAttachmentResponse(createdAttachment, uriInfo.getBaseUri().toString());
    } catch (Exception e) {
        throw new ActivitiException("Error creating attachment response", e);
    }
    return responseBuilder.status(Response.Status.CREATED).entity(result).build();
}
Also used : DataHandler(javax.activation.DataHandler) JAXBContext(javax.xml.bind.JAXBContext) Context(javax.ws.rs.core.Context) RestResponseFactory(org.wso2.carbon.bpmn.rest.common.RestResponseFactory) ServletInputStream(javax.servlet.ServletInputStream) BaseTaskService(org.wso2.carbon.bpmn.rest.service.base.BaseTaskService) XMLStreamException(javax.xml.stream.XMLStreamException) BPMNForbiddenException(org.wso2.carbon.bpmn.rest.common.exception.BPMNForbiddenException) BPMNConflictException(org.wso2.carbon.bpmn.rest.common.exception.BPMNConflictException) JAXBException(javax.xml.bind.JAXBException) DataResponse(org.wso2.carbon.bpmn.rest.model.common.DataResponse) Response(javax.ws.rs.core.Response)

Example 55 with Attachment

use of org.wso2.carbon.attachment.mgt.api.attachment.Attachment in project carbon-business-process by wso2.

the class WorkflowTaskService method getAttachmentContent.

@GET
@Path("/{taskId}/attachments/{attachmentId}/content")
public Response getAttachmentContent(@PathParam("taskId") String taskId, @PathParam("attachmentId") String attachmentId) {
    TaskService taskService = BPMNOSGIService.getTaskService();
    HistoricTaskInstance task = getHistoricTaskFromRequest(taskId);
    Attachment attachment = taskService.getAttachment(attachmentId);
    if (attachment == null) {
        throw new ActivitiObjectNotFoundException("Task '" + task.getId() + "' doesn't have an attachment with id '" + attachmentId + "'.", Attachment.class);
    }
    InputStream attachmentStream = taskService.getAttachmentContent(attachmentId);
    if (attachmentStream == null) {
        throw new ActivitiObjectNotFoundException("Attachment with id '" + attachmentId + "' doesn't have content associated with it.", Attachment.class);
    }
    Response.ResponseBuilder responseBuilder = Response.ok();
    String type = attachment.getType();
    MediaType mediaType = MediaType.valueOf(type);
    if (mediaType != null) {
        responseBuilder.type(mediaType);
    } else {
        responseBuilder.type("application/octet-stream");
    }
    byte[] attachmentArray;
    try {
        attachmentArray = IOUtils.toByteArray(attachmentStream);
    } catch (IOException e) {
        throw new ActivitiException("Error creating attachment data", e);
    }
    String dispositionValue = "inline; filename=\"" + attachment.getName() + "\"";
    responseBuilder.header("Content-Disposition", dispositionValue);
    return responseBuilder.entity(attachmentArray).build();
}
Also used : DataResponse(org.wso2.carbon.bpmn.rest.model.common.DataResponse) Response(javax.ws.rs.core.Response) HistoricTaskInstance(org.activiti.engine.history.HistoricTaskInstance) BaseTaskService(org.wso2.carbon.bpmn.rest.service.base.BaseTaskService) ServletInputStream(javax.servlet.ServletInputStream) MediaType(javax.ws.rs.core.MediaType)

Aggregations

HashMap (java.util.HashMap)11 AttachmentMgtException (org.wso2.carbon.attachment.mgt.skeleton.AttachmentMgtException)11 TAttachment (org.wso2.carbon.attachment.mgt.skeleton.types.TAttachment)10 DataHandler (javax.activation.DataHandler)9 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)9 ArrayList (java.util.ArrayList)8 BLangRecordLiteral (org.wso2.ballerinalang.compiler.tree.expressions.BLangRecordLiteral)8 ErrorDTO (org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO)8 File (java.io.File)7 Response (javax.ws.rs.core.Response)7 DiagnosticPos (org.wso2.ballerinalang.compiler.util.diagnotic.DiagnosticPos)7 RestResponseFactory (org.wso2.carbon.bpmn.rest.common.RestResponseFactory)7 TopLevelNode (org.ballerinalang.model.tree.TopLevelNode)6 AttachmentDAO (org.wso2.carbon.attachment.mgt.core.dao.AttachmentDAO)6 BaseTaskService (org.wso2.carbon.bpmn.rest.service.base.BaseTaskService)5 IOException (java.io.IOException)4 List (java.util.List)4 BLangExpression (org.wso2.ballerinalang.compiler.tree.expressions.BLangExpression)4 APIPublisher (org.wso2.carbon.apimgt.core.api.APIPublisher)4 Attachment (org.wso2.carbon.attachment.mgt.api.attachment.Attachment)4