Example usage for javax.activation DataHandler getInputStream

List of usage examples for javax.activation DataHandler getInputStream

Introduction

In this page you can find the example usage for javax.activation DataHandler getInputStream.

Prototype

public InputStream getInputStream() throws IOException 

Source Link

Document

Get the InputStream for this object.

Usage

From source file:org.mule.modules.wechat.common.HttpsConnection.java

public Map<String, Object> postFile(String httpsURL, String title, String introduction, DataHandler attachment)
        throws Exception {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost post = new HttpPost(httpsURL);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();

    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    // Get extension of attachment
    TikaConfig config = TikaConfig.getDefaultConfig();
    MimeTypes allTypes = config.getMimeRepository();
    String ext = allTypes.forName(attachment.getContentType()).getExtension();
    if (ext.equals("")) {
        ContentTypeEnum contentTypeEnum = ContentTypeEnum
                .getContentTypeEnumByContentType(attachment.getContentType().toLowerCase());
        ext = java.util.Optional.ofNullable(contentTypeEnum.getExtension()).orElse("");
    }//from   w  ww . j av a 2  s.  c  o  m

    // Create file
    InputStream fis = attachment.getInputStream();
    byte[] bytes = IOUtils.toByteArray(fis);
    File f = new File(System.getProperty("user.dir") + "/fileTemp/" + title + ext);
    FileUtils.writeByteArrayToFile(f, bytes);

    // Create JSON
    JSONObject obj = new JSONObject();
    obj.put("title", title);
    obj.put("introduction", introduction);
    ContentType contentType = ContentType.create("text/plain", Charset.forName("UTF-8"));
    builder.addBinaryBody("media", f);
    builder.addTextBody("description", obj.toString(), contentType);

    // Post to wechat
    HttpEntity entity = builder.build();
    post.setEntity(entity);
    CloseableHttpResponse httpResponse = httpClient.execute(post);
    String content = "";
    try {
        HttpEntity _entity = httpResponse.getEntity();
        content = EntityUtils.toString(_entity);
        EntityUtils.consume(_entity);
    } finally {
        httpResponse.close();
    }
    f.delete();

    // Convert JSON string to Map
    ObjectMapper mapper = new ObjectMapper();
    Map<String, Object> map = mapper.readValue(content, new TypeReference<Map<String, Object>>() {
    });

    return map;
}

From source file:org.apache.axis.utils.JavaUtils.java

/** Utility function to convert an Object to some desired Class.
 *
 * Right now this works for://from   w  w  w  . j  ava  2  s.  c  om
 *     arrays <-> Lists,
 *     Holders <-> held values
 * @param arg the array to convert
 * @param destClass the actual class we want
 */
