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.bimserver.shared.json.JsonConverter.java

public JsonElement toJson(Object object) throws IOException {
    if (object instanceof SBase) {
        SBase base = (SBase) object;/* w w  w  .  j  av a 2  s .co m*/
        JsonObject jsonObject = new JsonObject();
        jsonObject.add("__type", new JsonPrimitive(base.getSClass().getSimpleName()));
        for (SField field : base.getSClass().getOwnFields()) {
            jsonObject.add(field.getName(), toJson(base.sGet(field)));
        }
        return jsonObject;
    } else if (object instanceof Collection) {
        Collection<?> collection = (Collection<?>) object;
        JsonArray jsonArray = new JsonArray();
        for (Object value : collection) {
            jsonArray.add(toJson(value));
        }
        return jsonArray;
    } else if (object instanceof Date) {
        return new JsonPrimitive(((Date) object).getTime());
    } else if (object instanceof DataHandler) {
        DataHandler dataHandler = (DataHandler) object;
        InputStream inputStream = dataHandler.getInputStream();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        IOUtils.copy(inputStream, out);
        return new JsonPrimitive(new String(Base64.encodeBase64(out.toByteArray()), Charsets.UTF_8));
    } else if (object instanceof Boolean) {
        return new JsonPrimitive((Boolean) object);
    } else if (object instanceof String) {
        return new JsonPrimitive((String) object);
    } else if (object instanceof Long) {
        return new JsonPrimitive((Long) object);
    } else if (object instanceof Integer) {
        return new JsonPrimitive((Integer) object);
    } else if (object instanceof Double) {
        return new JsonPrimitive((Double) object);
    } else if (object instanceof Enum) {
        return new JsonPrimitive(object.toString());
    } else if (object == null) {
        return JsonNull.INSTANCE;
    } else if (object instanceof byte[]) {
        byte[] data = (byte[]) object;
        return new JsonPrimitive(new String(Base64.encodeBase64(data), Charsets.UTF_8));
    }
    throw new UnsupportedOperationException(object.getClass().getName());
}

From source file:org.apache.stratos.logging.view.ui.LogViewerClient.java

public void downloadArchivedLogFiles(String logFile, HttpServletResponse response, String domain,
        String serverKey) throws Exception {
    try {//  w w  w.j a  v a  2  s.  c om
        logFile = logFile.replace(".gz", "");
        ServletOutputStream outputStream = response.getOutputStream();
        response.setContentType("application/txt");
        response.setHeader("Content-Disposition", "attachment;filename=" + logFile.replaceAll("\\s", "_"));
        DataHandler data = stub.downloadArchivedLogFiles(logFile, domain, serverKey);
        InputStream fileToDownload = data.getInputStream();
        int c;
        while ((c = fileToDownload.read()) != -1) {
            outputStream.write(c);
        }
        outputStream.flush();
        outputStream.flush();
    } catch (Exception e) {
        String msg = "Error occurred while getting logger data. Backend service may be unavailable";
        log.error(msg, e);
        throw e;
    }
}

From source file:org.apache.axiom.util.stax.XMLStreamReaderUtilsTest.java

private void testGetDataHandlerFromElementWithZeroLength(boolean useDHR) throws Exception {
    XMLStreamReader reader = StAXUtils.createXMLStreamReader(new StringReader("<test/>"));
    if (useDHR) {
        // To have an XMLStreamReader that uses the DataHandlerReader extension, we wrap
        // the parser using an XOPDecodingStreamReader (even if the document doesn't contain
        // any xop:Include).
        reader = new XOPDecodingStreamReader(reader, null);
    }/*from   w  ww. jav a2  s .  com*/
    try {
        reader.next();

        // Check precondition
        assertTrue(reader.isStartElement());

        DataHandler dh = XMLStreamReaderUtils.getDataHandlerFromElement(reader);

        // Check postcondition
        assertTrue(reader.isEndElement());
        assertEquals(-1, dh.getInputStream().read());
    } finally {
        reader.close();
    }
}

From source file:org.bimserver.shared.pb.ProtocolBuffersConverter.java

