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.paxle.core.doc.impl.jaxb.JaxbFieldMapAdapter.java

private Serializable convert(Field<?> key, DataHandler handler) throws IOException, ClassNotFoundException {
    if (handler == null)
        return null;

    InputStream input = null;/*from w  ww  .j  a v  a 2 s . co  m*/
    OutputStream output = null;
    try {
        // getting the input stream
        input = handler.getInputStream();

        if (key.getType().isAssignableFrom(File.class)) {
            File tempFile = null;
            try {
                // getting the output stream
                tempFile = this.tempFileManager.createTempFile();
                output = new BufferedOutputStream(new FileOutputStream(tempFile));

                // copy data
                long byteCount = IOUtils.copy(input, output);
                System.out.println(byteCount + " bytes copied");
                return tempFile;
            } catch (IOException e) {
                if (tempFile != null && this.tempFileManager.isKnown(tempFile)) {
                    this.tempFileManager.releaseTempFile(tempFile);
                }
                throw e;
            }
        } else {
            input = new ObjectInputStream(input);
            return (Serializable) ((ObjectInputStream) input).readObject();
        }
    } finally {
        if (input != null)
            input.close();
        if (output != null)
            output.close();
    }
}

From source file:org.apache.axis2.saaj.AttachmentTest.java

@Validated
@Test//from w  w  w.  ja  v a 2  s .com
public void testSetBase64Content() {
    try {
        MessageFactory factory = MessageFactory.newInstance();
        SOAPMessage msg = factory.createMessage();
        AttachmentPart ap = msg.createAttachmentPart();

        String urlString = "http://ws.apache.org/images/project-logo.jpg";
        if (isNetworkedResourceAvailable(urlString)) {
            URL url = new URL(urlString);
            DataHandler dh = new DataHandler(url);
            //Create InputStream from DataHandler's InputStream
            InputStream is = dh.getInputStream();

            byte buf[] = IOUtils.getStreamAsByteArray(is);
            //Setting Content via InputStream for image/jpeg mime type
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            Base64.encode(buf, 0, buf.length, bos);
            buf = bos.toByteArray();
            InputStream stream = new ByteArrayInputStream(buf);
            ap.setBase64Content(stream, "image/jpeg");

            //Getting Content.. should return InputStream object
            InputStream r = ap.getBase64Content();
            if (r != null) {
                if (r instanceof InputStream) {
                    //InputStream object was returned (ok)
                } else {
                    fail("Unexpected object was returned");
                }
            }
        }
    } catch (Exception e) {
        fail("Exception: " + e);
    }
}

From source file:de.extra.client.plugins.responseprocessplugin.filesystem.FileSystemResultDataResponseProcessPlugin.java

/**
 * @param responseId/*from w ww.  j a v a2s  .  c  o  m*/
 * @param responseBody
 * @return
 */
private void saveBodyToFilesystem(final String responseId, final DataHandler dataHandler) {
    try {

        final String dateiName = buildFilename(responseId);

        final File responseFile = new File(eingangOrdner, dateiName);

        final FileOutputStream fileOutputStream = new FileOutputStream(responseFile);
        IOUtils.copyLarge(dataHandler.getInputStream(), fileOutputStream);

        transportObserver.responseDataForwarded(responseFile.getAbsolutePath(), responseFile.length());

        LOG.info("Response gespeichert in File: '" + dateiName + "'");

    } catch (final IOException ioException) {
        throw new ExtraResponseProcessPluginRuntimeException(ExceptionCode.UNEXPECTED_INTERNAL_EXCEPTION,
                "Fehler beim schreiben der Antwort", ioException);
    }
}

From source file:org.wso2.carbon.admin.service.AdminServiceProxyServiceAdmin.java