public static Object convert(Object arg, Class destClass) {
    if (destClass == null) {
        return arg;
    }

    Class argHeldType = null;
    if (arg != null) {
        argHeldType = getHolderValueType(arg.getClass());
    }

    if (arg != null && argHeldType == null && destClass.isAssignableFrom(arg.getClass())) {
        return arg;
    }

    if (log.isDebugEnabled()) {
        String clsName = "null";
        if (arg != null)
            clsName = arg.getClass().getName();
        log.debug(Messages.getMessage("convert00", clsName, destClass.getName()));
    }

    // See if a previously converted value is stored in the argument.
    Object destValue = null;
    if (arg instanceof ConvertCache) {
        destValue = ((ConvertCache) arg).getConvertedValue(destClass);
        if (destValue != null)
            return destValue;
    }

    // Get the destination held type or the argument held type if they exist
    Class destHeldType = getHolderValueType(destClass);

    // Convert between Axis special purpose HexBinary and byte[]
    if (arg instanceof HexBinary && destClass == byte[].class) {
        return ((HexBinary) arg).getBytes();
    } else if (arg instanceof byte[] && destClass == HexBinary.class) {
        return new HexBinary((byte[]) arg);
    }

    // Convert between Calendar and Date
    if (arg instanceof Calendar && destClass == Date.class) {
        return ((Calendar) arg).getTime();
    }
    if (arg instanceof Date && destClass == Calendar.class) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime((Date) arg);
        return calendar;
    }

    // Convert between Calendar and java.sql.Date
    if (arg instanceof Calendar && destClass == java.sql.Date.class) {
        return new java.sql.Date(((Calendar) arg).getTime().getTime());
    }

    // Convert between HashMap and Hashtable
    if (arg instanceof HashMap && destClass == Hashtable.class) {
        return new Hashtable((HashMap) arg);
    }

    // Convert an AttachmentPart to the given destination class.
    if (isAttachmentSupported()
            && (arg instanceof InputStream || arg instanceof AttachmentPart || arg instanceof DataHandler)) {
        try {
            String destName = destClass.getName();
            if (destClass == String.class || destClass == OctetStream.class || destClass == byte[].class
                    || destClass == Image.class || destClass == Source.class || destClass == DataHandler.class
                    || destName.equals("javax.mail.internet.MimeMultipart")) {
                DataHandler handler = null;
                if (arg instanceof AttachmentPart) {
                    handler = ((AttachmentPart) arg).getDataHandler();
                } else if (arg instanceof DataHandler) {
                    handler = (DataHandler) arg;
                }
                if (destClass == Image.class) {
                    // Note:  An ImageIO component is required to process an Image
                    // attachment, but if the image would be null
                    // (is.available == 0) then ImageIO component isn't needed
                    // and we can return null.
                    InputStream is = handler.getInputStream();
                    if (is.available() == 0) {
                        return null;
                    } else {
                        ImageIO imageIO = ImageIOFactory.getImageIO();
                        if (imageIO != null) {
                            return getImageFromStream(is);
                        } else {
                            log.info(Messages.getMessage("needImageIO"));
                            return arg;
                        }
                    }
                } else if (destClass == javax.xml.transform.Source.class) {
                    // For a reason unknown to me, the handler's
                    // content is a String.  Convert it to a
                    // StreamSource.
                    return new StreamSource(handler.getInputStream());
                } else if (destClass == OctetStream.class || destClass == byte[].class) {
                    InputStream in = null;
                    if (arg instanceof InputStream) {
                        in = (InputStream) arg;
                    } else {
                        in = handler.getInputStream();
                    }
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    int byte1 = -1;
                    while ((byte1 = in.read()) != -1)
                        baos.write(byte1);
                    return new OctetStream(baos.toByteArray());
                } else if (destClass == DataHandler.class) {
                    return handler;
                } else {
                    return handler.getContent();
                }
            }
        } catch (IOException ioe) {
        } catch (SOAPException se) {
        }
    }

    // If the destination is an array and the source
    // is a suitable component, return an array with 
    // the single item.
    if (arg != null && destClass.isArray() && !destClass.getComponentType().equals(Object.class)
            && destClass.getComponentType().isAssignableFrom(arg.getClass())) {
        Object array = Array.newInstance(destClass.getComponentType(), 1);
        Array.set(array, 0, arg);
        return array;
    }

    // in case destClass is array and arg is ArrayOfT class. (ArrayOfT -> T[])
    if (arg != null && destClass.isArray()) {
        Object newArg = ArrayUtil.convertObjectToArray(arg, destClass);
        if (newArg == null || (newArg != ArrayUtil.NON_CONVERTABLE && newArg != arg)) {
            return newArg;
        }
    }

    // in case arg is ArrayOfT and destClass is an array. (T[] -> ArrayOfT)
    if (arg != null && arg.getClass().isArray()) {
        Object newArg = ArrayUtil.convertArrayToObject(arg, destClass);
        if (newArg != null)
            return newArg;
    }

    // Return if no conversion is available
    if (!(arg instanceof Collection || (arg != null && arg.getClass().isArray()))
            && ((destHeldType == null && argHeldType == null)
                    || (destHeldType != null && argHeldType != null))) {
        return arg;
    }

    // Take care of Holder conversion
    if (destHeldType != null) {
        // Convert arg into Holder holding arg.
        Object newArg = convert(arg, destHeldType);
        Object argHolder = null;
        try {
            argHolder = destClass.newInstance();
            setHolderValue(argHolder, newArg);
            return argHolder;
        } catch (Exception e) {
            return arg;
        }
    } else if (argHeldType != null) {
        // Convert arg into the held type
        try {
            Object newArg = getHolderValue(arg);
            return convert(newArg, destClass);
        } catch (HolderException e) {
            return arg;
        }
    }

    // Flow to here indicates that neither arg or destClass is a Holder

    // Check to see if the argument has a prefered destination class.
    if (arg instanceof ConvertCache && ((ConvertCache) arg).getDestClass() != destClass) {
        Class hintClass = ((ConvertCache) arg).getDestClass();
        if (hintClass != null && hintClass.isArray() && destClass.isArray()
                && destClass.isAssignableFrom(hintClass)) {
            destClass = hintClass;
            destValue = ((ConvertCache) arg).getConvertedValue(destClass);
            if (destValue != null)
                return destValue;
        }
    }

    if (arg == null) {
        return arg;
    }

    // The arg may be an array or List 
    int length = 0;
    if (arg.getClass().isArray()) {
        length = Array.getLength(arg);
    } else {
        length = ((Collection) arg).size();
    }
    if (destClass.isArray()) {
        if (destClass.getComponentType().isPrimitive()) {

            Object array = Array.newInstance(destClass.getComponentType(), length);
            // Assign array elements
            if (arg.getClass().isArray()) {
                for (int i = 0; i < length; i++) {
                    Array.set(array, i, Array.get(arg, i));
                }
            } else {
                int idx = 0;
                for (Iterator i = ((Collection) arg).iterator(); i.hasNext();) {
                    Array.set(array, idx++, i.next());
                }
            }
            destValue = array;

        } else {
            Object[] array;
            try {
                array = (Object[]) Array.newInstance(destClass.getComponentType(), length);
            } catch (Exception e) {
                return arg;
            }

            // Use convert to assign array elements.
            if (arg.getClass().isArray()) {
                for (int i = 0; i < length; i++) {
                    array[i] = convert(Array.get(arg, i), destClass.getComponentType());
                }
            } else {
                int idx = 0;
                for (Iterator i = ((Collection) arg).iterator(); i.hasNext();) {
                    array[idx++] = convert(i.next(), destClass.getComponentType());
                }
            }
            destValue = array;
        }
    } else if (Collection.class.isAssignableFrom(destClass)) {
        Collection newList = null;
        try {
            // if we are trying to create an interface, build something
            // that implements the interface
            if (destClass == Collection.class || destClass == List.class) {
                newList = new ArrayList();
            } else if (destClass == Set.class) {
                newList = new HashSet();
            } else {
                newList = (Collection) destClass.newInstance();
            }
        } catch (Exception e) {
            // Couldn't build one for some reason... so forget it.
            return arg;
        }

        if (arg.getClass().isArray()) {
            for (int j = 0; j < length; j++) {
                newList.add(Array.get(arg, j));
            }
        } else {
            for (Iterator j = ((Collection) arg).iterator(); j.hasNext();) {
                newList.add(j.next());
            }
        }
        destValue = newList;
    } else {
        destValue = arg;
    }

    // Store the converted value in the argument if possible.
    if (arg instanceof ConvertCache) {
        ((ConvertCache) arg).setConvertedValue(destClass, destValue);
    }
    return destValue;
}