@SuppressWarnings({ "unchecked", "rawtypes" })
public Message convertSObjectToProtocolBuffersObject(SBase object, SClass definedType) throws ConvertException {
    Builder builder = null;//from  w  w  w. j ava2  s  .co  m
    MessageDescriptorContainer messageDescriptor = protocolBuffersMetaData
            .getMessageDescriptor(definedType.getSimpleName());
    if (messageDescriptor == null) {
        throw new ConvertException("No message descriptor found with name " + definedType.getSimpleName());
    }
    Descriptor definedDescriptor = messageDescriptor.getDescriptor();
    try {
        builder = DynamicMessage.getDefaultInstance(definedDescriptor).newBuilderForType();
    } catch (SecurityException e) {
        throw new ConvertException(e);
    } catch (IllegalArgumentException e) {
        throw new ConvertException(e);
    }
    SClass sClass = object.getSClass();
    SClass superClass = sClass;
    while (superClass.getSuperClass() != null
            && superClass.getSuperClass().getInstanceClass() != Object.class) {
        superClass = superClass.getSuperClass();
    }
    if (sClass != superClass && messageDescriptor.getField("__actual_type") != null) {
        builder.setField(messageDescriptor.getField("__actual_type"), sClass.getSimpleName());
        builder.setField(messageDescriptor.getField("__" + sClass.getSimpleName()),
                convertSObjectToProtocolBuffersObject(object, sClass));
    }
    for (SField field : definedType.getAllFields()) {
        try {
            Object value = object.sGet(field);
            FieldDescriptor fieldDescriptor = messageDescriptor.getField(field.getName());
            if (value != null) {
                if (value.getClass().isPrimitive() || value.getClass() == String.class
                        || value.getClass() == Long.class || value.getClass() == Double.class
                        || value.getClass() == Integer.class || value.getClass() == Boolean.class) {
                    builder.setField(fieldDescriptor, value);
                } else if (value.getClass().isEnum()) {
                    Enum eNum = (Enum) value;
                    int ordinal = eNum.ordinal();
                    EnumValueDescriptor findValueByNumber = fieldDescriptor.getEnumType()
                            .findValueByNumber(ordinal);
                    builder.setField(fieldDescriptor, findValueByNumber);
                } else if (value.getClass() == Date.class) {
                    builder.setField(fieldDescriptor, ((Date) value).getTime());
                } else if (value.getClass() == DataHandler.class) {
                    DataHandler dataHandler = (DataHandler) value;
                    InputStream inputStream = dataHandler.getInputStream();
                    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                    IOUtils.copy(inputStream, byteArrayOutputStream);
                    ByteString byteString = ByteString.copyFrom(byteArrayOutputStream.toByteArray());
                    builder.setField(fieldDescriptor, byteString);
                } else if (List.class.isAssignableFrom(value.getClass())) {
                    List list = (List) value;
                    List newList = new ArrayList();
                    for (Object o : list) {
                        if (fieldDescriptor.getJavaType() == JavaType.MESSAGE) {
                            newList.add(
                                    convertSObjectToProtocolBuffersObject((SBase) o, field.getGenericType()));
                        } else {
                            newList.add(o);
                        }
                    }
                    builder.setField(fieldDescriptor, newList);
                } else {
                    LOGGER.error("Unimplemented: " + fieldDescriptor.getName() + ": " + value);
                }
            }
        } catch (SecurityException e) {
            LOGGER.error("", e);
        } catch (IllegalArgumentException e) {
            LOGGER.error("", e);
        } catch (IOException e) {
            LOGGER.error("", e);
        }
    }
    return builder.build();
}

From source file:org.bimserver.shared.pb.Reflector.java

