List of usage examples for org.w3c.dom Element setAttributeNS
public void setAttributeNS(String namespaceURI, String qualifiedName, String value) throws DOMException;
From source file:be.fedict.eid.applet.service.signer.ooxml.RelationshipTransformService.java
public Data transform(Data data, XMLCryptoContext context) throws TransformException { LOG.debug("transform(data,context)"); LOG.debug("data java type: " + data.getClass().getName()); OctetStreamData octetStreamData = (OctetStreamData) data; LOG.debug("URI: " + octetStreamData.getURI()); InputStream octetStream = octetStreamData.getOctetStream(); Document relationshipsDocument; try {/*w ww .j av a 2 s. c om*/ relationshipsDocument = loadDocument(octetStream); } catch (Exception e) { throw new TransformException(e.getMessage(), e); } try { LOG.debug("relationships document: " + toString(relationshipsDocument)); } catch (TransformerException e) { throw new TransformException(e.getMessage(), e); } Element nsElement = relationshipsDocument.createElement("ns"); nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:tns", "http://schemas.openxmlformats.org/package/2006/relationships"); Element relationshipsElement = relationshipsDocument.getDocumentElement(); NodeList childNodes = relationshipsElement.getChildNodes(); for (int nodeIdx = 0; nodeIdx < childNodes.getLength(); nodeIdx++) { Node childNode = childNodes.item(nodeIdx); if (Node.ELEMENT_NODE != childNode.getNodeType()) { LOG.debug("removing node"); relationshipsElement.removeChild(childNode); nodeIdx--; continue; } Element childElement = (Element) childNode; String idAttribute = childElement.getAttribute("Id"); String typeAttribute = childElement.getAttribute("Type"); LOG.debug("Relationship id attribute: " + idAttribute); LOG.debug("Relationship type attribute: " + typeAttribute); if (false == this.sourceIds.contains(idAttribute) && false == this.sourceTypes.contains(typeAttribute)) { LOG.debug("removing Relationship element: " + idAttribute); relationshipsElement.removeChild(childNode); nodeIdx--; } /* * See: ISO/IEC 29500-2:2008(E) - 13.2.4.24 Relationships Transform * Algorithm. */ if (null == childElement.getAttributeNode("TargetMode")) { childElement.setAttribute("TargetMode", "Internal"); } } LOG.debug("# Relationship elements: " + relationshipsElement.getElementsByTagName("*").getLength()); sortRelationshipElements(relationshipsElement); try { return toOctetStreamData(relationshipsDocument); } catch (TransformerException e) { throw new TransformException(e.getMessage(), e); } }
From source file:be.fedict.eid.applet.service.signer.ooxml.RelationshipTransformService.java
@Override public void init(XMLStructure parent, XMLCryptoContext context) throws InvalidAlgorithmParameterException { LOG.debug("init(parent,context)"); LOG.debug("parent java type: " + parent.getClass().getName()); DOMStructure domParent = (DOMStructure) parent; Node parentNode = domParent.getNode(); try {/* w w w.ja v a2 s . c o m*/ LOG.debug("parent: " + toString(parentNode)); } catch (TransformerException e) { throw new InvalidAlgorithmParameterException(); } Element nsElement = parentNode.getOwnerDocument().createElement("ns"); nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:ds", Constants.SignatureSpecNS); nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:mdssi", "http://schemas.openxmlformats.org/package/2006/digital-signature"); /* * RelationshipReference */ NodeList nodeList; try { nodeList = XPathAPI.selectNodeList(parentNode, "mdssi:RelationshipReference/@SourceId", nsElement); } catch (TransformerException e) { LOG.error("transformer exception: " + e.getMessage(), e); throw new InvalidAlgorithmParameterException(); } for (int nodeIdx = 0; nodeIdx < nodeList.getLength(); nodeIdx++) { Node node = nodeList.item(nodeIdx); String sourceId = node.getTextContent(); LOG.debug("sourceId: " + sourceId); this.sourceIds.add(sourceId); } /* * RelationshipsGroupReference */ try { nodeList = XPathAPI.selectNodeList(parentNode, "mdssi:RelationshipsGroupReference/@SourceType", nsElement); } catch (TransformerException e) { LOG.error("transformer exception: " + e.getMessage(), e); throw new InvalidAlgorithmParameterException(); } for (int nodeIdx = 0; nodeIdx < nodeList.getLength(); nodeIdx++) { Node node = nodeList.item(nodeIdx); String sourceType = node.getTextContent(); LOG.debug("sourceType: " + sourceType); this.sourceTypes.add(sourceType); } }
From source file:be.fedict.eid.idp.protocol.ws_federation.sts.SecurityTokenServicePortImpl.java
private void validateToken(Element tokenElement, String expectedAudience, IdentityProviderConfiguration identityProviderConfiguration) throws Exception { List<X509Certificate> certificateChain = identityProviderConfiguration.getIdentityCertificateChain(); if (certificateChain.isEmpty()) { throw new SecurityException("no eID IdP service identity configured"); }/*www.j a va 2 s . c o m*/ Element nsElement = tokenElement.getOwnerDocument().createElement("nsElement"); nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:ds", "http://www.w3.org/2000/09/xmldsig#"); nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:saml2", "urn:oasis:names:tc:SAML:2.0:assertion"); LOG.debug("token element: " + tokenElement.getLocalName()); LOG.debug("token element namespace: " + tokenElement.getNamespaceURI()); LOG.debug("token: " + toString(tokenElement)); // fix for recent versions of Apache xmlsec. tokenElement.setIdAttribute("ID", true); Element signatureElement = (Element) XPathAPI.selectSingleNode(tokenElement, "ds:Signature", nsElement); if (null == signatureElement) { throw new SecurityException("missing XML signature"); } XMLSignature xmlSignature = new XMLSignature(signatureElement, ""); KeyInfo keyInfo = xmlSignature.getKeyInfo(); X509Certificate actualCertificate = keyInfo.getX509Certificate(); boolean signatureResult = xmlSignature.checkSignatureValue(actualCertificate); if (false == signatureResult) { throw new SecurityException("invalid XML signature"); } LOG.debug("XML signature OK"); X509Certificate serviceCertificate = certificateChain.get(0); if (false == Arrays.equals(serviceCertificate.getEncoded(), actualCertificate.getEncoded())) { throw new SecurityException("SAML signing certificate different from eID IdP service identity"); } LOG.debug("SAML signer OK"); String actualIssuer = XPathAPI.selectSingleNode(tokenElement, "saml2:Issuer/text()", nsElement) .getNodeValue(); String serviceIssuer = identityProviderConfiguration.getDefaultIssuer(); if (false == actualIssuer.equals(serviceIssuer)) { LOG.debug("actual issuer: " + actualIssuer); LOG.debug("service issuer: " + serviceIssuer); throw new SecurityException("wrong SAML issuer"); } LOG.debug("SAML issuer OK"); if (null != expectedAudience) { String audience = XPathAPI .selectSingleNode(tokenElement, "saml2:Conditions/saml2:AudienceRestriction/saml2:Audience/text()", nsElement) .getNodeValue(); if (false == expectedAudience.equals(audience)) { LOG.debug("expected audience: " + expectedAudience); LOG.debug("actual audience: " + audience); throw new SecurityException("incorrect SAML audience"); } LOG.debug("SAML Audience OK"); } else { LOG.warn("SAML audience restriction not checked"); } String authnContextClassRef = XPathAPI .selectSingleNode(tokenElement, "saml2:AuthnStatement/saml2:AuthnContext/saml2:AuthnContextClassRef/text()", nsElement) .getNodeValue(); LOG.debug("AuthnContextClassRef: " + authnContextClassRef); SamlAuthenticationPolicy samlAuthenticationPolicy = SamlAuthenticationPolicy .getAuthenticationPolicy(authnContextClassRef); if (SamlAuthenticationPolicy.AUTHENTICATION != samlAuthenticationPolicy && SamlAuthenticationPolicy.AUTHENTICATION_WITH_IDENTIFICATION != samlAuthenticationPolicy) { throw new SecurityException("wrong SAML authentication policy: " + samlAuthenticationPolicy); } String notBeforeStr = XPathAPI.selectSingleNode(tokenElement, "saml2:Conditions/@NotBefore", nsElement) .getNodeValue(); String notOnOrAfterStr = XPathAPI .selectSingleNode(tokenElement, "saml2:Conditions/@NotOnOrAfter", nsElement).getNodeValue(); DateTimeFormatter dateTimeFormatter = ISODateTimeFormat.dateTimeParser(); DateTime notBefore = dateTimeFormatter.parseDateTime(notBeforeStr); DateTime notOnOrAfter = dateTimeFormatter.parseDateTime(notOnOrAfterStr); DateTime now = new DateTime(); if (now.isBefore(notBefore)) { throw new SecurityException("SAML assertion in future"); } if (now.isAfter(notOnOrAfter)) { throw new SecurityException("SAML assertion expired"); } LOG.debug("SAML timestamp OK"); }
From source file:ch.entwine.weblounge.bridge.oaipmh.util.XmlGen.java
private Element appendNs(Element e, List<Namespace> namespaces) { for (Namespace n : namespaces) { e.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, XMLConstants.XMLNS_ATTRIBUTE + ":" + n.getPrefix(), n.getNamespace()); }//from ww w .ja v a2s .c o m return e; }
From source file:be.fedict.eid.idp.common.saml2.Saml2Util.java
private static Element getNSElement(Document document) { Element nsElement = document.createElement("nsElement"); nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:soap", "http://schemas.xmlsoap.org/soap/envelope/"); nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:ds", "http://www.w3.org/2000/09/xmldsig#"); nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:samlp", "urn:oasis:names:tc:SAML:2.0:protocol"); nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:saml", "urn:oasis:names:tc:SAML:2.0:assertion"); return nsElement; }
From source file:be.fedict.eid.applet.service.signer.ooxml.AbstractOOXMLSignatureService.java
private ZipOutputStream copyOOXMLContent(String signatureZipEntryName, OutputStream signedOOXMLOutputStream) throws IOException, ParserConfigurationException, SAXException, TransformerConfigurationException, TransformerFactoryConfigurationError, TransformerException { ZipOutputStream zipOutputStream = new ZipOutputStream(signedOOXMLOutputStream); ZipInputStream zipInputStream = new ZipInputStream(this.getOfficeOpenXMLDocumentURL().openStream()); ZipEntry zipEntry;// ww w .j av a 2 s.c om boolean hasOriginSigsRels = false; while (null != (zipEntry = zipInputStream.getNextEntry())) { LOG.debug("copy ZIP entry: " + zipEntry.getName()); ZipEntry newZipEntry = new ZipEntry(zipEntry.getName()); zipOutputStream.putNextEntry(newZipEntry); if ("[Content_Types].xml".equals(zipEntry.getName())) { Document contentTypesDocument = loadDocumentNoClose(zipInputStream); Element typesElement = contentTypesDocument.getDocumentElement(); /* * We need to add an Override element. */ Element overrideElement = contentTypesDocument.createElementNS( "http://schemas.openxmlformats.org/package/2006/content-types", "Override"); overrideElement.setAttribute("PartName", "/" + signatureZipEntryName); overrideElement.setAttribute("ContentType", "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml"); typesElement.appendChild(overrideElement); Element nsElement = contentTypesDocument.createElement("ns"); nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:tns", "http://schemas.openxmlformats.org/package/2006/content-types"); NodeList nodeList = XPathAPI.selectNodeList(contentTypesDocument, "/tns:Types/tns:Default[@Extension='sigs']", nsElement); if (0 == nodeList.getLength()) { /* * Add Default element for 'sigs' extension. */ Element defaultElement = contentTypesDocument.createElementNS( "http://schemas.openxmlformats.org/package/2006/content-types", "Default"); defaultElement.setAttribute("Extension", "sigs"); defaultElement.setAttribute("ContentType", "application/vnd.openxmlformats-package.digital-signature-origin"); typesElement.appendChild(defaultElement); } writeDocumentNoClosing(contentTypesDocument, zipOutputStream, false); } else if ("_rels/.rels".equals(zipEntry.getName())) { Document relsDocument = loadDocumentNoClose(zipInputStream); Element nsElement = relsDocument.createElement("ns"); nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:tns", "http://schemas.openxmlformats.org/package/2006/relationships"); NodeList nodeList = XPathAPI.selectNodeList(relsDocument, "/tns:Relationships/tns:Relationship[@Target='_xmlsignatures/origin.sigs']", nsElement); if (0 == nodeList.getLength()) { Element relationshipElement = relsDocument.createElementNS( "http://schemas.openxmlformats.org/package/2006/relationships", "Relationship"); relationshipElement.setAttribute("Id", "rel-id-" + UUID.randomUUID().toString()); relationshipElement.setAttribute("Type", "http://schemas.openxmlformats.org/package/2006/relationships/digital-signature/origin"); relationshipElement.setAttribute("Target", "_xmlsignatures/origin.sigs"); relsDocument.getDocumentElement().appendChild(relationshipElement); } writeDocumentNoClosing(relsDocument, zipOutputStream, false); } else if ("_xmlsignatures/_rels/origin.sigs.rels".equals(zipEntry.getName())) { hasOriginSigsRels = true; Document originSignRelsDocument = loadDocumentNoClose(zipInputStream); Element relationshipElement = originSignRelsDocument.createElementNS( "http://schemas.openxmlformats.org/package/2006/relationships", "Relationship"); String relationshipId = "rel-" + UUID.randomUUID().toString(); relationshipElement.setAttribute("Id", relationshipId); relationshipElement.setAttribute("Type", "http://schemas.openxmlformats.org/package/2006/relationships/digital-signature/signature"); String target = FilenameUtils.getName(signatureZipEntryName); LOG.debug("target: " + target); relationshipElement.setAttribute("Target", target); originSignRelsDocument.getDocumentElement().appendChild(relationshipElement); writeDocumentNoClosing(originSignRelsDocument, zipOutputStream, false); } else { IOUtils.copy(zipInputStream, zipOutputStream); } } if (false == hasOriginSigsRels) { /* * Add signature relationships document. */ addOriginSigsRels(signatureZipEntryName, zipOutputStream); addOriginSigs(zipOutputStream); } /* * Return. */ zipInputStream.close(); return zipOutputStream; }
From source file:es.gob.afirma.signers.ooxml.be.fedict.eid.applet.service.signer.AbstractXmlSignatureService.java
@Override public byte[] postSign(final byte[] signedXML, final List<X509Certificate> signingCertificateChain, final String signatureId, final byte[] signatureValue) throws ParserConfigurationException, SAXException, IOException, TransformerException { // Load the signature DOM document. final Document document = loadDocument(new ByteArrayInputStream(signedXML)); // Locate the correct ds:Signature node. final Element nsElement = document.createElement("ns"); //$NON-NLS-1$ nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:ds", Constants.SignatureSpecNS); //$NON-NLS-1$ final Element signatureElement = (Element) XPathAPI.selectSingleNode(document, "//ds:Signature[@Id='" + signatureId + "']", nsElement); //$NON-NLS-1$ //$NON-NLS-2$ if (null == signatureElement) { throw new IllegalArgumentException("ds:Signature not found for @Id: " + signatureId); //$NON-NLS-1$ }/*from www. ja v a 2 s . c o m*/ // Insert signature value into the ds:SignatureValue element final NodeList signatureValueNodeList = signatureElement .getElementsByTagNameNS(javax.xml.crypto.dsig.XMLSignature.XMLNS, "SignatureValue"); //$NON-NLS-1$ final Element signatureValueElement = (Element) signatureValueNodeList.item(0); signatureValueElement.setTextContent(Base64.encode(signatureValue)); // TODO: Cambiar a OOXMLSignedDocumentOutputStream final ByteArrayOutputStream signedDocumentOutputStream = new ByteArrayOutputStream(); writeDocument(document, signedDocumentOutputStream); return signedDocumentOutputStream.toByteArray(); }
From source file:info.joseluismartin.gtc.WmsCache.java
/** * {@inheritDoc}//w w w .j a v a2 s.c o m * @throws IOException */ @Override public InputStream parseResponse(InputStream serverStream, String remoteUri, String localUri) throws IOException { UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(remoteUri); UriComponents remoteComponents = builder.build(); String localUrl = localUri + "/" + getPath(); InputStream is = serverStream; MultiValueMap<String, String> params = remoteComponents.getQueryParams(); if (GET_CAPABILITIES.equals(params.getFirst(REQUEST))) { String response = IOUtils.toString(serverStream); Document doc = XMLUtils.newDocument(response); if (log.isDebugEnabled()) XMLUtils.prettyDocumentToString(doc); // Fix GetMapUrl Element getMapElement = (Element) doc.getElementsByTagName(GET_MAP).item(0); if (getMapElement != null) { if (log.isDebugEnabled()) { log.debug("Found GetMapUrl: " + this.getMapUrl); } NodeList nl = getMapElement.getElementsByTagName(ONLINE_RESOURCE_ELEMENT); if (nl.getLength() > 0) { Element resource = (Element) nl.item(0); if (resource.hasAttributeNS(XLINK_NS, HREF_ATTRIBUTE)) { this.getMapUrl = resource.getAttributeNS(XLINK_NS, HREF_ATTRIBUTE).replace("?", ""); resource.setAttributeNS(XLINK_NS, HREF_ATTRIBUTE, localUrl); } } } // Fix GetFeatureInfoUrl Element getFeatureElement = (Element) doc.getElementsByTagName(GET_FEATURE_INFO).item(0); if (getFeatureElement != null) { if (log.isDebugEnabled()) { log.debug("Found GetFeatureInfoUrl: " + this.getFeatureInfoUrl); } NodeList nl = getFeatureElement.getElementsByTagName(ONLINE_RESOURCE_ELEMENT); if (nl.getLength() > 0) { Element resource = (Element) nl.item(0); if (resource.hasAttributeNS(XLINK_NS, HREF_ATTRIBUTE)) { this.getFeatureInfoUrl = resource.getAttributeNS(XLINK_NS, HREF_ATTRIBUTE).replace("?", ""); resource.setAttributeNS(XLINK_NS, HREF_ATTRIBUTE, localUrl); } } } response = XMLUtils.documentToString(doc); response = response.replaceAll(getServerUrl(), localUrl); // response = "<?xml version='1.0' encoding='UTF-8'>" + response; is = IOUtils.toInputStream(response); } return is; }
From source file:be.fedict.eid.applet.service.signer.ooxml.AbstractOOXMLSignatureService.java
private void addOriginSigsRels(String signatureZipEntryName, ZipOutputStream zipOutputStream) throws ParserConfigurationException, IOException, TransformerConfigurationException, TransformerFactoryConfigurationError, TransformerException { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document originSignRelsDocument = documentBuilder.newDocument(); Element relationshipsElement = originSignRelsDocument .createElementNS("http://schemas.openxmlformats.org/package/2006/relationships", "Relationships"); relationshipsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns", "http://schemas.openxmlformats.org/package/2006/relationships"); originSignRelsDocument.appendChild(relationshipsElement); Element relationshipElement = originSignRelsDocument .createElementNS("http://schemas.openxmlformats.org/package/2006/relationships", "Relationship"); String relationshipId = "rel-" + UUID.randomUUID().toString(); relationshipElement.setAttribute("Id", relationshipId); relationshipElement.setAttribute("Type", "http://schemas.openxmlformats.org/package/2006/relationships/digital-signature/signature"); String target = FilenameUtils.getName(signatureZipEntryName); LOG.debug("target: " + target); relationshipElement.setAttribute("Target", target); relationshipsElement.appendChild(relationshipElement); zipOutputStream.putNextEntry(new ZipEntry("_xmlsignatures/_rels/origin.sigs.rels")); writeDocumentNoClosing(originSignRelsDocument, zipOutputStream, false); }
From source file:org.openmeetings.servlet.outputhandler.ExportToImage.java
@Override protected void service(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException { try {//w w w. jav a2 s. c o m if (getUserManagement() == null || getSessionManagement() == null || getGenerateImage() == null) { return; } String sid = httpServletRequest.getParameter("sid"); if (sid == null) { sid = "default"; } log.debug("sid: " + sid); String hash = httpServletRequest.getParameter("hash"); if (hash == null) { hash = ""; } log.debug("hash: " + hash); String fileName = httpServletRequest.getParameter("fileName"); if (fileName == null) { fileName = "file_xyz"; } String exportType = httpServletRequest.getParameter("exportType"); if (exportType == null) { exportType = "svg"; } Long users_id = getSessionManagement().checkSession(sid); Long user_level = getUserManagement().getUserLevelByID(users_id); log.debug("users_id: " + users_id); log.debug("user_level: " + user_level); if (user_level != null && user_level > 0 && hash != "") { PrintBean pBean = PrintService.getPrintItemByHash(hash); // Whiteboard Objects @SuppressWarnings("rawtypes") List whiteBoardMap = pBean.getMap(); // Get a DOMImplementation. DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation(); // Create an instance of org.w3c.dom.Document. // String svgNS = "http://www.w3.org/2000/svg"; String svgNS = SVGDOMImplementation.SVG_NAMESPACE_URI; Document document = domImpl.createDocument(svgNS, "svg", null); // Get the root element (the 'svg' element). Element svgRoot = document.getDocumentElement(); // Set the width and height attributes on the root 'svg' // element. svgRoot.setAttributeNS(null, "width", "" + pBean.getWidth()); svgRoot.setAttributeNS(null, "height", "" + pBean.getHeight()); log.debug("pBean.getWidth(),pBean.getHeight()" + pBean.getWidth() + "," + pBean.getHeight()); // Create an instance of the SVG Generator. SVGGraphics2D svgGenerator = new SVGGraphics2D(document); svgGenerator = WhiteboardMapToSVG.getInstance().convertMapToSVG(svgGenerator, whiteBoardMap); // Finally, stream out SVG to the standard output using // UTF-8 encoding. boolean useCSS = true; // we want to use CSS style attributes // Writer out = new OutputStreamWriter(System.out, "UTF-8"); if (exportType.equals("svg")) { // OutputStream out = httpServletResponse.getOutputStream(); // httpServletResponse.setContentType("APPLICATION/OCTET-STREAM"); // httpServletResponse.setHeader("Content-Disposition","attachment; filename=\"" // + requestedFile + "\""); Writer out = httpServletResponse.getWriter(); svgGenerator.stream(out, useCSS); } else if (exportType.equals("png") || exportType.equals("jpg") || exportType.equals("gif") || exportType.equals("tif") || exportType.equals("pdf")) { String current_dir = getServletContext().getRealPath("/"); String working_dir = current_dir + OpenmeetingsVariables.UPLOAD_TEMP_DIR + File.separatorChar; String requestedFileSVG = fileName + "_" + CalendarPatterns.getTimeForStreamId(new Date()) + ".svg"; String resultFileName = fileName + "_" + CalendarPatterns.getTimeForStreamId(new Date()) + "." + exportType; log.debug("current_dir: " + current_dir); log.debug("working_dir: " + working_dir); log.debug("requestedFileSVG: " + requestedFileSVG); log.debug("resultFileName: " + resultFileName); File svgFile = new File(working_dir + requestedFileSVG); File resultFile = new File(working_dir + resultFileName); log.debug("svgFile: " + svgFile.getAbsolutePath()); log.debug("resultFile: " + resultFile.getAbsolutePath()); log.debug("svgFile P: " + svgFile.getPath()); log.debug("resultFile P: " + resultFile.getPath()); FileWriter out = new FileWriter(svgFile); svgGenerator.stream(out, useCSS); // Get file and handle download RandomAccessFile rf = new RandomAccessFile(resultFile.getAbsoluteFile(), "r"); httpServletResponse.reset(); httpServletResponse.resetBuffer(); OutputStream outStream = httpServletResponse.getOutputStream(); httpServletResponse.setContentType("APPLICATION/OCTET-STREAM"); httpServletResponse.setHeader("Content-Disposition", "attachment; filename=\"" + resultFileName + "\""); httpServletResponse.setHeader("Content-Length", "" + rf.length()); byte[] buffer = new byte[1024]; int readed = -1; while ((readed = rf.read(buffer, 0, buffer.length)) > -1) { outStream.write(buffer, 0, readed); } outStream.close(); rf.close(); out.flush(); out.close(); } } } catch (Exception er) { log.error("ERROR ", er); System.out.println("Error exporting: " + er); er.printStackTrace(); } }