/** * Copy the AndroidManifest.xml from sourceManifestFile to androidManifestFile * * @throws MojoExecutionException */ protected void copyManifest() throws MojoExecutionException { getLog().debug("copyManifest: " + sourceManifestFile + " -> " + androidManifestFile); if (sourceManifestFile == null) { getLog().debug("Manifest copying disabled. Using default manifest only"); return; } try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(sourceManifestFile); Source source = new DOMSource(doc); TransformerFactory xfactory = TransformerFactory.newInstance(); Transformer xformer = xfactory.newTransformer(); xformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); FileWriter writer = null; try { androidManifestFile.getParentFile().mkdirs(); writer = new FileWriter(androidManifestFile, false); if (doc.getXmlEncoding() != null && doc.getXmlVersion() != null) { String xmldecl = String.format( "<?xml version=\"%s\" encoding=\"%s\"?>%n", doc.getXmlVersion(), doc.getXmlEncoding()); writer.write(xmldecl); } Result result = new StreamResult(writer); xformer.transform(source, result); getLog().info("Manifest copied from " + sourceManifestFile + " to " + androidManifestFile); } finally { IOUtils.closeQuietly(writer); } } catch (Exception e) { getLog().error("Error during copyManifest"); throw new MojoExecutionException("Error during copyManifest", e); } }
@Override public DocumentNode convert(Document document) { DocumentTypeNode documentTypeNode = convert(document.getDoctype()); ElementNode rootElementNode = convert(document.getDocumentElement()); DocumentBuilder documentBuilder = NodeBuilderFactory.newDocumentBuilder(); DocumentNode documentNode = null; documentNode = documentBuilder // documentNode define .nodeName(document.getNodeName()) // node name .version(document.getXmlEncoding()) // Version .encoding(document.getXmlEncoding()) // encoding .standalone(document.getXmlStandalone()) // standalone .documentTypeNode(documentTypeNode) // DOCTYPE .rootElementNode(rootElementNode) // rootElementNode .build(); // return result return documentNode; }
/** * Serielizes a document to a file. The file is being encoded in accordance with the value given * in the xml declaration. If no encoding is found then "utf-8" is used. The method covers for * some Daisy 2.02 readers related problems: * * <ol> * <li>navigation point line breaks * <li>order of attributes in meta elements * </ol> * * <p>Ad. 1.<br> * Some Daisy readers require that each navigation point in an ncc document constitues a single * line in html code.<br> * <br> * Such readers require also CRLF line break markers.<br> * <br> * The input navigation file document uses LF as line break markers, which * formatNavPointsLineBreaks replaces with LFCR in such a manner that each navigation point * constitues a single line in html code of an ncc.<br> * <br> * In other kinds of documents it just replaces LF with CRLF. * * <p>Ad. 2.<br> * PlexTalk Daisy reader requires a specific order of attributes, * * <ul> * <li>in meta elements: - name="" content="" * <li>in smil/audio elements: src="" clip-begin="" clip-end="" id="" * <ul> */ public static File serializeDaisy202DocToFile(Document doc, String outputFilePath) throws IOException { String _encoding = doc.getXmlEncoding(); if (_encoding == null) { _encoding = DtbSerializer.DEFAULT_ENCODING; } File _file = DtbSerializer.serializeDocToFile(doc, outputFilePath); if (FilesetRegex.getInstance().matches(FilesetRegex.getInstance().FILE_NCC, _file.getName())) { DtbSerializer.formatNavPointsLineBreaks(_file, _encoding); } DtbSerializer.formatPlexTalkAttributesOrder(_file, _encoding); return _file; }
/* * Writes the wsdl definition to the file at the given path, relative to the target folder. */ private String writeXMLObj(IPath path, Definition definition, IProgressMonitor monitor) throws WSDLException, URIException, IOException, CoreException { String[] targetURI = appendPathToURI(targetFolderURI, path); OutputStream os = uriFactory.newURI(targetURI[0]).getOutputStream(); DefinitionImpl definitionImpl = (DefinitionImpl) definition; WSDLResourceImpl resource = (WSDLResourceImpl) definitionImpl.eResource(); Document document = definitionImpl.getDocument(); resource.serialize(os, document, document.getXmlEncoding()); os.close(); return targetURI[1]; }
/** * Serielizes a document to a file. The file is being encoded in accordance with the value given * in the xml declaration. If no encoding is found then "utf-8" is used. * * @throws IOException */ public static File serializeDocToFile(Document doc, String outputFilePath) throws IOException { File outputFile = new File(outputFilePath); if (outputFile.exists()) { // just in case the user runs DTBSM with the same output URI outputFile.delete(); } FileOutputStream fos = null; OutputStreamWriter osWriter = null; try { String encoding = doc.getXmlEncoding(); if (encoding == null) { encoding = DtbSerializer.DEFAULT_ENCODING; } boolean prettyIndenting = true; OutputFormat of = new OutputFormat(doc, encoding, prettyIndenting); XMLSerializer ser = new XMLSerializer(of); // Create a new (empty) file on disk in the target directory fos = new FileOutputStream(outputFile); if (encoding != null) { osWriter = new OutputStreamWriter(fos, encoding); ser.setOutputCharStream(osWriter); } else { osWriter = new OutputStreamWriter(fos); ser.setOutputCharStream(osWriter); } // Serialize our document into the output stream held by the xml-serializer ser.serialize(doc); } catch (IOException e) { throw e; } finally { try { fos.close(); osWriter.close(); } catch (IOException e) { throw e; } } return outputFile; }
/** * 将XML文档写入到文件<br> * * @param doc XML文档 * @param absolutePath 文件绝对路径,不存在会自动创建 * @param charset 自定义XML文件的编码 */ public static void toFile(Document doc, String absolutePath, String charset) { if (StrUtil.isBlank(charset)) { charset = doc.getXmlEncoding(); } if (StrUtil.isBlank(charset)) { charset = CharsetUtil.UTF_8; } BufferedWriter writer = null; try { writer = FileUtil.getBufferedWriter(absolutePath, charset, false); Source source = new DOMSource(doc); final Transformer xformer = TransformerFactory.newInstance().newTransformer(); xformer.setOutputProperty(OutputKeys.ENCODING, charset); xformer.setOutputProperty(OutputKeys.INDENT, "yes"); xformer.transform(source, new StreamResult(writer)); } catch (Exception e) { throw new UtilException("Trans xml document to string error!", e); } finally { FileUtil.close(writer); } }
@Override public void writeResponse( String baseUri, String ctxUri, EndpointInfo endpointInfo, OutputStream os) { try { int idx = baseUri.toLowerCase().indexOf("?"); Map<String, String> params = UrlUtils.parseQueryString(baseUri.substring(idx + 1)); String base; if (endpointInfo.getProperty("publishedEndpointUrl") != null) { base = String.valueOf(endpointInfo.getProperty("publishedEndpointUrl")); } else { base = baseUri.substring(0, baseUri.toLowerCase().indexOf("?")); } String wsdl = params.get("wsdl"); if (wsdl != null) { // Always use the URL decoded version to ensure that we have a // canonical representation of the import URL for lookup. wsdl = URLDecoder.decode(wsdl, "utf-8"); } String xsd = params.get("xsd"); if (xsd != null) { // Always use the URL decoded version to ensure that we have a // canonical representation of the import URL for lookup. xsd = URLDecoder.decode(xsd, "utf-8"); } Map<String, Definition> mp = CastUtils.cast( (Map) endpointInfo.getService().getProperty(WSDLQueryHandler.class.getName())); Map<String, SchemaReference> smp = CastUtils.cast( (Map) endpointInfo .getService() .getProperty(WSDLQueryHandler.class.getName() + ".Schemas")); if (mp == null) { endpointInfo .getService() .setProperty(WSDLQueryHandler.class.getName(), new ConcurrentHashMap()); mp = CastUtils.cast( (Map) endpointInfo.getService().getProperty(WSDLQueryHandler.class.getName())); } if (smp == null) { endpointInfo .getService() .setProperty(WSDLQueryHandler.class.getName() + ".Schemas", new ConcurrentHashMap()); smp = CastUtils.cast( (Map) endpointInfo .getService() .getProperty(WSDLQueryHandler.class.getName() + ".Schemas")); } if (!mp.containsKey("")) { Definition def = getDefinition(endpointInfo); mp.put("", def); updateDefinition(def, mp, smp, base, endpointInfo); } Document doc; if (xsd == null) { Definition def = mp.get(wsdl); if (def == null) { String wsdl2 = resolveWithCatalogs(OASISCatalogManager.getCatalogManager(bus), wsdl, base); if (wsdl2 != null) { def = mp.get(wsdl2); } } if (def == null) { throw new WSDLQueryException( new org.apache.cxf.common.i18n.Message("WSDL_NOT_FOUND", LOG, wsdl), null); } synchronized (def) { // writing a def is not threadsafe. Sync on it to make sure // we don't get any ConcurrentModificationExceptions if (endpointInfo.getProperty("publishedEndpointUrl") != null) { String publishingUrl = String.valueOf(endpointInfo.getProperty("publishedEndpointUrl")); updatePublishedEndpointUrl(publishingUrl, def, endpointInfo.getName()); } WSDLWriter wsdlWriter = bus.getExtension(WSDLManager.class).getWSDLFactory().newWSDLWriter(); def.setExtensionRegistry(bus.getExtension(WSDLManager.class).getExtensionRegistry()); doc = wsdlWriter.getDocument(def); } } else { SchemaReference si = smp.get(xsd); if (si == null) { String xsd2 = resolveWithCatalogs(OASISCatalogManager.getCatalogManager(bus), xsd, base); if (xsd2 != null) { si = smp.get(xsd2); } } if (si == null) { throw new WSDLQueryException( new org.apache.cxf.common.i18n.Message("SCHEMA_NOT_FOUND", LOG, wsdl), null); } String uri = si.getReferencedSchema().getDocumentBaseURI(); uri = resolveWithCatalogs( OASISCatalogManager.getCatalogManager(bus), uri, si.getReferencedSchema().getDocumentBaseURI()); if (uri == null) { uri = si.getReferencedSchema().getDocumentBaseURI(); } ResourceManagerWSDLLocator rml = new ResourceManagerWSDLLocator(uri, bus); InputSource src = rml.getBaseInputSource(); doc = XMLUtils.getParser().parse(src); } updateDoc(doc, base, mp, smp, endpointInfo); String enc = null; try { enc = doc.getXmlEncoding(); } catch (Exception ex) { // ignore - not dom level 3 } if (enc == null) { enc = "utf-8"; } XMLStreamWriter writer = StaxUtils.createXMLStreamWriter(os, enc); StaxUtils.writeNode(doc, writer, true); writer.flush(); } catch (WSDLQueryException wex) { throw wex; } catch (Exception wex) { throw new WSDLQueryException( new org.apache.cxf.common.i18n.Message("COULD_NOT_PROVIDE_WSDL", LOG, baseUri), wex); } }
/* */ private void setDocumentInfo(Document document) /* */ { /* 377 */ if (!document.getXmlStandalone()) /* 378 */ this._handler.setStandalone(Boolean.toString(document.getXmlStandalone())); /* 379 */ setXMLVersion(document.getXmlVersion()); /* 380 */ setEncoding(document.getXmlEncoding()); /* */ }
public boolean validate() { boolean retval = false; FileObject xmlfile = null; FileObject DTDfile = null; ByteArrayInputStream ba = null; try { if (xmlfilename != null && ((getDTDFilename() != null && !isInternDTD()) || (isInternDTD()))) { xmlfile = KettleVFS.getFileObject(getXMLFilename()); if (xmlfile.exists()) { URL xmlFile = new File(KettleVFS.getFilename(xmlfile)).toURI().toURL(); StringBuffer xmlStringbuffer = new StringBuffer(""); BufferedReader xmlBufferedReader = null; InputStreamReader is = null; try { // open XML File is = new InputStreamReader(xmlFile.openStream()); xmlBufferedReader = new BufferedReader(is); char[] buffertXML = new char[1024]; int LenXML = -1; while ((LenXML = xmlBufferedReader.read(buffertXML)) != -1) { xmlStringbuffer.append(buffertXML, 0, LenXML); } } finally { if (is != null) { is.close(); } if (xmlBufferedReader != null) { xmlBufferedReader.close(); } } // Prepare parsing ... DocumentBuilderFactory DocBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder DocBuilder = DocBuilderFactory.newDocumentBuilder(); // Let's try to get XML document encoding DocBuilderFactory.setValidating(false); ba = new ByteArrayInputStream(xmlStringbuffer.toString().getBytes("UTF-8")); Document xmlDocDTD = DocBuilder.parse(ba); if (ba != null) { ba.close(); } String encoding = null; if (xmlDocDTD.getXmlEncoding() == null) { encoding = "UTF-8"; } else { encoding = xmlDocDTD.getXmlEncoding(); } int xmlStartDTD = xmlStringbuffer.indexOf("<!DOCTYPE"); if (isInternDTD()) { // DTD find in the XML document if (xmlStartDTD != -1) { log.logBasic( BaseMessages.getString( PKG, "JobEntryDTDValidator.ERRORDTDFound.Label", getXMLFilename())); } else { setErrorMessage( BaseMessages.getString( PKG, "JobEntryDTDValidator.ERRORDTDNotFound.Label", getXMLFilename())); } } else { // DTD in external document // If we find an intern declaration, we remove it DTDfile = KettleVFS.getFileObject(getDTDFilename()); if (DTDfile.exists()) { if (xmlStartDTD != -1) { int EndDTD = xmlStringbuffer.indexOf(">", xmlStartDTD); // String DocTypeDTD = xmlStringbuffer.substring(xmlStartDTD, EndDTD + 1); xmlStringbuffer.replace(xmlStartDTD, EndDTD + 1, ""); } String xmlRootnodeDTD = xmlDocDTD.getDocumentElement().getNodeName(); String RefDTD = "<?xml version='" + xmlDocDTD.getXmlVersion() + "' encoding='" + encoding + "'?>\n<!DOCTYPE " + xmlRootnodeDTD + " SYSTEM '" + KettleVFS.getFilename(DTDfile) + "'>\n"; int xmloffsetDTD = xmlStringbuffer.indexOf("<" + xmlRootnodeDTD); xmlStringbuffer.replace(0, xmloffsetDTD, RefDTD); } else { log.logError( BaseMessages.getString(PKG, "JobEntryDTDValidator.ERRORDTDFileNotExists.Subject"), BaseMessages.getString( PKG, "JobEntryDTDValidator.ERRORDTDFileNotExists.Msg", getDTDFilename())); } } if (!(isInternDTD() && xmlStartDTD == -1 || (!isInternDTD() && !DTDfile.exists()))) { // Let's parse now ... MyErrorHandler error = new MyErrorHandler(); DocBuilderFactory.setValidating(true); DocBuilder = DocBuilderFactory.newDocumentBuilder(); DocBuilder.setErrorHandler(error); ba = new ByteArrayInputStream(xmlStringbuffer.toString().getBytes(encoding)); xmlDocDTD = DocBuilder.parse(ba); if (error.errorMessage == null) { log.logBasic( BaseMessages.getString(PKG, "JobEntryDTDValidator.DTDValidatorOK.Subject"), BaseMessages.getString( PKG, "JobEntryDTDValidator.DTDValidatorOK.Label", getXMLFilename())); // Everything is OK retval = true; } else { // Invalid DTD setNrErrors(error.nrErrors); setErrorMessage( BaseMessages.getString( PKG, "JobEntryDTDValidator.DTDValidatorKO", getXMLFilename(), error.nrErrors, error.errorMessage)); } } } else { if (!xmlfile.exists()) { setErrorMessage( BaseMessages.getString( PKG, "JobEntryDTDValidator.FileDoesNotExist.Label", getXMLFilename())); } } } else { setErrorMessage(BaseMessages.getString(PKG, "JobEntryDTDValidator.AllFilesNotNull.Label")); } } catch (Exception e) { setErrorMessage( BaseMessages.getString( PKG, "JobEntryDTDValidator.ErrorDTDValidator.Label", getXMLFilename(), getDTDFilename(), e.getMessage())); } finally { try { if (xmlfile != null) { xmlfile.close(); } if (DTDfile != null) { DTDfile.close(); } if (ba != null) { ba.close(); } } catch (IOException e) { // Ignore close errors } } return retval; }
/** * Prefirma (firma simple) en formato XAdES. * * @param data Datos a prefirmar * @param algorithm Algoritmo de firma * @param certChain Cadena de certificados del firmante * @param xParams Parámetros adicionales de la firma * @param op Operación específica de firma a realizar * @return Listado de prefirma XML * @throws NoSuchAlgorithmException Si el JRE no soporta algún algoritmo necesario. * @throws AOException Si ocurre cualquier otro error. * @throws SAXException Si hay problemas en el análisis XML. * @throws IOException Si hay problemas en el tratamiento de datos. * @throws ParserConfigurationException Si hay problemas con el analizador por defecto de XML. * @throws MarshalException Si hay problemas con el empaquetado XML. * @throws XMLSignatureException Si hay problemas en la propia firma XMLDSig. * @throws InvalidKeyException Si la clave proporcinoada no es válida. * @throws SignatureException Si hay problemas con la firma PKCS#1. * @throws XmlPreSignException Si hay un error en la pre-firma XAdES. */ public static XmlPreSignResult preSign( final byte[] data, final String algorithm, final Certificate[] certChain, final Properties xParams, final Op op) throws NoSuchAlgorithmException, AOException, SAXException, IOException, ParserConfigurationException, MarshalException, XMLSignatureException, InvalidKeyException, SignatureException, XmlPreSignException { if (data == null || data.length < 1) { throw new IllegalArgumentException( "Los datos a prefirmar no pueden ser nulos ni vacios"); //$NON-NLS-1$ } if (algorithm == null || "".equals(algorithm)) { // $NON-NLS-1$ throw new IllegalArgumentException( "El algoritmo de firma no puede ser nulo ni vacio"); //$NON-NLS-1$ } if (certChain == null || certChain.length < 1) { throw new IllegalArgumentException( "La cadena de certificados no puede ser nula y debe contener al menos un certificado" //$NON-NLS-1$ ); } // Miramos si la entrada es un XML que ya contenga firmas (almacenando los ID para luego // localizar cual es la firma // nueva y no confundirla con las antiguas), y si lo es cual es su codificacion con un // Document.getXmlEncoding() final List<String> previousSignaturesIds = new ArrayList<String>(); Document xml = null; String xmlEncoding = XML_DEFAULT_ENCODING; try { xml = DocumentBuilderFactory.newInstance() .newDocumentBuilder() .parse(new ByteArrayInputStream(data)); if (xml.getXmlEncoding() != null) { xmlEncoding = xml.getXmlEncoding(); } } catch (final Exception e) { Logger.getLogger("es.gob.afirma") .info( "El documento a firmar no es XML, por lo que no contiene firmas previas"); //$NON-NLS-1$//$NON-NLS-2$ } if (xml == null && (op == Op.COSIGN || op == Op.COUNTERSIGN)) { Logger.getLogger("es.gob.afirma") .severe("Solo se pueden cofirmar y contrafirmar firmas XML"); // $NON-NLS-1$//$NON-NLS-2$ throw new AOException( "Los datos introducidos no se corresponden con una firma XML"); //$NON-NLS-1$ } // Si los datos eran XML, comprobamos y almacenamos las firmas previas if (xml != null) { final Element rootElement = xml.getDocumentElement(); if (rootElement.getNodeName().endsWith(":" + AOXAdESSigner.SIGNATURE_TAG)) { // $NON-NLS-1$ final NamedNodeMap nnm = rootElement.getAttributes(); if (nnm != null) { final Node node = nnm.getNamedItem(XML_NODE_ID); if (node != null) { final String id = node.getNodeValue(); if (id != null) { previousSignaturesIds.add(id); } } } } else { final NodeList mainChildNodes = xml.getDocumentElement().getChildNodes(); for (int i = 0; i < mainChildNodes.getLength(); i++) { final Node currentNode = mainChildNodes.item(i); if (currentNode.getNodeType() == Node.ELEMENT_NODE && currentNode .getNodeName() .endsWith(":" + AOXAdESSigner.SIGNATURE_TAG)) { // $NON-NLS-1$ final NamedNodeMap nnm = currentNode.getAttributes(); if (nnm != null) { final Node node = nnm.getNamedItem(XML_NODE_ID); if (node != null) { final String id = node.getNodeValue(); if (id != null) { previousSignaturesIds.add(id); } } } } } } } // Generamos un par de claves para hacer la firma temporal, que despues sustituiremos por la // real final RSAPrivateKey prk = (RSAPrivateKey) generateKeyPair( ((RSAPublicKey) ((X509Certificate) certChain[0]).getPublicKey()) .getModulus() .bitLength()) .getPrivate(); final byte[] result; switch (op) { case SIGN: result = XAdESSigner.sign(data, algorithm, prk, certChain, xParams); break; case COSIGN: result = XAdESCoSigner.cosign(data, algorithm, prk, certChain, xParams); break; case COUNTERSIGN: final CounterSignTarget targets = xParams != null && CounterSignTarget.LEAFS .name() .equalsIgnoreCase(xParams.getProperty(COUNTERSIGN_TARGET_KEY)) ? CounterSignTarget.LEAFS : CounterSignTarget.TREE; result = XAdESCounterSigner.countersign(data, algorithm, targets, null, prk, certChain, xParams); break; default: throw new IllegalStateException( "No se puede dar una operacion no contemplada en el enumerado de operaciones" //$NON-NLS-1$ ); } // Cargamos el XML firmado en un String String xmlResult = new String(result, xmlEncoding); // Recuperamos los signed info que se han firmado final List<byte[]> signedInfos = XAdESTriPhaseSignerServerSide.getSignedInfos( result, certChain[0].getPublicKey(), previousSignaturesIds // Identificadores de firmas previas, para poder omitirlos ); // Ponemos un reemplazo en el XML en lugar de los PKCS#1 de las firmas generadas for (int i = 0; i < signedInfos.size(); i++) { final byte[] signedInfo = signedInfos.get(i); // Calculamos el valor PKCS#1 con la clave privada impostada, para conocer los valores que // debemos sustituir final Signature signature = Signature.getInstance(algorithm); signature.initSign(prk); signature.update(signedInfo); final String cleanSignatureValue = cleanBase64(Base64.encode(signature.sign())); // Buscamos el PKCS#1 en Base64 en el XML original y lo sustituimos por la cadena de reemplazo final String signValuePrefix = ">" + cleanSignatureValue.substring(0, NUM_CHARACTERS_TO_COMPARE); // $NON-NLS-1$ final int signValuePos = xmlResult.indexOf(signValuePrefix) + 1; final int signValueFinalPos = xmlResult.indexOf('<', signValuePos); final String pkcs1String = xmlResult.substring(signValuePos, signValueFinalPos); final String cleanPkcs1String = cleanBase64(pkcs1String); if (cleanSignatureValue.equals(cleanPkcs1String)) { xmlResult = xmlResult.replace( pkcs1String, REPLACEMENT_STRING.replace(REPLACEMENT_CODE, Integer.toString(i))); } } return new XmlPreSignResult(xmlResult.getBytes(xmlEncoding), signedInfos); }