List of usage examples for javax.activation DataHandler getInputStream
public InputStream getInputStream() throws IOException
From source file:org.github.alexwibowo.opentext.client.AxiomVRDClient.java
@Override public String storeDocument(String documentSource, Map<String, Object> sourceAttributes, String mimeType, File file) throws Exception { OMNamespace ns1 = factory.createOMNamespace("http://record.webservices.rd.vignette.com/", ""); OMElement addRecordMappedElement = factory.createOMElement("addRecordMapped", ns1); OMElement licenseElement = factory.createOMElement("license", ns1); addRecordMappedElement.addChild(licenseElement); OMElement docSourceNameElement = factory.createOMElement("docSourceName", ns1); docSourceNameElement.setText(documentSource); addRecordMappedElement.addChild(docSourceNameElement); OMElement sourceVREFElement = factory.createOMElement("sourceVREF", ns1); sourceVREFElement.setText(""); addRecordMappedElement.addChild(sourceVREFElement); for (Map.Entry<String, Object> attributeEntry : sourceAttributes.entrySet()) { addRecordMappedElement.addChild(createAttributeElement(factory, ns1, attributeEntry)); }/*w w w. j a v a 2 s .c o m*/ OMElement contentElement = factory.createOMElement("content", ns1); OMElement sectionIDElement = factory.createOMElement("sectionID", ns1); sectionIDElement.setText("1"); contentElement.addChild(sectionIDElement); OMElement sectionDataElement = factory.createOMElement("sectionData", ns1); DataHandler dataHandler = new DataHandler(new FileDataSource(file)); sectionDataElement.addChild(factory.createOMText(dataHandler, true)); contentElement.addChild(sectionDataElement); OMElement renditionTypeElement = factory.createOMElement("renditionType", ns1); renditionTypeElement.setText(mimeType); contentElement.addChild(renditionTypeElement); addRecordMappedElement.addChild(contentElement); addRecordMappedElement.addChild(getOptionElement(factory, ns1)); SOAPMessageBuilder soap11MessageBuilder = new AxiomSOAP11MessageBuilder(jaxbContext, soap11Factory) .withPayload(addRecordMappedElement) .withUsernameToken(configuration.getUsername(), configuration.getPassword()); SOAPEnvelope envelope = (SOAPEnvelope) soap11MessageBuilder.build(); HttpResponse httpResponse = postAsMultipart(envelope, VRDOperationQName.AddRecordMapped.getQName()); dataHandler.getInputStream().close(); if (httpResponse.getEntity() != null && httpResponse.getEntity().getContent() != null) { InputStream in = httpResponse.getEntity().getContent(); Attachments attachments = new Attachments(in, httpResponse.getEntity().getContentType().getValue()); SOAPEnvelope response = OMXMLBuilderFactory.createSOAPModelBuilder(attachments).getSOAPEnvelope(); // retrieveContentResponse is addRecordMappedResponse OMElement addRecordMappedResponseElement = response.getBody().getFirstElement(); // Unfortunately, our beautiful VRD responds with 'recDesc' in a null namespace. Hence if we use JAXB to unmarshall the response, we will get // null recDesc inside AddRecordMappedResponse object. such is life.. OMElement recordDescElement = addRecordMappedResponseElement.getFirstElement(); String recordID = recordDescElement.getFirstChildWithName(new QName("recordID")).getText(); IOUtils.closeQuietly(in); return recordID; } return null; }
From source file:com.docdoku.client.data.MainModel.java
public File getFile(Component pParent, DocumentMasterTemplate pTemplate, BinaryResource pBin) throws Exception { File folder = Config.getCacheFolder(pTemplate); File localFile = new File(folder, pBin.getName()); if (!localFile.exists()) { MainModel model = MainModel.getInstance(); folder.mkdirs();/* www . ja v a2 s . co m*/ try { Map<String, Object> ctxt = ((BindingProvider) mFileService).getRequestContext(); try { if (ctxt.containsKey(Config.HTTP_CLIENT_STREAMING_CHUNK_SIZE)) { DataHandler dh = mFileService.downloadFromTemplate(model.getWorkspace().getId(), pTemplate.getId(), pBin.getName()); downloadFile(pParent, localFile, (int) pBin.getContentLength(), dh.getInputStream()); } else { //workaround mode downloadFileWithServlet(pParent, localFile, getServletURL(pTemplate, pBin.getName())); } } catch (Exception ex) { if (ex.getCause() instanceof InterruptedIOException) { throw ex; } if (ctxt.containsKey(Config.HTTP_CLIENT_STREAMING_CHUNK_SIZE)) { System.out.println("Disabling chunked mode"); ctxt.remove(Config.HTTP_CLIENT_STREAMING_CHUNK_SIZE); downloadFileWithServlet(pParent, localFile, getServletURL(pTemplate, pBin.getName())); } else { //we were already not using the chunked mode //there's not much to do... throw ex; } } } catch (WebServiceException pWSEx) { Throwable t = pWSEx.getCause(); if (t instanceof Exception) { throw (Exception) t; } else { throw pWSEx; } } localFile.deleteOnExit(); } return localFile; }
From source file:es.pode.administracion.presentacion.informes.listarInformes.ListarInformesControllerImpl.java
/** * @see es.pode.administracion.presentacion.informes.listarInformes.ListarInformesController#recuperarInforme(org.apache.struts.action.ActionMapping, es.pode.administracion.presentacion.informes.listarInformes.RecuperarInformeForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) *//*from w w w . j a va2s. co m*/ public final void recuperarInforme(ActionMapping mapping, es.pode.administracion.presentacion.informes.listarInformes.RecuperarInformeForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { try { String fichero = (String) form.getNombre(); DataHandler dataHandler = null; SrvInformeService informeService = this.getSrvInformeService(); try { dataHandler = informeService.recuperarInforme(fichero); } catch (Exception e) { log.error("Error al recuperar el fichero"); } if (dataHandler == null) { log.error("El fichero recuperado est vacio"); throw new ValidatorException("{recuperarInforme.FALLO}"); } if (fichero.endsWith(".pdf")) { response.setContentType("application/pdf"); } else if (fichero.endsWith(".html") || fichero.endsWith(".htm")) { response.setContentType("application/html"); } else if (fichero.endsWith(".xls")) { response.setContentType("application/xls"); } else if (fichero.endsWith(".doc")) { response.setContentType("application/doc"); } response.setHeader("Content-Disposition", "attachment;filename=" + fichero); OutputStream out = response.getOutputStream(); InputStream in = dataHandler.getInputStream(); if (log.isDebugEnabled()) log.debug("recuperando el fichero " + fichero); byte[] buffer = new byte[BUFFER_SIZE]; int count; while ((count = in.read(buffer, 0, BUFFER_SIZE)) != -1) { out.write(buffer, 0, count); } out.flush(); out.close(); } catch (ValidatorException e) { throw e; } catch (Exception e) { log.error("Se ha producido el siguiente error: " + e); throw e; } }
From source file:es.pode.administracion.presentacion.informes.listarInformesFederados.ListarInformesFederadosControllerImpl.java
/** * @see es.pode.administracion.presentacion.informes.listarInformesFederados.ListarInformesFederadosController#recuperarInformeFederado(org.apache.struts.action.ActionMapping, es.pode.administracion.presentacion.informes.listarInformesFederados.RecuperarInformeFederadoForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) *//*from w w w. ja va 2 s. c om*/ public final void recuperarInformeFederado(ActionMapping mapping, es.pode.administracion.presentacion.informes.listarInformesFederados.RecuperarInformeFederadoForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { try { String fichero = (String) form.getNombre(); DataHandler dataHandler = null; SrvInformeService informeService = this.getSrvInformeService(); try { dataHandler = informeService.recuperarInformesFederados(fichero); } catch (Exception e) { logger.error("Error al recuperar el fichero"); } if (dataHandler == null) { logger.error("El fichero recuperado est vacio"); throw new ValidatorException("{recuperarInforme.FALLO}"); } if (fichero.endsWith(".pdf")) { response.setContentType("application/pdf"); } else if (fichero.endsWith(".html") || fichero.endsWith(".htm")) { response.setContentType("application/html"); } else if (fichero.endsWith(".xls")) { response.setContentType("application/xls"); } else if (fichero.endsWith(".doc")) { response.setContentType("application/doc"); } response.setHeader("Content-Disposition", "attachment;filename=" + fichero); OutputStream out = response.getOutputStream(); InputStream in = dataHandler.getInputStream(); if (logger.isDebugEnabled()) logger.debug("recuperando el fichero federado" + fichero); byte[] buffer = new byte[BUFFER_SIZE]; int count; while ((count = in.read(buffer, 0, BUFFER_SIZE)) != -1) { out.write(buffer, 0, count); } out.flush(); out.close(); } catch (ValidatorException e) { throw e; } catch (Exception e) { logger.error("Se ha producido el siguiente error: " + e); throw e; } }
From source file:org.mule.transport.http.transformers.ObjectToHttpClientMethodRequest.java
protected MultipartRequestEntity createMultiPart(MuleMessage msg, EntityEnclosingMethod method) throws Exception { Part[] parts;//w w w. j a va 2 s. c om int i = 0; if (msg.getPayload() instanceof NullPayload) { parts = new Part[msg.getOutboundAttachmentNames().size()]; } else { parts = new Part[msg.getOutboundAttachmentNames().size() + 1]; parts[i++] = new FilePart("payload", new ByteArrayPartSource("payload", msg.getPayloadAsBytes())); } for (final Iterator<String> iterator = msg.getOutboundAttachmentNames().iterator(); iterator .hasNext(); i++) { final String attachmentNames = iterator.next(); String fileName = attachmentNames; final DataHandler dh = msg.getOutboundAttachment(attachmentNames); if (dh.getDataSource() instanceof StringDataSource) { final StringDataSource ds = (StringDataSource) dh.getDataSource(); parts[i] = new StringPart(ds.getName(), IOUtils.toString(ds.getInputStream())); } else { if (dh.getDataSource() instanceof FileDataSource) { fileName = ((FileDataSource) dh.getDataSource()).getFile().getName(); } else if (dh.getDataSource() instanceof URLDataSource) { fileName = ((URLDataSource) dh.getDataSource()).getURL().getFile(); // Don't use the whole file path, just the file name final int x = fileName.lastIndexOf("/"); if (x > -1) { fileName = fileName.substring(x + 1); } } parts[i] = new FilePart(dh.getName(), new ByteArrayPartSource(fileName, IOUtils.toByteArray(dh.getInputStream())), dh.getContentType(), null); } } return new MultipartRequestEntity(parts, method.getParams()); }
From source file:com.docdoku.client.data.MainModel.java
public File getFile(Component pParent, DocumentIteration pDocument, BinaryResource pBin) throws Exception { DocumentMaster docM = pDocument.getDocumentMaster(); File folder = null;//from w ww. j a v a 2 s . com boolean readOnly; if (!docM.isCheckedOut() || !docM.getCheckOutUser().equals(getUser()) || !docM.getLastIteration().equals(pDocument)) { folder = new File(Config.getCacheFolder(docM), pDocument.getIteration() + ""); readOnly = true; } else { folder = Config.getCheckOutFolder(docM); readOnly = false; } File localFile = new File(folder, pBin.getName()); if (!localFile.exists()) { folder.mkdirs(); try { Map<String, Object> ctxt = ((BindingProvider) mFileService).getRequestContext(); try { if (ctxt.containsKey(Config.HTTP_CLIENT_STREAMING_CHUNK_SIZE)) { DataHandler dh = mFileService.downloadFromDocument(getWorkspace().getId(), pDocument.getDocumentMasterId(), pDocument.getDocumentMasterVersion(), pDocument.getIteration(), pBin.getName()); downloadFile(pParent, localFile, (int) pBin.getContentLength(), dh.getInputStream()); } else { //workaround mode downloadFileWithServlet(pParent, localFile, getServletURL(pDocument, pBin.getName())); } } catch (Exception ex) { if (ex.getCause() instanceof InterruptedIOException) { throw ex; } if (ctxt.containsKey(Config.HTTP_CLIENT_STREAMING_CHUNK_SIZE)) { System.out.println("Disabling chunked mode"); ctxt.remove(Config.HTTP_CLIENT_STREAMING_CHUNK_SIZE); downloadFileWithServlet(pParent, localFile, getServletURL(pDocument, pBin.getName())); } else { //we were already not using the chunked mode //there's not much to do... throw ex; } } } catch (WebServiceException pWSEx) { Throwable t = pWSEx.getCause(); if (t instanceof Exception) { throw (Exception) t; } else { throw pWSEx; } } if (readOnly) { localFile.setReadOnly(); localFile.deleteOnExit(); } else { Prefs.storeDocInfo(docM, localFile.getName(), localFile.lastModified()); } } return localFile; }
From source file:eu.forgestore.ws.repo.FStoreRepositoryAPIImpl.java
private String saveFile(Attachment att, String filePath) { DataHandler handler = att.getDataHandler(); try {//from w w w.j a v a 2 s . c o m InputStream stream = handler.getInputStream(); MultivaluedMap map = att.getHeaders(); File f = new File(filePath); OutputStream out = new FileOutputStream(f); int read = 0; byte[] bytes = new byte[1024]; while ((read = stream.read(bytes)) != -1) { out.write(bytes, 0, read); } stream.close(); out.flush(); out.close(); return f.getAbsolutePath(); } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:org.apache.synapse.samples.framework.clients.MTOMSwASampleClient.java
public SampleClientResult sendUsingMTOM(String fileName, String targetEPR) { clientResult = new SampleClientResult(); try {//from w w w .j av a 2 s .c o m OMFactory factory = OMAbstractFactory.getOMFactory(); OMNamespace ns = factory.createOMNamespace("http://services.samples", "m0"); payload = factory.createOMElement("uploadFileUsingMTOM", ns); OMElement request = factory.createOMElement("request", ns); OMElement image = factory.createOMElement("image", ns); log.info("Sending file : " + fileName + " as MTOM"); FileDataSource fileDataSource = new FileDataSource(new File(fileName)); DataHandler dataHandler = new DataHandler(fileDataSource); OMText textData = factory.createOMText(dataHandler, true); image.addChild(textData); request.addChild(image); payload.addChild(request); ConfigurationContext configContext = ConfigurationContextFactory .createConfigurationContextFromFileSystem(configuration.getClientRepo(), configuration.getAxis2Xml()); serviceClient = new ServiceClient(configContext, null); Options options = new Options(); options.setTo(new EndpointReference(targetEPR)); options.setAction("urn:uploadFileUsingMTOM"); options.setProperty(Constants.Configuration.ENABLE_MTOM, Constants.VALUE_TRUE); serviceClient.setOptions(options); OMElement response = serviceClient.sendReceive(payload); OMText binaryNode = (OMText) response .getFirstChildWithName(new QName("http://services.samples", "response")) .getFirstChildWithName(new QName("http://services.samples", "image")).getFirstOMChild(); dataHandler = (DataHandler) binaryNode.getDataHandler(); InputStream is = dataHandler.getInputStream(); log.info("temp.dir: " + System.getProperty("java.io.tmpdir")); File tempFile = File.createTempFile("mtom-", ".gif"); FileOutputStream fos = new FileOutputStream(tempFile); BufferedOutputStream dest = new BufferedOutputStream(fos, 2048); byte data[] = new byte[2048]; int count; while ((count = is.read(data, 0, 2048)) != -1) { dest.write(data, 0, count); } dest.flush(); dest.close(); log.info("Saved response to file : " + tempFile.getAbsolutePath()); clientResult.incrementResponseCount(); } catch (Exception e) { log.error("Error invoking service", e); clientResult.setException(e); } return clientResult; }
From source file:com.vangent.hieos.services.xds.repository.transactions.ProvideAndRegisterDocumentSet.java
/** * * @param pnr/* ww w . j av a2 s .c o m*/ * @throws com.vangent.hieos.xutil.exception.MetadataValidationException * @throws com.vangent.hieos.xutil.exception.SchemaValidationException * @throws com.vangent.hieos.xutil.exception.XdsInternalException * @throws com.vangent.hieos.xutil.exception.MetadataException * @throws com.vangent.hieos.xutil.exception.XdsConfigurationException * @throws com.vangent.hieos.xutil.exception.XdsIOException * @throws com.vangent.hieos.xutil.exception.XdsException * @throws java.io.IOException */ private void provide_and_register(OMElement pnr) throws MetadataValidationException, SchemaValidationException, XdsInternalException, MetadataException, XdsConfigurationException, XdsIOException, XdsException, IOException { RegistryUtility.schema_validate_local(pnr, MetadataTypes.METADATA_TYPE_RET); OMElement sor = find_sor(pnr); Metadata m = new Metadata(sor); //AUDIT:POINT //call to audit message for document repository //for Transaction id = ITI-41. (Provide & Register Document set-b) //Here document consumer is treated as document repository performAudit(XATNALogger.TXN_ITI41, sor, null, XATNALogger.ActorType.REPOSITORY, XATNALogger.OutcomeIndicator.SUCCESS); log_message.addOtherParam("SSuid", m.getSubmissionSetUniqueId()); log_message.addOtherParam("Structure", m.structure()); this.validate_docs_and_metadata_b(pnr, m); if (this.validater != null && !this.validater.runContentValidationService(m, response)) { return; } int eo_count = m.getExtrinsicObjectIds().size(); int doc_count = 0; for (OMElement document : MetadataSupport.childrenWithLocalName(pnr, "Document")) { doc_count++; String id = document.getAttributeValue(MetadataSupport.id_qname); OMText binaryNode = (OMText) document.getFirstOMChild(); if (!accept_xop) { if (binaryNode.isOptimized() == true) { throw new XdsIOException( "Submission uses XOP for optimized encoding - not acceptable on this endpoint"); } } boolean optimized = false; javax.activation.DataHandler datahandler = null; try { datahandler = (javax.activation.DataHandler) binaryNode.getDataHandler(); optimized = true; } catch (Exception e) { // good - message not optimized } if (!accept_xop) { if (optimized) { throw new XdsIOException( "Submission uses XOP for optimized encoding - this is not acceptable on this endpoint"); } } // Create the XDSDocument to hold relevant storage parameters. XDSDocument doc = new XDSDocument(Repository.getRepositoryUniqueId()); doc.setDocumentId(id); if (optimized) { InputStream is = null; try { is = datahandler.getInputStream(); } catch (IOException e) { throw new XdsIOException("Error accessing document content from message"); } this.store_document_swa_xop(m, doc, is); } else { String base64 = binaryNode.getText(); byte[] ba = Base64.decodeBase64(base64.getBytes()); /* BHT: Replaced code (with above line) to get rid of sun.misc dependency. BASE64Decoder d = new BASE64Decoder(); byte[] ba = d.decodeBuffer(base64); */ store_document_mtom(m, doc, ba); } } if (eo_count != doc_count) { throw new XDSMissingDocumentMetadataException("Submission contained " + doc_count + " documents but " + eo_count + " ExtrinsicObjects in metadata - they must match"); } setRepositoryUniqueId(m); OMElement register_transaction = m.getV3SubmitObjectsRequest(); String epr = registry_endpoint(); log_message.addOtherParam("Register transaction endpoint", epr); log_message.addOtherParam("Register transaction", register_transaction.toString()); Soap soap = new Soap(); try { OMElement result; try { soap.soapCall(register_transaction, epr, false, true, true, "urn:ihe:iti:2007:RegisterDocumentSet-b", "urn:ihe:iti:2007:RegisterDocumentSet-bResponse"); //AUDIT:POINT //call to audit message for document repository //for Transaction id = ITI-42. (Register Document set-b) //Here document consumer is treated as document repository performAudit(XATNALogger.TXN_ITI42, register_transaction, epr, XATNALogger.ActorType.REPOSITORY, XATNALogger.OutcomeIndicator.SUCCESS); } catch (XdsException e) { response.add_error(MetadataSupport.XDSRegistryNotAvailable, e.getMessage(), this.getClass().getName(), log_message); return; // Early exit!! } result = soap.getResult(); log_headers(soap); if (result == null) { response.add_error(MetadataSupport.XDSRepositoryError, "Null response message from Registry", this.getClass().getName(), log_message); log_message.addOtherParam("Register transaction response", "null"); } else { log_message.addOtherParam("Register transaction response", result.toString()); String status = result.getAttributeValue(MetadataSupport.status_qname); if (status == null) { response.add_error(MetadataSupport.XDSRepositoryError, "Null status from Registry", this.getClass().getName(), log_message); } else { status = m.stripNamespace(status); if (!status.equals("Success")) { OMElement registry_error_list = MetadataSupport.firstChildWithLocalName(result, "RegistryErrorList"); if (registry_error_list != null) { response.addRegistryErrorList(registry_error_list, log_message); } else { response.add_error(MetadataSupport.XDSRepositoryError, "Registry returned Failure but no error list", this.getClass().getName(), log_message); } } } } } catch (Exception e) { response.add_error(MetadataSupport.XDSRepositoryError, e.getMessage(), this.getClass().getName(), log_message); } }
From source file:it.cnr.icar.eric.server.profile.ws.wsdl.cataloger.WSDLCatalogerEngine.java
public CatalogingServiceOutput catalogContent(CatalogingServiceInput input) throws CatalogingException { try {/* www . ja va 2 s . co m*/ this.input = input; resetState(); //registryObject MUST be ExrinsicObject or ExternalLink of objectType WSDL RegistryObjectType registryObject = input.getRegistryObject(); if (registryObject instanceof ExtrinsicObjectType) { ExtrinsicObjectType eo = (ExtrinsicObjectType) input.getRegistryObject(); DataHandler repositoryItem = input.getRepositoryItem(); InputSource inputSource = new InputSource(repositoryItem.getInputStream()); if (eo.getMimeType().equalsIgnoreCase("text/xml")) { performWSDLCataloging(eo, inputSource, true); } else { catalogWSDLExtrinsicObject(eo, inputSource); } } else if (registryObject instanceof ExternalLinkType) { ExternalLinkType extLink = (ExternalLinkType) input.getRegistryObject(); String urlStr = extLink.getExternalURI(); String wsdlLoc = Utility.absolutize(Utility.getFileOrURLName(urlStr)); InputSource inputSource = new InputSource(wsdlLoc); catalogWSDLExternalLink(extLink, inputSource); } else { throw new CatalogingException(ServerResourceBundle.getInstance().getString( "message.ExtrinsicObjectOrExternalLinkExpected", new Object[] { registryObject.getObjectType() })); } } catch (CatalogingException ce) { throw ce; } catch (Exception e) { throw new CatalogingException(e); } registryObjects.addAll(idToRIMMap.values()); output = new CatalogingServiceOutput(registryObjects, idToRepositoryItemMap); return output; }