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.tests.TestBimQlSoap.java

public static void main(String[] args) {
    BimServerClientFactory factory = new SoapBimServerClientFactory("localhost");
    try {/*  w w  w  .  jav  a  2  s  .  com*/
        BimServerClient bimServerClient = factory
                .create(new UsernamePasswordAuthenticationInfo("admin@bimserver.org", "admin"));

        List<SProject> projects = bimServerClient.getBimsie1ServiceInterface().getAllProjects(true, true);
        if (projects.isEmpty()) {
            throw new RuntimeException("No projects");
        }
        for (SProject project : projects) {
            List<SRevision> revisionsOfProject = bimServerClient.getBimsie1ServiceInterface()
                    .getAllRevisionsOfProject(project.getOid());
            if (!revisionsOfProject.isEmpty()) {
                SRevision revision = revisionsOfProject.get(0);
                SSerializerPluginConfiguration serializerPluginConfiguration = bimServerClient
                        .getBimsie1ServiceInterface().getSerializerByContentType("application/ifc");
                SQueryEnginePluginConfiguration queryEngine = bimServerClient.getBimsie1ServiceInterface()
                        .getQueryEngineByName("BimQL Engine");
                if (queryEngine == null) {
                    throw new RuntimeException("No BIMQL query engines found");
                }
                Long downloadId = bimServerClient.getBimsie1ServiceInterface().downloadQuery(revision.getOid(),
                        queryEngine.getOid(), "Select $Var1Where $Var1.EntityType = IfcDoor", true,
                        serializerPluginConfiguration.getOid());
                SDownloadResult downloadData = bimServerClient.getBimsie1ServiceInterface()
                        .getDownloadData(downloadId);
                DataHandler dataHandler = downloadData.getFile();
                IOUtils.copy(dataHandler.getInputStream(), new FileOutputStream(new File("test.ifc")));
            }
        }
    } catch (ChannelConnectionException e) {
        e.printStackTrace();
    } catch (ServerException e) {
        e.printStackTrace();
    } catch (UserException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ServiceException e) {
        e.printStackTrace();
    } catch (PublicInterfaceNotFoundException e) {
        e.printStackTrace();
    }
}

From source file:org.apache.axis.attachments.ManagedMemoryDataSource.java

/**
 * Method main//from w  w w .  j a  v a2  s.  com
 *
 * @param arg
 */
public static void main(String arg[]) { // test

    try {
        String readFile = arg[0];
        String writeFile = arg[1];
        java.io.FileInputStream ss = new java.io.FileInputStream(readFile);
        ManagedMemoryDataSource ms = new ManagedMemoryDataSource(ss, 1024 * 1024, "foo/data", true);
        javax.activation.DataHandler dh = new javax.activation.DataHandler(ms);
        java.io.InputStream is = dh.getInputStream();
        java.io.FileOutputStream fo = new java.io.FileOutputStream(writeFile);
        byte[] buf = new byte[512];
        int read = 0;

        do {
            read = is.read(buf);

            if (read > 0) {
                fo.write(buf, 0, read);
            }
        } while (read > -1);

        fo.close();
        is.close();
    } catch (java.lang.Exception e) {
        log.error(Messages.getMessage("exception00"), e);
    }
}

From source file:es.caib.sgtsic.util.DataHandlers.java

public static byte[] dataHandlerToByteArray(DataHandler dataHandler) throws IOException {

    InputStream is = dataHandler.getInputStream();
    return IOUtils.toByteArray(is);

}

From source file:org.ojbc.util.camel.helper.MtomUtils.java

/**
 * Get the MTOM attachment by attachmentId from an exchange. 
 * @param exchange//  w w  w.ja v  a 2s  .co  m
 * @param transactionNumber
 * @param attachmentId
 * @return
 * @throws IOException
 */