public void addProxyService(String sessionCookie, DataHandler dh)
        throws ProxyAdminException, IOException, XMLStreamException {
    ProxyServiceAdminClient adminServiceProxyServiceAdminClient = new ProxyServiceAdminClient(null, backEndUrl,
            sessionCookie, Locale.US);

    new AuthenticateStub().authenticateStub(sessionCookie, proxyServiceAdminStub);

    XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader(dh.getInputStream());
    //create the builder
    StAXOMBuilder builder = new StAXOMBuilder(parser);
    //get the root element (in this case the envelope)
    OMElement documentElement = builder.getDocumentElement();

    ProxyData proxyData = adminServiceProxyServiceAdminClient.getDesignView(documentElement.toString());
    proxyServiceAdminStub.addProxy(proxyData);
    log.info("Proxy Added");

}

From source file:it.cnr.icar.eric.service.validationTest.cppaValidation.CPPAValidation.java

public SOAPElement validateContent(SOAPElement partValidateContentRequest) throws RemoteException {
    try {/*from  ww  w.j a  va  2  s . c  o m*/
        if (log.isDebugEnabled()) {
            printNodeToConsole(partValidateContentRequest);
        }

        HashMap<String, DataHandler> repositoryItemDHMap = getRepositoryItemDHMap();

        if (log.isDebugEnabled()) {
            log.debug("Attachments: " + repositoryItemDHMap.size());
        }

        Object requestObj = getBindingObjectFromNode(partValidateContentRequest);

        if (!(requestObj instanceof ValidateContentRequest)) {
            throw new Exception(
                    "Wrong response received from validation service.  Expected ValidationContentRequest, got: "
                            + partValidateContentRequest.getElementName().getQualifiedName());
        }

        vcReq = (ValidateContentRequest) requestObj;

        IdentifiableType originalContentIT = vcReq.getOriginalContent().getIdentifiable().get(0).getValue();
        IdentifiableType invocationControlIT = vcReq.getInvocationControlFile().get(0);

        DataHandler originalContentDH = repositoryItemDHMap.get(originalContentIT.getId());
        DataHandler invocationControlDH = repositoryItemDHMap.get(invocationControlIT.getId());

        if (log.isDebugEnabled()) {
            log.debug("originalContentIT id: " + originalContentIT.getId());
            log.debug("invocationControlIT id: " + invocationControlIT.getId());
        }

        StreamSource invocationControlSrc = new StreamSource(invocationControlDH.getInputStream());

        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer(invocationControlSrc);

        StringWriter sw = new StringWriter();
        transformer.transform(new StreamSource(originalContentDH.getInputStream()), new StreamResult(sw));

        vcResp = cmsFac.createValidateContentResponse();

        boolean success = Boolean.valueOf(sw.toString()).booleanValue();

        if (success) {
            vcResp.setStatus(CANONICAL_RESPONSE_STATUS_TYPE_ID_Success);
        } else {
            RegistryError re = rsFac.createRegistryError();
            re.setValue(sw.toString());
            re.setCodeContext(errorCodeContext);
            re.setErrorCode("InvalidContentException");

            RegistryErrorList el = rsFac.createRegistryErrorList();
            el.getRegistryError().add(re);
            el.setHighestSeverity("Failure");

            vcResp.setStatus(CANONICAL_RESPONSE_STATUS_TYPE_ID_Failure);
            vcResp.setRegistryErrorList(el);
        }

        vcRespElement = getSOAPElementFromBindingObject(vcResp);
    } catch (Exception e) {
        throw new RemoteException("Could not create response.", e);
    }

    return vcRespElement;
}

From source file:es.pode.administracion.presentacion.estructuraseducativas.arboles.listar.ListarArbolesControllerImpl.java