@SuppressWarnings({ "rawtypes", "unchecked" })
public Object callMethod(String interfaceName, String methodName, Class<?> definedReturnType, Object... args)
        throws ServerException, UserException {
    try {/*from  w  w w.j  ava  2 s .  co  m*/
        MethodDescriptorContainer methodDescriptorContainer = protocolBuffersMetaData.getMethod(interfaceName,
                methodName);
        SMethod sMethod = sService.getSMethod(methodName);
        Descriptor inputDescriptor = methodDescriptorContainer.getInputDescriptor();
        Builder builder = DynamicMessage.newBuilder(methodDescriptorContainer.getInputDescriptor());
        int i = 0;
        for (FieldDescriptor field : inputDescriptor.getFields()) {
            Object arg = args[i];
            if (field.getJavaType() == JavaType.ENUM) {
                EnumDescriptor enumType = field.getEnumType();
                builder.setField(field, enumType.findValueByName(arg.toString()));
            } else {
                if (arg instanceof SBase) {
                    builder.setField(field, convertSObjectToProtocolBuffersObject((SBase) arg,
                            sMethod.getParameter(i).getType()));
                } else if (arg instanceof DataHandler) {
                    DataHandler dataHandler = (DataHandler) arg;
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    try {
                        IOUtils.copy(dataHandler.getInputStream(), baos);
                    } catch (IOException e) {
                        LOGGER.error("", e);
                    }
                    builder.setField(field, ByteString.copyFrom(baos.toByteArray()));
                } else {
                    if (arg != null) {
                        if (arg instanceof Collection) {
                            Collection col = (Collection) arg;
                            Iterator iterator = col.iterator();
                            while (iterator.hasNext()) {
                                Object o = iterator.next();
                                builder.addRepeatedField(field, o);
                            }
                        } else {
                            builder.setField(field, arg);
                        }
                    }
                }
            }
            i++;
        }
        DynamicMessage message = builder.build();
        Message result = channel.callBlockingMethod(methodDescriptorContainer, message);
        FieldDescriptor errorMessageField = methodDescriptorContainer.getOutputField("errorMessage");
        String errorMessage = (String) result.getField(errorMessageField);
        if (errorMessage.equals("OKE")) {
            if (result.getDescriptorForType().getName().equals("VoidResponse")) {
                return null;
            } else {
                FieldDescriptor outputField = methodDescriptorContainer.getOutputField("value");
                Object value = result.getField(outputField);
                if (outputField.isRepeated()) {
                    if (value instanceof Collection) {
                        Collection collection = (Collection) value;
                        Collection x = null;
                        if (definedReturnType == List.class) {
                            x = new ArrayList();
                        } else if (definedReturnType == Set.class) {
                            x = new HashSet();
                        }
                        for (Object v : collection) {
                            if (v instanceof DynamicMessage) {
                                x.add(convertProtocolBuffersMessageToSObject((DynamicMessage) v, null,
                                        sMethod.getBestReturnType()));
                            } else {
                                x.add(v);
                            }
                        }
                        return x;
                    } else {
                        return new ArrayList();
                    }
                } else if (outputField.getJavaType() == JavaType.ENUM) {
                    EnumDescriptor enumType = outputField.getEnumType();
                    return enumType.findValueByName(value.toString());
                } else if (value instanceof DynamicMessage) {
                    return convertProtocolBuffersMessageToSObject((DynamicMessage) value, null,
                            sMethod.getBestReturnType());
                } else {
                    if (definedReturnType == Date.class) {
                        return new Date((Long) value);
                    }
                    return value;
                }
            }
        } else {
            throw new UserException(errorMessage);
        }
    } catch (ConvertException e) {
        throw new ServerException(e);
    } catch (ServiceException e) {
        throw new ServerException(e.getMessage());
    }
}

From source file:org.apache.axiom.util.stax.XMLStreamReaderUtilsTest.java

private void testGetDataHandlerFromElementNonCoalescing(boolean useDHR) throws Exception {
    // We generate base64 that is sufficiently large to force the parser to generate
    // multiple CHARACTER events
    StringBuffer buffer = new StringBuffer("<test>");
    Base64EncodingStringBufferOutputStream out = new Base64EncodingStringBufferOutputStream(buffer);
    byte[] data = new byte[65536];
    new Random().nextBytes(data);
    out.write(data);/*ww  w. j av a2s  . c  o  m*/
    out.complete();
    buffer.append("</test>");
    XMLStreamReader reader = StAXUtils.createXMLStreamReader(StAXParserConfiguration.NON_COALESCING,
            new StringReader(buffer.toString()));
    if (useDHR) {
        reader = new XOPDecodingStreamReader(reader, null);
    }
    try {
        reader.next();

        // Check precondition
        assertTrue(reader.isStartElement());

        DataHandler dh = XMLStreamReaderUtils.getDataHandlerFromElement(reader);

        // Check postcondition
        assertTrue(reader.isEndElement());
        assertTrue(Arrays.equals(data, IOUtils.toByteArray(dh.getInputStream())));
    } finally {
        reader.close();
    }
}

