Search in sources :

Example 46 with Attachment

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

the class AttachmentMgtDAOBasicOperationsTest method testAttachmentDAOGetInfoTest.

/**
 * This method tests whether it's possible to get the attachment-info for a given attachment id
 */
public void testAttachmentDAOGetInfoTest() {
    AttachmentManagerService service = new AttachmentManagerService();
    try {
        TAttachment attachment = service.getAttachmentInfo(attachmentID);
        dummyAttachment = createAttachment();
        assertEquals(dummyAttachment.getName(), attachment.getName());
        assertEquals(dummyAttachment.getCreatedBy(), attachment.getCreatedBy());
        assertEquals(dummyAttachment.getContentType(), attachment.getContentType());
        log.info("Attachment information retrieved for id : " + attachment.getId());
    } catch (AttachmentMgtException e) {
        log.error(e.getLocalizedMessage(), e);
        Assert.fail("Attachment information retrieval failed due to reason: " + e.getLocalizedMessage());
    }
}
Also used : AttachmentManagerService(org.wso2.carbon.attachment.mgt.core.service.AttachmentManagerService) AttachmentMgtException(org.wso2.carbon.attachment.mgt.skeleton.AttachmentMgtException) TAttachment(org.wso2.carbon.attachment.mgt.skeleton.types.TAttachment)

Example 47 with Attachment

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

the class URLGeneratorUtil method getPermanentLink.

/**
 * Generate the permanent link for the given attachment uri based on current system configurations like host, port
 * eg - if {@code uniqueID} is abc123, then the resultant permanent link would {@code https://127.0.0.1:9443/context/abc123}
 * So this url can be used to download the attachment
 *
 * @param uniqueID uri for the attachment
 * @return downloadable url of the attachment
 * @throws AttachmentMgtException
 */