public static byte[] getAttachment(Exchange exchange, String transactionNumber, String attachmentId)
        throws IOException {
    byte[] attachment;
    DataHandler dataHandler = exchange.getIn().getAttachment(StringUtils.substringAfter(attachmentId, "cid:"));

    if (dataHandler != null) {
        attachment = IOUtils.readBytesFromStream(dataHandler.getInputStream());
    } else {
        log.error("No valid file found in the attachement for transaction "
                + StringUtils.trimToEmpty(transactionNumber));
        throw new IllegalArgumentException("No file found in the attachement");
    }
    return attachment;
}

From source file:org.apromore.util.StreamUtil.java

/**
 * Convert a DataHandler to a String//from   www  .  jav a 2s  .c  om
 *
 * @param dh the DataHandler to convert
 * @return the string for that DataHandler
 */
public static String convertStreamToString(final DataHandler dh) {
    try {
        return inputStream2String(dh.getInputStream());
    } catch (IOException e) {
        return "error in readin the DataHandler: " + e.toString();
    }
}

From source file:org.apache.stratos.theme.mgt.ui.processors.AddThemeResourceProcessor.java

private static DataHandler scaleImage(DataHandler dataHandler, int height, int width) throws IOException {

    Image image = ImageIO.read(new BufferedInputStream(dataHandler.getInputStream()));
    // Check if the image has transparent pixels
    boolean hasAlpha = ((BufferedImage) image).getColorModel().hasAlpha();

    // Maintain Aspect ratio
    int thumbHeight = height;
    int thumbWidth = width;
    double thumbRatio = (double) width / (double) height;
    double imageRatio = (double) image.getWidth(null) / (double) image.getHeight(null);
    if (thumbRatio < imageRatio) {
        thumbHeight = (int) (thumbWidth / imageRatio);
    } else {//from  ww w  . java  2 s .c o  m
        thumbWidth = (int) (thumbHeight * imageRatio);
    }

    BufferedImage thumb;
    // Check if transparent pixels are available and set the color mode accordingly 
    if (hasAlpha) {
        thumb = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_ARGB);
    } else {
        thumb = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB);
    }
    Graphics2D graphics2D = thumb.createGraphics();
    graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null);

    // Save the image as PNG so that transparent images are rendered as intended
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    ImageIO.write(thumb, "PNG", output);

    DataSource dataSource = new ByteArrayDataSource(output.toByteArray(), "application/octet-stream");
    return new DataHandler(dataSource);
}

From source file:be.medx.mcn.SendRequestMapper.java

private static byte[] convertToByteArray(final DataHandler value) throws TechnicalConnectorException {
    if (value == null) {
        return new byte[0];
    }/*from w  w  w  . j ava 2  s  .c o m*/
    try {
        return IOUtils.toByteArray(value.getInputStream());
    } catch (IOException e) {
        throw new TechnicalConnectorException();
    }
}

From source file:org.chemid.structure.dbclient.chemspider.ChemSpiderClient.java

/**
 * @param dh//from ww  w  . ja va 2s.c  o m
 * @param location
 * @return savedpath
 * @throws ChemIDStructureException
 */
private static String saveFile(DataHandler dh, String location) throws ChemIDStructureException {
    String savedFile = null;
    InputStream is = null;
    try {
        is = dh.getInputStream();
        File dir = new File(location);
        dir.mkdirs();
        String fileName = new SimpleDateFormat(Constants.ZIP_FILE_NAME).format(new Date());
        File tmp = new File(dir, fileName);
        OutputStream os = new FileOutputStream(tmp);
        // This will copy the file from the two streams
        IOUtils.copy(is, os);
        // This will close two streams catching exception
        IOUtils.closeQuietly(os);
        IOUtils.closeQuietly(is);
        if (location.endsWith(Constants.LOCATION_SEPARATOR)) {
            savedFile = location + fileName;

        } else {
            savedFile = location + Constants.LOCATION_SEPARATOR + fileName;
        }
    } catch (IOException e) {
        throw new ChemIDStructureException("error occured while saving chemspider sdf file to the location", e);

    }
    return savedFile;
}

From source file:it.cnr.icar.eric.client.xml.registry.util.CertificateUtil.java