From source file:org.wso2.carbon.logging.view.ui.LogViewerClient.java

public void downloadArchivedLogFiles(String logFile, HttpServletResponse response, String tenantDomain,
        String serverKey) throws RemoteException, LogViewerException {
    String msg = "Error occurred while getting logger data. Backend service may be " + "unavailable";

    InputStream fileToDownload = null;
    try {//from www .  j a  v  a2s  .  co  m
        logFile = logFile.replace(".gz", "");
        ServletOutputStream outputStream = response.getOutputStream();
        response.setContentType("application/txt");
        response.setHeader("Content-Disposition", "attachment;filename=" + logFile.replaceAll("\\s", "_"));
        DataHandler data = stub.downloadArchivedLogFiles(logFile, tenantDomain, serverKey);
        fileToDownload = data.getInputStream();
        int c;
        while ((c = fileToDownload.read()) != -1) {
            outputStream.write(c);
        }
        outputStream.flush();
        outputStream.flush();
    } catch (RemoteException e) {
        log.error(msg, e);
        throw e;
    } catch (LogViewerException e) {
        log.error(msg, e);
        throw e;
    } catch (IOException e) {
        String errorWhileDownloadingMsg = "Error while downloading file.";
        log.error(errorWhileDownloadingMsg, e);
        throw new LogViewerException(errorWhileDownloadingMsg, e);
    } finally {
        try {
            if (fileToDownload != null) {
                fileToDownload.close();
            }
        } catch (IOException e) {
            log.error("Couldn't close the InputStream " + e.getMessage(), e);
        }
    }
}

From source file:it.cnr.icar.eric.client.xml.registry.infomodel.ExtrinsicObjectImpl.java

/**
 * Gets the size in bytes of repositoryItem associated with this objects (if any). 
 *
 * Add to JAXR 2.0/*from  w w  w .  ja v  a  2 s.c om*/
 *
 * @return if object has repositoryItem return its size in bytes.
 *  if object has no repositoryItem return 0
 */
public long getRepositoryItemSize() throws JAXRException {
    long size = 0;

    InputStream is = null;
    try {
        DataHandler dh = getRepositoryItem();

        if (dh != null) {
            is = dh.getInputStream();

            while (is.read() != -1) {
                size++;
            }
        }
    } catch (IOException e) {
        throw new JAXRException(e);
    } finally {
        try {
            if (is != null) {
                is.close();
            }
        } catch (Exception e) {
            log.error(e, e);
        }
    }

    return size;
}

From source file:org.shredzone.cilla.admin.AbstractImageBean.java

/**
 * Creates a {@link StreamedContent} for the given {@link DataHandler}, with the image
 * having the given width and height. The aspect ratio is kept. A PNG type image is
 * returned./*www.  j a  v  a 2  s  .c  o m*/
 * <p>
 * <em>NOTE:</em> The scaled image is cached related to the {@link DataHandler}. Thus,
 * it is not possible to create different sizes of the same {@link DataHandler} using
 * this method. A weak cache is used, to keep the memory footprint as small as
 * possible.
 *
 * @param dh
 *            {@link DataHandler} to stream
 * @param process
 *            Width, height and image type to be used
 * @return {@link StreamedContent} containing that image
 */
protected StreamedContent createStreamedContent(DataHandler dh, ImageProcessing process) {
    byte[] scaledData = null;
    if (dh != null) {
        scaledData = weakScaleCache.get(dh);
        if (scaledData == null) {
            try {
                BufferedImage image = ImageIO.read(dh.getInputStream());
                if (image != null) {
                    BufferedImage scaled = scale(image, process.getWidth(), process.getHeight());
                    try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
                        ImageIO.write(scaled, process.getType().getFormatName(), bos);
                        scaledData = bos.toByteArray();
                    }
                    if (weakScaleCache.size() < maxCache) {
                        weakScaleCache.put(dh, scaledData);
                    }
                }
            } catch (IOException ex) {
                log.error("Exception while streaming scaled content: " + dh.getName(), ex);
            }
        }
    }

    if (scaledData != null) {
        return new DefaultStreamedContent(new ByteArrayInputStream(scaledData),
                process.getType().getContentType());
    } else {
        return createEmptyStreamedContent();
    }
}