public void exportarArbol(ActionMapping mapping, ExportarArbolForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    final int BUFFER_SIZE = 2048;
    if (form.getNombre() != null && !form.getNombre().equals("")) {
        DataHandler dh = null;
        try {/*from  w w w .  j  a  v a2s . co  m*/
            dh = this.getSrvEstructurasEducativasService().exportarVdex(form.getNombre(), TipoVdex.ARBOL);
            if (dh != null) {
                response.setContentType("text/xml;charset=utf-8");
                response.setHeader("Content-Disposition", "attachment;filename=" + form.getNombre());
                OutputStream out = response.getOutputStream();
                InputStream in = dh.getInputStream();
                logger.debug("Descargando metadata.xml");
                byte[] buffer = new byte[BUFFER_SIZE];
                int count;
                while ((count = in.read(buffer, 0, BUFFER_SIZE)) != -1) {
                    out.write(buffer, 0, count);
                }
                out.flush();

            } else {
                //               logger.error("Fichero  vacio. Abortamos descarga.");
                //                throw new ValidatorException("{catalogadorAvanzado.exportar.error.fichero}");
            }

        } catch (Exception e) {
            logger.debug("error en la llamada al servicio estructuras educativas " + e.getMessage());
        }

    } else {
        logger.debug("error al intentar exportar el arbol curricular ");
    }

}

From source file:es.pode.administracion.presentacion.estructuraseducativas.tesauros.listar.ListarTesaurosControllerImpl.java

public void exportarTesauro(ActionMapping mapping, ExportarTesauroForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    final int BUFFER_SIZE = 2048;
    if (form.getNombre() != null && !form.getNombre().equals("")) {
        DataHandler dh = null;
        try {// w w  w.ja  va  2  s . co m
            dh = this.getSrvEstructurasEducativasService().exportarVdex(form.getNombre(), TipoVdex.TESAURO);
            if (dh != null) {
                response.setContentType("text/xml;charset=utf-8");
                response.setHeader("Content-Disposition", "attachment;filename=" + form.getNombre());
                OutputStream out = response.getOutputStream();
                InputStream in = dh.getInputStream();
                logger.debug("Descargando metadata.xml");
                byte[] buffer = new byte[BUFFER_SIZE];
                int count;
                while ((count = in.read(buffer, 0, BUFFER_SIZE)) != -1) {
                    out.write(buffer, 0, count);
                }
                out.flush();

            } else {
                //               logger.error("Fichero  vacio. Abortamos descarga.");
                //                throw new ValidatorException("{catalogadorAvanzado.exportar.error.fichero}");
            }

        } catch (Exception e) {
            logger.debug("error en la llamada al servicio estructuras educativas " + e.getMessage());
        }

    } else {
        logger.debug("error al intentar exportar el tesauro seleccionado");
    }

}

From source file:de.extra.client.plugins.outputplugin.mtomws.WsCxfIT.java

private void saveAttachment(final ResponseTransport responseTransport) throws IOException {
    final DataHandler dataHandler = responseTransport.getTransportBody().getData().getBase64CharSequence()
            .getValue();//ww  w . j  av  a  2 s .  co m
    final File receivedFile = new File(outputDirectory,
            "tempClientInput" + DateFormatUtils.ISO_DATE_FORMAT.format(new Date()) + ".txt");

    final FileOutputStream fileOutputStream = new FileOutputStream(receivedFile);
    IOUtils.copyLarge(dataHandler.getInputStream(), fileOutputStream);
    logger.info("Attachment saved into " + receivedFile.getAbsolutePath());
}

From source file:com.utest.webservice.impl.v2.ProductWebServiceImpl.java

@Override
@Secured(Permission.TEST_CASE_EDIT)
@POST//  ww  w.j a v  a  2  s . c om
@Path("/{id}/import_multistep_testcases/")
public Boolean importMultiStepTestCasesFromCsv(MultipartBody body_, @PathParam("id") final Integer productId_)
        throws Exception {
    List<org.apache.cxf.jaxrs.ext.multipart.Attachment> attachments = body_.getAllAttachments();
    javax.activation.DataHandler dataHandler = attachments.get(0).getDataHandler();
    InputStream inputStream = dataHandler.getInputStream();
    OutputStream outputStream = new ByteArrayOutputStream();
    IOUtils.copy(inputStream, outputStream);
    inputStream.close();
    outputStream.close();
    testCaseService.importMultiStepTestCasesFromCsv(outputStream.toString(), productId_);
    return Boolean.TRUE;
}