From source file:com.collabnet.tracker.core.TrackerWebServicesClient.java

/**
 * Download an attachment from PT//from  www  . j  a  va 2s. c o  m
 * 
 * @param taskId
 * @param attachmentId
 * @return
 * @throws ServiceException
 * @throws NumberFormatException
 * @throws IOException
 */
public InputStream downloadAttachmentAsStream(String taskId, String attachmentId)
        throws ServiceException, NumberFormatException, IOException {

    EngineConfiguration config = mClient.getEngineConfiguration();
    AttachmentService service = new AttachmentServiceLocator(config);
    URL portAddress = mClient.constructServiceURL("/tracker/Attachment");
    AttachmentManager theService = service.getAttachmentService(portAddress);

    DataHandler handler = theService.getAttachment(taskId, Long.parseLong(attachmentId));

    return handler.getInputStream();
    //
    // byte[] attachment = null;
    // InputStream inputStream = null;
    // ByteArrayOutputStream baos = null;
    // try {
    // inputStream = handler.getInputStream();
    // baos = new ByteArrayOutputStream(2048);
    // byte[] buffer = new byte[2048];
    // int n = 0;
    // while (-1 != (n = inputStream.read(buffer))) {
    // baos.write(buffer, 0, n);
    // }
    //
    // attachment = baos.toByteArray();
    // baos.close();
    // inputStream.close();
    // return attachment;
    // } finally {
    // if (baos != null)
    // baos.close();
    // if (inputStream != null)
    // inputStream.close();
    // }
}