public static URL getPermanentLink(URI uniqueID) throws AttachmentMgtException {
    String scheme = CarbonConstants.HTTPS_TRANSPORT;
    String host;
    try {
        host = NetworkUtils.getLocalHostname();
    } catch (SocketException e) {
        log.error(e.getMessage(), e);
        throw new AttachmentMgtException(e.getLocalizedMessage(), e);
    }
    int port = 9443;
    try {
        ConfigurationContext serverConfigContext = AttachmentServerHolder.getInstance().getConfigurationContextService().getServerConfigContext();
        port = CarbonUtils.getTransportProxyPort(serverConfigContext, scheme);
        if (port == -1) {
            port = CarbonUtils.getTransportPort(serverConfigContext, scheme);
        }
    } catch (Exception ex) {
        log.warn("Using default port settings");
    }
    String webContext = ServerConfiguration.getInstance().getFirstProperty("WebContextRoot");
    if (webContext == null || webContext.equals("/")) {
        webContext = "";
    }
    String tenantDomain = String.valueOf(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
    try {
        tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain();
    } catch (Throwable e) {
        tenantDomain = null;
    }
    String url = null;
    try {
        String link = scheme + "://" + host + ":" + port + webContext + ((tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) ? "/" + MultitenantConstants.TENANT_AWARE_URL_PREFIX + "/" + tenantDomain : "") + AttachmentMgtConfigurationConstants.ATTACHMENT_DOWNLOAD_SERVELET_URL_PATTERN + "/" + uniqueID.toString();
        return new URL(link);
    } catch (MalformedURLException e) {
        log.error(e.getMessage(), e);
        throw new AttachmentMgtException(e.getLocalizedMessage(), e);
    }
}
Also used : AttachmentMgtException(org.wso2.carbon.attachment.mgt.core.exceptions.AttachmentMgtException) SocketException(java.net.SocketException) ConfigurationContext(org.apache.axis2.context.ConfigurationContext) MalformedURLException(java.net.MalformedURLException) MalformedURLException(java.net.MalformedURLException) AttachmentMgtException(org.wso2.carbon.attachment.mgt.core.exceptions.AttachmentMgtException) SocketException(java.net.SocketException) URL(java.net.URL)

Example 48 with Attachment

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

the class AttachmentManagerService method add.

/**
 * {@inheritDoc}
 */
@Override
public String add(final TAttachment attachment) throws AttachmentMgtException {
    if (log.isDebugEnabled() && attachment != null) {
        log.debug("Saving the attachment with id " + attachment.getId());
    }
    try {
        Attachment att = TransformerUtil.convertAttachment(attachment);
        // 1. get Att-Mgt DAO Conn factory
        // 2. get Att-Mgt DAO Connection
        // 3. addAttachment
        // getDaoConnectionFactory().getDAOConnection().addAttachment(att);
        AttachmentDAO daoImpl = getDaoConnectionFactory().getDAOConnection().getAttachmentMgtDAOFactory().addAttachment(att);
        return daoImpl.getID().toString();
    } catch (org.wso2.carbon.attachment.mgt.core.exceptions.AttachmentMgtException ex) {
        String errMsg = "org.wso2.carbon.attachment.mgt.core.service.AttachmentManagerService.add " + "operation failed. Reason:" + ex.getLocalizedMessage();
        log.error(errMsg, ex);
        throw new AttachmentMgtException(errMsg, ex);
    }
}
Also used : AttachmentMgtException(org.wso2.carbon.attachment.mgt.skeleton.AttachmentMgtException) AttachmentDAO(org.wso2.carbon.attachment.mgt.core.dao.AttachmentDAO) TAttachment(org.wso2.carbon.attachment.mgt.skeleton.types.TAttachment) Attachment(org.wso2.carbon.attachment.mgt.api.attachment.Attachment)

Example 49 with Attachment

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

the class AttachmentMgtDAOConnectionFactoryImpl method init.

@Override
public void init() {
    if (transactionManager == null) {
        log.debug("Transaction-Manager is not initialized before initializing entityManager. So internal " + "transaction-manager in entity manager will be used.");
    }
    JPAVendorAdapter vendorAdapter = getJPAVendorAdapter();
    // Here we pass a "null" valued transaction manager,
    // as we enforce the entity-manager-factory to use its local transactions. In future,
    // if required to use external JTA transactions, a transaction reference should be passed
    // as the input parameter.
    this.entityManagerFactory = Persistence.createEntityManagerFactory("Attachment-Mgt-PU", vendorAdapter.getJpaPropertyMap(null));
}
Also used : JPAVendorAdapter(org.wso2.carbon.attachment.mgt.core.dao.impl.jpa.JPAVendorAdapter)

Example 50 with Attachment

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

the class BaseTaskService method setBinaryVariable.

protected RestVariable setBinaryVariable(MultipartBody multipartBody, Task task, boolean isNew, UriInfo uriInfo) throws IOException {
    boolean debugEnabled = log.isDebugEnabled();
    if (debugEnabled) {
        log.debug("Processing Binary variables");
    }
    Object result = null;
    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("Binary Variable 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("\"Binary Variable 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("Binary Variable scopeDescription Reading error " + "occured", e);
                }
                if (outputStream != null) {
                    String scope = outputStream.toString();
                    attachmentDataHolder.setScope(scope);
                }
            }
            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 BinaryV variable Body Failed.", e);
                        }
                        attachmentDataHolder.setAttachmentArray(attachmentArray);
                    }
                }
            }
        }
    }
    attachmentDataHolder.printDebug();
    String variableScope = attachmentDataHolder.getScope();
    String variableName = attachmentDataHolder.getName();
    String variableType = attachmentDataHolder.getType();
    byte[] attachmentArray = attachmentDataHolder.getAttachmentArray();
    try {
        if (variableName == null) {
            throw new ActivitiIllegalArgumentException("No variable name was found in request body.");
        }
        if (attachmentArray == null) {
            throw new ActivitiIllegalArgumentException("Empty attachment body was found in request body after " + "decoding the request" + ".");
        }
        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 {
            attachmentDataHolder.setType(RestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE);
        }
        RestVariable.RestVariableScope scope = RestVariable.RestVariableScope.LOCAL;
        if (variableScope != null) {
            scope = RestVariable.getScopeFromString(variableScope);
        }
        if (variableScope != null) {
            scope = RestVariable.getScopeFromString(variableScope);
        }
        if (RestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE.equals(variableType)) {
            // Use raw bytes as variable value
            setVariable(task, variableName, attachmentArray, scope, isNew);
        } else {
            // Try deserializing the object
            try (InputStream inputStream = new ByteArrayInputStream(attachmentArray);
                ObjectInputStream stream = new ObjectInputStream(inputStream)) {
                Object value = stream.readObject();
                setVariable(task, variableName, value, scope, isNew);
            }
        }
        return new RestResponseFactory().createBinaryRestVariable(variableName, scope, variableType, task.getId(), null, null, uriInfo.getBaseUri().toString());
    } catch (IOException ioe) {
        throw new ActivitiIllegalArgumentException("Error getting binary variable", 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) AttachmentDataHolder(org.wso2.carbon.bpmn.rest.model.runtime.AttachmentDataHolder) RestResponseFactory(org.wso2.carbon.bpmn.rest.common.RestResponseFactory)

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