Search in sources :

Example 31 with Attachment

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

the class AttachmentMgtDAOFactoryImpl method getAttachmentInfoFromURL.

@Override
public AttachmentDAO getAttachmentInfoFromURL(final String attachmentURI) throws AttachmentMgtException {
    try {
        AttachmentDAO resultantDAO = jobExecutor.execTransaction(new Callable<AttachmentDAO>() {

            @Override
            public AttachmentDAO call() throws Exception {
                Query query = entityManager.createQuery("SELECT x FROM org.wso2.carbon.attachment.mgt.core.dao.impl.jpa.openjpa.entity.AttachmentDAOImpl AS x WHERE x.url = :attachmentURI");
                query.setParameter("attachmentURI", attachmentURI);
                List<AttachmentDAO> daoList = query.getResultList();
                if (daoList.isEmpty()) {
                    throw new AttachmentMgtException("Attachment not found for the uri:" + attachmentURI);
                } else if (daoList.size() != 1) {
                    String errorMsg = "There exist more than one attachment for the attachment URI:" + attachmentURI + ". org" + ".wso2.carbon.attachment.mgt.util.URLGeneratorUtil.generateURL method has generated " + "similar uris for different attachments. This has caused a major inconsistency for " + "attachment management.";
                    log.fatal(errorMsg);
                    throw new AttachmentMgtException(errorMsg);
                } else {
                    return daoList.get(0);
                }
            }
        });
        return resultantDAO;
    } catch (Exception e) {
        String errorMsg = "org.wso2.carbon.attachment.mgt.core.dao.impl.jpa.openjpa.AttachmentMgtDAOFactoryImpl.getAttachmentInfoFromURL operation failed. " + "Reason: " + e.getLocalizedMessage();
        log.error(errorMsg, e);
        throw new AttachmentMgtException(errorMsg, e);
    }
}
Also used : AttachmentMgtException(org.wso2.carbon.attachment.mgt.core.exceptions.AttachmentMgtException) AttachmentDAO(org.wso2.carbon.attachment.mgt.core.dao.AttachmentDAO) Query(javax.persistence.Query) List(java.util.List) AttachmentMgtException(org.wso2.carbon.attachment.mgt.core.exceptions.AttachmentMgtException)

Example 32 with Attachment

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

the class OpenJPAVendorAdapter method getJpaPropertyMap.

@Override
public Map<String, ?> getJpaPropertyMap(TransactionManager transactionManager) {
    // TODO: Inorder to support external transaction manager, need to fix these property map
    // properly.
    Map<String, Object> jpaProperties = new HashMap<String, Object>();
    if (getDataSource() != null) {
        jpaProperties.put("openjpa.ConnectionFactory", getDataSource());
        String dbDictionary = determineDbDictionary();
        if (dbDictionary != null) {
            log.info("[Attachment-Mgt OpenJPA] DB Dictionary: " + dbDictionary);
            jpaProperties.put("openjpa.jdbc.DBDictionary", dbDictionary);
        }
    // jpaProperties.put("openjpa.jdbc.TransactionIsolation", "read-committed");
    }
    if (isGenerateDDL()) {
        log.info("[Attachment-Mgt OpenJPA] Generate DDL Enabled.");
        jpaProperties.put("openjpa.jdbc.SynchronizeMappings", "buildSchema(ForeignKeys=true)");
    }
    if (isShowSQL()) {
        log.info("[Attachment-Mgt OpenJPA] Show SQL enabled.");
        jpaProperties.put("openjpa.Log", "DefaultLevel=WARN, Runtime=INFO, Tool=INFO, SQL=TRACE");
        jpaProperties.put("openjpa.ConnectionFactoryProperties", "PrettyPrint=true, PrettyPrintLineLength=72");
    }
    if (transactionManager != null) {
        // Using managed transactions
        jpaProperties.put("openjpa.ConnectionFactoryMode", "managed");
        jpaProperties.put("openjpa.ManagedRuntime", new TransactionManagerProvider(transactionManager));
    }
    jpaProperties.put("openjpa.Id", "Attachment-Mgt-PU");
    jpaProperties.put("openjpa.QueryCache", "false");
    jpaProperties.put("openjpa.DataCache", "false");
    jpaProperties.put("openjpa.jdbc.QuerySQLCache", "false");
    return jpaProperties;
}
Also used : HashMap(java.util.HashMap) TransactionManagerProvider(org.wso2.carbon.attachment.mgt.core.dao.impl.TransactionManagerProvider)