From source file:org.wso2.carbon.bpmn.rest.service.base.BaseExecutionService.java

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");
    }//w  ww.  ja va  2  s  .  co m
    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());
    }

}

From source file:cz.zcu.kiv.eegdatabase.webservices.client.ClientServiceImpl.java

@Override
public int addDataFile(DataFileInfo info, DataHandler inputData) throws ClientServiceException {
    DataFile file = new DataFile();
    Experiment e = experimentDao.read(info.getExperimentId());
    file.setExperiment(e);//from  www .  ja v  a2s .c o m
    file.setDescription(info.getDescription());
    file.setFilename(info.getFilename());
    file.setMimetype(info.getMimetype());

    try {
        if (inputData != null) {

            file.setFileContent(Hibernate.createBlob(inputData.getInputStream()));
        }
    } catch (IOException ex) {
        log.error(ex.getMessage(), ex);
        throw new ClientServiceException(ex);
    }

    int fileId = dataFileDao.create(file);
    e.getDataFiles().add(file);
    experimentDao.update(e);
    log.debug("User " + personDao.getLoggedPerson().getEmail() + " created new data file (primary key " + fileId
            + ").");
    return fileId;
}

From source file:org.apache.axis.handlers.MD5AttachHandler.java

public void invoke(MessageContext msgContext) throws AxisFault {
    log.debug("Enter: MD5AttachHandler::invoke");
    try {/*from  w  w  w  . j a  va2 s. co m*/
        // log.debug("IN MD5");        
        Message msg = msgContext.getRequestMessage();
        SOAPConstants soapConstants = msgContext.getSOAPConstants();
        org.apache.axis.message.SOAPEnvelope env = (org.apache.axis.message.SOAPEnvelope) msg.getSOAPEnvelope();
        org.apache.axis.message.SOAPBodyElement sbe = env.getFirstBody();//env.getBodyByName("ns1", "addedfile");
        org.w3c.dom.Element sbElement = sbe.getAsDOM();
        //get the first level accessor  ie parameter
        org.w3c.dom.Node n = sbElement.getFirstChild();

        for (; n != null && !(n instanceof org.w3c.dom.Element); n = n.getNextSibling())
            ;
        org.w3c.dom.Element paramElement = (org.w3c.dom.Element) n;
        //Get the href associated with the attachment.
        String href = paramElement.getAttribute(soapConstants.getAttrHref());
        org.apache.axis.Part ap = msg.getAttachmentsImpl().getAttachmentByReference(href);
        javax.activation.DataHandler dh = org.apache.axis.attachments.AttachmentUtils
                .getActivationDataHandler(ap);
        org.w3c.dom.Node timeNode = paramElement.getFirstChild();
        long startTime = -1;

        if (timeNode != null && timeNode instanceof org.w3c.dom.Text) {
            String startTimeStr = ((org.w3c.dom.Text) timeNode).getData();

            startTime = Long.parseLong(startTimeStr);
        }
        // log.debug("GOTIT");

        long receivedTime = System.currentTimeMillis();
        long elapsedTime = -1;

        // log.debug("startTime=" + startTime);
        // log.debug("receivedTime=" + receivedTime);            
        if (startTime > 0)
            elapsedTime = receivedTime - startTime;
        String elapsedTimeStr = elapsedTime + "";
        // log.debug("elapsedTimeStr=" + elapsedTimeStr);            

        java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
        java.io.InputStream attachmentStream = dh.getInputStream();
        int bread = 0;
        byte[] buf = new byte[64 * 1024];

        do {
            bread = attachmentStream.read(buf);
            if (bread > 0) {
                md.update(buf, 0, bread);
            }
        } while (bread > -1);
        attachmentStream.close();
        buf = null;
        //Add the mime type to the digest.
        String contentType = dh.getContentType();

        if (contentType != null && contentType.length() != 0) {
            md.update(contentType.getBytes("US-ASCII"));
        }

        sbe = env.getFirstBody();
        sbElement = sbe.getAsDOM();
        //get the first level accessor  ie parameter
        n = sbElement.getFirstChild();
        for (; n != null && !(n instanceof org.w3c.dom.Element); n = n.getNextSibling())
            ;
        paramElement = (org.w3c.dom.Element) n;
        // paramElement.setAttribute(soapConstants.getAttrHref(), respHref);
        String MD5String = org.apache.axis.encoding.Base64.encode(md.digest());
        String senddata = " elapsedTime=" + elapsedTimeStr + " MD5=" + MD5String;

        // log.debug("senddata=" + senddata);            
        paramElement.appendChild(paramElement.getOwnerDocument().createTextNode(senddata));

        sbe = new org.apache.axis.message.SOAPBodyElement(sbElement);
        env.clearBody();
        env.addBodyElement(sbe);
        msg = new Message(env);

        msgContext.setResponseMessage(msg);
    } catch (Exception e) {
        log.error(Messages.getMessage("exception00"), e);
        throw AxisFault.makeFault(e);
    }

    log.debug("Exit: MD5AttachHandler::invoke");
}