From source file:org.bimserver.shared.pb.ProtocolBuffersReflector.java

@SuppressWarnings({ "rawtypes", "unchecked" })
@Override//  w  ww .  j  a v a 2s  .  c  o m
public Object callMethod(String interfaceName, String methodName, Class<?> definedReturnType,
        KeyValuePair... args) throws ServerException, UserException {
    try {
        MethodDescriptorContainer methodDescriptorContainer;
        try {
            methodDescriptorContainer = protocolBuffersMetaData.getMethod(interfaceName, methodName);
            SMethod sMethod = servicesMap.getBySimpleName(interfaceName).getSMethod(methodName);
            Descriptor inputDescriptor = methodDescriptorContainer.getInputDescriptor();
            Builder builder = DynamicMessage.newBuilder(methodDescriptorContainer.getInputDescriptor());
            int i = 0;
            for (FieldDescriptor field : inputDescriptor.getFields()) {
                Object arg = args[i].getValue();
                if (field.getJavaType() == JavaType.ENUM) {
                    EnumDescriptor enumType = field.getEnumType();
                    builder.setField(field, enumType.findValueByName(arg.toString()));
                } else {
                    if (arg instanceof SBase) {
                        builder.setField(field, convertSObjectToProtocolBuffersObject((SBase) arg,
                                sMethod.getParameter(i).getType()));
                    } else if (arg instanceof DataHandler) {
                        DataHandler dataHandler = (DataHandler) arg;
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        try {
                            IOUtils.copy(dataHandler.getInputStream(), baos);
                        } catch (IOException e) {
                            LOGGER.error("", e);
                        }
                        builder.setField(field, ByteString.copyFrom(baos.toByteArray()));
                    } else {
                        if (arg != null) {
                            if (arg instanceof Collection) {
                                Collection col = (Collection) arg;
                                Iterator iterator = col.iterator();
                                while (iterator.hasNext()) {
                                    Object o = iterator.next();
                                    builder.addRepeatedField(field, o);
                                }
                            } else {
                                builder.setField(field, arg);
                            }
                        }
                    }
                }
                i++;
            }
            DynamicMessage message = builder.build();
            Message result = channel.callBlockingMethod(methodDescriptorContainer, message);
            FieldDescriptor errorMessageField = methodDescriptorContainer.getOutputField("errorMessage");
            String errorMessage = (String) result.getField(errorMessageField);
            if (errorMessage.equals("OKE")) {
                if (result.getDescriptorForType().getName().equals("VoidResponse")) {
                    return null;
                } else {
                    FieldDescriptor outputField = methodDescriptorContainer.getOutputField("value");
                    Object value = result.getField(outputField);
                    if (outputField.isRepeated()) {
                        if (value instanceof Collection) {
                            Collection collection = (Collection) value;
                            Collection x = null;
                            if (definedReturnType == List.class) {
                                x = new ArrayList();
                            } else if (definedReturnType == Set.class) {
                                x = new HashSet();
                            }
                            for (Object v : collection) {
                                if (v instanceof DynamicMessage) {
                                    x.add(convertProtocolBuffersMessageToSObject((DynamicMessage) v, null,
                                            sMethod.getBestReturnType()));
                                } else {
                                    x.add(v);
                                }
                            }
                            return x;
                        } else {
                            return new ArrayList();
                        }
                    } else if (outputField.getJavaType() == JavaType.ENUM) {
                        EnumDescriptor enumType = outputField.getEnumType();
                        return enumType.findValueByName(value.toString());
                    } else if (value instanceof DynamicMessage) {
                        return convertProtocolBuffersMessageToSObject((DynamicMessage) value, null,
                                sMethod.getBestReturnType());
                    } else {
                        if (definedReturnType == Date.class) {
                            return new Date((Long) value);
                        }
                        return value;
                    }
                }
            } else {
                throw new UserException(errorMessage);
            }
        } catch (ConvertException e) {
            throw new ServerException(e);
        } catch (ServiceException e) {
            throw new ServerException(e.getMessage());
        }
    } catch (ServiceNotFoundException e) {
        throw new ServerException(e);
    } catch (ServiceMethodNotFoundException e) {
        throw new ServerException(e);
    }
}