Example 33 with Attachment

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

the class AttachmentMgtDAOTransformerFactoryImpl method convertAttachment.

@Override
public AttachmentDAO convertAttachment(Attachment attachment) throws AttachmentMgtException {
    AttachmentDAO attachmentDAO = new AttachmentDAOImpl();
    attachmentDAO.setName(attachment.getName());
    attachmentDAO.setCreatedBy(attachment.getCreatedBy());
    attachmentDAO.setContent(attachment.getContent());
    attachmentDAO.setContentType(attachment.getContentType());
    return attachmentDAO;
}
Also used : AttachmentDAO(org.wso2.carbon.attachment.mgt.core.dao.AttachmentDAO) AttachmentDAOImpl(org.wso2.carbon.attachment.mgt.core.dao.impl.jpa.openjpa.entity.AttachmentDAOImpl)

Example 34 with Attachment

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

the class BaseExecutionService method createBinaryExecutionVariable.

protected RestVariable createBinaryExecutionVariable(Execution execution, int responseVariableType, UriInfo uriInfo, boolean isNew, MultipartBody multipartBody) {
    boolean debugEnabled = log.isDebugEnabled();
    Response.ResponseBuilder responseBuilder = Response.ok();
    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 ("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 description = outputStream.toString();
                    attachmentDataHolder.setScope(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" + ".");
    }
    String variableScope = attachmentDataHolder.getScope();
    String variableName = attachmentDataHolder.getName();
    String variableType = attachmentDataHolder.getType();
    if (log.isDebugEnabled()) {
        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 (RestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE.equals(variableType)) {
            // 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);
            }
        }
        if (responseVariableType == RestResponseFactory.VARIABLE_PROCESS) {
            return new RestResponseFactory().createBinaryRestVariable(variableName, scope, variableType, null, null, execution.getId(), uriInfo.getBaseUri().toString());
        } else {
            return new 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 nog found: " + ioe.getMessage());
    }
}
Also used : 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) JAXBContext(javax.xml.bind.JAXBContext) RestResponseFactory(org.wso2.carbon.bpmn.rest.common.RestResponseFactory) DataResponse(org.wso2.carbon.bpmn.rest.model.common.DataResponse) Response(javax.ws.rs.core.Response)

Example 35 with Attachment

use of org.wso2.carbon.attachment.mgt.api.attachment.Attachment in project product-iots by wso2.

the class DeviceTypeServiceImpl method downloadSketch.

/**
 * To download device type agent source code as zip file.
 *
 * @param deviceName name for the device type instance
 * @param sketchType folder name where device type agent was installed into server
 * @return Agent source code as zip file
 */
@Path("/device/download")
@GET
@Produces("application/zip")
public Response downloadSketch(@QueryParam("deviceName") String deviceName, @QueryParam("sketchType") String sketchType) {
    try {
        ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), deviceName, sketchType);
        Response.ResponseBuilder response = Response.ok(FileUtils.readFileToByteArray(zipFile.getZipFile()));
        response.status(Response.Status.OK);
        response.type("application/zip");
        response.header("Content-Disposition", "attachment; filename=\"" + zipFile.getFileName() + "\"");
        Response resp = response.build();
        zipFile.getZipFile().delete();
        return resp;
    } catch (IllegalArgumentException ex) {
        // bad request
        return Response.status(400).entity(ex.getMessage()).build();
    } catch (DeviceManagementException ex) {
        log.error(ex.getMessage(), ex);
        return Response.status(500).entity(ex.getMessage()).build();
    } catch (JWTClientException ex) {
        log.error(ex.getMessage(), ex);
        return Response.status(500).entity(ex.getMessage()).build();
    } catch (APIManagerException ex) {
        log.error(ex.getMessage(), ex);
        return Response.status(500).entity(ex.getMessage()).build();
    } catch (IOException ex) {
        log.error(ex.getMessage(), ex);
        return Response.status(500).entity(ex.getMessage()).build();
    } catch (UserStoreException ex) {
        log.error(ex.getMessage(), ex);
        return Response.status(500).entity(ex.getMessage()).build();
    }
}
Also used : Response(javax.ws.rs.core.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) DeviceManagementException(org.wso2.carbon.device.mgt.common.DeviceManagementException) APIManagerException(org.wso2.carbon.apimgt.application.extension.exception.APIManagerException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) ZipArchive(org.wso2.iot.sampledevice.api.util.ZipArchive) IOException(java.io.IOException) JWTClientException(org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

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