From source file:cz.zcu.kiv.eegdatabase.webservices.datadownload.UserDataImpl.java

@Override
public int addOrUpdateDataFile(DataFileInfo dataFile, DataHandler inputData) throws UserDataServiceException {
    DataFile file;//from w  w  w  .j a  v  a2s  .co m
    if (dataFile.isAdded()) {
        file = new DataFile();
    } else {
        file = (DataFile) experimentDao.getDataFilesWhereId(dataFile.getFileId()).get(0);
    }
    file.setExperiment((Experiment) experimentDao.read(dataFile.getExperimentId()));
    file.setDescription(dataFile.getDescription());
    file.setFilename(dataFile.getFileName());
    file.setMimetype(dataFile.getMimeType());

    try {
        if (inputData != null) {
            file.setFileContent(Hibernate.createBlob(inputData.getInputStream()));
        }
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        throw new UserDataServiceException(e);
    }

    if (dataFile.isAdded()) {
        int fileId = dataFileDao.create(file);
        log.debug("User " + personDao.getLoggedPerson().getEmail() + " created new data file (primary key "
                + fileId + ").");
        return fileId;
    } else {
        dataFileDao.update(file);
        log.debug("User " + personDao.getLoggedPerson().getEmail() + " edited existing data file (primary key "
                + file.getDataFileId() + ").");
        return file.getDataFileId();
    }
}

From source file:org.wso2.carbon.bpmn.rest.service.base.BaseTaskService.java

protected RestVariable setBinaryVariable(MultipartBody multipartBody, Task task, boolean isNew, UriInfo uriInfo)
        throws IOException {

    boolean debugEnabled = log.isDebugEnabled();

    if (debugEnabled) {
        log.debug("Processing Binary variables");
    }/* w  ww.  j  av a  2  s.  c  o m*/

    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());
    }
}

From source file:com.idega.xroad.client.business.impl.XRoadServicesImpl.java

@Override
public java.io.InputStream getProcessedDocument(String serviceProviderID, String documentID, User user) {
    com.idega.xroad.client.wsdl.EhubserviceServiceStub.Document response = getDocument(serviceProviderID,
            documentID, user);/*w ww.j  a  v a  2s .c  o m*/
    if (response == null) {
        getLogger()
                .warning("Unable to get: " + com.idega.xroad.client.wsdl.EhubserviceServiceStub.Document.class
                        + " by service provider ID: " + serviceProviderID + " and document id: " + documentID);
        return null;
    }

    DataHandler documentHandler = response.getDocument();
    try {
        return documentHandler.getInputStream();
    } catch (IOException e) {
        getLogger().log(Level.WARNING, "Unable to open stream for document reading: ", e);
    }

    return null;
}

From source file:com.idega.xroad.client.business.impl.XRoadServicesImpl.java

@Override
public java.io.InputStream getXFormsDocumentTemplate(String serviceProviderID, String documentID, User user) {
    com.idega.xroad.client.wsdl.EhubserviceServiceStub.Document response = getDocument(serviceProviderID,
            documentID, user);/*w ww  .  j  a va 2 s.  c  o m*/
    if (response == null) {
        getLogger().warning("Unable to get: " + Response_type6.class + " by service provider ID: "
                + serviceProviderID + " and document id: " + documentID);
        return null;
    }

    DataHandler documentHandler = response.getXFormsTemplate();
    try {
        return documentHandler.getInputStream();
    } catch (IOException e) {
        getLogger().log(Level.WARNING, "Unable to open stream for document reading: ", e);
    }

    return null;
}