@SuppressWarnings("static-access")
private static Certificate[] getCertificateSignedByRegistry(LifeCycleManager lcm, X509Certificate inCert)
        throws JAXRException {
    Certificate[] certChain = new Certificate[2];

    try {/*  w  ww.  j av  a  2s.com*/
        // Save cert in a temporary keystore file which is sent as
        // repository item to server so it can be signed
        KeyStore tmpKeystore = KeyStore.getInstance("JKS");
        tmpKeystore.load(null, bu.FREEBXML_REGISTRY_KS_PASS_REQ.toCharArray());

        tmpKeystore.setCertificateEntry(bu.FREEBXML_REGISTRY_USERCERT_ALIAS_REQ, inCert);
        File repositoryItemFile = File.createTempFile(".eric-ca-req", ".jks");
        repositoryItemFile.deleteOnExit();
        FileOutputStream fos = new java.io.FileOutputStream(repositoryItemFile);
        tmpKeystore.store(fos, bu.FREEBXML_REGISTRY_KS_PASS_REQ.toCharArray());
        fos.flush();
        fos.close();

        // Now have server sign the cert using extensionRequest
        javax.activation.DataHandler repositoryItem = new DataHandler(new FileDataSource(repositoryItemFile));
        String id = it.cnr.icar.eric.common.Utility.getInstance().createId();
        HashMap<String, Object> idToRepositoryItemsMap = new HashMap<String, Object>();
        idToRepositoryItemsMap.put(id, repositoryItem);

        HashMap<String, String> slotsMap = new HashMap<String, String>();
        slotsMap.put(BindingUtility.FREEBXML_REGISTRY_PROTOCOL_SIGNCERT, "true");

        RegistryRequestType req = bu.rsFac.createRegistryRequestType();
        bu.addSlotsToRequest(req, slotsMap);

        RegistryResponseHolder respHolder = ((LifeCycleManagerImpl) lcm).extensionRequest(req,
                idToRepositoryItemsMap);
        DataHandler responseRepositoryItem = (DataHandler) respHolder.getAttachmentsMap().get(id);

        InputStream is = responseRepositoryItem.getInputStream();
        KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(is, bu.FREEBXML_REGISTRY_KS_PASS_RESP.toCharArray());
        is.close();

        certChain[0] = keyStore.getCertificate(bu.FREEBXML_REGISTRY_USERCERT_ALIAS_RESP);
        if (certChain[0] == null) {
            throw new JAXRException(JAXRResourceBundle.getInstance().getString("message.CannotFindUserCert"));
        }
        certChain[1] = keyStore.getCertificate(bu.FREEBXML_REGISTRY_CACERT_ALIAS);
        if (certChain[1] == null) {
            throw new JAXRException(JAXRResourceBundle.getInstance().getString("message.CannotFindCARootCert"));
        }
    } catch (Exception e) {
        throw new JAXRException(JAXRResourceBundle.getInstance().getString("message.CertSignFailed"), e);
    }

    return certChain;
}

From source file:org.wso2.carbon.connector.apns.Utils.java

/**
 * Returns the attachment in the message context for the given attachment
 * name.//from  www.  j a  v a 2  s  .  c om
 * 
 * @param messageContext
 *            Synapse message context.
 * @param attachmentName
 *            Attachment name.
 * @return The content of the attachment as a stream.
 */
public static InputStream extractAttachment(MessageContext messageContext, String attachmentName) {

    org.apache.axis2.context.MessageContext axis2mc = ((Axis2MessageContext) messageContext)
            .getAxis2MessageContext();

    DataHandler dataHandler = axis2mc.getAttachment(attachmentName);

    if (dataHandler == null) {
        log.error(String.format("No attachment found for the name %s", attachmentName));
        return null;
    }

    try {
        InputStream attachmentInputStream = dataHandler.getInputStream();
        return attachmentInputStream;
    } catch (IOException e) {
        log.error(String.format("Cannot read the attachment %s"), e);
        return null;
    }

}